From bb52b04c2573856cb6ee9713666d5a1f46edac16 Mon Sep 17 00:00:00 2001 From: Mike Ellery Date: Tue, 4 Sep 2018 17:14:08 -0700 Subject: [PATCH] Remove subtrees for soci, sqlite, lz4, snappy, nudb --- src/lz4/.gitattributes | 21 - src/lz4/.gitignore | 31 - src/lz4/.travis.yml | 150 - src/lz4/INSTALL | 15 - src/lz4/LICENSE | 11 - src/lz4/Makefile | 181 - src/lz4/NEWS | 231 - src/lz4/README.md | 114 - src/lz4/appveyor.yml | 141 - src/lz4/circle.yml | 39 - src/lz4/contrib/cmake_unofficial/.gitignore | 9 - .../contrib/cmake_unofficial/CMakeLists.txt | 221 - src/lz4/contrib/debian/changelog | 10 - src/lz4/contrib/debian/compat | 1 - src/lz4/contrib/debian/control | 23 - src/lz4/contrib/debian/copyright | 9 - src/lz4/contrib/debian/dirs | 1 - src/lz4/contrib/debian/docs | 0 src/lz4/contrib/debian/liblz4-dev.install | 2 - src/lz4/contrib/debian/liblz4.install | 2 - src/lz4/contrib/debian/rules | 8 - src/lz4/contrib/djgpp/LICENSE | 24 - src/lz4/contrib/djgpp/Makefile | 130 - src/lz4/contrib/djgpp/README.MD | 21 - src/lz4/contrib/gen_manual/.gitignore | 2 - src/lz4/contrib/gen_manual/Makefile | 76 - src/lz4/contrib/gen_manual/README.md | 31 - src/lz4/contrib/gen_manual/gen-lz4-manual.sh | 10 - src/lz4/contrib/gen_manual/gen_manual.cpp | 247 - src/lz4/doc/lz4_Block_format.md | 135 - src/lz4/doc/lz4_Frame_format.md | 411 - src/lz4/doc/lz4_manual.html | 325 - src/lz4/doc/lz4frame_manual.html | 277 - src/lz4/examples/.gitignore | 10 - src/lz4/examples/COPYING | 339 - src/lz4/examples/HCStreaming_ringBuffer.c | 229 - src/lz4/examples/Makefile | 98 - src/lz4/examples/README.md | 11 - .../examples/blockStreaming_doubleBuffer.c | 202 - .../examples/blockStreaming_doubleBuffer.md | 100 - src/lz4/examples/blockStreaming_lineByLine.c | 211 - src/lz4/examples/blockStreaming_lineByLine.md | 122 - src/lz4/examples/blockStreaming_ringBuffer.c | 201 - src/lz4/examples/compress_functions.c | 363 - src/lz4/examples/dictionaryRandomAccess.c | 280 - src/lz4/examples/dictionaryRandomAccess.md | 67 - src/lz4/examples/frameCompress.c | 312 - src/lz4/examples/printVersion.c | 13 - src/lz4/examples/simple_buffer.c | 94 - src/lz4/examples/streaming_api_basics.md | 87 - src/lz4/lib/.gitignore | 2 - src/lz4/lib/LICENSE | 24 - src/lz4/lib/Makefile | 180 - src/lz4/lib/README.md | 73 - src/lz4/lib/dll/example/Makefile | 63 - src/lz4/lib/dll/example/README.md | 69 - src/lz4/lib/dll/example/fullbench-dll.sln | 25 - src/lz4/lib/dll/example/fullbench-dll.vcxproj | 182 - src/lz4/lib/dll/liblz4.def | 62 - src/lz4/lib/liblz4.pc.in | 14 - src/lz4/lib/lz4.c | 1478 - src/lz4/lib/lz4.h | 463 - src/lz4/lib/lz4frame.c | 1669 - src/lz4/lib/lz4frame.h | 391 - src/lz4/lib/lz4frame_static.h | 143 - src/lz4/lib/lz4hc.c | 807 - src/lz4/lib/lz4hc.h | 278 - src/lz4/lib/lz4opt.h | 366 - src/lz4/lib/xxhash.c | 894 - src/lz4/lib/xxhash.h | 293 - src/lz4/programs/.gitignore | 20 - src/lz4/programs/COPYING | 339 - src/lz4/programs/Makefile | 172 - src/lz4/programs/README.md | 71 - src/lz4/programs/bench.c | 521 - src/lz4/programs/bench.h | 37 - src/lz4/programs/datagen.c | 189 - src/lz4/programs/datagen.h | 40 - src/lz4/programs/lz4.1 | 220 - src/lz4/programs/lz4.1.md | 218 - src/lz4/programs/lz4cli.c | 647 - src/lz4/programs/lz4io.c | 1045 - src/lz4/programs/lz4io.h | 101 - src/lz4/programs/platform.h | 154 - src/lz4/programs/util.h | 494 - src/lz4/tests/.gitignore | 14 - src/lz4/tests/COPYING | 339 - src/lz4/tests/Makefile | 387 - src/lz4/tests/README.md | 71 - src/lz4/tests/datagencli.c | 172 - src/lz4/tests/fasttest.c | 131 - src/lz4/tests/frametest.c | 1066 - src/lz4/tests/fullbench.c | 723 - src/lz4/tests/fuzzer.c | 1180 - src/lz4/tests/test-lz4-speed.py | 351 - src/lz4/tests/test-lz4-versions.py | 156 - src/lz4/visual/.gitignore | 10 - src/lz4/visual/README.md | 53 - src/lz4/visual/VS2010/datagen/datagen.vcxproj | 165 - .../visual/VS2010/frametest/frametest.vcxproj | 172 - .../fullbench-dll/fullbench-dll.vcxproj | 176 - .../visual/VS2010/fullbench/fullbench.vcxproj | 172 - src/lz4/visual/VS2010/fuzzer/fuzzer.vcxproj | 169 - .../visual/VS2010/liblz4-dll/liblz4-dll.rc | 51 - .../VS2010/liblz4-dll/liblz4-dll.vcxproj | 175 - src/lz4/visual/VS2010/liblz4/liblz4.vcxproj | 171 - src/lz4/visual/VS2010/lz4.sln | 98 - src/lz4/visual/VS2010/lz4/lz4.rc | 51 - src/lz4/visual/VS2010/lz4/lz4.vcxproj | 185 - src/nudb/.gitignore | 2 - src/nudb/.gitmodules | 9 - src/nudb/.travis.yml | 89 - src/nudb/CHANGELOG.md | 58 - src/nudb/CMakeLists.txt | 87 - src/nudb/Jamroot | 93 - src/nudb/LICENSE_1_0.txt | 23 - src/nudb/README.md | 466 - src/nudb/TODO.txt | 2 - src/nudb/bench/CMakeLists.txt | 363 - src/nudb/bench/Jamfile | 226 - src/nudb/bench/README.md | 102 - src/nudb/bench/bench.cpp | 535 - src/nudb/bench/plot_bench.py | 37 - src/nudb/doc/.gitignore | 5 - src/nudb/doc/Jamfile.v2 | 77 - src/nudb/doc/boostbook.dtd | 439 - src/nudb/doc/docca | 1 - src/nudb/doc/images/logo.png | Bin 153828 -> 0 bytes src/nudb/doc/images/logo.psd | Bin 737507 -> 0 bytes src/nudb/doc/images/readme2.png | Bin 106410 -> 0 bytes src/nudb/doc/index.xml | 14 - src/nudb/doc/main.qbk | 342 - src/nudb/doc/makeqbk.sh | 12 - src/nudb/doc/quickref.xml | 82 - src/nudb/doc/reference.xsl | 14 - src/nudb/doc/source.dox | 333 - src/nudb/doc/types/File.qbk | 159 - src/nudb/doc/types/Hasher.qbk | 56 - src/nudb/doc/types/Progress.qbk | 40 - src/nudb/examples/CMakeLists.txt | 17 - src/nudb/examples/Jamfile | 12 - src/nudb/examples/example.cpp | 46 - src/nudb/extras/README.md | 5 - src/nudb/extras/beast | 1 - src/nudb/extras/nudb/test/fail_file.hpp | 343 - src/nudb/extras/nudb/test/temp_dir.hpp | 73 - src/nudb/extras/nudb/test/test_store.hpp | 451 - .../extras/nudb/test/xor_shift_engine.hpp | 105 - src/nudb/extras/nudb/util.hpp | 288 - src/nudb/extras/rocksdb | 1 - src/nudb/include/nudb/basic_store.hpp | 436 - src/nudb/include/nudb/concepts.hpp | 205 - src/nudb/include/nudb/create.hpp | 117 - src/nudb/include/nudb/detail/arena.hpp | 296 - src/nudb/include/nudb/detail/bucket.hpp | 473 - src/nudb/include/nudb/detail/buffer.hpp | 86 - src/nudb/include/nudb/detail/bulkio.hpp | 196 - src/nudb/include/nudb/detail/cache.hpp | 236 - src/nudb/include/nudb/detail/endian.hpp | 93 - src/nudb/include/nudb/detail/field.hpp | 265 - src/nudb/include/nudb/detail/format.hpp | 629 - src/nudb/include/nudb/detail/gentex.hpp | 259 - src/nudb/include/nudb/detail/mutex.hpp | 26 - src/nudb/include/nudb/detail/pool.hpp | 243 - src/nudb/include/nudb/detail/stream.hpp | 149 - src/nudb/include/nudb/detail/xxhash.hpp | 328 - src/nudb/include/nudb/error.hpp | 263 - src/nudb/include/nudb/file.hpp | 53 - src/nudb/include/nudb/impl/basic_store.ipp | 793 - src/nudb/include/nudb/impl/create.ipp | 163 - src/nudb/include/nudb/impl/error.ipp | 180 - src/nudb/include/nudb/impl/posix_file.ipp | 259 - src/nudb/include/nudb/impl/recover.ipp | 209 - src/nudb/include/nudb/impl/rekey.ipp | 248 - src/nudb/include/nudb/impl/verify.ipp | 630 - src/nudb/include/nudb/impl/visit.ipp | 96 - src/nudb/include/nudb/impl/win32_file.ipp | 264 - src/nudb/include/nudb/native_file.hpp | 76 - src/nudb/include/nudb/nudb.hpp | 27 - src/nudb/include/nudb/posix_file.hpp | 228 - src/nudb/include/nudb/progress.hpp | 32 - src/nudb/include/nudb/recover.hpp | 73 - src/nudb/include/nudb/rekey.hpp | 110 - src/nudb/include/nudb/store.hpp | 27 - src/nudb/include/nudb/type_traits.hpp | 63 - src/nudb/include/nudb/verify.hpp | 200 - src/nudb/include/nudb/version.hpp | 21 - src/nudb/include/nudb/visit.hpp | 63 - src/nudb/include/nudb/win32_file.hpp | 246 - src/nudb/include/nudb/xxhasher.hpp | 45 - src/nudb/scripts/blacklist.supp | 38 - src/nudb/scripts/build-and-test.sh | 150 - src/nudb/scripts/install-boost.sh | 27 - src/nudb/scripts/install-dependencies.sh | 90 - src/nudb/scripts/install-valgrind.sh | 20 - src/nudb/scripts/run-with-debugger.sh | 22 - src/nudb/scripts/run-with-gdb.sh | 9 - src/nudb/test/CMakeLists.txt | 38 - src/nudb/test/Jamfile | 30 - src/nudb/test/basic_store.cpp | 250 - src/nudb/test/buffer.cpp | 77 - src/nudb/test/callgrind_test.cpp | 92 - src/nudb/test/concepts.cpp | 9 - src/nudb/test/create.cpp | 49 - src/nudb/test/error.cpp | 83 - src/nudb/test/file.cpp | 9 - src/nudb/test/native_file.cpp | 9 - src/nudb/test/posix_file.cpp | 9 - src/nudb/test/recover.cpp | 191 - src/nudb/test/rekey.cpp | 136 - src/nudb/test/store.cpp | 9 - src/nudb/test/type_traits.cpp | 9 - src/nudb/test/verify.cpp | 94 - src/nudb/test/version.cpp | 9 - src/nudb/test/visit.cpp | 114 - src/nudb/test/win32_file.cpp | 9 - src/nudb/test/xxhasher.cpp | 9 - src/nudb/tools/CMakeLists.txt | 17 - src/nudb/tools/Jamfile | 12 - src/nudb/tools/nudb.cpp | 514 - src/ripple/unity/soci.cpp | 61 - src/snappy/config/snappy-stubs-public.h | 79 - src/snappy/snappy/.appveyor.yml | 41 - src/snappy/snappy/.travis.yml | 59 - src/snappy/snappy/AUTHORS | 1 - src/snappy/snappy/CMakeLists.txt | 174 - src/snappy/snappy/CONTRIBUTING.md | 26 - src/snappy/snappy/COPYING | 54 - src/snappy/snappy/NEWS | 180 - src/snappy/snappy/README.md | 149 - src/snappy/snappy/cmake/SnappyConfig.cmake | 1 - src/snappy/snappy/cmake/config.h.in | 62 - src/snappy/snappy/format_description.txt | 110 - src/snappy/snappy/framing_format.txt | 135 - src/snappy/snappy/snappy-c.cc | 90 - src/snappy/snappy/snappy-c.h | 138 - src/snappy/snappy/snappy-internal.h | 224 - src/snappy/snappy/snappy-sinksource.cc | 104 - src/snappy/snappy/snappy-sinksource.h | 182 - src/snappy/snappy/snappy-stubs-internal.cc | 42 - src/snappy/snappy/snappy-stubs-internal.h | 561 - src/snappy/snappy/snappy-stubs-public.h.in | 94 - src/snappy/snappy/snappy-test.cc | 612 - src/snappy/snappy/snappy-test.h | 573 - src/snappy/snappy/snappy.cc | 1515 - src/snappy/snappy/snappy.h | 203 - src/snappy/snappy/snappy_unittest.cc | 1410 - src/snappy/snappy/testdata/alice29.txt | 3609 - src/snappy/snappy/testdata/asyoulik.txt | 4122 - src/snappy/snappy/testdata/baddata1.snappy | Bin 27512 -> 0 bytes src/snappy/snappy/testdata/baddata2.snappy | Bin 27483 -> 0 bytes src/snappy/snappy/testdata/baddata3.snappy | Bin 28384 -> 0 bytes src/snappy/snappy/testdata/fireworks.jpeg | Bin 123093 -> 0 bytes src/snappy/snappy/testdata/geo.protodata | Bin 118588 -> 0 bytes src/snappy/snappy/testdata/html | 1 - src/snappy/snappy/testdata/html_x_4 | 1 - src/snappy/snappy/testdata/kppkn.gtb | Bin 184320 -> 0 bytes src/snappy/snappy/testdata/lcet10.txt | 7519 - src/snappy/snappy/testdata/paper-100k.pdf | 598 - src/snappy/snappy/testdata/plrabn12.txt | 10699 - src/snappy/snappy/testdata/urls.10K | 10000 - src/soci/.circleci/config.yml | 59 - src/soci/.editorconfig | 32 - src/soci/.gitattributes | 30 - src/soci/.gitignore | 44 - src/soci/.markdownlint.json | 7 - src/soci/.travis.yml | 60 - src/soci/AUTHORS | 78 - src/soci/CHANGELOG.md | 456 - src/soci/CHANGES | 384 - src/soci/CMakeLists.txt | 207 - src/soci/LICENSE_1_0.txt | 23 - src/soci/README.md | 59 - src/soci/TODO | 110 - src/soci/Vagrantfile | 56 - src/soci/appveyor.yml | 104 - src/soci/cmake/.gitignore | 21 - src/soci/cmake/CMakeLists.txt | 13 - src/soci/cmake/SociBackend.cmake | 394 - src/soci/cmake/SociConfig.cmake | 106 - src/soci/cmake/SociDependencies.cmake | 84 - src/soci/cmake/SociUtilities.cmake | 426 - src/soci/cmake/SociVersion.cmake | 62 - src/soci/cmake/configs/test-access.cmake | 13 - src/soci/cmake/configs/test-mysql.cmake | 4 - src/soci/cmake/dependencies/Boost.cmake | 13 - src/soci/cmake/dependencies/DB2.cmake | 5 - src/soci/cmake/dependencies/Firebird.cmake | 9 - src/soci/cmake/dependencies/MySQL.cmake | 5 - src/soci/cmake/dependencies/ODBC.cmake | 5 - src/soci/cmake/dependencies/Oracle.cmake | 5 - src/soci/cmake/dependencies/PostgreSQL.cmake | 5 - src/soci/cmake/dependencies/SQLite3.cmake | 5 - src/soci/cmake/dependencies/Threads.cmake | 4 - src/soci/cmake/modules/FindDB2.cmake | 105 - src/soci/cmake/modules/FindDL.cmake | 21 - src/soci/cmake/modules/FindFirebird.cmake | 38 - src/soci/cmake/modules/FindMySQL.cmake | 129 - src/soci/cmake/modules/FindODBC.cmake | 69 - src/soci/cmake/modules/FindOracle.cmake | 81 - src/soci/cmake/modules/FindPostgreSQL.cmake | 176 - src/soci/cmake/modules/FindSQLite3.cmake | 62 - src/soci/cmake/modules/FindSoci.cmake | 98 - .../vs2010-test-cmd-args.vcxproj.user.in | 7 - src/soci/docs/api/backend.md | 313 - src/soci/docs/api/client.md | 753 - src/soci/docs/backends/db2.md | 93 - src/soci/docs/backends/firebird.md | 154 - src/soci/docs/backends/index.md | 14 - src/soci/docs/backends/mysql.md | 130 - src/soci/docs/backends/odbc.md | 173 - src/soci/docs/backends/oracle.md | 171 - src/soci/docs/backends/postgresql.md | 171 - src/soci/docs/backends/sqlite3.md | 147 - src/soci/docs/beyond.md | 89 - src/soci/docs/binding.md | 184 - src/soci/docs/boost.md | 83 - src/soci/docs/connections.md | 162 - src/soci/docs/errors.md | 99 - src/soci/docs/faq.md | 129 - src/soci/docs/images/structure.png | Bin 26919 -> 0 bytes src/soci/docs/index.md | 68 - src/soci/docs/indicators.md | 102 - src/soci/docs/installation.md | 221 - src/soci/docs/interfaces.md | 84 - src/soci/docs/languages/ada/concepts.md | 29 - src/soci/docs/languages/ada/idioms.md | 242 - src/soci/docs/languages/ada/index.md | 37 - src/soci/docs/languages/ada/reference.md | 522 - src/soci/docs/languages/index.md | 3 - src/soci/docs/license.md | 29 - src/soci/docs/lobs.md | 71 - src/soci/docs/logging.md | 26 - src/soci/docs/multithreading.md | 47 - src/soci/docs/procedures.md | 20 - src/soci/docs/queries.md | 94 - src/soci/docs/quickstart.md | 56 - src/soci/docs/statements.md | 249 - src/soci/docs/structure.md | 27 - src/soci/docs/transactions.md | 45 - src/soci/docs/types.md | 292 - src/soci/docs/utilities.md | 151 - src/soci/docs/vagrant.md | 125 - src/soci/include/private/README.md | 5 - src/soci/include/private/firebird/common.h | 271 - .../include/private/firebird/error-firebird.h | 35 - src/soci/include/private/soci-compiler.h | 39 - src/soci/include/private/soci-cpp.h | 30 - src/soci/include/private/soci-cstrtod.h | 80 - src/soci/include/private/soci-dtocstr.h | 58 - src/soci/include/private/soci-exchange-cast.h | 97 - src/soci/include/private/soci-mktime.h | 51 - src/soci/include/private/soci-static-assert.h | 19 - src/soci/include/soci/backend-loader.h | 37 - src/soci/include/soci/bind-values.h | 197 - src/soci/include/soci/blob-exchange.h | 59 - src/soci/include/soci/blob.h | 61 - src/soci/include/soci/boost-fusion.h | 28 - src/soci/include/soci/boost-gregorian-date.h | 47 - src/soci/include/soci/boost-optional.h | 56 - src/soci/include/soci/boost-tuple.h | 18 - src/soci/include/soci/callbacks.h | 47 - src/soci/include/soci/column-info.h | 123 - src/soci/include/soci/connection-parameters.h | 69 - src/soci/include/soci/connection-pool.h | 41 - src/soci/include/soci/db2/soci-db2.h | 300 - src/soci/include/soci/empty/soci-empty.h | 196 - src/soci/include/soci/error.h | 66 - src/soci/include/soci/exchange-traits.h | 155 - .../include/soci/firebird/soci-firebird.h | 365 - src/soci/include/soci/into-type.h | 207 - src/soci/include/soci/into.h | 90 - src/soci/include/soci/mysql/soci-mysql.h | 280 - src/soci/include/soci/noreturn.h | 22 - src/soci/include/soci/odbc/soci-odbc.h | 476 - src/soci/include/soci/once-temp-type.h | 160 - src/soci/include/soci/oracle/soci-oracle.h | 481 - .../include/soci/postgresql/soci-postgresql.h | 421 - src/soci/include/soci/prepare-temp-type.h | 65 - src/soci/include/soci/procedure.h | 90 - src/soci/include/soci/query_transformation.h | 59 - .../include/soci/ref-counted-prepare-info.h | 66 - src/soci/include/soci/ref-counted-statement.h | 102 - src/soci/include/soci/row-exchange.h | 80 - src/soci/include/soci/row.h | 140 - src/soci/include/soci/rowid-exchange.h | 59 - src/soci/include/soci/rowid.h | 41 - src/soci/include/soci/rowset.h | 220 - src/soci/include/soci/session.h | 203 - src/soci/include/soci/soci-backend.h | 483 - src/soci/include/soci/soci-config.h | 49 - src/soci/include/soci/soci-config.h.in | 16 - src/soci/include/soci/soci-platform.h | 143 - src/soci/include/soci/soci-simple.h | 159 - src/soci/include/soci/soci.h | 58 - src/soci/include/soci/sqlite3/soci-sqlite3.h | 358 - src/soci/include/soci/statement.h | 323 - src/soci/include/soci/transaction.h | 36 - .../include/soci/type-conversion-traits.h | 41 - src/soci/include/soci/type-conversion.h | 507 - src/soci/include/soci/type-holder.h | 70 - src/soci/include/soci/type-ptr.h | 30 - src/soci/include/soci/type-wrappers.h | 33 - src/soci/include/soci/unsigned-types.h | 114 - src/soci/include/soci/use-type.h | 340 - src/soci/include/soci/use.h | 116 - src/soci/include/soci/values-exchange.h | 150 - src/soci/include/soci/values.h | 354 - src/soci/include/soci/version.h | 34 - src/soci/languages/ada/postgresql_client.gpr | 8 - src/soci/languages/ada/soci-mysql.ads | 16 - src/soci/languages/ada/soci-oracle.ads | 16 - src/soci/languages/ada/soci-postgresql.ads | 16 - src/soci/languages/ada/soci.adb | 1465 - src/soci/languages/ada/soci.ads | 486 - src/soci/languages/ada/soci_ada.gpr | 14 - src/soci/languages/ada/soci_core.gpr | 7 - src/soci/languages/ada/soci_postgresql.gpr | 8 - src/soci/languages/ada/std_cpp.gpr | 7 - .../languages/ada/test/postgresql_test.adb | 609 - .../languages/ada/test/postgresql_test.gpr | 12 - src/soci/mkdocs.yml | 51 - src/soci/scripts/build.bat | 79 - src/soci/scripts/changelog.sh | 24 - src/soci/scripts/travis/before_install.sh | 20 - src/soci/scripts/travis/before_install_db2.sh | 37 - .../scripts/travis/before_install_firebird.sh | 16 - .../scripts/travis/before_install_odbc.sh | 13 - .../scripts/travis/before_install_oracle.sh | 27 - src/soci/scripts/travis/before_script.sh | 12 - src/soci/scripts/travis/before_script_db2.sh | 10 - .../scripts/travis/before_script_firebird.sh | 11 - .../scripts/travis/before_script_mysql.sh | 9 - src/soci/scripts/travis/before_script_odbc.sh | 11 - .../scripts/travis/before_script_oracle.sh | 41 - .../travis/before_script_postgresql.sh | 9 - .../scripts/travis/before_script_valgrind.sh | 12 - src/soci/scripts/travis/common.sh | 39 - src/soci/scripts/travis/oracle.sh | 12 - src/soci/scripts/travis/script.sh | 16 - src/soci/scripts/travis/script_db2.sh | 27 - src/soci/scripts/travis/script_empty.sh | 25 - src/soci/scripts/travis/script_firebird.sh | 26 - src/soci/scripts/travis/script_mysql.sh | 26 - src/soci/scripts/travis/script_odbc.sh | 33 - src/soci/scripts/travis/script_oracle.sh | 28 - src/soci/scripts/travis/script_postgresql.sh | 26 - src/soci/scripts/travis/script_sqlite3.sh | 26 - src/soci/scripts/travis/script_valgrind.sh | 17 - src/soci/scripts/vagrant/bootstrap.sh | 18 - src/soci/scripts/vagrant/build.sh | 42 - src/soci/scripts/vagrant/common.env | 11 - src/soci/scripts/vagrant/db2.sh | 25 - src/soci/scripts/vagrant/db2cli.sh | 55 - src/soci/scripts/vagrant/devel.sh | 27 - src/soci/scripts/vagrant/firebird.sh | 49 - src/soci/scripts/vagrant/mysql.sh | 27 - src/soci/scripts/vagrant/postgresql.sh | 27 - .../scripts/vm/debian-oracle10g-install.sh | 89 - src/soci/scripts/windows/Get-ODBCList.ps1 | 105 - src/soci/scripts/windows/mssql_db_create.sql | 1 - src/soci/src/.gitignore | 20 - src/soci/src/CMakeLists.txt | 14 - src/soci/src/backends/.gitignore | 5 - src/soci/src/backends/CMakeLists.txt | 50 - src/soci/src/backends/db2/CMakeLists.txt | 14 - src/soci/src/backends/db2/blob.cpp | 62 - src/soci/src/backends/db2/common.h | 21 - src/soci/src/backends/db2/factory.cpp | 40 - src/soci/src/backends/db2/row-id.cpp | 28 - src/soci/src/backends/db2/session.cpp | 248 - .../src/backends/db2/standard-into-type.cpp | 163 - .../src/backends/db2/standard-use-type.cpp | 204 - src/soci/src/backends/db2/statement.cpp | 322 - .../src/backends/db2/vector-into-type.cpp | 427 - src/soci/src/backends/db2/vector-use-type.cpp | 402 - src/soci/src/backends/empty/CMakeLists.txt | 14 - src/soci/src/backends/empty/Makefile.basic | 88 - src/soci/src/backends/empty/blob.cpp | 61 - src/soci/src/backends/empty/factory.cpp | 42 - src/soci/src/backends/empty/row-id.cpp | 27 - src/soci/src/backends/empty/session.cpp | 63 - .../src/backends/empty/standard-into-type.cpp | 39 - .../src/backends/empty/standard-use-type.cpp | 47 - src/soci/src/backends/empty/statement.cpp | 109 - .../src/backends/empty/vector-into-type.cpp | 46 - .../src/backends/empty/vector-use-type.cpp | 46 - src/soci/src/backends/firebird/CMakeLists.txt | 16 - src/soci/src/backends/firebird/Makefile.basic | 101 - src/soci/src/backends/firebird/blob.cpp | 314 - src/soci/src/backends/firebird/common.cpp | 221 - .../src/backends/firebird/error-firebird.cpp | 87 - src/soci/src/backends/firebird/factory.cpp | 36 - src/soci/src/backends/firebird/session.cpp | 369 - .../backends/firebird/standard-into-type.cpp | 167 - .../backends/firebird/standard-use-type.cpp | 206 - src/soci/src/backends/firebird/statement.cpp | 738 - .../backends/firebird/vector-into-type.cpp | 208 - .../src/backends/firebird/vector-use-type.cpp | 207 - src/soci/src/backends/mysql/CMakeLists.txt | 15 - src/soci/src/backends/mysql/Makefile.basic | 97 - src/soci/src/backends/mysql/blob.cpp | 62 - src/soci/src/backends/mysql/common.cpp | 23 - src/soci/src/backends/mysql/common.h | 90 - src/soci/src/backends/mysql/factory.cpp | 45 - src/soci/src/backends/mysql/row-id.cpp | 32 - src/soci/src/backends/mysql/session.cpp | 422 - .../src/backends/mysql/standard-into-type.cpp | 120 - .../src/backends/mysql/standard-use-type.cpp | 170 - src/soci/src/backends/mysql/statement.cpp | 484 - .../src/backends/mysql/vector-into-type.cpp | 227 - .../src/backends/mysql/vector-use-type.cpp | 217 - src/soci/src/backends/odbc/CMakeLists.txt | 15 - src/soci/src/backends/odbc/Makefile.basic | 89 - src/soci/src/backends/odbc/blob.cpp | 57 - src/soci/src/backends/odbc/factory.cpp | 39 - src/soci/src/backends/odbc/makefile.msvc | 48 - src/soci/src/backends/odbc/row-id.cpp | 23 - src/soci/src/backends/odbc/session.cpp | 383 - .../src/backends/odbc/standard-into-type.cpp | 208 - .../src/backends/odbc/standard-use-type.cpp | 267 - src/soci/src/backends/odbc/statement.cpp | 366 - src/soci/src/backends/odbc/utility.h | 62 - .../src/backends/odbc/vector-into-type.cpp | 490 - .../src/backends/odbc/vector-use-type.cpp | 495 - src/soci/src/backends/oracle/CMakeLists.txt | 15 - src/soci/src/backends/oracle/Makefile.basic | 95 - src/soci/src/backends/oracle/blob.cpp | 112 - src/soci/src/backends/oracle/error.cpp | 82 - src/soci/src/backends/oracle/error.h | 33 - src/soci/src/backends/oracle/factory.cpp | 207 - src/soci/src/backends/oracle/row-id.cpp | 32 - src/soci/src/backends/oracle/session.cpp | 441 - .../backends/oracle/standard-into-type.cpp | 372 - .../src/backends/oracle/standard-use-type.cpp | 609 - src/soci/src/backends/oracle/statement.cpp | 352 - .../src/backends/oracle/vector-into-type.cpp | 504 - .../src/backends/oracle/vector-use-type.cpp | 426 - .../src/backends/postgresql/CMakeLists.txt | 59 - .../src/backends/postgresql/Makefile.basic | 114 - src/soci/src/backends/postgresql/blob.cpp | 116 - src/soci/src/backends/postgresql/common.h | 129 - src/soci/src/backends/postgresql/error.cpp | 157 - src/soci/src/backends/postgresql/factory.cpp | 142 - src/soci/src/backends/postgresql/row-id.cpp | 40 - src/soci/src/backends/postgresql/session.cpp | 146 - .../postgresql/standard-into-type.cpp | 171 - .../backends/postgresql/standard-use-type.cpp | 204 - .../src/backends/postgresql/statement.cpp | 898 - .../backends/postgresql/vector-into-type.cpp | 313 - .../backends/postgresql/vector-use-type.cpp | 295 - src/soci/src/backends/sqlite3/CMakeLists.txt | 16 - src/soci/src/backends/sqlite3/Makefile.basic | 114 - src/soci/src/backends/sqlite3/blob.cpp | 118 - src/soci/src/backends/sqlite3/common.h | 84 - src/soci/src/backends/sqlite3/error.cpp | 23 - src/soci/src/backends/sqlite3/factory.cpp | 42 - src/soci/src/backends/sqlite3/row-id.cpp | 27 - src/soci/src/backends/sqlite3/session.cpp | 170 - .../backends/sqlite3/standard-into-type.cpp | 177 - .../backends/sqlite3/standard-use-type.cpp | 213 - src/soci/src/backends/sqlite3/statement.cpp | 558 - .../src/backends/sqlite3/vector-into-type.cpp | 354 - .../src/backends/sqlite3/vector-use-type.cpp | 215 - src/soci/src/core/.gitignore | 5 - src/soci/src/core/CMakeLists.txt | 139 - src/soci/src/core/Makefile.basic | 94 - src/soci/src/core/backend-loader.cpp | 349 - src/soci/src/core/blob.cpp | 62 - src/soci/src/core/common.cpp | 93 - src/soci/src/core/connection-parameters.cpp | 62 - src/soci/src/core/connection-pool.cpp | 326 - src/soci/src/core/error.cpp | 147 - src/soci/src/core/into-type.cpp | 129 - src/soci/src/core/once-temp-type.cpp | 188 - src/soci/src/core/prepare-temp-type.cpp | 47 - src/soci/src/core/procedure.cpp | 33 - .../src/core/ref-counted-prepare-info.cpp | 34 - src/soci/src/core/ref-counted-statement.cpp | 43 - src/soci/src/core/row.cpp | 111 - src/soci/src/core/rowid.cpp | 23 - src/soci/src/core/session.cpp | 502 - src/soci/src/core/soci-simple.cpp | 2138 - src/soci/src/core/soci_backends_config.h.in | 12 - src/soci/src/core/statement.cpp | 806 - src/soci/src/core/transaction.cpp | 53 - src/soci/src/core/use-type.cpp | 219 - src/soci/src/core/values.cpp | 69 - src/soci/tests/CMakeLists.txt | 32 - src/soci/tests/README.md | 10 - src/soci/tests/catch.hpp | 11545 - src/soci/tests/common-tests.h | 4426 - src/soci/tests/db2/CMakeLists.txt | 16 - src/soci/tests/db2/test-db2.cpp | 424 - src/soci/tests/empty/CMakeLists.txt | 15 - src/soci/tests/empty/test-empty.cpp | 178 - src/soci/tests/firebird/CMakeLists.txt | 16 - src/soci/tests/firebird/test-firebird.cpp | 1389 - src/soci/tests/mysql/CMakeLists.txt | 16 - src/soci/tests/mysql/test-mysql.cpp | 867 - src/soci/tests/mysql/test-mysql.h | 137 - src/soci/tests/odbc/CMakeLists.txt | 58 - src/soci/tests/odbc/soci_test.mdb | Bin 77824 -> 0 bytes src/soci/tests/odbc/test-mssql.dsn | 10 - src/soci/tests/odbc/test-odbc-access.cpp | 148 - src/soci/tests/odbc/test-odbc-db2.cpp | 287 - src/soci/tests/odbc/test-odbc-mssql.cpp | 233 - src/soci/tests/odbc/test-odbc-mysql.cpp | 49 - src/soci/tests/odbc/test-odbc-postgresql.cpp | 295 - src/soci/tests/odbc/test-postgresql-win64.dsn | 9 - src/soci/tests/odbc/test-postgresql.dsn | 9 - src/soci/tests/oracle/CMakeLists.txt | 16 - src/soci/tests/oracle/Makefile.basic | 13 - src/soci/tests/oracle/test-oracle.cpp | 1589 - src/soci/tests/postgresql/CMakeLists.txt | 16 - src/soci/tests/postgresql/Makefile.basic | 12 - src/soci/tests/postgresql/test-postgresql.cpp | 1200 - src/soci/tests/sqlite3/CMakeLists.txt | 16 - src/soci/tests/sqlite3/Makefile.basic | 12 - src/soci/tests/sqlite3/test-sqlite3.cpp | 421 - src/soci/valgrind.suppress | 9 - src/soci/www/articles.html | 47 - src/soci/www/doc.html | 46 - src/soci/www/doc/README.md | 11 - src/soci/www/doc/index.html | 46 - src/soci/www/events.html | 101 - src/soci/www/forkus_github.png | Bin 5735 -> 0 bytes src/soci/www/index.html | 134 - src/soci/www/links.html | 78 - src/soci/www/people.html | 122 - src/soci/www/style.css | 87 - src/sqlite/sqlite.h | 34 - src/sqlite/sqlite/sqlite3.c | 205352 --------------- src/sqlite/sqlite/sqlite3.h | 10727 - src/sqlite/sqlite/sqlite3ext.h | 578 - src/sqlite/sqlite3.h | 1 - 636 files changed, 369249 deletions(-) delete mode 100644 src/lz4/.gitattributes delete mode 100644 src/lz4/.gitignore delete mode 100644 src/lz4/.travis.yml delete mode 100644 src/lz4/INSTALL delete mode 100644 src/lz4/LICENSE delete mode 100644 src/lz4/Makefile delete mode 100644 src/lz4/NEWS delete mode 100644 src/lz4/README.md delete mode 100644 src/lz4/appveyor.yml delete mode 100644 src/lz4/circle.yml delete mode 100644 src/lz4/contrib/cmake_unofficial/.gitignore delete mode 100644 src/lz4/contrib/cmake_unofficial/CMakeLists.txt delete mode 100644 src/lz4/contrib/debian/changelog delete mode 100644 src/lz4/contrib/debian/compat delete mode 100644 src/lz4/contrib/debian/control delete mode 100644 src/lz4/contrib/debian/copyright delete mode 100644 src/lz4/contrib/debian/dirs delete mode 100644 src/lz4/contrib/debian/docs delete mode 100644 src/lz4/contrib/debian/liblz4-dev.install delete mode 100644 src/lz4/contrib/debian/liblz4.install delete mode 100755 src/lz4/contrib/debian/rules delete mode 100644 src/lz4/contrib/djgpp/LICENSE delete mode 100644 src/lz4/contrib/djgpp/Makefile delete mode 100644 src/lz4/contrib/djgpp/README.MD delete mode 100644 src/lz4/contrib/gen_manual/.gitignore delete mode 100644 src/lz4/contrib/gen_manual/Makefile delete mode 100644 src/lz4/contrib/gen_manual/README.md delete mode 100644 src/lz4/contrib/gen_manual/gen-lz4-manual.sh delete mode 100644 src/lz4/contrib/gen_manual/gen_manual.cpp delete mode 100644 src/lz4/doc/lz4_Block_format.md delete mode 100644 src/lz4/doc/lz4_Frame_format.md delete mode 100644 src/lz4/doc/lz4_manual.html delete mode 100644 src/lz4/doc/lz4frame_manual.html delete mode 100644 src/lz4/examples/.gitignore delete mode 100644 src/lz4/examples/COPYING delete mode 100644 src/lz4/examples/HCStreaming_ringBuffer.c delete mode 100644 src/lz4/examples/Makefile delete mode 100644 src/lz4/examples/README.md delete mode 100644 src/lz4/examples/blockStreaming_doubleBuffer.c delete mode 100644 src/lz4/examples/blockStreaming_doubleBuffer.md delete mode 100644 src/lz4/examples/blockStreaming_lineByLine.c delete mode 100644 src/lz4/examples/blockStreaming_lineByLine.md delete mode 100644 src/lz4/examples/blockStreaming_ringBuffer.c delete mode 100644 src/lz4/examples/compress_functions.c delete mode 100644 src/lz4/examples/dictionaryRandomAccess.c delete mode 100644 src/lz4/examples/dictionaryRandomAccess.md delete mode 100644 src/lz4/examples/frameCompress.c delete mode 100644 src/lz4/examples/printVersion.c delete mode 100644 src/lz4/examples/simple_buffer.c delete mode 100644 src/lz4/examples/streaming_api_basics.md delete mode 100644 src/lz4/lib/.gitignore delete mode 100644 src/lz4/lib/LICENSE delete mode 100644 src/lz4/lib/Makefile delete mode 100644 src/lz4/lib/README.md delete mode 100644 src/lz4/lib/dll/example/Makefile delete mode 100644 src/lz4/lib/dll/example/README.md delete mode 100644 src/lz4/lib/dll/example/fullbench-dll.sln delete mode 100644 src/lz4/lib/dll/example/fullbench-dll.vcxproj delete mode 100644 src/lz4/lib/dll/liblz4.def delete mode 100644 src/lz4/lib/liblz4.pc.in delete mode 100644 src/lz4/lib/lz4.c delete mode 100644 src/lz4/lib/lz4.h delete mode 100644 src/lz4/lib/lz4frame.c delete mode 100644 src/lz4/lib/lz4frame.h delete mode 100644 src/lz4/lib/lz4frame_static.h delete mode 100644 src/lz4/lib/lz4hc.c delete mode 100644 src/lz4/lib/lz4hc.h delete mode 100644 src/lz4/lib/lz4opt.h delete mode 100644 src/lz4/lib/xxhash.c delete mode 100644 src/lz4/lib/xxhash.h delete mode 100644 src/lz4/programs/.gitignore delete mode 100644 src/lz4/programs/COPYING delete mode 100644 src/lz4/programs/Makefile delete mode 100644 src/lz4/programs/README.md delete mode 100644 src/lz4/programs/bench.c delete mode 100644 src/lz4/programs/bench.h delete mode 100644 src/lz4/programs/datagen.c delete mode 100644 src/lz4/programs/datagen.h delete mode 100644 src/lz4/programs/lz4.1 delete mode 100644 src/lz4/programs/lz4.1.md delete mode 100644 src/lz4/programs/lz4cli.c delete mode 100644 src/lz4/programs/lz4io.c delete mode 100644 src/lz4/programs/lz4io.h delete mode 100644 src/lz4/programs/platform.h delete mode 100644 src/lz4/programs/util.h delete mode 100644 src/lz4/tests/.gitignore delete mode 100644 src/lz4/tests/COPYING delete mode 100644 src/lz4/tests/Makefile delete mode 100644 src/lz4/tests/README.md delete mode 100644 src/lz4/tests/datagencli.c delete mode 100644 src/lz4/tests/fasttest.c delete mode 100644 src/lz4/tests/frametest.c delete mode 100644 src/lz4/tests/fullbench.c delete mode 100644 src/lz4/tests/fuzzer.c delete mode 100644 src/lz4/tests/test-lz4-speed.py delete mode 100644 src/lz4/tests/test-lz4-versions.py delete mode 100644 src/lz4/visual/.gitignore delete mode 100644 src/lz4/visual/README.md delete mode 100644 src/lz4/visual/VS2010/datagen/datagen.vcxproj delete mode 100644 src/lz4/visual/VS2010/frametest/frametest.vcxproj delete mode 100644 src/lz4/visual/VS2010/fullbench-dll/fullbench-dll.vcxproj delete mode 100644 src/lz4/visual/VS2010/fullbench/fullbench.vcxproj delete mode 100644 src/lz4/visual/VS2010/fuzzer/fuzzer.vcxproj delete mode 100644 src/lz4/visual/VS2010/liblz4-dll/liblz4-dll.rc delete mode 100644 src/lz4/visual/VS2010/liblz4-dll/liblz4-dll.vcxproj delete mode 100644 src/lz4/visual/VS2010/liblz4/liblz4.vcxproj delete mode 100644 src/lz4/visual/VS2010/lz4.sln delete mode 100644 src/lz4/visual/VS2010/lz4/lz4.rc delete mode 100644 src/lz4/visual/VS2010/lz4/lz4.vcxproj delete mode 100644 src/nudb/.gitignore delete mode 100644 src/nudb/.gitmodules delete mode 100644 src/nudb/.travis.yml delete mode 100644 src/nudb/CHANGELOG.md delete mode 100644 src/nudb/CMakeLists.txt delete mode 100644 src/nudb/Jamroot delete mode 100644 src/nudb/LICENSE_1_0.txt delete mode 100644 src/nudb/README.md delete mode 100644 src/nudb/TODO.txt delete mode 100644 src/nudb/bench/CMakeLists.txt delete mode 100644 src/nudb/bench/Jamfile delete mode 100644 src/nudb/bench/README.md delete mode 100644 src/nudb/bench/bench.cpp delete mode 100644 src/nudb/bench/plot_bench.py delete mode 100644 src/nudb/doc/.gitignore delete mode 100644 src/nudb/doc/Jamfile.v2 delete mode 100644 src/nudb/doc/boostbook.dtd delete mode 160000 src/nudb/doc/docca delete mode 100644 src/nudb/doc/images/logo.png delete mode 100644 src/nudb/doc/images/logo.psd delete mode 100644 src/nudb/doc/images/readme2.png delete mode 100644 src/nudb/doc/index.xml delete mode 100644 src/nudb/doc/main.qbk delete mode 100644 src/nudb/doc/makeqbk.sh delete mode 100644 src/nudb/doc/quickref.xml delete mode 100644 src/nudb/doc/reference.xsl delete mode 100644 src/nudb/doc/source.dox delete mode 100644 src/nudb/doc/types/File.qbk delete mode 100644 src/nudb/doc/types/Hasher.qbk delete mode 100644 src/nudb/doc/types/Progress.qbk delete mode 100644 src/nudb/examples/CMakeLists.txt delete mode 100644 src/nudb/examples/Jamfile delete mode 100644 src/nudb/examples/example.cpp delete mode 100644 src/nudb/extras/README.md delete mode 160000 src/nudb/extras/beast delete mode 100644 src/nudb/extras/nudb/test/fail_file.hpp delete mode 100644 src/nudb/extras/nudb/test/temp_dir.hpp delete mode 100644 src/nudb/extras/nudb/test/test_store.hpp delete mode 100644 src/nudb/extras/nudb/test/xor_shift_engine.hpp delete mode 100644 src/nudb/extras/nudb/util.hpp delete mode 160000 src/nudb/extras/rocksdb delete mode 100644 src/nudb/include/nudb/basic_store.hpp delete mode 100644 src/nudb/include/nudb/concepts.hpp delete mode 100644 src/nudb/include/nudb/create.hpp delete mode 100644 src/nudb/include/nudb/detail/arena.hpp delete mode 100644 src/nudb/include/nudb/detail/bucket.hpp delete mode 100644 src/nudb/include/nudb/detail/buffer.hpp delete mode 100644 src/nudb/include/nudb/detail/bulkio.hpp delete mode 100644 src/nudb/include/nudb/detail/cache.hpp delete mode 100644 src/nudb/include/nudb/detail/endian.hpp delete mode 100644 src/nudb/include/nudb/detail/field.hpp delete mode 100644 src/nudb/include/nudb/detail/format.hpp delete mode 100644 src/nudb/include/nudb/detail/gentex.hpp delete mode 100644 src/nudb/include/nudb/detail/mutex.hpp delete mode 100644 src/nudb/include/nudb/detail/pool.hpp delete mode 100644 src/nudb/include/nudb/detail/stream.hpp delete mode 100644 src/nudb/include/nudb/detail/xxhash.hpp delete mode 100644 src/nudb/include/nudb/error.hpp delete mode 100644 src/nudb/include/nudb/file.hpp delete mode 100644 src/nudb/include/nudb/impl/basic_store.ipp delete mode 100644 src/nudb/include/nudb/impl/create.ipp delete mode 100644 src/nudb/include/nudb/impl/error.ipp delete mode 100644 src/nudb/include/nudb/impl/posix_file.ipp delete mode 100644 src/nudb/include/nudb/impl/recover.ipp delete mode 100644 src/nudb/include/nudb/impl/rekey.ipp delete mode 100644 src/nudb/include/nudb/impl/verify.ipp delete mode 100644 src/nudb/include/nudb/impl/visit.ipp delete mode 100644 src/nudb/include/nudb/impl/win32_file.ipp delete mode 100644 src/nudb/include/nudb/native_file.hpp delete mode 100644 src/nudb/include/nudb/nudb.hpp delete mode 100644 src/nudb/include/nudb/posix_file.hpp delete mode 100644 src/nudb/include/nudb/progress.hpp delete mode 100644 src/nudb/include/nudb/recover.hpp delete mode 100644 src/nudb/include/nudb/rekey.hpp delete mode 100644 src/nudb/include/nudb/store.hpp delete mode 100644 src/nudb/include/nudb/type_traits.hpp delete mode 100644 src/nudb/include/nudb/verify.hpp delete mode 100644 src/nudb/include/nudb/version.hpp delete mode 100644 src/nudb/include/nudb/visit.hpp delete mode 100644 src/nudb/include/nudb/win32_file.hpp delete mode 100644 src/nudb/include/nudb/xxhasher.hpp delete mode 100644 src/nudb/scripts/blacklist.supp delete mode 100755 src/nudb/scripts/build-and-test.sh delete mode 100755 src/nudb/scripts/install-boost.sh delete mode 100755 src/nudb/scripts/install-dependencies.sh delete mode 100755 src/nudb/scripts/install-valgrind.sh delete mode 100755 src/nudb/scripts/run-with-debugger.sh delete mode 100755 src/nudb/scripts/run-with-gdb.sh delete mode 100644 src/nudb/test/CMakeLists.txt delete mode 100644 src/nudb/test/Jamfile delete mode 100644 src/nudb/test/basic_store.cpp delete mode 100644 src/nudb/test/buffer.cpp delete mode 100644 src/nudb/test/callgrind_test.cpp delete mode 100644 src/nudb/test/concepts.cpp delete mode 100644 src/nudb/test/create.cpp delete mode 100644 src/nudb/test/error.cpp delete mode 100644 src/nudb/test/file.cpp delete mode 100644 src/nudb/test/native_file.cpp delete mode 100644 src/nudb/test/posix_file.cpp delete mode 100644 src/nudb/test/recover.cpp delete mode 100644 src/nudb/test/rekey.cpp delete mode 100644 src/nudb/test/store.cpp delete mode 100644 src/nudb/test/type_traits.cpp delete mode 100644 src/nudb/test/verify.cpp delete mode 100644 src/nudb/test/version.cpp delete mode 100644 src/nudb/test/visit.cpp delete mode 100644 src/nudb/test/win32_file.cpp delete mode 100644 src/nudb/test/xxhasher.cpp delete mode 100644 src/nudb/tools/CMakeLists.txt delete mode 100644 src/nudb/tools/Jamfile delete mode 100644 src/nudb/tools/nudb.cpp delete mode 100644 src/ripple/unity/soci.cpp delete mode 100644 src/snappy/config/snappy-stubs-public.h delete mode 100644 src/snappy/snappy/.appveyor.yml delete mode 100644 src/snappy/snappy/.travis.yml delete mode 100644 src/snappy/snappy/AUTHORS delete mode 100644 src/snappy/snappy/CMakeLists.txt delete mode 100644 src/snappy/snappy/CONTRIBUTING.md delete mode 100644 src/snappy/snappy/COPYING delete mode 100644 src/snappy/snappy/NEWS delete mode 100644 src/snappy/snappy/README.md delete mode 100644 src/snappy/snappy/cmake/SnappyConfig.cmake delete mode 100644 src/snappy/snappy/cmake/config.h.in delete mode 100644 src/snappy/snappy/format_description.txt delete mode 100644 src/snappy/snappy/framing_format.txt delete mode 100644 src/snappy/snappy/snappy-c.cc delete mode 100644 src/snappy/snappy/snappy-c.h delete mode 100644 src/snappy/snappy/snappy-internal.h delete mode 100644 src/snappy/snappy/snappy-sinksource.cc delete mode 100644 src/snappy/snappy/snappy-sinksource.h delete mode 100644 src/snappy/snappy/snappy-stubs-internal.cc delete mode 100644 src/snappy/snappy/snappy-stubs-internal.h delete mode 100644 src/snappy/snappy/snappy-stubs-public.h.in delete mode 100644 src/snappy/snappy/snappy-test.cc delete mode 100644 src/snappy/snappy/snappy-test.h delete mode 100644 src/snappy/snappy/snappy.cc delete mode 100644 src/snappy/snappy/snappy.h delete mode 100644 src/snappy/snappy/snappy_unittest.cc delete mode 100644 src/snappy/snappy/testdata/alice29.txt delete mode 100644 src/snappy/snappy/testdata/asyoulik.txt delete mode 100644 src/snappy/snappy/testdata/baddata1.snappy delete mode 100644 src/snappy/snappy/testdata/baddata2.snappy delete mode 100644 src/snappy/snappy/testdata/baddata3.snappy delete mode 100644 src/snappy/snappy/testdata/fireworks.jpeg delete mode 100644 src/snappy/snappy/testdata/geo.protodata delete mode 100644 src/snappy/snappy/testdata/html delete mode 100644 src/snappy/snappy/testdata/html_x_4 delete mode 100644 src/snappy/snappy/testdata/kppkn.gtb delete mode 100644 src/snappy/snappy/testdata/lcet10.txt delete mode 100644 src/snappy/snappy/testdata/paper-100k.pdf delete mode 100644 src/snappy/snappy/testdata/plrabn12.txt delete mode 100644 src/snappy/snappy/testdata/urls.10K delete mode 100644 src/soci/.circleci/config.yml delete mode 100644 src/soci/.editorconfig delete mode 100644 src/soci/.gitattributes delete mode 100644 src/soci/.gitignore delete mode 100644 src/soci/.markdownlint.json delete mode 100644 src/soci/.travis.yml delete mode 100644 src/soci/AUTHORS delete mode 100644 src/soci/CHANGELOG.md delete mode 100644 src/soci/CHANGES delete mode 100644 src/soci/CMakeLists.txt delete mode 100644 src/soci/LICENSE_1_0.txt delete mode 100644 src/soci/README.md delete mode 100644 src/soci/TODO delete mode 100644 src/soci/Vagrantfile delete mode 100644 src/soci/appveyor.yml delete mode 100644 src/soci/cmake/.gitignore delete mode 100644 src/soci/cmake/CMakeLists.txt delete mode 100644 src/soci/cmake/SociBackend.cmake delete mode 100644 src/soci/cmake/SociConfig.cmake delete mode 100644 src/soci/cmake/SociDependencies.cmake delete mode 100644 src/soci/cmake/SociUtilities.cmake delete mode 100644 src/soci/cmake/SociVersion.cmake delete mode 100644 src/soci/cmake/configs/test-access.cmake delete mode 100644 src/soci/cmake/configs/test-mysql.cmake delete mode 100644 src/soci/cmake/dependencies/Boost.cmake delete mode 100644 src/soci/cmake/dependencies/DB2.cmake delete mode 100644 src/soci/cmake/dependencies/Firebird.cmake delete mode 100644 src/soci/cmake/dependencies/MySQL.cmake delete mode 100644 src/soci/cmake/dependencies/ODBC.cmake delete mode 100644 src/soci/cmake/dependencies/Oracle.cmake delete mode 100644 src/soci/cmake/dependencies/PostgreSQL.cmake delete mode 100644 src/soci/cmake/dependencies/SQLite3.cmake delete mode 100644 src/soci/cmake/dependencies/Threads.cmake delete mode 100644 src/soci/cmake/modules/FindDB2.cmake delete mode 100644 src/soci/cmake/modules/FindDL.cmake delete mode 100644 src/soci/cmake/modules/FindFirebird.cmake delete mode 100644 src/soci/cmake/modules/FindMySQL.cmake delete mode 100644 src/soci/cmake/modules/FindODBC.cmake delete mode 100644 src/soci/cmake/modules/FindOracle.cmake delete mode 100644 src/soci/cmake/modules/FindPostgreSQL.cmake delete mode 100644 src/soci/cmake/modules/FindSQLite3.cmake delete mode 100644 src/soci/cmake/modules/FindSoci.cmake delete mode 100644 src/soci/cmake/resources/vs2010-test-cmd-args.vcxproj.user.in delete mode 100644 src/soci/docs/api/backend.md delete mode 100644 src/soci/docs/api/client.md delete mode 100644 src/soci/docs/backends/db2.md delete mode 100644 src/soci/docs/backends/firebird.md delete mode 100644 src/soci/docs/backends/index.md delete mode 100644 src/soci/docs/backends/mysql.md delete mode 100644 src/soci/docs/backends/odbc.md delete mode 100644 src/soci/docs/backends/oracle.md delete mode 100644 src/soci/docs/backends/postgresql.md delete mode 100644 src/soci/docs/backends/sqlite3.md delete mode 100644 src/soci/docs/beyond.md delete mode 100644 src/soci/docs/binding.md delete mode 100644 src/soci/docs/boost.md delete mode 100644 src/soci/docs/connections.md delete mode 100644 src/soci/docs/errors.md delete mode 100644 src/soci/docs/faq.md delete mode 100644 src/soci/docs/images/structure.png delete mode 100644 src/soci/docs/index.md delete mode 100644 src/soci/docs/indicators.md delete mode 100644 src/soci/docs/installation.md delete mode 100644 src/soci/docs/interfaces.md delete mode 100644 src/soci/docs/languages/ada/concepts.md delete mode 100644 src/soci/docs/languages/ada/idioms.md delete mode 100644 src/soci/docs/languages/ada/index.md delete mode 100644 src/soci/docs/languages/ada/reference.md delete mode 100644 src/soci/docs/languages/index.md delete mode 100644 src/soci/docs/license.md delete mode 100644 src/soci/docs/lobs.md delete mode 100644 src/soci/docs/logging.md delete mode 100644 src/soci/docs/multithreading.md delete mode 100644 src/soci/docs/procedures.md delete mode 100644 src/soci/docs/queries.md delete mode 100644 src/soci/docs/quickstart.md delete mode 100644 src/soci/docs/statements.md delete mode 100644 src/soci/docs/structure.md delete mode 100644 src/soci/docs/transactions.md delete mode 100644 src/soci/docs/types.md delete mode 100644 src/soci/docs/utilities.md delete mode 100644 src/soci/docs/vagrant.md delete mode 100644 src/soci/include/private/README.md delete mode 100644 src/soci/include/private/firebird/common.h delete mode 100644 src/soci/include/private/firebird/error-firebird.h delete mode 100644 src/soci/include/private/soci-compiler.h delete mode 100644 src/soci/include/private/soci-cpp.h delete mode 100644 src/soci/include/private/soci-cstrtod.h delete mode 100644 src/soci/include/private/soci-dtocstr.h delete mode 100644 src/soci/include/private/soci-exchange-cast.h delete mode 100644 src/soci/include/private/soci-mktime.h delete mode 100644 src/soci/include/private/soci-static-assert.h delete mode 100644 src/soci/include/soci/backend-loader.h delete mode 100644 src/soci/include/soci/bind-values.h delete mode 100644 src/soci/include/soci/blob-exchange.h delete mode 100644 src/soci/include/soci/blob.h delete mode 100644 src/soci/include/soci/boost-fusion.h delete mode 100644 src/soci/include/soci/boost-gregorian-date.h delete mode 100644 src/soci/include/soci/boost-optional.h delete mode 100644 src/soci/include/soci/boost-tuple.h delete mode 100644 src/soci/include/soci/callbacks.h delete mode 100644 src/soci/include/soci/column-info.h delete mode 100644 src/soci/include/soci/connection-parameters.h delete mode 100644 src/soci/include/soci/connection-pool.h delete mode 100644 src/soci/include/soci/db2/soci-db2.h delete mode 100644 src/soci/include/soci/empty/soci-empty.h delete mode 100644 src/soci/include/soci/error.h delete mode 100644 src/soci/include/soci/exchange-traits.h delete mode 100644 src/soci/include/soci/firebird/soci-firebird.h delete mode 100644 src/soci/include/soci/into-type.h delete mode 100644 src/soci/include/soci/into.h delete mode 100644 src/soci/include/soci/mysql/soci-mysql.h delete mode 100644 src/soci/include/soci/noreturn.h delete mode 100644 src/soci/include/soci/odbc/soci-odbc.h delete mode 100644 src/soci/include/soci/once-temp-type.h delete mode 100644 src/soci/include/soci/oracle/soci-oracle.h delete mode 100644 src/soci/include/soci/postgresql/soci-postgresql.h delete mode 100644 src/soci/include/soci/prepare-temp-type.h delete mode 100644 src/soci/include/soci/procedure.h delete mode 100644 src/soci/include/soci/query_transformation.h delete mode 100644 src/soci/include/soci/ref-counted-prepare-info.h delete mode 100644 src/soci/include/soci/ref-counted-statement.h delete mode 100644 src/soci/include/soci/row-exchange.h delete mode 100644 src/soci/include/soci/row.h delete mode 100644 src/soci/include/soci/rowid-exchange.h delete mode 100644 src/soci/include/soci/rowid.h delete mode 100644 src/soci/include/soci/rowset.h delete mode 100644 src/soci/include/soci/session.h delete mode 100644 src/soci/include/soci/soci-backend.h delete mode 100644 src/soci/include/soci/soci-config.h delete mode 100644 src/soci/include/soci/soci-config.h.in delete mode 100644 src/soci/include/soci/soci-platform.h delete mode 100644 src/soci/include/soci/soci-simple.h delete mode 100644 src/soci/include/soci/soci.h delete mode 100644 src/soci/include/soci/sqlite3/soci-sqlite3.h delete mode 100644 src/soci/include/soci/statement.h delete mode 100644 src/soci/include/soci/transaction.h delete mode 100644 src/soci/include/soci/type-conversion-traits.h delete mode 100644 src/soci/include/soci/type-conversion.h delete mode 100644 src/soci/include/soci/type-holder.h delete mode 100644 src/soci/include/soci/type-ptr.h delete mode 100644 src/soci/include/soci/type-wrappers.h delete mode 100644 src/soci/include/soci/unsigned-types.h delete mode 100644 src/soci/include/soci/use-type.h delete mode 100644 src/soci/include/soci/use.h delete mode 100644 src/soci/include/soci/values-exchange.h delete mode 100644 src/soci/include/soci/values.h delete mode 100644 src/soci/include/soci/version.h delete mode 100644 src/soci/languages/ada/postgresql_client.gpr delete mode 100644 src/soci/languages/ada/soci-mysql.ads delete mode 100644 src/soci/languages/ada/soci-oracle.ads delete mode 100644 src/soci/languages/ada/soci-postgresql.ads delete mode 100644 src/soci/languages/ada/soci.adb delete mode 100644 src/soci/languages/ada/soci.ads delete mode 100644 src/soci/languages/ada/soci_ada.gpr delete mode 100644 src/soci/languages/ada/soci_core.gpr delete mode 100644 src/soci/languages/ada/soci_postgresql.gpr delete mode 100644 src/soci/languages/ada/std_cpp.gpr delete mode 100644 src/soci/languages/ada/test/postgresql_test.adb delete mode 100644 src/soci/languages/ada/test/postgresql_test.gpr delete mode 100644 src/soci/mkdocs.yml delete mode 100644 src/soci/scripts/build.bat delete mode 100644 src/soci/scripts/changelog.sh delete mode 100755 src/soci/scripts/travis/before_install.sh delete mode 100755 src/soci/scripts/travis/before_install_db2.sh delete mode 100755 src/soci/scripts/travis/before_install_firebird.sh delete mode 100755 src/soci/scripts/travis/before_install_odbc.sh delete mode 100755 src/soci/scripts/travis/before_install_oracle.sh delete mode 100755 src/soci/scripts/travis/before_script.sh delete mode 100755 src/soci/scripts/travis/before_script_db2.sh delete mode 100755 src/soci/scripts/travis/before_script_firebird.sh delete mode 100755 src/soci/scripts/travis/before_script_mysql.sh delete mode 100755 src/soci/scripts/travis/before_script_odbc.sh delete mode 100755 src/soci/scripts/travis/before_script_oracle.sh delete mode 100755 src/soci/scripts/travis/before_script_postgresql.sh delete mode 100755 src/soci/scripts/travis/before_script_valgrind.sh delete mode 100755 src/soci/scripts/travis/common.sh delete mode 100755 src/soci/scripts/travis/oracle.sh delete mode 100755 src/soci/scripts/travis/script.sh delete mode 100755 src/soci/scripts/travis/script_db2.sh delete mode 100755 src/soci/scripts/travis/script_empty.sh delete mode 100755 src/soci/scripts/travis/script_firebird.sh delete mode 100755 src/soci/scripts/travis/script_mysql.sh delete mode 100755 src/soci/scripts/travis/script_odbc.sh delete mode 100755 src/soci/scripts/travis/script_oracle.sh delete mode 100755 src/soci/scripts/travis/script_postgresql.sh delete mode 100755 src/soci/scripts/travis/script_sqlite3.sh delete mode 100755 src/soci/scripts/travis/script_valgrind.sh delete mode 100755 src/soci/scripts/vagrant/bootstrap.sh delete mode 100755 src/soci/scripts/vagrant/build.sh delete mode 100644 src/soci/scripts/vagrant/common.env delete mode 100755 src/soci/scripts/vagrant/db2.sh delete mode 100755 src/soci/scripts/vagrant/db2cli.sh delete mode 100755 src/soci/scripts/vagrant/devel.sh delete mode 100755 src/soci/scripts/vagrant/firebird.sh delete mode 100755 src/soci/scripts/vagrant/mysql.sh delete mode 100755 src/soci/scripts/vagrant/postgresql.sh delete mode 100755 src/soci/scripts/vm/debian-oracle10g-install.sh delete mode 100644 src/soci/scripts/windows/Get-ODBCList.ps1 delete mode 100644 src/soci/scripts/windows/mssql_db_create.sql delete mode 100644 src/soci/src/.gitignore delete mode 100644 src/soci/src/CMakeLists.txt delete mode 100644 src/soci/src/backends/.gitignore delete mode 100644 src/soci/src/backends/CMakeLists.txt delete mode 100644 src/soci/src/backends/db2/CMakeLists.txt delete mode 100644 src/soci/src/backends/db2/blob.cpp delete mode 100644 src/soci/src/backends/db2/common.h delete mode 100644 src/soci/src/backends/db2/factory.cpp delete mode 100644 src/soci/src/backends/db2/row-id.cpp delete mode 100644 src/soci/src/backends/db2/session.cpp delete mode 100644 src/soci/src/backends/db2/standard-into-type.cpp delete mode 100644 src/soci/src/backends/db2/standard-use-type.cpp delete mode 100644 src/soci/src/backends/db2/statement.cpp delete mode 100644 src/soci/src/backends/db2/vector-into-type.cpp delete mode 100644 src/soci/src/backends/db2/vector-use-type.cpp delete mode 100644 src/soci/src/backends/empty/CMakeLists.txt delete mode 100644 src/soci/src/backends/empty/Makefile.basic delete mode 100644 src/soci/src/backends/empty/blob.cpp delete mode 100644 src/soci/src/backends/empty/factory.cpp delete mode 100644 src/soci/src/backends/empty/row-id.cpp delete mode 100644 src/soci/src/backends/empty/session.cpp delete mode 100644 src/soci/src/backends/empty/standard-into-type.cpp delete mode 100644 src/soci/src/backends/empty/standard-use-type.cpp delete mode 100644 src/soci/src/backends/empty/statement.cpp delete mode 100644 src/soci/src/backends/empty/vector-into-type.cpp delete mode 100644 src/soci/src/backends/empty/vector-use-type.cpp delete mode 100644 src/soci/src/backends/firebird/CMakeLists.txt delete mode 100644 src/soci/src/backends/firebird/Makefile.basic delete mode 100644 src/soci/src/backends/firebird/blob.cpp delete mode 100644 src/soci/src/backends/firebird/common.cpp delete mode 100644 src/soci/src/backends/firebird/error-firebird.cpp delete mode 100644 src/soci/src/backends/firebird/factory.cpp delete mode 100644 src/soci/src/backends/firebird/session.cpp delete mode 100644 src/soci/src/backends/firebird/standard-into-type.cpp delete mode 100644 src/soci/src/backends/firebird/standard-use-type.cpp delete mode 100644 src/soci/src/backends/firebird/statement.cpp delete mode 100644 src/soci/src/backends/firebird/vector-into-type.cpp delete mode 100644 src/soci/src/backends/firebird/vector-use-type.cpp delete mode 100644 src/soci/src/backends/mysql/CMakeLists.txt delete mode 100644 src/soci/src/backends/mysql/Makefile.basic delete mode 100644 src/soci/src/backends/mysql/blob.cpp delete mode 100644 src/soci/src/backends/mysql/common.cpp delete mode 100644 src/soci/src/backends/mysql/common.h delete mode 100644 src/soci/src/backends/mysql/factory.cpp delete mode 100644 src/soci/src/backends/mysql/row-id.cpp delete mode 100644 src/soci/src/backends/mysql/session.cpp delete mode 100644 src/soci/src/backends/mysql/standard-into-type.cpp delete mode 100644 src/soci/src/backends/mysql/standard-use-type.cpp delete mode 100644 src/soci/src/backends/mysql/statement.cpp delete mode 100644 src/soci/src/backends/mysql/vector-into-type.cpp delete mode 100644 src/soci/src/backends/mysql/vector-use-type.cpp delete mode 100644 src/soci/src/backends/odbc/CMakeLists.txt delete mode 100644 src/soci/src/backends/odbc/Makefile.basic delete mode 100644 src/soci/src/backends/odbc/blob.cpp delete mode 100644 src/soci/src/backends/odbc/factory.cpp delete mode 100644 src/soci/src/backends/odbc/makefile.msvc delete mode 100644 src/soci/src/backends/odbc/row-id.cpp delete mode 100644 src/soci/src/backends/odbc/session.cpp delete mode 100644 src/soci/src/backends/odbc/standard-into-type.cpp delete mode 100644 src/soci/src/backends/odbc/standard-use-type.cpp delete mode 100644 src/soci/src/backends/odbc/statement.cpp delete mode 100644 src/soci/src/backends/odbc/utility.h delete mode 100644 src/soci/src/backends/odbc/vector-into-type.cpp delete mode 100644 src/soci/src/backends/odbc/vector-use-type.cpp delete mode 100644 src/soci/src/backends/oracle/CMakeLists.txt delete mode 100644 src/soci/src/backends/oracle/Makefile.basic delete mode 100644 src/soci/src/backends/oracle/blob.cpp delete mode 100644 src/soci/src/backends/oracle/error.cpp delete mode 100644 src/soci/src/backends/oracle/error.h delete mode 100644 src/soci/src/backends/oracle/factory.cpp delete mode 100644 src/soci/src/backends/oracle/row-id.cpp delete mode 100644 src/soci/src/backends/oracle/session.cpp delete mode 100644 src/soci/src/backends/oracle/standard-into-type.cpp delete mode 100644 src/soci/src/backends/oracle/standard-use-type.cpp delete mode 100644 src/soci/src/backends/oracle/statement.cpp delete mode 100644 src/soci/src/backends/oracle/vector-into-type.cpp delete mode 100644 src/soci/src/backends/oracle/vector-use-type.cpp delete mode 100644 src/soci/src/backends/postgresql/CMakeLists.txt delete mode 100644 src/soci/src/backends/postgresql/Makefile.basic delete mode 100644 src/soci/src/backends/postgresql/blob.cpp delete mode 100644 src/soci/src/backends/postgresql/common.h delete mode 100644 src/soci/src/backends/postgresql/error.cpp delete mode 100644 src/soci/src/backends/postgresql/factory.cpp delete mode 100644 src/soci/src/backends/postgresql/row-id.cpp delete mode 100644 src/soci/src/backends/postgresql/session.cpp delete mode 100644 src/soci/src/backends/postgresql/standard-into-type.cpp delete mode 100644 src/soci/src/backends/postgresql/standard-use-type.cpp delete mode 100644 src/soci/src/backends/postgresql/statement.cpp delete mode 100644 src/soci/src/backends/postgresql/vector-into-type.cpp delete mode 100644 src/soci/src/backends/postgresql/vector-use-type.cpp delete mode 100644 src/soci/src/backends/sqlite3/CMakeLists.txt delete mode 100644 src/soci/src/backends/sqlite3/Makefile.basic delete mode 100644 src/soci/src/backends/sqlite3/blob.cpp delete mode 100644 src/soci/src/backends/sqlite3/common.h delete mode 100644 src/soci/src/backends/sqlite3/error.cpp delete mode 100644 src/soci/src/backends/sqlite3/factory.cpp delete mode 100644 src/soci/src/backends/sqlite3/row-id.cpp delete mode 100644 src/soci/src/backends/sqlite3/session.cpp delete mode 100644 src/soci/src/backends/sqlite3/standard-into-type.cpp delete mode 100644 src/soci/src/backends/sqlite3/standard-use-type.cpp delete mode 100644 src/soci/src/backends/sqlite3/statement.cpp delete mode 100644 src/soci/src/backends/sqlite3/vector-into-type.cpp delete mode 100644 src/soci/src/backends/sqlite3/vector-use-type.cpp delete mode 100644 src/soci/src/core/.gitignore delete mode 100644 src/soci/src/core/CMakeLists.txt delete mode 100644 src/soci/src/core/Makefile.basic delete mode 100644 src/soci/src/core/backend-loader.cpp delete mode 100644 src/soci/src/core/blob.cpp delete mode 100644 src/soci/src/core/common.cpp delete mode 100644 src/soci/src/core/connection-parameters.cpp delete mode 100644 src/soci/src/core/connection-pool.cpp delete mode 100644 src/soci/src/core/error.cpp delete mode 100644 src/soci/src/core/into-type.cpp delete mode 100644 src/soci/src/core/once-temp-type.cpp delete mode 100644 src/soci/src/core/prepare-temp-type.cpp delete mode 100644 src/soci/src/core/procedure.cpp delete mode 100644 src/soci/src/core/ref-counted-prepare-info.cpp delete mode 100644 src/soci/src/core/ref-counted-statement.cpp delete mode 100644 src/soci/src/core/row.cpp delete mode 100644 src/soci/src/core/rowid.cpp delete mode 100644 src/soci/src/core/session.cpp delete mode 100644 src/soci/src/core/soci-simple.cpp delete mode 100644 src/soci/src/core/soci_backends_config.h.in delete mode 100644 src/soci/src/core/statement.cpp delete mode 100644 src/soci/src/core/transaction.cpp delete mode 100644 src/soci/src/core/use-type.cpp delete mode 100644 src/soci/src/core/values.cpp delete mode 100644 src/soci/tests/CMakeLists.txt delete mode 100644 src/soci/tests/README.md delete mode 100644 src/soci/tests/catch.hpp delete mode 100644 src/soci/tests/common-tests.h delete mode 100644 src/soci/tests/db2/CMakeLists.txt delete mode 100644 src/soci/tests/db2/test-db2.cpp delete mode 100644 src/soci/tests/empty/CMakeLists.txt delete mode 100644 src/soci/tests/empty/test-empty.cpp delete mode 100644 src/soci/tests/firebird/CMakeLists.txt delete mode 100644 src/soci/tests/firebird/test-firebird.cpp delete mode 100644 src/soci/tests/mysql/CMakeLists.txt delete mode 100644 src/soci/tests/mysql/test-mysql.cpp delete mode 100644 src/soci/tests/mysql/test-mysql.h delete mode 100644 src/soci/tests/odbc/CMakeLists.txt delete mode 100644 src/soci/tests/odbc/soci_test.mdb delete mode 100644 src/soci/tests/odbc/test-mssql.dsn delete mode 100644 src/soci/tests/odbc/test-odbc-access.cpp delete mode 100644 src/soci/tests/odbc/test-odbc-db2.cpp delete mode 100644 src/soci/tests/odbc/test-odbc-mssql.cpp delete mode 100644 src/soci/tests/odbc/test-odbc-mysql.cpp delete mode 100644 src/soci/tests/odbc/test-odbc-postgresql.cpp delete mode 100644 src/soci/tests/odbc/test-postgresql-win64.dsn delete mode 100644 src/soci/tests/odbc/test-postgresql.dsn delete mode 100644 src/soci/tests/oracle/CMakeLists.txt delete mode 100644 src/soci/tests/oracle/Makefile.basic delete mode 100644 src/soci/tests/oracle/test-oracle.cpp delete mode 100644 src/soci/tests/postgresql/CMakeLists.txt delete mode 100644 src/soci/tests/postgresql/Makefile.basic delete mode 100644 src/soci/tests/postgresql/test-postgresql.cpp delete mode 100644 src/soci/tests/sqlite3/CMakeLists.txt delete mode 100644 src/soci/tests/sqlite3/Makefile.basic delete mode 100644 src/soci/tests/sqlite3/test-sqlite3.cpp delete mode 100644 src/soci/valgrind.suppress delete mode 100644 src/soci/www/articles.html delete mode 100644 src/soci/www/doc.html delete mode 100644 src/soci/www/doc/README.md delete mode 100644 src/soci/www/doc/index.html delete mode 100644 src/soci/www/events.html delete mode 100644 src/soci/www/forkus_github.png delete mode 100644 src/soci/www/index.html delete mode 100644 src/soci/www/links.html delete mode 100644 src/soci/www/people.html delete mode 100644 src/soci/www/style.css delete mode 100644 src/sqlite/sqlite.h delete mode 100644 src/sqlite/sqlite/sqlite3.c delete mode 100644 src/sqlite/sqlite/sqlite3.h delete mode 100644 src/sqlite/sqlite/sqlite3ext.h delete mode 100644 src/sqlite/sqlite3.h diff --git a/src/lz4/.gitattributes b/src/lz4/.gitattributes deleted file mode 100644 index 6212bd405b..0000000000 --- a/src/lz4/.gitattributes +++ /dev/null @@ -1,21 +0,0 @@ -# Set the default behavior -* text eol=lf - -# Explicitly declare source files -*.c text eol=lf -*.h text eol=lf - -# Denote files that should not be modified. -*.odt binary -*.png binary - -# Visual Studio -*.sln text eol=crlf -*.vcxproj* text eol=crlf -*.vcproj* text eol=crlf -*.suo binary -*.rc text eol=crlf - -# Windows -*.bat text eol=crlf -*.cmd text eol=crlf diff --git a/src/lz4/.gitignore b/src/lz4/.gitignore deleted file mode 100644 index 117b02d143..0000000000 --- a/src/lz4/.gitignore +++ /dev/null @@ -1,31 +0,0 @@ -# Object files -*.o -*.ko - -# Libraries -*.lib -*.a - -# Shared objects (inc. Windows DLLs) -*.dll -*.so -*.so.* -*.dylib -*.dSYM # apple - -# Executables -*.exe -*.out -*.app -lz4 - -# IDE / editors files -.clang_complete -_codelite/ -_codelite_lz4/ -bin/ -*.zip - -# Mac -.DS_Store -*.dSYM diff --git a/src/lz4/.travis.yml b/src/lz4/.travis.yml deleted file mode 100644 index dc6150593d..0000000000 --- a/src/lz4/.travis.yml +++ /dev/null @@ -1,150 +0,0 @@ -language: c -matrix: - fast_finish: true - include: - # OS X Mavericks - - os: osx - install: - - export CC=clang - env: Ubu=OS_X_Mavericks Cmd='make -C tests test-lz4 MOREFLAGS="-Werror -Wconversion -Wno-sign-conversion" && CFLAGS=-m32 make -C tests clean test-lz4-contentSize' COMPILER=clang - - # Container-based 12.04 LTS Server Edition 64 bit (doesn't support 32-bit includes) - - os: linux - sudo: false - env: Ubu=12.04cont Cmd='make -C tests test-lz4 test-lz4c test-fasttest test-fullbench' COMPILER=cc - - - os: linux - sudo: false - env: Ubu=12.04cont Cmd='make -C tests test-frametest test-fuzzer' COMPILER=cc - - - os: linux - sudo: false - env: Ubu=12.04cont Cmd="make gpptest && make clean examples && make clean cmake && make clean travis-install && make clean clangtest" COMPILER=cc - - - # 14.04 LTS Server Edition 64 bit - - env: Ubu=14.04 Cmd='make -C tests test MOREFLAGS=-mx32' COMPILER=cc - dist: trusty - sudo: required - addons: - apt: - packages: - - libc6-dev-i386 - - gcc-multilib - - - env: Ubu=14.04 Cmd='make usan' COMPILER=clang - dist: trusty - sudo: required - addons: - apt: - packages: - - clang - - - env: Ubu=14.04 Cmd='make c_standards && make -C tests test-lz4 test-mem' COMPILER=cc - dist: trusty - sudo: required - addons: - apt: - packages: - - valgrind - - - env: Ubu=14.04 Cmd='make -C tests test-lz4c32 test-fullbench32 versionsTest' COMPILER=cc - dist: trusty - sudo: required - addons: - apt: - packages: - - python3 - - libc6-dev-i386 - - gcc-multilib - - - env: Ubu=14.04 Cmd='make -C tests test-frametest32 test-fuzzer32' COMPILER=cc - dist: trusty - sudo: required - addons: - apt: - packages: - - libc6-dev-i386 - - gcc-multilib - - - env: Ubu=14.04 Cmd='make c_standards CC=gcc-6 && make -C tests test-lz4 CC=gcc-6 MOREFLAGS=-Werror' COMPILER=gcc-6 - dist: trusty - sudo: required - addons: - apt: - sources: - - ubuntu-toolchain-r-test - packages: - - gcc-6 - - - env: Ubu=14.04 Cmd='make platformTest CC=arm-linux-gnueabi-gcc QEMU_SYS=qemu-arm-static && make platformTest CC=aarch64-linux-gnu-gcc QEMU_SYS=qemu-aarch64-static' COMPILER=arm-linux-gnueabi-gcc - dist: trusty - sudo: required - addons: - apt: - packages: - - qemu-system-arm - - qemu-user-static - - gcc-arm-linux-gnueabi - - libc6-dev-armel-cross - - gcc-aarch64-linux-gnu - - libc6-dev-arm64-cross - - - env: Ubu=14.04 Cmd='make -C tests test-lz4 clean test-lz4c32 CC=gcc-5 MOREFLAGS=-Werror' COMPILER=gcc-5 - dist: trusty - sudo: required - addons: - apt: - sources: - - ubuntu-toolchain-r-test - packages: - - libc6-dev-i386 - - gcc-multilib - - gcc-5 - - gcc-5-multilib - - - env: Ubu=14.04 Cmd='make -C tests test-lz4 CC=clang-3.8' COMPILER=clang-3.8 - dist: trusty - sudo: required - addons: - apt: - sources: - - ubuntu-toolchain-r-test - - llvm-toolchain-precise-3.8 - packages: - - clang-3.8 - - - env: Ubu=14.04 Cmd='make platformTest CC=powerpc-linux-gnu-gcc QEMU_SYS=qemu-ppc-static && make platformTest CC=powerpc-linux-gnu-gcc QEMU_SYS=qemu-ppc64-static MOREFLAGS=-m64' COMPILER=powerpc-linux-gnu-gcc - dist: trusty - sudo: required - addons: - apt: - packages: - - qemu-system-ppc - - qemu-user-static - - gcc-powerpc-linux-gnu - - - env: Ubu=14.04 Cmd='make staticAnalyze' COMPILER=clang - dist: trusty - sudo: required - addons: - apt: - packages: - - clang - - - env: Ubu=14.04 Cmd='make clean all CC=gcc-4.4 MOREFLAGS=-Werror && make clean && CFLAGS=-fPIC LDFLAGS="-pie -fPIE -D_FORTIFY_SOURCE=2" make -C programs' COMPILER=gcc-4.4 - dist: trusty - sudo: required - addons: - apt: - sources: - - ubuntu-toolchain-r-test - packages: - - libc6-dev-i386 - - gcc-multilib - - gcc-4.4 - -script: - - echo Cmd=$Cmd - - $COMPILER -v - - sh -c "$Cmd" diff --git a/src/lz4/INSTALL b/src/lz4/INSTALL deleted file mode 100644 index f5ac0a0f5d..0000000000 --- a/src/lz4/INSTALL +++ /dev/null @@ -1,15 +0,0 @@ -Installation -============= - -``` -make -make install # this command may require root access -``` - -LZ4's `Makefile` supports standard [Makefile conventions], -including [staged installs], [redirection], or [command redefinition]. - -[Makefile conventions]: https://www.gnu.org/prep/standards/html_node/Makefile-Conventions.html -[staged installs]: https://www.gnu.org/prep/standards/html_node/DESTDIR.html -[redirection]: https://www.gnu.org/prep/standards/html_node/Directory-Variables.html -[command redefinition]: https://www.gnu.org/prep/standards/html_node/Utilities-in-Makefiles.html diff --git a/src/lz4/LICENSE b/src/lz4/LICENSE deleted file mode 100644 index c221aebd26..0000000000 --- a/src/lz4/LICENSE +++ /dev/null @@ -1,11 +0,0 @@ -This repository uses 2 different licenses : -- all files in the `lib` directory use a BSD 2-Clause license -- all other files use a GPLv2 license, unless explicitly stated otherwise - -Relevant license is reminded at the top of each source file, -and with presence of COPYING or LICENSE file in associated directories. - -This model is selected to emphasize that -files in the `lib` directory are designed to be included into 3rd party applications, -while all other files, in `programs`, `tests` or `examples`, -receive more limited attention and support for such scenario. diff --git a/src/lz4/Makefile b/src/lz4/Makefile deleted file mode 100644 index da485a182b..0000000000 --- a/src/lz4/Makefile +++ /dev/null @@ -1,181 +0,0 @@ -# ################################################################ -# LZ4 - Makefile -# Copyright (C) Yann Collet 2011-2016 -# All rights reserved. -# -# This Makefile is validated for Linux, macOS, *BSD, Hurd, Solaris, MSYS2 targets -# -# BSD license -# Redistribution and use in source and binary forms, with or without modification, -# are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright notice, this -# list of conditions and the following disclaimer. -# -# * Redistributions in binary form must reproduce the above copyright notice, this -# list of conditions and the following disclaimer in the documentation and/or -# other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# -# You can contact the author at : -# - LZ4 source repository : https://github.com/lz4/lz4 -# - LZ4 forum froup : https://groups.google.com/forum/#!forum/lz4c -# ################################################################ - -LZ4DIR = lib -PRGDIR = programs -TESTDIR = tests -EXDIR = examples - - -# Define nul output -ifneq (,$(filter Windows%,$(OS))) -EXT = .exe -VOID = nul -else -EXT = -VOID = /dev/null -endif - - -.PHONY: default -default: lib-release lz4-release - -.PHONY: all -all: allmost manuals - -.PHONY: allmost -allmost: lib lz4 examples - -.PHONY: lib lib-release -lib lib-release: - @$(MAKE) -C $(LZ4DIR) $@ - -.PHONY: lz4 lz4-release -lz4 : lib -lz4-release : lib-release -lz4 lz4-release : - @$(MAKE) -C $(PRGDIR) $@ - @cp $(PRGDIR)/lz4$(EXT) . - -.PHONY: examples -examples: lib lz4 - $(MAKE) -C $(EXDIR) test - -.PHONY: manuals -manuals: - @$(MAKE) -C contrib/gen_manual $@ - -.PHONY: clean -clean: - @$(MAKE) -C $(LZ4DIR) $@ > $(VOID) - @$(MAKE) -C $(PRGDIR) $@ > $(VOID) - @$(MAKE) -C $(TESTDIR) $@ > $(VOID) - @$(MAKE) -C $(EXDIR) $@ > $(VOID) - @$(MAKE) -C contrib/gen_manual $@ - @$(RM) lz4$(EXT) - @echo Cleaning completed - - -#----------------------------------------------------------------------------- -# make install is validated only for Linux, OSX, BSD, Hurd and Solaris targets -#----------------------------------------------------------------------------- -ifneq (,$(filter $(shell uname),Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD NetBSD DragonFly SunOS)) -HOST_OS = POSIX - -.PHONY: install uninstall -install uninstall: - @$(MAKE) -C $(LZ4DIR) $@ - @$(MAKE) -C $(PRGDIR) $@ - -travis-install: - $(MAKE) -j1 install DESTDIR=~/install_test_dir - -cmake: - @cd contrib/cmake_unofficial; cmake $(CMAKE_PARAMS) CMakeLists.txt; $(MAKE) - -endif - - -ifneq (,$(filter MSYS%,$(shell uname))) -HOST_OS = MSYS -CMAKE_PARAMS = -G"MSYS Makefiles" -endif - - -#------------------------------------------------------------------------ -#make tests validated only for MSYS, Linux, OSX, kFreeBSD and Hurd targets -#------------------------------------------------------------------------ -ifneq (,$(filter $(HOST_OS),MSYS POSIX)) - -.PHONY: list -list: - @$(MAKE) -pRrq -f $(lastword $(MAKEFILE_LIST)) : 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | sort | egrep -v -e '^[^[:alnum:]]' -e '^$@$$' | xargs - -.PHONY: test -test: - $(MAKE) -C $(TESTDIR) $@ - -clangtest: clean - clang -v - @CFLAGS="-O3 -Werror -Wconversion -Wno-sign-conversion" $(MAKE) -C $(LZ4DIR) all CC=clang - @CFLAGS="-O3 -Werror -Wconversion -Wno-sign-conversion" $(MAKE) -C $(PRGDIR) all CC=clang - @CFLAGS="-O3 -Werror -Wconversion -Wno-sign-conversion" $(MAKE) -C $(TESTDIR) all CC=clang - -clangtest-native: clean - clang -v - @CFLAGS="-O3 -Werror -Wconversion -Wno-sign-conversion" $(MAKE) -C $(LZ4DIR) all CC=clang - @CFLAGS="-O3 -Werror -Wconversion -Wno-sign-conversion" $(MAKE) -C $(PRGDIR) native CC=clang - @CFLAGS="-O3 -Werror -Wconversion -Wno-sign-conversion" $(MAKE) -C $(TESTDIR) native CC=clang - -usan: clean - CC=clang CFLAGS="-O3 -g -fsanitize=undefined" $(MAKE) test FUZZER_TIME="-T1mn" NB_LOOPS=-i1 - -usan32: clean - CFLAGS="-m32 -O3 -g -fsanitize=undefined" $(MAKE) test FUZZER_TIME="-T1mn" NB_LOOPS=-i1 - -staticAnalyze: clean - CFLAGS=-g scan-build --status-bugs -v $(MAKE) all - -platformTest: clean - @echo "\n ---- test lz4 with $(CC) compiler ----" - @$(CC) -v - CFLAGS="-O3 -Werror" $(MAKE) -C $(LZ4DIR) all - CFLAGS="-O3 -Werror -static" $(MAKE) -C $(PRGDIR) all - CFLAGS="-O3 -Werror -static" $(MAKE) -C $(TESTDIR) all - $(MAKE) -C $(TESTDIR) test-platform - -.PHONY: versionsTest -versionsTest: clean - $(MAKE) -C $(TESTDIR) $@ - -gpptest: clean - g++ -v - CC=g++ $(MAKE) -C $(LZ4DIR) all CFLAGS="-O3 -Wall -Wextra -Wundef -Wshadow -Wcast-align -Werror" - CC=g++ $(MAKE) -C $(PRGDIR) all CFLAGS="-O3 -Wall -Wextra -Wundef -Wshadow -Wcast-align -Werror" - CC=g++ $(MAKE) -C $(TESTDIR) all CFLAGS="-O3 -Wall -Wextra -Wundef -Wshadow -Wcast-align -Werror" - -gpptest32: clean - g++ -v - CC=g++ $(MAKE) -C $(LZ4DIR) all CFLAGS="-m32 -O3 -Wall -Wextra -Wundef -Wshadow -Wcast-align -Werror" - CC=g++ $(MAKE) -C $(PRGDIR) native CFLAGS="-m32 -O3 -Wall -Wextra -Wundef -Wshadow -Wcast-align -Werror" - CC=g++ $(MAKE) -C $(TESTDIR) native CFLAGS="-m32 -O3 -Wall -Wextra -Wundef -Wshadow -Wcast-align -Werror" - -c_standards: clean - # note : lz4 is not C90 compatible, because it requires long long support - CFLAGS="-std=gnu90 -Werror" $(MAKE) clean allmost - CFLAGS="-std=c99 -Werror" $(MAKE) clean allmost - CFLAGS="-std=gnu99 -Werror" $(MAKE) clean allmost - CFLAGS="-std=c11 -Werror" $(MAKE) clean allmost - -endif diff --git a/src/lz4/NEWS b/src/lz4/NEWS deleted file mode 100644 index e63a82f713..0000000000 --- a/src/lz4/NEWS +++ /dev/null @@ -1,231 +0,0 @@ -v1.8.0 -cli : fix : do not modify /dev/null permissions, reported by @Maokaman1 -cli : added GNU separator -- specifying that all following arguments are files -API : added LZ4_compress_HC_destSize(), by Oleg (@remittor) -API : added LZ4F_resetDecompressionContext() -API : lz4frame : negative compression levels trigger fast acceleration, request by Lawrence Chan -API : lz4frame : can control block checksum and dictionary ID -API : fix : expose obsolete decoding functions, reported by Chen Yufei -API : experimental : lz4frame_static : new dictionary compression API -build : fix : static lib installation, by Ido Rosen -build : dragonFlyBSD, OpenBSD, NetBSD supported -build : LZ4_MEMORY_USAGE can be modified at compile time, through external define -doc : Updated LZ4 Frame format to v1.6.0, restoring Dictionary-ID field -doc : lz4 api manual, by Przemyslaw Skibinski - -v1.7.5 -lz4hc : new high compression mode : levels 10-12 compress more and slower, by Przemyslaw Skibinski -lz4cat : fix : works with relative path (#284) and stdin (#285) (reported by @beiDei8z) -cli : fix minor notification when using -r recursive mode -API : lz4frame : LZ4F_frameBound(0) gives upper bound of *flush() and *End() operations (#290, #280) -doc : markdown version of man page, by Takayuki Matsuoka (#279) -build : Makefile : fix make -jX lib+exe concurrency (#277) -build : cmake : improvements by Michał Górny (#296) - -v1.7.4.2 -fix : Makefile : release build compatible with PIE and customized compilation directives provided through environment variables (#274, reported by Antoine Martin) - -v1.7.4 -Improved : much better speed in -mx32 mode -cli : fix : Large file support in 32-bits mode on Mac OS-X -fix : compilation on gcc 4.4 (#272), reported by Antoine Martin - -v1.7.3 -Changed : moved to versioning; package, cli and library have same version number -Improved: Small decompression speed boost -Improved: Small compression speed improvement on 64-bits systems -Improved: Small compression ratio and speed improvement on small files -Improved: Significant speed boost on ARMv6 and ARMv7 -Fix : better ratio on 64-bits big-endian targets -Improved cmake build script, by Evan Nemerson -New liblz4-dll project, by Przemyslaw Skibinki -Makefile: Generates object files (*.o) for faster (re)compilation on low power systems -cli : new : --rm and --help commands -cli : new : preserved file attributes, by Przemyslaw Skibinki -cli : fix : crash on some invalid inputs -cli : fix : -t correctly validates lz4-compressed files, by Nick Terrell -cli : fix : detects and reports fread() errors, thanks to Hiroshi Fujishima report #243 -cli : bench : new : -r recursive mode -lz4cat : can cat multiple files in a single command line (#184) -Added : doc/lz4_manual.html, by Przemyslaw Skibinski -Added : dictionary compression and frame decompression examples, by Nick Terrell -Added : Debianization, by Evgeniy Polyakov - -r131 -New : Dos/DJGPP target, thanks to Louis Santillan (#114) -Added : Example using lz4frame library, by Zbigniew Jędrzejewski-Szmek (#118) -Changed: xxhash symbols are modified (namespace emulation) within liblz4 - -r130: -Fixed : incompatibility sparse mode vs console, reported by Yongwoon Cho (#105) -Fixed : LZ4IO exits too early when frame crc not present, reported by Yongwoon Cho (#106) -Fixed : incompatibility sparse mode vs append mode, reported by Takayuki Matsuoka (#110) -Performance fix : big compression speed boost for clang (+30%) -New : cross-version test, by Takayuki Matsuoka - -r129: -Added : LZ4_compress_fast(), LZ4_compress_fast_continue() -Added : LZ4_compress_destSize() -Changed: New lz4 and lz4hc compression API. Previous function prototypes still supported. -Changed: Sparse file support enabled by default -New : LZ4 CLI improved performance compressing/decompressing multiple files (#86, kind contribution from Kyle J. Harper & Takayuki Matsuoka) -Fixed : GCC 4.9+ optimization bug - Reported by Markus Trippelsdorf, Greg Slazinski & Evan Nemerson -Changed: Enums converted to LZ4F_ namespace convention - by Takayuki Matsuoka -Added : AppVeyor CI environment, for Visual tests - Suggested by Takayuki Matsuoka -Modified:Obsolete functions generate warnings - Suggested by Evan Nemerson, contributed by Takayuki Matsuoka -Fixed : Bug #75 (unfinished stream), reported by Yongwoon Cho -Updated: Documentation converted to MarkDown format - -r128: -New : lz4cli sparse file support (Requested by Neil Wilson, and contributed by Takayuki Matsuoka) -New : command -m, to compress multiple files in a single command (suggested by Kyle J. Harper) -Fixed : Restored lz4hc compression ratio (slightly lower since r124) -New : lz4 cli supports long commands (suggested by Takayuki Matsuoka) -New : lz4frame & lz4cli frame content size support -New : lz4frame supports skippable frames, as requested by Sergey Cherepanov -Changed: Default "make install" directory is /usr/local, as notified by Ron Johnson -New : lz4 cli supports "pass-through" mode, requested by Neil Wilson -New : datagen can generate sparse files -New : scan-build tests, thanks to kind help by Takayuki Matsuoka -New : g++ compatibility tests -New : arm cross-compilation test, thanks to kind help by Takayuki Matsuoka -Fixed : Fuzzer + frametest compatibility with NetBSD (issue #48, reported by Thomas Klausner) -Added : Visual project directory -Updated: Man page & Specification - -r127: -N/A : added a file on SVN - -r126: -New : lz4frame API is now integrated into liblz4 -Fixed : GCC 4.9 bug on highest performance settings, reported by Greg Slazinski -Fixed : bug within LZ4 HC streaming mode, reported by James Boyle -Fixed : older compiler don't like nameless unions, reported by Cheyi Lin -Changed : lz4 is C90 compatible -Changed : added -pedantic option, fixed a few mminor warnings - -r125: -Changed : endian and alignment code -Changed : directory structure : new "lib" directory -Updated : lz4io, now uses lz4frame -Improved: slightly improved decoding speed -Fixed : LZ4_compress_limitedOutput(); Special thanks to Christopher Speller ! -Fixed : some alignment warnings under clang -Fixed : deprecated function LZ4_slideInputBufferHC() - -r124: -New : LZ4 HC streaming mode -Fixed : LZ4F_compressBound() using null preferencesPtr -Updated : xxHash to r38 -Updated library number, to 1.4.0 - -r123: -Added : experimental lz4frame API, thanks to Takayuki Matsuoka and Christopher Jackson for testings -Fix : s390x support, thanks to Nobuhiro Iwamatsu -Fix : test mode (-t) no longer requires confirmation, thanks to Thary Nguyen - -r122: -Fix : AIX & AIX64 support (SamG) -Fix : mips 64-bits support (lew van) -Added : Examples directory, using code examples from Takayuki Matsuoka -Updated : Framing specification, to v1.4.1 -Updated : xxHash, to r36 - -r121: -Added : Makefile : install for kFreeBSD and Hurd (Nobuhiro Iwamatsu) -Fix : Makefile : install for OS-X and BSD, thanks to Takayuki Matsuoka - -r120: -Modified : Streaming API, using strong types -Added : LZ4_versionNumber(), thanks to Takayuki Matsuoka -Fix : OS-X : library install name, thanks to Clemens Lang -Updated : Makefile : synchronize library version number with lz4.h, thanks to Takayuki Matsuoka -Updated : Makefile : stricter compilation flags -Added : pkg-config, thanks to Zbigniew Jędrzejewski-Szmek (issue 135) -Makefile : lz4-test only test native binaries, as suggested by Michał Górny (issue 136) -Updated : xxHash to r35 - -r119: -Fix : Issue 134 : extended malicious address space overflow in 32-bits mode for some specific configurations - -r118: -New : LZ4 Streaming API (Fast version), special thanks to Takayuki Matsuoka -New : datagen : parametrable synthetic data generator for tests -Improved : fuzzer, support more test cases, more parameters, ability to jump to specific test -fix : support ppc64le platform (issue 131) -fix : Issue 52 (malicious address space overflow in 32-bits mode when using large custom format) -fix : Makefile : minor issue 130 : header files permissions - -r117: -Added : man pages for lz4c and lz4cat -Added : automated tests on Travis, thanks to Takayuki Matsuoka ! -fix : block-dependency command line (issue 127) -fix : lz4fullbench (issue 128) - -r116: -hotfix (issue 124 & 125) - -r115: -Added : lz4cat utility, installed on POSX systems (issue 118) -OS-X compatible compilation of dynamic library (issue 115) - -r114: -Makefile : library correctly compiled with -O3 switch (issue 114) -Makefile : library compilation compatible with clang -Makefile : library is versioned and linked (issue 119) -lz4.h : no more static inline prototypes (issue 116) -man : improved header/footer (issue 111) -Makefile : Use system default $(CC) & $(MAKE) variables (issue 112) -xxhash : updated to r34 - -r113: -Large decompression speed improvement for GCC 32-bits. Thanks to Valery Croizier ! -LZ4HC : Compression Level is now a programmable parameter (CLI from 4 to 9) -Separated IO routines from command line (lz4io.c) -Version number into lz4.h (suggested by Francesc Alted) - -r112: -quickfix - -r111 : -Makefile : added capability to install libraries -Modified Directory tree, to better separate libraries from programs. - -r110 : -lz4 & lz4hc : added capability to allocate state & stream state with custom allocator (issue 99) -fuzzer & fullbench : updated to test new functions -man : documented -l command (Legacy format, for Linux kernel compression) (issue 102) -cmake : improved version by Mika Attila, building programs and libraries (issue 100) -xxHash : updated to r33 -Makefile : clean also delete local package .tar.gz - -r109 : -lz4.c : corrected issue 98 (LZ4_compress_limitedOutput()) -Makefile : can specify version number from makefile - -r108 : -lz4.c : corrected compression efficiency issue 97 in 64-bits chained mode (-BD) for streams > 4 GB (thanks Roman Strashkin for reporting) - -r107 : -Makefile : support DESTDIR for staged installs. Thanks Jorge Aparicio. -Makefile : make install installs both lz4 and lz4c (Jorge Aparicio) -Makefile : removed -Wno-implicit-declaration compilation switch -lz4cli.c : include for isatty() (Luca Barbato) -lz4.h : introduced LZ4_MAX_INPUT_SIZE constant (Shay Green) -lz4.h : LZ4_compressBound() : unified macro and inline definitions (Shay Green) -lz4.h : LZ4_decompressSafe_partial() : clarify comments (Shay Green) -lz4.c : LZ4_compress() verify input size condition (Shay Green) -bench.c : corrected a bug in free memory size evaluation -cmake : install into bin/ directory (Richard Yao) -cmake : check for just C compiler (Elan Ruusamae) - -r106 : -Makefile : make dist modify text files in the package to respect Unix EoL convention -lz4cli.c : corrected small display bug in HC mode - -r105 : -Makefile : New install script and man page, contributed by Prasad Pandit -lz4cli.c : Minor modifications, for easier extensibility -COPYING : added license file -LZ4_Streaming_Format.odt : modified file name to remove white space characters -Makefile : .exe suffix now properly added only for Windows target diff --git a/src/lz4/README.md b/src/lz4/README.md deleted file mode 100644 index ec99630ef9..0000000000 --- a/src/lz4/README.md +++ /dev/null @@ -1,114 +0,0 @@ -LZ4 - Extremely fast compression -================================ - -LZ4 is lossless compression algorithm, -providing compression speed at 400 MB/s per core, -scalable with multi-cores CPU. -It features an extremely fast decoder, -with speed in multiple GB/s per core, -typically reaching RAM speed limits on multi-core systems. - -Speed can be tuned dynamically, selecting an "acceleration" factor -which trades compression ratio for more speed up. -On the other end, a high compression derivative, LZ4_HC, is also provided, -trading CPU time for improved compression ratio. -All versions feature the same decompression speed. - -LZ4 library is provided as open-source software using BSD 2-Clause license. - - -|Branch |Status | -|------------|---------| -|master | [![Build Status][travisMasterBadge]][travisLink] [![Build status][AppveyorMasterBadge]][AppveyorLink] [![coverity][coverBadge]][coverlink] | -|dev | [![Build Status][travisDevBadge]][travisLink] [![Build status][AppveyorDevBadge]][AppveyorLink] | - -[travisMasterBadge]: https://travis-ci.org/lz4/lz4.svg?branch=master "Continuous Integration test suite" -[travisDevBadge]: https://travis-ci.org/lz4/lz4.svg?branch=dev "Continuous Integration test suite" -[travisLink]: https://travis-ci.org/lz4/lz4 -[AppveyorMasterBadge]: https://ci.appveyor.com/api/projects/status/github/lz4/lz4?branch=master&svg=true "Windows test suite" -[AppveyorDevBadge]: https://ci.appveyor.com/api/projects/status/github/lz4/lz4?branch=dev&svg=true "Windows test suite" -[AppveyorLink]: https://ci.appveyor.com/project/YannCollet/lz4-1lndh -[coverBadge]: https://scan.coverity.com/projects/4735/badge.svg "Static code analysis of Master branch" -[coverlink]: https://scan.coverity.com/projects/4735 - -> **Branch Policy:** -> - The "master" branch is considered stable, at all times. -> - The "dev" branch is the one where all contributions must be merged - before being promoted to master. -> + If you plan to propose a patch, please commit into the "dev" branch, - or its own feature branch. - Direct commit to "master" are not permitted. - -Benchmarks -------------------------- - -The benchmark uses [lzbench], from @inikep -compiled with GCC v6.2.0 on Linux 64-bits. -The reference system uses a Core i7-3930K CPU @ 4.5GHz. -Benchmark evaluates the compression of reference [Silesia Corpus] -in single-thread mode. - -[lzbench]: https://github.com/inikep/lzbench -[Silesia Corpus]: http://sun.aei.polsl.pl/~sdeor/index.php?page=silesia - -| Compressor | Ratio | Compression | Decompression | -| ---------- | ----- | ----------- | ------------- | -| memcpy | 1.000 | 7300 MB/s | 7300 MB/s | -|**LZ4 fast 8 (v1.7.3)**| 1.799 |**911 MB/s** | **3360 MB/s** | -|**LZ4 default (v1.7.3)**|**2.101**|**625 MB/s** | **3220 MB/s** | -| LZO 2.09 | 2.108 | 620 MB/s | 845 MB/s | -| QuickLZ 1.5.0 | 2.238 | 510 MB/s | 600 MB/s | -| Snappy 1.1.3 | 2.091 | 450 MB/s | 1550 MB/s | -| LZF v3.6 | 2.073 | 365 MB/s | 820 MB/s | -| [Zstandard] 1.1.1 -1 | 2.876 | 330 MB/s | 930 MB/s | -| [Zstandard] 1.1.1 -3 | 3.164 | 200 MB/s | 810 MB/s | -| [zlib] deflate 1.2.8 -1| 2.730 | 100 MB/s | 370 MB/s | -|**LZ4 HC -9 (v1.7.3)** |**2.720**| 34 MB/s | **3240 MB/s** | -| [zlib] deflate 1.2.8 -6| 3.099 | 33 MB/s | 390 MB/s | - -[zlib]: http://www.zlib.net/ -[Zstandard]: http://www.zstd.net/ - -LZ4 is also compatible and well optimized for x32 mode, for which it provides an additional +10% speed performance. - - -Installation -------------------------- - -``` -make -make install # this command may require root access -``` - -LZ4's `Makefile` supports standard [Makefile conventions], -including [staged installs], [redirection], or [command redefinition]. - -[Makefile conventions]: https://www.gnu.org/prep/standards/html_node/Makefile-Conventions.html -[staged installs]: https://www.gnu.org/prep/standards/html_node/DESTDIR.html -[redirection]: https://www.gnu.org/prep/standards/html_node/Directory-Variables.html -[command redefinition]: https://www.gnu.org/prep/standards/html_node/Utilities-in-Makefiles.html - - -Documentation -------------------------- - -The raw LZ4 block compression format is detailed within [lz4_Block_format]. - -To compress an arbitrarily long file or data stream, multiple blocks are required. -Organizing these blocks and providing a common header format to handle their content -is the purpose of the Frame format, defined into [lz4_Frame_format]. -Interoperable versions of LZ4 must respect this frame format. - -[lz4_Block_format]: doc/lz4_Block_format.md -[lz4_Frame_format]: doc/lz4_Frame_format.md - - -Other source versions -------------------------- - -Beyond the C reference source, -many contributors have created versions of lz4 in multiple languages -(Java, C#, Python, Perl, Ruby, etc.). -A list of known source ports is maintained on the [LZ4 Homepage]. - -[LZ4 Homepage]: http://www.lz4.org diff --git a/src/lz4/appveyor.yml b/src/lz4/appveyor.yml deleted file mode 100644 index 93c1101083..0000000000 --- a/src/lz4/appveyor.yml +++ /dev/null @@ -1,141 +0,0 @@ -version: 1.0.{build} -environment: - matrix: - - COMPILER: "visual" - CONFIGURATION: "Debug" - PLATFORM: "x64" - - COMPILER: "visual" - CONFIGURATION: "Debug" - PLATFORM: "Win32" - - COMPILER: "visual" - CONFIGURATION: "Release" - PLATFORM: "x64" - - COMPILER: "visual" - CONFIGURATION: "Release" - PLATFORM: "Win32" - - COMPILER: "gcc" - PLATFORM: "mingw64" - - COMPILER: "gcc" - PLATFORM: "mingw32" - - COMPILER: "gcc" - PLATFORM: "clang" - -install: - - ECHO Installing %COMPILER% %PLATFORM% %CONFIGURATION% - - MKDIR bin - - if [%COMPILER%]==[gcc] SET PATH_ORIGINAL=%PATH% - - if [%COMPILER%]==[gcc] ( - SET "PATH_MINGW32=c:\MinGW\bin;c:\MinGW\usr\bin" && - SET "PATH_MINGW64=c:\msys64\mingw64\bin;c:\msys64\usr\bin" && - COPY C:\MinGW\bin\mingw32-make.exe C:\MinGW\bin\make.exe && - COPY C:\MinGW\bin\gcc.exe C:\MinGW\bin\cc.exe - ) else ( - IF [%PLATFORM%]==[x64] (SET ADDITIONALPARAM=/p:LibraryPath="C:\Program Files\Microsoft SDKs\Windows\v7.1\lib\x64;c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib\amd64;C:\Program Files (x86)\Microsoft Visual Studio 10.0\;C:\Program Files (x86)\Microsoft Visual Studio 10.0\lib\amd64;") - ) - -build_script: - - if [%PLATFORM%]==[mingw32] SET PATH=%PATH_MINGW32%;%PATH_ORIGINAL% - - if [%PLATFORM%]==[mingw64] SET PATH=%PATH_MINGW64%;%PATH_ORIGINAL% - - if [%PLATFORM%]==[clang] SET PATH=%PATH_MINGW64%;%PATH_ORIGINAL% - - ECHO *** && - ECHO Building %COMPILER% %PLATFORM% %CONFIGURATION% && - ECHO *** - - if [%PLATFORM%]==[clang] (clang -v) - - if [%COMPILER%]==[gcc] (gcc -v) - - if [%COMPILER%]==[gcc] ( - echo ----- && - make -v && - echo ----- && - if not [%PLATFORM%]==[clang] ( - make -C programs lz4 && make -C tests fullbench && make -C lib lib - ) ELSE ( - make -C programs lz4 CC=clang MOREFLAGS="--target=x86_64-w64-mingw32 -Werror -Wconversion -Wno-sign-conversion" && - make -C tests fullbench CC=clang MOREFLAGS="--target=x86_64-w64-mingw32 -Werror -Wconversion -Wno-sign-conversion" && - make -C lib lib CC=clang MOREFLAGS="--target=x86_64-w64-mingw32 -Werror -Wconversion -Wno-sign-conversion" - ) - ) - - if [%COMPILER%]==[gcc] if not [%PLATFORM%]==[clang] ( - MKDIR bin\dll bin\static bin\example bin\include && - COPY tests\fullbench.c bin\example\ && - COPY lib\xxhash.c bin\example\ && - COPY lib\xxhash.h bin\example\ && - COPY lib\lz4.h bin\include\ && - COPY lib\lz4hc.h bin\include\ && - COPY lib\lz4frame.h bin\include\ && - COPY lib\liblz4.a bin\static\liblz4_static.lib && - COPY lib\dll\liblz4.* bin\dll\ && - COPY lib\dll\example\Makefile bin\example\ && - COPY lib\dll\example\fullbench-dll.* bin\example\ && - COPY lib\dll\example\README.md bin\ && - COPY programs\lz4.exe bin\lz4.exe - ) - - if [%COMPILER%]==[gcc] if [%PLATFORM%]==[mingw64] ( - 7z.exe a bin\lz4_x64.zip NEWS .\bin\lz4.exe .\bin\README.md .\bin\example .\bin\dll .\bin\static .\bin\include && - appveyor PushArtifact bin\lz4_x64.zip - ) - - if [%COMPILER%]==[gcc] if [%PLATFORM%]==[mingw32] ( - 7z.exe a bin\lz4_x86.zip NEWS .\bin\lz4.exe .\bin\README.md .\bin\example .\bin\dll .\bin\static .\bin\include && - appveyor PushArtifact bin\lz4_x86.zip - ) - - if [%COMPILER%]==[gcc] (COPY tests\fullbench.exe programs\) - - if [%COMPILER%]==[visual] ( - ECHO *** && - ECHO *** Building Visual Studio 2010 %PLATFORM%\%CONFIGURATION% && - ECHO *** && - msbuild "visual\VS2010\lz4.sln" %ADDITIONALPARAM% /m /verbosity:minimal /property:PlatformToolset=v100 /t:Clean,Build /p:Platform=%PLATFORM% /p:Configuration=%CONFIGURATION% /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" && - ECHO *** && - ECHO *** Building Visual Studio 2012 %PLATFORM%\%CONFIGURATION% && - ECHO *** && - msbuild "visual\VS2010\lz4.sln" /m /verbosity:minimal /property:PlatformToolset=v110 /t:Clean,Build /p:Platform=%PLATFORM% /p:Configuration=%CONFIGURATION% /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" && - ECHO *** && - ECHO *** Building Visual Studio 2013 %PLATFORM%\%CONFIGURATION% && - ECHO *** && - msbuild "visual\VS2010\lz4.sln" /m /verbosity:minimal /property:PlatformToolset=v120 /t:Clean,Build /p:Platform=%PLATFORM% /p:Configuration=%CONFIGURATION% /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" && - ECHO *** && - ECHO *** Building Visual Studio 2015 %PLATFORM%\%CONFIGURATION% && - ECHO *** && - msbuild "visual\VS2010\lz4.sln" /m /verbosity:minimal /property:PlatformToolset=v140 /t:Clean,Build /p:Platform=%PLATFORM% /p:Configuration=%CONFIGURATION% /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" && - COPY visual\VS2010\bin\%PLATFORM%_%CONFIGURATION%\*.exe programs\ - ) - -test_script: - - ECHO *** && - ECHO Testing %COMPILER% %PLATFORM% %CONFIGURATION% && - ECHO *** - - if not [%COMPILER%]==[unknown] ( - CD programs && - lz4 -h && - lz4 -i1b lz4.exe && - lz4 -i1b5 lz4.exe && - lz4 -i1b10 lz4.exe && - lz4 -i1b15 lz4.exe && - echo ------- lz4 tested ------- && - fullbench.exe -i1 fullbench.exe - ) - -artifacts: - - path: bin\lz4_x64.zip - - path: bin\lz4_x86.zip - -deploy: -- provider: GitHub - artifact: bin\lz4_x64.zip - auth_token: - secure: w6UJaGie0qbZvffr/fqyhO/Vj8rMiQWnv9a8qm3gxfngdHDTMT42wYupqJpIExId - force_update: true - prerelease: true - on: - COMPILER: gcc - PLATFORM: "mingw64" - appveyor_repo_tag: true - -- provider: GitHub - artifact: bin\lz4_x86.zip - auth_token: - secure: w6UJaGie0qbZvffr/fqyhO/Vj8rMiQWnv9a8qm3gxfngdHDTMT42wYupqJpIExId - force_update: true - prerelease: true - on: - COMPILER: gcc - PLATFORM: "mingw32" - appveyor_repo_tag: true diff --git a/src/lz4/circle.yml b/src/lz4/circle.yml deleted file mode 100644 index b3faae0d71..0000000000 --- a/src/lz4/circle.yml +++ /dev/null @@ -1,39 +0,0 @@ -dependencies: - override: - - sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test; sudo apt-get -y -qq update - - sudo apt-get -y install qemu-system-ppc qemu-user-static gcc-powerpc-linux-gnu - - sudo apt-get -y install qemu-system-arm gcc-arm-linux-gnueabi libc6-dev-armel-cross gcc-aarch64-linux-gnu libc6-dev-arm64-cross - - sudo apt-get -y install libc6-dev-i386 clang gcc-5 gcc-5-multilib gcc-6 valgrind - -test: - override: - # Tests compilers and C standards - - clang -v; make clangtest && make clean - - g++ -v; make gpptest && make clean - - gcc -v; make c_standards && make clean - - gcc-5 -v; make -C tests test-lz4 CC=gcc-5 MOREFLAGS=-Werror && make clean - - gcc-5 -v; make -C tests test-lz4c32 CC=gcc-5 MOREFLAGS="-I/usr/include/x86_64-linux-gnu -Werror" && make clean - - gcc-6 -v; make c_standards CC=gcc-6 && make clean - - gcc-6 -v; make -C tests test-lz4 CC=gcc-6 MOREFLAGS=-Werror && make clean -# Shorter tests - - make cmake && make clean - - make -C tests test-lz4 - - make -C tests test-lz4c - - make -C tests test-fasttest - - make -C tests test-frametest - - make -C tests test-fullbench - - make -C tests test-fuzzer && make clean - - make -C lib all && make clean - - pyenv global 3.4.4; CFLAGS=-I/usr/include/x86_64-linux-gnu make versionsTest && make clean - - make travis-install && make clean - # Longer tests - - gcc -v; make -C tests test32 MOREFLAGS="-I/usr/include/x86_64-linux-gnu" && make clean - - make usan && make clean - - clang -v; make staticAnalyze && make clean - # Valgrind tests - - make -C tests test-mem && make clean - # ARM, AArch64, PowerPC, PowerPC64 tests - - make platformTest CC=powerpc-linux-gnu-gcc QEMU_SYS=qemu-ppc-static && make clean - - make platformTest CC=powerpc-linux-gnu-gcc QEMU_SYS=qemu-ppc64-static MOREFLAGS=-m64 && make clean - - make platformTest CC=arm-linux-gnueabi-gcc QEMU_SYS=qemu-arm-static && make clean - - make platformTest CC=aarch64-linux-gnu-gcc QEMU_SYS=qemu-aarch64-static && make clean diff --git a/src/lz4/contrib/cmake_unofficial/.gitignore b/src/lz4/contrib/cmake_unofficial/.gitignore deleted file mode 100644 index d39505da74..0000000000 --- a/src/lz4/contrib/cmake_unofficial/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -# cmake artefact - -CMakeCache.txt -CMakeFiles -*.cmake -Makefile -liblz4.pc -lz4c -install_manifest.txt diff --git a/src/lz4/contrib/cmake_unofficial/CMakeLists.txt b/src/lz4/contrib/cmake_unofficial/CMakeLists.txt deleted file mode 100644 index 27c3a78817..0000000000 --- a/src/lz4/contrib/cmake_unofficial/CMakeLists.txt +++ /dev/null @@ -1,221 +0,0 @@ -# CMake support for LZ4 -# -# To the extent possible under law, the author(s) have dedicated all -# copyright and related and neighboring rights to this software to -# the public domain worldwide. This software is distributed without -# any warranty. -# -# For details, see . -# -# LZ4's CMake support is maintained by Evan Nemerson; when filing -# bugs please mention @nemequ to make sure I see it. - -set(LZ4_TOP_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../..") - -# Parse version information -file(STRINGS "${LZ4_TOP_SOURCE_DIR}/lib/lz4.h" LZ4_VERSION_MAJOR REGEX "^#define LZ4_VERSION_MAJOR +([0-9]+) +.*$") -string(REGEX REPLACE "^#define LZ4_VERSION_MAJOR +([0-9]+) +.*$" "\\1" LZ4_VERSION_MAJOR "${LZ4_VERSION_MAJOR}") -file(STRINGS "${LZ4_TOP_SOURCE_DIR}/lib/lz4.h" LZ4_VERSION_MINOR REGEX "^#define LZ4_VERSION_MINOR +([0-9]+) +.*$") -string(REGEX REPLACE "^#define LZ4_VERSION_MINOR +([0-9]+) +.*$" "\\1" LZ4_VERSION_MINOR "${LZ4_VERSION_MINOR}") -file(STRINGS "${LZ4_TOP_SOURCE_DIR}/lib/lz4.h" LZ4_VERSION_RELEASE REGEX "^#define LZ4_VERSION_RELEASE +([0-9]+) +.*$") -string(REGEX REPLACE "^#define LZ4_VERSION_RELEASE +([0-9]+) +.*$" "\\1" LZ4_VERSION_RELEASE "${LZ4_VERSION_RELEASE}") -set(LZ4_VERSION_STRING "${LZ4_VERSION_MAJOR}.${LZ4_VERSION_MINOR}.${LZ4_VERSION_RELEASE}") -mark_as_advanced(LZ4_VERSION_STRING LZ4_VERSION_MAJOR LZ4_VERSION_MINOR LZ4_VERSION_RELEASE) - -if("${CMAKE_VERSION}" VERSION_LESS "3.0") - project(LZ4 C) -else() - cmake_policy (SET CMP0048 NEW) - project(LZ4 - VERSION ${LZ4_VERSION_STRING} - LANGUAGES C) -endif() - -cmake_minimum_required (VERSION 2.8.6) - -# If LZ4 is being bundled in another project, we don't want to -# install anything. However, we want to let people override this, so -# we'll use the LZ4_BUNDLED_MODE variable to let them do that; just -# set it to OFF in your project before you add_subdirectory(lz4/contrib/cmake_unofficial). -get_directory_property(LZ4_PARENT_DIRECTORY PARENT_DIRECTORY) -if("${LZ4_BUNDLED_MODE}" STREQUAL "") - # Bundled mode hasn't been set one way or the other, set the default - # depending on whether or not we are the top-level project. - if("${LZ4_PARENT_DIRECTORY}" STREQUAL "") - set(LZ4_BUNDLED_MODE OFF) - else() - set(LZ4_BUNDLED_MODE ON) - endif() -endif() -mark_as_advanced(LZ4_BUNDLED_MODE) - -# CPack -if(NOT LZ4_BUNDLED_MODE AND NOT CPack_CMake_INCLUDED) - set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "LZ4 compression library") - set(CPACK_PACKAGE_DESCRIPTION_FILE "${LZ4_TOP_SOURCE_DIR}/README.md") - set(CPACK_RESOURCE_FILE_LICENSE "${LZ4_TOP_SOURCE_DIR}/LICENSE") - set(CPACK_PACKAGE_VERSION_MAJOR ${LZ4_VERSION_MAJOR}) - set(CPACK_PACKAGE_VERSION_MINOR ${LZ4_VERSION_MINOR}) - set(CPACK_PACKAGE_VERSION_PATCH ${LZ4_VERSION_RELEASE}) - include(CPack) -endif(NOT LZ4_BUNDLED_MODE AND NOT CPack_CMake_INCLUDED) - -# Allow people to choose whether to build shared or static libraries -# via the BUILD_SHARED_LIBS option unless we are in bundled mode, in -# which case we always use static libraries. -include(CMakeDependentOption) -CMAKE_DEPENDENT_OPTION(BUILD_SHARED_LIBS "Build shared libraries" ON "NOT LZ4_BUNDLED_MODE" OFF) -CMAKE_DEPENDENT_OPTION(BUILD_STATIC_LIBS "Build static libraries" OFF "BUILD_SHARED_LIBS" ON) - -if(NOT BUILD_SHARED_LIBS AND NOT BUILD_STATIC_LIBS) - message(FATAL_ERROR "Both BUILD_SHARED_LIBS and BUILD_STATIC_LIBS have been disabled") -endif() - -set(LZ4_LIB_SOURCE_DIR "${LZ4_TOP_SOURCE_DIR}/lib") -set(LZ4_PROG_SOURCE_DIR "${LZ4_TOP_SOURCE_DIR}/programs") - -include_directories("${LZ4_LIB_SOURCE_DIR}") - -# CLI sources -set(LZ4_SOURCES - "${LZ4_LIB_SOURCE_DIR}/lz4.c" - "${LZ4_LIB_SOURCE_DIR}/lz4hc.c" - "${LZ4_LIB_SOURCE_DIR}/lz4.h" - "${LZ4_LIB_SOURCE_DIR}/lz4hc.h" - "${LZ4_LIB_SOURCE_DIR}/lz4frame.c" - "${LZ4_LIB_SOURCE_DIR}/lz4frame.h" - "${LZ4_LIB_SOURCE_DIR}/xxhash.c") -set(LZ4_CLI_SOURCES - "${LZ4_PROG_SOURCE_DIR}/bench.c" - "${LZ4_PROG_SOURCE_DIR}/lz4cli.c" - "${LZ4_PROG_SOURCE_DIR}/lz4io.c" - "${LZ4_PROG_SOURCE_DIR}/datagen.c") - -# Whether to use position independent code for the static library. If -# we're building a shared library this is ignored and PIC is always -# used. -option(LZ4_POSITION_INDEPENDENT_LIB "Use position independent code for static library (if applicable)" ON) - -# liblz4 -set(LZ4_LIBRARIES_BUILT) -if(BUILD_SHARED_LIBS) - add_library(lz4_shared SHARED ${LZ4_SOURCES}) - set_target_properties(lz4_shared PROPERTIES - OUTPUT_NAME lz4 - SOVERSION "${LZ4_VERSION_MAJOR}" - VERSION "${LZ4_VERSION_STRING}") - list(APPEND LZ4_LIBRARIES_BUILT lz4_shared) -endif() -if(BUILD_STATIC_LIBS) - add_library(lz4_static STATIC ${LZ4_SOURCES}) - set_target_properties(lz4_static PROPERTIES - OUTPUT_NAME lz4 - POSITION_INDEPENDENT_CODE ${LZ4_POSITION_INDEPENDENT_LIB}) - list(APPEND LZ4_LIBRARIES_BUILT lz4_static) -endif() - -# link to shared whenever possible, to static otherwise -if(BUILD_SHARED_LIBS) - set(LZ4_LINK_LIBRARY lz4_shared) -else() - set(LZ4_LINK_LIBRARY lz4_static) -endif() - -# lz4 -add_executable(lz4cli ${LZ4_CLI_SOURCES}) -set_target_properties(lz4cli PROPERTIES OUTPUT_NAME lz4) -target_link_libraries(lz4cli ${LZ4_LINK_LIBRARY}) - -# lz4c -add_executable(lz4c ${LZ4_CLI_SOURCES}) -set_target_properties(lz4c PROPERTIES COMPILE_DEFINITIONS "ENABLE_LZ4C_LEGACY_OPTIONS") -target_link_libraries(lz4c ${LZ4_LINK_LIBRARY}) - -# Extra warning flags -include (CheckCCompilerFlag) -foreach (flag - # GCC-style - -Wall - -Wextra - -Wundef - -Wcast-qual - -Wcast-align - -Wshadow - -Wswitch-enum - -Wdeclaration-after-statement - -Wstrict-prototypes - -Wpointer-arith - - # MSVC-style - /W4) - # Because https://gcc.gnu.org/wiki/FAQ#wnowarning - string(REGEX REPLACE "\\-Wno\\-(.+)" "-W\\1" flag_to_test "${flag}") - string(REGEX REPLACE "[^a-zA-Z0-9]+" "_" test_name "CFLAG_${flag_to_test}") - - check_c_compiler_flag("${ADD_COMPILER_FLAGS_PREPEND} ${flag_to_test}" ${test_name}) - - if(${test_name}) - set(CMAKE_C_FLAGS "${flag} ${CMAKE_C_FLAGS}") - endif() - - unset(test_name) - unset(flag_to_test) -endforeach (flag) - -if(NOT LZ4_BUNDLED_MODE) - include(GNUInstallDirs) - - install(TARGETS lz4cli lz4c - RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") - install(TARGETS ${LZ4_LIBRARIES_BUILT} - LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" - ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" - RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") - install(FILES - "${LZ4_LIB_SOURCE_DIR}/lz4.h" - "${LZ4_LIB_SOURCE_DIR}/lz4frame.h" - "${LZ4_LIB_SOURCE_DIR}/lz4hc.h" - DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") - install(FILES "${LZ4_PROG_SOURCE_DIR}/lz4.1" - DESTINATION "${CMAKE_INSTALL_MANDIR}/man1") - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/liblz4.pc" - DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") - - # install lz4cat and unlz4 symlinks on *nix - if(UNIX) - install(CODE " - foreach(f lz4cat unlz4) - set(dest \"\$ENV{DESTDIR}${CMAKE_INSTALL_FULL_BINDIR}/\${f}\") - message(STATUS \"Symlinking: \${dest} -> lz4\") - execute_process( - COMMAND \"${CMAKE_COMMAND}\" -E create_symlink lz4 \"\${dest}\") - endforeach() - ") - - # create manpage aliases - foreach(f lz4cat unlz4) - file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/${f}.1" ".so man1/lz4.1\n") - install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${f}.1" - DESTINATION "${CMAKE_INSTALL_MANDIR}/man1") - endforeach() - endif(UNIX) -endif(NOT LZ4_BUNDLED_MODE) - -# pkg-config -set(PREFIX "${CMAKE_INSTALL_PREFIX}") - -if("${CMAKE_INSTALL_FULL_LIBDIR}" STREQUAL "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR}") - set(LIBDIR "\${prefix}/${CMAKE_INSTALL_LIBDIR}") -else() - set(LIBDIR "${CMAKE_INSTALL_FULL_LIBDIR}") -endif() - -if("${CMAKE_INSTALL_FULL_INCLUDEDIR}" STREQUAL "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_INCLUDEDIR}") - set(INCLUDEDIR "\${prefix}/${CMAKE_INSTALL_INCLUDEDIR}") -else() - set(INCLUDEDIR "${CMAKE_INSTALL_FULL_INCLUDEDIR}") -endif() - -# for liblz4.pc substitution -set(VERSION ${LZ4_VERSION_STRING}) -configure_file(${LZ4_LIB_SOURCE_DIR}/liblz4.pc.in liblz4.pc @ONLY) diff --git a/src/lz4/contrib/debian/changelog b/src/lz4/contrib/debian/changelog deleted file mode 100644 index 87ac0169ee..0000000000 --- a/src/lz4/contrib/debian/changelog +++ /dev/null @@ -1,10 +0,0 @@ -liblz4 (1.7.2) unstable; urgency=low - - * Changed : moved to versioning; package, cli and library have same version number - * Improved: Small decompression speed boost (+4%) - * Improved: Performance on ARMv6 and ARMv7 - * Added : Debianization, by Evgeniy Polyakov - * Makefile: Generates object files (*.o) for faster (re)compilation on low power systems - * Fix : cli : crash on some invalid inputs - - -- Yann Collet Sun, 28 Jun 2015 01:00:00 +0000 diff --git a/src/lz4/contrib/debian/compat b/src/lz4/contrib/debian/compat deleted file mode 100644 index 7f8f011eb7..0000000000 --- a/src/lz4/contrib/debian/compat +++ /dev/null @@ -1 +0,0 @@ -7 diff --git a/src/lz4/contrib/debian/control b/src/lz4/contrib/debian/control deleted file mode 100644 index ac3b4601e6..0000000000 --- a/src/lz4/contrib/debian/control +++ /dev/null @@ -1,23 +0,0 @@ -Source: liblz4 -Section: devel -Priority: optional -Maintainer: Evgeniy Polyakov -Build-Depends: - cmake (>= 2.6), - debhelper (>= 7.0.50~), - cdbs -Standards-Version: 3.8.0 -Homepage: http://www.lz4.org/ -Vcs-Git: git://github.com/lz4/lz4.git -Vcs-Browser: https://github.com/lz4/lz4 - -Package: liblz4 -Architecture: any -Depends: ${shlibs:Depends}, ${misc:Depends} -Description: Extremely Fast Compression algorithm http://www.lz4.org - -Package: liblz4-dev -Architecture: any -Depends: ${shlibs:Depends}, ${misc:Depends} -Description: Extremely Fast Compression algorithm http://www.lz4.org - Development files. diff --git a/src/lz4/contrib/debian/copyright b/src/lz4/contrib/debian/copyright deleted file mode 100644 index 18a7f48479..0000000000 --- a/src/lz4/contrib/debian/copyright +++ /dev/null @@ -1,9 +0,0 @@ -Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ -Upstream-Name: liblz4 -Upstream-Contact: Yann Collet -Source: https://github.com/lz4/lz4 - -Files: * -Copyright: (C) 2011+ Yann Collet -License: GPL-2+ - The full text of license: https://github.com/Cyan4973/lz4/blob/master/lib/LICENSE diff --git a/src/lz4/contrib/debian/dirs b/src/lz4/contrib/debian/dirs deleted file mode 100644 index e772481755..0000000000 --- a/src/lz4/contrib/debian/dirs +++ /dev/null @@ -1 +0,0 @@ -usr/bin diff --git a/src/lz4/contrib/debian/docs b/src/lz4/contrib/debian/docs deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/src/lz4/contrib/debian/liblz4-dev.install b/src/lz4/contrib/debian/liblz4-dev.install deleted file mode 100644 index 3a029096f5..0000000000 --- a/src/lz4/contrib/debian/liblz4-dev.install +++ /dev/null @@ -1,2 +0,0 @@ -usr/include/lz4* -usr/lib/liblz4.so diff --git a/src/lz4/contrib/debian/liblz4.install b/src/lz4/contrib/debian/liblz4.install deleted file mode 100644 index e444956d9c..0000000000 --- a/src/lz4/contrib/debian/liblz4.install +++ /dev/null @@ -1,2 +0,0 @@ -usr/lib/liblz4.so.* -usr/bin/* diff --git a/src/lz4/contrib/debian/rules b/src/lz4/contrib/debian/rules deleted file mode 100755 index 748e68d169..0000000000 --- a/src/lz4/contrib/debian/rules +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/make -f - -include /usr/share/cdbs/1/rules/debhelper.mk -include /usr/share/cdbs/1/class/cmake.mk - - -DEB_CMAKE_EXTRA_FLAGS := -DCMAKE_BUILD_TYPE=RelWithDebInfo ../cmake_unofficial - diff --git a/src/lz4/contrib/djgpp/LICENSE b/src/lz4/contrib/djgpp/LICENSE deleted file mode 100644 index fee0d3b3e2..0000000000 --- a/src/lz4/contrib/djgpp/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -Copyright (c) 2014, lpsantil -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/src/lz4/contrib/djgpp/Makefile b/src/lz4/contrib/djgpp/Makefile deleted file mode 100644 index 8cd3580823..0000000000 --- a/src/lz4/contrib/djgpp/Makefile +++ /dev/null @@ -1,130 +0,0 @@ -# Copyright (c) 2015, Louis P. Santillan -# All rights reserved. -# See LICENSE for licensing details. -DESTDIR ?= /opt/local - -# Pulled the code below from lib/Makefile. Might be nicer to derive this somehow without sed -# Version numbers -VERSION ?= 129 -RELEASE ?= r$(VERSION) -LIBVER_MAJOR=$(shell sed -n '/define LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < lib/lz4.h) -LIBVER_MINOR=$(shell sed -n '/define LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < lib/lz4.h) -LIBVER_PATCH=$(shell sed -n '/define LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < lib/lz4.h) -LIBVER=$(LIBVER_MAJOR).$(LIBVER_MINOR).$(LIBVER_PATCH) - -###################################################################### - -CROSS ?= i586-pc-msdosdjgpp -CC = $(CROSS)-gcc -AR = $(CROSS)-ar -LD = $(CROSS)-gcc - -CFLAGS ?= -O3 -std=gnu99 -Wall -Wextra -Wundef -Wshadow -Wcast-qual -Wcast-align -Wstrict-prototypes -pedantic -DLZ4_VERSION=\"$(RELEASE)\" -LDFLAGS ?= -s -SRC = programs/bench.c programs/lz4io.c programs/lz4cli.c -OBJ = $(SRC:.c=.o) -SDEPS = $(SRC:.c=.d) -IDIR = lib -EDIR = . -EXE = lz4.exe -LNK = lz4 -LDIR = lib -LSRC = lib/lz4.c lib/lz4hc.c lib/lz4frame.c lib/xxhash.c -INC = $(LSRC:.c=.h) -LOBJ = $(LSRC:.c=.o) -LSDEPS = $(LSRC:.c=.d) -LIB = $(LDIR)/lib$(LNK).a - -# Since LDFLAGS defaults to "-s", probably better to override unless -# you have a default you would like to maintain -ifeq ($(WITH_DEBUG), 1) - CFLAGS += -g - LDFLAGS += -g -endif - -# Since LDFLAGS defaults to "-s", probably better to override unless -# you have a default you would like to maintain -ifeq ($(WITH_PROFILING), 1) - CFLAGS += -pg - LDFLAGS += -pg -endif - -%.o: %.c $(INC) Makefile - $(CC) $(CFLAGS) -MMD -MP -I$(IDIR) -c $< -o $@ - -%.exe: %.o $(LIB) Makefile - $(LD) $< -L$(LDIR) -l$(LNK) $(LDFLAGS) $(LIBDEP) -o $@ - -###################################################################### -######################## DO NOT MODIFY BELOW ######################### -###################################################################### - -.PHONY: all install uninstall showconfig gstat gpush - -all: $(LIB) $(EXE) - -$(LIB): $(LOBJ) - $(AR) -rcs $@ $^ - -$(EXE): $(LOBJ) $(OBJ) - $(LD) $(LDFLAGS) $(LOBJ) $(OBJ) -o $(EDIR)/$@ - -clean: - rm -f $(OBJ) $(EXE) $(LOBJ) $(LIB) *.tmp $(SDEPS) $(LSDEPS) $(TSDEPS) - -install: $(INC) $(LIB) $(EXE) - mkdir -p $(DESTDIR)/bin $(DESTDIR)/include $(DESTDIR)/lib - rm -f .footprint - echo $(DESTDIR)/bin/$(EXE) >> .footprint - cp -v $(EXE) $(DESTDIR)/bin/ - @for T in $(LIB); \ - do ( \ - echo $(DESTDIR)/$$T >> .footprint; \ - cp -v --parents $$T $(DESTDIR) \ - ); done - @for T in $(INC); \ - do ( \ - echo $(DESTDIR)/include/`basename -a $$T` >> .footprint; \ - cp -v $$T $(DESTDIR)/include/ \ - ); done - -uninstall: .footprint - @for T in $(shell cat .footprint); do rm -v $$T; done - --include $(SDEPS) $(LSDEPS) - -showconfig: - @echo "PWD="$(PWD) - @echo "VERSION="$(VERSION) - @echo "RELEASE="$(RELEASE) - @echo "LIBVER_MAJOR="$(LIBVER_MAJOR) - @echo "LIBVER_MINOR="$(LIBVER_MINOR) - @echo "LIBVER_PATCH="$(LIBVER_PATCH) - @echo "LIBVER="$(LIBVER) - @echo "CROSS="$(CROSS) - @echo "CC="$(CC) - @echo "AR="$(AR) - @echo "LD="$(LD) - @echo "DESTDIR="$(DESTDIR) - @echo "CFLAGS="$(CFLAGS) - @echo "LDFLAGS="$(LDFLAGS) - @echo "SRC="$(SRC) - @echo "OBJ="$(OBJ) - @echo "IDIR="$(IDIR) - @echo "INC="$(INC) - @echo "EDIR="$(EDIR) - @echo "EXE="$(EXE) - @echo "LDIR="$(LDIR) - @echo "LSRC="$(LSRC) - @echo "LOBJ="$(LOBJ) - @echo "LNK="$(LNK) - @echo "LIB="$(LIB) - @echo "SDEPS="$(SDEPS) - @echo "LSDEPS="$(LSDEPS) - -gstat: - git status - -gpush: - git commit - git push diff --git a/src/lz4/contrib/djgpp/README.MD b/src/lz4/contrib/djgpp/README.MD deleted file mode 100644 index 0f4cae6df7..0000000000 --- a/src/lz4/contrib/djgpp/README.MD +++ /dev/null @@ -1,21 +0,0 @@ -# lz4 for DOS/djgpp -This file details on how to compile lz4.exe, and liblz4.a for use on DOS/djgpp using -Andrew Wu's build-djgpp cross compilers ([GH][0], [Binaries][1]) on OSX, Linux. - -## Setup -* Download a djgpp tarball [binaries][1] for your platform. -* Extract and install it (`tar jxvf djgpp-linux64-gcc492.tar.bz2`). Note the path. We'll assume `/home/user/djgpp`. -* Add the `bin` folder to your `PATH`. In bash, do `export PATH=/home/user/djgpp/bin:$PATH`. -* The `Makefile` in `contrib/djgpp/` sets up `CC`, `AR`, `LD` for you. So, `CC=i586-pc-msdosdjgpp-gcc`, `AR=i586-pc-msdosdjgpp-ar`, `LD=i586-pc-msdosdjgpp-gcc`. - -## Building LZ4 for DOS -In the base dir of lz4 and with `contrib/djgpp/Makefile`, try: -Try: -* `make -f contrib/djgpp/Makefile` -* `make -f contrib/djgpp/Makefile liblz4.a` -* `make -f contrib/djgpp/Makefile lz4.exe` -* `make -f contrib/djgpp/Makefile DESTDIR=/home/user/dos install`, however it doesn't make much sense on a \*nix. -* You can also do `make -f contrib/djgpp/Makefile uninstall` - -[0]: https://github.com/andrewwutw/build-djgpp -[1]: https://github.com/andrewwutw/build-djgpp/releases diff --git a/src/lz4/contrib/gen_manual/.gitignore b/src/lz4/contrib/gen_manual/.gitignore deleted file mode 100644 index 6ea967f7c1..0000000000 --- a/src/lz4/contrib/gen_manual/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -# build artefact -gen_manual diff --git a/src/lz4/contrib/gen_manual/Makefile b/src/lz4/contrib/gen_manual/Makefile deleted file mode 100644 index 9fbe858a01..0000000000 --- a/src/lz4/contrib/gen_manual/Makefile +++ /dev/null @@ -1,76 +0,0 @@ -# ################################################################ -# Copyright (C) Przemyslaw Skibinski 2016-present -# All rights reserved. -# -# BSD license -# Redistribution and use in source and binary forms, with or without modification, -# are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright notice, this -# list of conditions and the following disclaimer. -# -# * Redistributions in binary form must reproduce the above copyright notice, this -# list of conditions and the following disclaimer in the documentation and/or -# other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# -# You can contact the author at : -# - LZ4 source repository : https://github.com/Cyan4973/lz4 -# - LZ4 forum froup : https://groups.google.com/forum/#!forum/lz4c -# ################################################################ - - -CFLAGS ?= -O3 -CFLAGS += -Wall -Wextra -Wcast-qual -Wcast-align -Wshadow -Wstrict-aliasing=1 -Wswitch-enum -Wno-comment -CFLAGS += $(MOREFLAGS) -FLAGS = $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) - -LZ4API = ../../lib/lz4.h -LZ4MANUAL = ../../doc/lz4_manual.html -LZ4FAPI = ../../lib/lz4frame.h -LZ4FMANUAL = ../../doc/lz4frame_manual.html -LIBVER_MAJOR_SCRIPT:=`sed -n '/define LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LZ4API)` -LIBVER_MINOR_SCRIPT:=`sed -n '/define LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LZ4API)` -LIBVER_PATCH_SCRIPT:=`sed -n '/define LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LZ4API)` -LIBVER_SCRIPT:= $(LIBVER_MAJOR_SCRIPT).$(LIBVER_MINOR_SCRIPT).$(LIBVER_PATCH_SCRIPT) -LZ4VER := $(shell echo $(LIBVER_SCRIPT)) - -# Define *.exe as extension for Windows systems -ifneq (,$(filter Windows%,$(OS))) -EXT =.exe -else -EXT = -endif - - -.PHONY: default -default: gen_manual - -gen_manual: gen_manual.cpp - $(CXX) $(FLAGS) $^ -o $@$(EXT) - -$(LZ4MANUAL) : gen_manual $(LZ4API) - echo "Update lz4 manual in /doc" - ./gen_manual $(LZ4VER) $(LZ4API) $@ - -$(LZ4FMANUAL) : gen_manual $(LZ4FAPI) - echo "Update lz4frame manual in /doc" - ./gen_manual $(LZ4VER) $(LZ4FAPI) $@ - -.PHONY: manuals -manuals: gen_manual $(LZ4MANUAL) $(LZ4FMANUAL) - -.PHONY: clean -clean: - @$(RM) gen_manual$(EXT) - @echo Cleaning completed diff --git a/src/lz4/contrib/gen_manual/README.md b/src/lz4/contrib/gen_manual/README.md deleted file mode 100644 index 7664ac6eb9..0000000000 --- a/src/lz4/contrib/gen_manual/README.md +++ /dev/null @@ -1,31 +0,0 @@ -gen_manual - a program for automatic generation of manual from source code -========================================================================== - -#### Introduction - -This simple C++ program generates a single-page HTML manual from `lz4.h`. - -The format of recognized comment blocks is following: -- comments of type `/*!` mean: this is a function declaration; switch comments with declarations -- comments of type `/**` and `/*-` mean: this is a comment; use a `

` header for the first line -- comments of type `/*=` and `/**=` mean: use a `

` header and show also all functions until first empty line -- comments of type `/*X` where `X` is different from above-mentioned are ignored - -Moreover: -- `LZ4LIB_API` is removed to improve readability -- `typedef` are detected and included even if uncommented -- comments of type `/**<` and `/*!<` are detected and only function declaration is highlighted (bold) - - -#### Usage - -The program requires 3 parameters: -``` -gen_manual [lz4_version] [input_file] [output_html] -``` - -To compile program and generate lz4 manual we have used: -``` -make -./gen_manual.exe 1.7.3 ../../lib/lz4.h lz4_manual.html -``` diff --git a/src/lz4/contrib/gen_manual/gen-lz4-manual.sh b/src/lz4/contrib/gen_manual/gen-lz4-manual.sh deleted file mode 100644 index 73a7214820..0000000000 --- a/src/lz4/contrib/gen_manual/gen-lz4-manual.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/sh - -LIBVER_MAJOR_SCRIPT=`sed -n '/define LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ../../lib/lz4.h` -LIBVER_MINOR_SCRIPT=`sed -n '/define LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ../../lib/lz4.h` -LIBVER_PATCH_SCRIPT=`sed -n '/define LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ../../lib/lz4.h` -LIBVER_SCRIPT=$LIBVER_MAJOR_SCRIPT.$LIBVER_MINOR_SCRIPT.$LIBVER_PATCH_SCRIPT - -echo LZ4_VERSION=$LIBVER_SCRIPT -./gen_manual "lz4 $LIBVER_SCRIPT" ../../lib/lz4.h ./lz4_manual.html -./gen_manual "lz4frame $LIBVER_SCRIPT" ../../lib/lz4frame.h ./lz4frame_manual.html diff --git a/src/lz4/contrib/gen_manual/gen_manual.cpp b/src/lz4/contrib/gen_manual/gen_manual.cpp deleted file mode 100644 index 65abd3a408..0000000000 --- a/src/lz4/contrib/gen_manual/gen_manual.cpp +++ /dev/null @@ -1,247 +0,0 @@ -/* -Copyright (c) 2016-present, Przemyslaw Skibinski -All rights reserved. - -BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -* Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -You can contact the author at : -- LZ4 homepage : http://www.lz4.org -- LZ4 source repository : https://github.com/lz4/lz4 -*/ - -#include -#include -#include -#include -using namespace std; - - -/* trim string at the beginning and at the end */ -void trim(string& s, string characters) -{ - size_t p = s.find_first_not_of(characters); - s.erase(0, p); - - p = s.find_last_not_of(characters); - if (string::npos != p) - s.erase(p+1); -} - - -/* trim C++ style comments */ -void trim_comments(string &s) -{ - size_t spos, epos; - - spos = s.find("/*"); - epos = s.find("*/"); - s = s.substr(spos+3, epos-(spos+3)); -} - - -/* get lines until a given terminator */ -vector get_lines(vector& input, int& linenum, string terminator) -{ - vector out; - string line; - size_t epos; - - while ((size_t)linenum < input.size()) { - line = input[linenum]; - - if (terminator.empty() && line.empty()) { linenum--; break; } - - epos = line.find(terminator); - if (!terminator.empty() && epos!=string::npos) { - out.push_back(line); - break; - } - out.push_back(line); - linenum++; - } - return out; -} - - -/* print line with LZ4LIB_API removed and C++ comments not bold */ -void print_line(stringstream &sout, string line) -{ - size_t spos, epos; - - if (line.substr(0,11) == "LZ4LIB_API ") line = line.substr(11); - if (line.substr(0,12) == "LZ4FLIB_API ") line = line.substr(12); - spos = line.find("/*"); - epos = line.find("*/"); - if (spos!=string::npos && epos!=string::npos) { - sout << line.substr(0, spos); - sout << "" << line.substr(spos) << "" << endl; - } else { - // fprintf(stderr, "lines=%s\n", line.c_str()); - sout << line << endl; - } -} - - -int main(int argc, char *argv[]) { - char exclam; - int linenum, chapter = 1; - vector input, lines, comments, chapters; - string line, version; - size_t spos, l; - stringstream sout; - ifstream istream; - ofstream ostream; - - if (argc < 4) { - cout << "usage: " << argv[0] << " [lz4_version] [input_file] [output_html]" << endl; - return 1; - } - - version = string(argv[1]) + " Manual"; - - istream.open(argv[2], ifstream::in); - if (!istream.is_open()) { - cout << "Error opening file " << argv[2] << endl; - return 1; - } - - ostream.open(argv[3], ifstream::out); - if (!ostream.is_open()) { - cout << "Error opening file " << argv[3] << endl; - return 1; - } - - while (getline(istream, line)) { - input.push_back(line); - } - - for (linenum=0; (size_t)linenum < input.size(); linenum++) { - line = input[linenum]; - - /* typedefs are detected and included even if uncommented */ - if (line.substr(0,7) == "typedef" && line.find("{")!=string::npos) { - lines = get_lines(input, linenum, "}"); - sout << "
";
-            for (l=0; l

" << endl; - continue; - } - - /* comments of type /**< and /*!< are detected and only function declaration is highlighted (bold) */ - if ((line.find("/**<")!=string::npos || line.find("/*!<")!=string::npos) && line.find("*/")!=string::npos) { - sout << "
";
-            print_line(sout, line);
-            sout << "

" << endl; - continue; - } - - spos = line.find("/**="); - if (spos==string::npos) { - spos = line.find("/*!"); - if (spos==string::npos) - spos = line.find("/**"); - if (spos==string::npos) - spos = line.find("/*-"); - if (spos==string::npos) - spos = line.find("/*="); - if (spos==string::npos) - continue; - exclam = line[spos+2]; - } - else exclam = '='; - - comments = get_lines(input, linenum, "*/"); - if (!comments.empty()) comments[0] = line.substr(spos+3); - if (!comments.empty()) comments[comments.size()-1] = comments[comments.size()-1].substr(0, comments[comments.size()-1].find("*/")); - for (l=0; l"; - for (l=0; l

"; - for (l=0; l
" << endl << endl; - } else if (exclam == '=') { /* comments of type /*= and /**= mean: use a

header and show also all functions until first empty line */ - trim(comments[0], " "); - sout << "

" << comments[0] << "

";
-            for (l=1; l
";
-            lines = get_lines(input, ++linenum, "");
-            for (l=0; l
" << endl; - } else { /* comments of type /** and /*- mean: this is a comment; use a

header for the first line */ - if (comments.empty()) continue; - - trim(comments[0], " "); - sout << "

" << comments[0] << "

";
-            chapters.push_back(comments[0]);
-            chapter++;
-
-            for (l=1; l 1)
-                sout << "
" << endl << endl; - else - sout << "
" << endl << endl; - } - } - - ostream << "\n\n\n" << version << "\n\n" << endl; - ostream << "

" << version << "

\n"; - - ostream << "
\n

Contents

\n
    \n"; - for (size_t i=0; i" << chapters[i].c_str() << "\n"; - ostream << "
\n
\n"; - - ostream << sout.str(); - ostream << "" << endl << "" << endl; - - return 0; -} \ No newline at end of file diff --git a/src/lz4/doc/lz4_Block_format.md b/src/lz4/doc/lz4_Block_format.md deleted file mode 100644 index 4e39b41f56..0000000000 --- a/src/lz4/doc/lz4_Block_format.md +++ /dev/null @@ -1,135 +0,0 @@ -LZ4 Block Format Description -============================ -Last revised: 2015-05-07. -Author : Yann Collet - - -This specification is intended for developers -willing to produce LZ4-compatible compressed data blocks -using any programming language. - -LZ4 is an LZ77-type compressor with a fixed, byte-oriented encoding. -There is no entropy encoder back-end nor framing layer. -The latter is assumed to be handled by other parts of the system (see [LZ4 Frame format]). -This design is assumed to favor simplicity and speed. -It helps later on for optimizations, compactness, and features. - -This document describes only the block format, -not how the compressor nor decompressor actually work. -The correctness of the decompressor should not depend -on implementation details of the compressor, and vice versa. - -[LZ4 Frame format]: lz4_Frame_format.md - - - -Compressed block format ------------------------ -An LZ4 compressed block is composed of sequences. -A sequence is a suite of literals (not-compressed bytes), -followed by a match copy. - -Each sequence starts with a token. -The token is a one byte value, separated into two 4-bits fields. -Therefore each field ranges from 0 to 15. - - -The first field uses the 4 high-bits of the token. -It provides the length of literals to follow. - -If the field value is 0, then there is no literal. -If it is 15, then we need to add some more bytes to indicate the full length. -Each additional byte then represent a value from 0 to 255, -which is added to the previous value to produce a total length. -When the byte value is 255, another byte is output. -There can be any number of bytes following the token. There is no "size limit". -(Side note : this is why a not-compressible input block is expanded by 0.4%). - -Example 1 : A length of 48 will be represented as : - - - 15 : value for the 4-bits High field - - 33 : (=48-15) remaining length to reach 48 - -Example 2 : A length of 280 will be represented as : - - - 15 : value for the 4-bits High field - - 255 : following byte is maxed, since 280-15 >= 255 - - 10 : (=280 - 15 - 255) ) remaining length to reach 280 - -Example 3 : A length of 15 will be represented as : - - - 15 : value for the 4-bits High field - - 0 : (=15-15) yes, the zero must be output - -Following the token and optional length bytes, are the literals themselves. -They are exactly as numerous as previously decoded (length of literals). -It's possible that there are zero literal. - - -Following the literals is the match copy operation. - -It starts by the offset. -This is a 2 bytes value, in little endian format -(the 1st byte is the "low" byte, the 2nd one is the "high" byte). - -The offset represents the position of the match to be copied from. -1 means "current position - 1 byte". -The maximum offset value is 65535, 65536 cannot be coded. -Note that 0 is an invalid value, not used. - -Then we need to extract the match length. -For this, we use the second token field, the low 4-bits. -Value, obviously, ranges from 0 to 15. -However here, 0 means that the copy operation will be minimal. -The minimum length of a match, called minmatch, is 4. -As a consequence, a 0 value means 4 bytes, and a value of 15 means 19+ bytes. -Similar to literal length, on reaching the highest possible value (15), -we output additional bytes, one at a time, with values ranging from 0 to 255. -They are added to total to provide the final match length. -A 255 value means there is another byte to read and add. -There is no limit to the number of optional bytes that can be output this way. -(This points towards a maximum achievable compression ratio of about 250). - -Decoding the matchlength reaches the end of current sequence. -Next byte will be the start of another sequence. -But before moving to next sequence, -it's time to use the decoded match position and length. -The decoder copies matchlength bytes from match position to current position. - -In some cases, matchlength is larger than offset. -Therefore, match pos + match length > current pos, -which means that later bytes to copy are not yet decoded. -This is called an "overlap match", and must be handled with special care. -The most common case is an offset of 1, -meaning the last byte is repeated matchlength times. - - -Parsing restrictions ------------------------ -There are specific parsing rules to respect in order to remain compatible -with assumptions made by the decoder : - -1. The last 5 bytes are always literals -2. The last match must start at least 12 bytes before end of block. - Consequently, a block with less than 13 bytes cannot be compressed. - -These rules are in place to ensure that the decoder -will never read beyond the input buffer, nor write beyond the output buffer. - -Note that the last sequence is also incomplete, -and stops right after literals. - - -Additional notes ------------------------ -There is no assumption nor limits to the way the compressor -searches and selects matches within the source data block. -It could be a fast scan, a multi-probe, a full search using BST, -standard hash chains or MMC, well whatever. - -Advanced parsing strategies can also be implemented, such as lazy match, -or full optimal parsing. - -All these trade-off offer distinctive speed/memory/compression advantages. -Whatever the method used by the compressor, its result will be decodable -by any LZ4 decoder if it follows the format specification described above. diff --git a/src/lz4/doc/lz4_Frame_format.md b/src/lz4/doc/lz4_Frame_format.md deleted file mode 100644 index 77454b2d4c..0000000000 --- a/src/lz4/doc/lz4_Frame_format.md +++ /dev/null @@ -1,411 +0,0 @@ -LZ4 Frame Format Description -============================ - -### Notices - -Copyright (c) 2013-2015 Yann Collet - -Permission is granted to copy and distribute this document -for any purpose and without charge, -including translations into other languages -and incorporation into compilations, -provided that the copyright notice and this notice are preserved, -and that any substantive changes or deletions from the original -are clearly marked. -Distribution of this document is unlimited. - -### Version - -1.6.0 (08/08/2017) - - -Introduction ------------- - -The purpose of this document is to define a lossless compressed data format, -that is independent of CPU type, operating system, -file system and character set, suitable for -File compression, Pipe and streaming compression -using the [LZ4 algorithm](http://www.lz4.org). - -The data can be produced or consumed, -even for an arbitrarily long sequentially presented input data stream, -using only an a priori bounded amount of intermediate storage, -and hence can be used in data communications. -The format uses the LZ4 compression method, -and optional [xxHash-32 checksum method](https://github.com/Cyan4973/xxHash), -for detection of data corruption. - -The data format defined by this specification -does not attempt to allow random access to compressed data. - -This specification is intended for use by implementers of software -to compress data into LZ4 format and/or decompress data from LZ4 format. -The text of the specification assumes a basic background in programming -at the level of bits and other primitive data representations. - -Unless otherwise indicated below, -a compliant compressor must produce data sets -that conform to the specifications presented here. -It doesn’t need to support all options though. - -A compliant decompressor must be able to decompress -at least one working set of parameters -that conforms to the specifications presented here. -It may also ignore checksums. -Whenever it does not support a specific parameter within the compressed stream, -it must produce a non-ambiguous error code -and associated error message explaining which parameter is unsupported. - - -General Structure of LZ4 Frame format -------------------------------------- - -| MagicNb | F. Descriptor | Block | (...) | EndMark | C. Checksum | -|:-------:|:-------------:| ----- | ----- | ------- | ----------- | -| 4 bytes | 3-15 bytes | | | 4 bytes | 0-4 bytes | - -__Magic Number__ - -4 Bytes, Little endian format. -Value : 0x184D2204 - -__Frame Descriptor__ - -3 to 15 Bytes, to be detailed in the next part. -Most important part of the spec. - -__Data Blocks__ - -To be detailed later on. -That’s where compressed data is stored. - -__EndMark__ - -The flow of blocks ends when the last data block has a size of “0â€. -The size is expressed as a 32-bits value. - -__Content Checksum__ - -Content Checksum verify that the full content has been decoded correctly. -The content checksum is the result -of [xxh32() hash function](https://github.com/Cyan4973/xxHash) -digesting the original (decoded) data as input, and a seed of zero. -Content checksum is only present when its associated flag -is set in the frame descriptor. -Content Checksum validates the result, -that all blocks were fully transmitted in the correct order and without error, -and also that the encoding/decoding process itself generated no distortion. -Its usage is recommended. - -__Frame Concatenation__ - -In some circumstances, it may be preferable to append multiple frames, -for example in order to add new data to an existing compressed file -without re-framing it. - -In such case, each frame has its own set of descriptor flags. -Each frame is considered independent. -The only relation between frames is their sequential order. - -The ability to decode multiple concatenated frames -within a single stream or file -is left outside of this specification. -As an example, the reference lz4 command line utility behavior is -to decode all concatenated frames in their sequential order. - - -Frame Descriptor ----------------- - -| FLG | BD | (Content Size) | (Dictionary ID) | HC | -| ------- | ------- |:--------------:|:---------------:| ------- | -| 1 byte | 1 byte | 0 - 8 bytes | 0 - 4 bytes | 1 byte | - -The descriptor uses a minimum of 3 bytes, -and up to 15 bytes depending on optional parameters. - -__FLG byte__ - -| BitNb | 7-6 | 5 | 4 | 3 | 2 | 1 | 0 | -| ------- |-------|-------|----------|------|----------|----------|------| -|FieldName|Version|B.Indep|B.Checksum|C.Size|C.Checksum|*Reserved*|DictID| - - -__BD byte__ - -| BitNb | 7 | 6-5-4 | 3-2-1-0 | -| ------- | -------- | ------------- | -------- | -|FieldName|*Reserved*| Block MaxSize |*Reserved*| - -In the tables, bit 7 is highest bit, while bit 0 is lowest. - -__Version Number__ - -2-bits field, must be set to `01`. -Any other value cannot be decoded by this version of the specification. -Other version numbers will use different flag layouts. - -__Block Independence flag__ - -If this flag is set to “1â€, blocks are independent. -If this flag is set to “0â€, each block depends on previous ones -(up to LZ4 window size, which is 64 KB). -In such case, it’s necessary to decode all blocks in sequence. - -Block dependency improves compression ratio, especially for small blocks. -On the other hand, it makes random access or multi-threaded decoding impossible. - -__Block checksum flag__ - -If this flag is set, each data block will be followed by a 4-bytes checksum, -calculated by using the xxHash-32 algorithm on the raw (compressed) data block. -The intention is to detect data corruption (storage or transmission errors) -immediately, before decoding. -Block checksum usage is optional. - -__Content Size flag__ - -If this flag is set, the uncompressed size of data included within the frame -will be present as an 8 bytes unsigned little endian value, after the flags. -Content Size usage is optional. - -__Content checksum flag__ - -If this flag is set, a 32-bits content checksum will be appended -after the EndMark. - -__Dictionary ID flag__ - -If this flag is set, a 4-bytes Dict-ID field will be present, -after the descriptor flags and the Content Size. - -__Block Maximum Size__ - -This information is useful to help the decoder allocate memory. -Size here refers to the original (uncompressed) data size. -Block Maximum Size is one value among the following table : - -| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | -| --- | --- | --- | --- | ----- | ------ | ---- | ---- | -| N/A | N/A | N/A | N/A | 64 KB | 256 KB | 1 MB | 4 MB | - -The decoder may refuse to allocate block sizes above any system-specific size. -Unused values may be used in a future revision of the spec. -A decoder conformant with the current version of the spec -is only able to decode block sizes defined in this spec. - -__Reserved bits__ - -Value of reserved bits **must** be 0 (zero). -Reserved bit might be used in a future version of the specification, -typically enabling new optional features. -When this happens, a decoder respecting the current specification version -shall not be able to decode such a frame. - -__Content Size__ - -This is the original (uncompressed) size. -This information is optional, and only present if the associated flag is set. -Content size is provided using unsigned 8 Bytes, for a maximum of 16 HexaBytes. -Format is Little endian. -This value is informational, typically for display or memory allocation. -It can be skipped by a decoder, or used to validate content correctness. - -__Dictionary ID__ - -Dict-ID is only present if the associated flag is set. -It's an unsigned 32-bits value, stored using little-endian convention. -A dictionary is useful to compress short input sequences. -The compressor can take advantage of the dictionary context -to encode the input in a more compact manner. -It works as a kind of “known prefix†which is used by -both the compressor and the decompressor to “warm-up†reference tables. - -The decompressor can use Dict-ID identifier to determine -which dictionary must be used to correctly decode data. -The compressor and the decompressor must use exactly the same dictionary. -It's presumed that the 32-bits dictID uniquely identifies a dictionary. - -Within a single frame, a single dictionary can be defined. -When the frame descriptor defines independent blocks, -each block will be initialized with the same dictionary. -If the frame descriptor defines linked blocks, -the dictionary will only be used once, at the beginning of the frame. - -__Header Checksum__ - -One-byte checksum of combined descriptor fields, including optional ones. -The value is the second byte of `xxh32()` : ` (xxh32()>>8) & 0xFF ` -using zero as a seed, and the full Frame Descriptor as an input -(including optional fields when they are present). -A wrong checksum indicates an error in the descriptor. -Header checksum is informational and can be skipped. - - -Data Blocks ------------ - -| Block Size | data | (Block Checksum) | -|:----------:| ------ |:----------------:| -| 4 bytes | | 0 - 4 bytes | - - -__Block Size__ - -This field uses 4-bytes, format is little-endian. - -The highest bit is “1†if data in the block is uncompressed. - -The highest bit is “0†if data in the block is compressed by LZ4. - -All other bits give the size, in bytes, of the following data block -(the size does not include the block checksum if present). - -Block Size shall never be larger than Block Maximum Size. -Such a thing could happen for incompressible source data. -In such case, such a data block shall be passed in uncompressed format. - -__Data__ - -Where the actual data to decode stands. -It might be compressed or not, depending on previous field indications. -Uncompressed size of Data can be any size, up to “block maximum sizeâ€. -Note that data block is not necessarily full : -an arbitrary “flush†may happen anytime. Any block can be “partially filledâ€. - -__Block checksum__ - -Only present if the associated flag is set. -This is a 4-bytes checksum value, in little endian format, -calculated by using the xxHash-32 algorithm on the raw (undecoded) data block, -and a seed of zero. -The intention is to detect data corruption (storage or transmission errors) -before decoding. - -Block checksum is cumulative with Content checksum. - - -Skippable Frames ----------------- - -| Magic Number | Frame Size | User Data | -|:------------:|:----------:| --------- | -| 4 bytes | 4 bytes | | - -Skippable frames allow the integration of user-defined data -into a flow of concatenated frames. -Its design is pretty straightforward, -with the sole objective to allow the decoder to quickly skip -over user-defined data and continue decoding. - -For the purpose of facilitating identification, -it is discouraged to start a flow of concatenated frames with a skippable frame. -If there is a need to start such a flow with some user data -encapsulated into a skippable frame, -it’s recommended to start with a zero-byte LZ4 frame -followed by a skippable frame. -This will make it easier for file type identifiers. - - -__Magic Number__ - -4 Bytes, Little endian format. -Value : 0x184D2A5X, which means any value from 0x184D2A50 to 0x184D2A5F. -All 16 values are valid to identify a skippable frame. - -__Frame Size__ - -This is the size, in bytes, of the following User Data -(without including the magic number nor the size field itself). -4 Bytes, Little endian format, unsigned 32-bits. -This means User Data can’t be bigger than (2^32-1) Bytes. - -__User Data__ - -User Data can be anything. Data will just be skipped by the decoder. - - -Legacy frame ------------- - -The Legacy frame format was defined into the initial versions of “LZ4Demoâ€. -Newer compressors should not use this format anymore, as it is too restrictive. - -Main characteristics of the legacy format : - -- Fixed block size : 8 MB. -- All blocks must be completely filled, except the last one. -- All blocks are always compressed, even when compression is detrimental. -- The last block is detected either because - it is followed by the “EOF†(End of File) mark, - or because it is followed by a known Frame Magic Number. -- No checksum -- Convention is Little endian - -| MagicNb | B.CSize | CData | B.CSize | CData | (...) | EndMark | -| ------- | ------- | ----- | ------- | ----- | ------- | ------- | -| 4 bytes | 4 bytes | CSize | 4 bytes | CSize | x times | EOF | - - -__Magic Number__ - -4 Bytes, Little endian format. -Value : 0x184C2102 - -__Block Compressed Size__ - -This is the size, in bytes, of the following compressed data block. -4 Bytes, Little endian format. - -__Data__ - -Where the actual compressed data stands. -Data is always compressed, even when compression is detrimental. - -__EndMark__ - -End of legacy frame is implicit only. -It must be followed by a standard EOF (End Of File) signal, -wether it is a file or a stream. - -Alternatively, if the frame is followed by a valid Frame Magic Number, -it is considered completed. -This policy makes it possible to concatenate legacy frames. - -Any other value will be interpreted as a block size, -and trigger an error if it does not fit within acceptable range. - - -Version changes ---------------- - -1.6.0 : restored Dictionary ID field in Frame header - -1.5.1 : changed document format to MarkDown - -1.5 : removed Dictionary ID from specification - -1.4.1 : changed wording from “stream†to “frame†- -1.4 : added skippable streams, re-added stream checksum - -1.3 : modified header checksum - -1.2 : reduced choice of “block sizeâ€, to postpone decision on “dynamic size of BlockSize Fieldâ€. - -1.1 : optional fields are now part of the descriptor - -1.0 : changed “block size†specification, adding a compressed/uncompressed flag - -0.9 : reduced scale of “block maximum size†table - -0.8 : removed : high compression flag - -0.7 : removed : stream checksum - -0.6 : settled : stream size uses 8 bytes, endian convention is little endian - -0.5: added copyright notice - -0.4 : changed format to Google Doc compatible OpenDocument diff --git a/src/lz4/doc/lz4_manual.html b/src/lz4/doc/lz4_manual.html deleted file mode 100644 index 9ab1984c36..0000000000 --- a/src/lz4/doc/lz4_manual.html +++ /dev/null @@ -1,325 +0,0 @@ - - - -1.8.0 Manual - - -

1.8.0 Manual

-
-

Contents

-
    -
  1. Introduction
  2. -
  3. Version
  4. -
  5. Tuning parameter
  6. -
  7. Simple Functions
  8. -
  9. Advanced Functions
  10. -
  11. Streaming Compression Functions
  12. -
  13. Streaming Decompression Functions
  14. -
  15. Private definitions
  16. -
  17. Obsolete Functions
  18. -
-
-

Introduction

-  LZ4 is lossless compression algorithm, providing compression speed at 400 MB/s per core,
-  scalable with multi-cores CPU. It features an extremely fast decoder, with speed in
-  multiple GB/s per core, typically reaching RAM speed limits on multi-core systems.
-
-  The LZ4 compression library provides in-memory compression and decompression functions.
-  Compression can be done in:
-    - a single step (described as Simple Functions)
-    - a single step, reusing a context (described in Advanced Functions)
-    - unbounded multiple steps (described as Streaming compression)
-
-  lz4.h provides block compression functions. It gives full buffer control to user.
-  Decompressing an lz4-compressed block also requires metadata (such as compressed size).
-  Each application is free to encode such metadata in whichever way it wants.
-
-  An additional format, called LZ4 frame specification (doc/lz4_Frame_format.md),
-  take care of encoding standard metadata alongside LZ4-compressed blocks.
-  If your application requires interoperability, it's recommended to use it.
-  A library is provided to take care of it, see lz4frame.h.
-
- -

Version


-
-
int LZ4_versionNumber (void);  /**< library version number; to be used when checking dll version */
-

-
const char* LZ4_versionString (void);   /**< library version string; to be used when checking dll version */
-

-

Tuning parameter


-
-
#ifndef LZ4_MEMORY_USAGE
-# define LZ4_MEMORY_USAGE 14
-#endif
-

Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.) - Increasing memory usage improves compression ratio - Reduced memory usage can improve speed, due to cache effect - Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache - -


- -

Simple Functions


-
-
int LZ4_compress_default(const char* source, char* dest, int sourceSize, int maxDestSize);
-

Compresses 'sourceSize' bytes from buffer 'source' - into already allocated 'dest' buffer of size 'maxDestSize'. - Compression is guaranteed to succeed if 'maxDestSize' >= LZ4_compressBound(sourceSize). - It also runs faster, so it's a recommended setting. - If the function cannot compress 'source' into a more limited 'dest' budget, - compression stops *immediately*, and the function result is zero. - As a consequence, 'dest' content is not valid. - This function never writes outside 'dest' buffer, nor read outside 'source' buffer. - sourceSize : Max supported value is LZ4_MAX_INPUT_VALUE - maxDestSize : full or partial size of buffer 'dest' (which must be already allocated) - return : the number of bytes written into buffer 'dest' (necessarily <= maxOutputSize) - or 0 if compression fails -


- -
int LZ4_decompress_safe (const char* source, char* dest, int compressedSize, int maxDecompressedSize);
-

compressedSize : is the precise full size of the compressed block. - maxDecompressedSize : is the size of destination buffer, which must be already allocated. - return : the number of bytes decompressed into destination buffer (necessarily <= maxDecompressedSize) - If destination buffer is not large enough, decoding will stop and output an error code (<0). - If the source stream is detected malformed, the function will stop decoding and return a negative result. - This function is protected against buffer overflow exploits, including malicious data packets. - It never writes outside output buffer, nor reads outside input buffer. -


- -

Advanced Functions


-
-
int LZ4_compressBound(int inputSize);
-

Provides the maximum size that LZ4 compression may output in a "worst case" scenario (input data not compressible) - This function is primarily useful for memory allocation purposes (destination buffer size). - Macro LZ4_COMPRESSBOUND() is also provided for compilation-time evaluation (stack memory allocation for example). - Note that LZ4_compress_default() compress faster when dest buffer size is >= LZ4_compressBound(srcSize) - inputSize : max supported value is LZ4_MAX_INPUT_SIZE - return : maximum output size in a "worst case" scenario - or 0, if input size is too large ( > LZ4_MAX_INPUT_SIZE) -


- -
int LZ4_compress_fast (const char* source, char* dest, int sourceSize, int maxDestSize, int acceleration);
-

Same as LZ4_compress_default(), but allows to select an "acceleration" factor. - The larger the acceleration value, the faster the algorithm, but also the lesser the compression. - It's a trade-off. It can be fine tuned, with each successive value providing roughly +~3% to speed. - An acceleration value of "1" is the same as regular LZ4_compress_default() - Values <= 0 will be replaced by ACCELERATION_DEFAULT (see lz4.c), which is 1. -


- -
int LZ4_sizeofState(void);
-int LZ4_compress_fast_extState (void* state, const char* source, char* dest, int inputSize, int maxDestSize, int acceleration);
-

Same compression function, just using an externally allocated memory space to store compression state. - Use LZ4_sizeofState() to know how much memory must be allocated, - and allocate it on 8-bytes boundaries (using malloc() typically). - Then, provide it as 'void* state' to compression function. -


- -
int LZ4_compress_destSize (const char* source, char* dest, int* sourceSizePtr, int targetDestSize);
-

Reverse the logic, by compressing as much data as possible from 'source' buffer - into already allocated buffer 'dest' of size 'targetDestSize'. - This function either compresses the entire 'source' content into 'dest' if it's large enough, - or fill 'dest' buffer completely with as much data as possible from 'source'. - *sourceSizePtr : will be modified to indicate how many bytes where read from 'source' to fill 'dest'. - New value is necessarily <= old value. - return : Nb bytes written into 'dest' (necessarily <= targetDestSize) - or 0 if compression fails -


- -
int LZ4_decompress_fast (const char* source, char* dest, int originalSize);
-

originalSize : is the original and therefore uncompressed size - return : the number of bytes read from the source buffer (in other words, the compressed size) - If the source stream is detected malformed, the function will stop decoding and return a negative result. - Destination buffer must be already allocated. Its size must be a minimum of 'originalSize' bytes. - note : This function fully respect memory boundaries for properly formed compressed data. - It is a bit faster than LZ4_decompress_safe(). - However, it does not provide any protection against intentionally modified data stream (malicious input). - Use this function in trusted environment only (data to decode comes from a trusted source). -


- -
int LZ4_decompress_safe_partial (const char* source, char* dest, int compressedSize, int targetOutputSize, int maxDecompressedSize);
-

This function decompress a compressed block of size 'compressedSize' at position 'source' - into destination buffer 'dest' of size 'maxDecompressedSize'. - The function tries to stop decompressing operation as soon as 'targetOutputSize' has been reached, - reducing decompression time. - return : the number of bytes decoded in the destination buffer (necessarily <= maxDecompressedSize) - Note : this number can be < 'targetOutputSize' should the compressed block to decode be smaller. - Always control how many bytes were decoded. - If the source stream is detected malformed, the function will stop decoding and return a negative result. - This function never writes outside of output buffer, and never reads outside of input buffer. It is therefore protected against malicious data packets -


- -

Streaming Compression Functions


-
-
LZ4_stream_t* LZ4_createStream(void);
-int           LZ4_freeStream (LZ4_stream_t* streamPtr);
-

LZ4_createStream() will allocate and initialize an `LZ4_stream_t` structure. - LZ4_freeStream() releases its memory. - -


- -
void LZ4_resetStream (LZ4_stream_t* streamPtr);
-

An LZ4_stream_t structure can be allocated once and re-used multiple times. - Use this function to init an allocated `LZ4_stream_t` structure and start a new compression. - -


- -
int LZ4_loadDict (LZ4_stream_t* streamPtr, const char* dictionary, int dictSize);
-

Use this function to load a static dictionary into LZ4_stream. - Any previous data will be forgotten, only 'dictionary' will remain in memory. - Loading a size of 0 is allowed. - Return : dictionary size, in bytes (necessarily <= 64 KB) - -


- -
int LZ4_compress_fast_continue (LZ4_stream_t* streamPtr, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration);
-

Compress buffer content 'src', using data from previously compressed blocks as dictionary to improve compression ratio. - Important : Previous data blocks are assumed to remain present and unmodified ! - 'dst' buffer must be already allocated. - If dstCapacity >= LZ4_compressBound(srcSize), compression is guaranteed to succeed, and runs faster. - If not, and if compressed data cannot fit into 'dst' buffer size, compression stops, and function @return==0. - After an error, the stream status is invalid, it can only be reset or freed. - -


- -
int LZ4_saveDict (LZ4_stream_t* streamPtr, char* safeBuffer, int dictSize);
-

If previously compressed data block is not guaranteed to remain available at its current memory location, - save it into a safer place (char* safeBuffer). - Note : it's not necessary to call LZ4_loadDict() after LZ4_saveDict(), dictionary is immediately usable. - @return : saved dictionary size in bytes (necessarily <= dictSize), or 0 if error. - -


- -

Streaming Decompression Functions

  Bufferless synchronous API
-
- -
LZ4_streamDecode_t* LZ4_createStreamDecode(void);
-int                 LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream);
-

creation / destruction of streaming decompression tracking structure -


- -
int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize);
-

Use this function to instruct where to find the dictionary. - Setting a size of 0 is allowed (same effect as reset). - @return : 1 if OK, 0 if error - -


- -
int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxDecompressedSize);
-int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize);
-

These decoding functions allow decompression of multiple blocks in "streaming" mode. - Previously decoded blocks *must* remain available at the memory position where they were decoded (up to 64 KB) - In the case of a ring buffers, decoding buffer must be either : - - Exactly same size as encoding buffer, with same update rule (block boundaries at same positions) - In which case, the decoding & encoding ring buffer can have any size, including very small ones ( < 64 KB). - - Larger than encoding buffer, by a minimum of maxBlockSize more bytes. - maxBlockSize is implementation dependent. It's the maximum size you intend to compress into a single block. - In which case, encoding and decoding buffers do not need to be synchronized, - and encoding ring buffer can have any size, including small ones ( < 64 KB). - - _At least_ 64 KB + 8 bytes + maxBlockSize. - In which case, encoding and decoding buffers do not need to be synchronized, - and encoding ring buffer can have any size, including larger than decoding buffer. - Whenever these conditions are not possible, save the last 64KB of decoded data into a safe buffer, - and indicate where it is saved using LZ4_setStreamDecode() -


- -
int LZ4_decompress_safe_usingDict (const char* source, char* dest, int compressedSize, int maxDecompressedSize, const char* dictStart, int dictSize);
-int LZ4_decompress_fast_usingDict (const char* source, char* dest, int originalSize, const char* dictStart, int dictSize);
-

These decoding functions work the same as - a combination of LZ4_setStreamDecode() followed by LZ4_decompress_*_continue() - They are stand-alone, and don't need an LZ4_streamDecode_t structure. - -


- -

Private definitions

- Do not use these definitions.
- They are exposed to allow static allocation of `LZ4_stream_t` and `LZ4_streamDecode_t`.
- Using these definitions will expose code to API and/or ABI break in future versions of the library.
-
- -
typedef struct {
-    uint32_t hashTable[LZ4_HASH_SIZE_U32];
-    uint32_t currentOffset;
-    uint32_t initCheck;
-    const uint8_t* dictionary;
-    uint8_t* bufferStart;   /* obsolete, used for slideInputBuffer */
-    uint32_t dictSize;
-} LZ4_stream_t_internal;
-

-
typedef struct {
-    const uint8_t* externalDict;
-    size_t extDictSize;
-    const uint8_t* prefixEnd;
-    size_t prefixSize;
-} LZ4_streamDecode_t_internal;
-

-
typedef struct {
-    unsigned int hashTable[LZ4_HASH_SIZE_U32];
-    unsigned int currentOffset;
-    unsigned int initCheck;
-    const unsigned char* dictionary;
-    unsigned char* bufferStart;   /* obsolete, used for slideInputBuffer */
-    unsigned int dictSize;
-} LZ4_stream_t_internal;
-

-
typedef struct {
-    const unsigned char* externalDict;
-    size_t extDictSize;
-    const unsigned char* prefixEnd;
-    size_t prefixSize;
-} LZ4_streamDecode_t_internal;
-

-
#define LZ4_STREAMSIZE_U64 ((1 << (LZ4_MEMORY_USAGE-3)) + 4)
-#define LZ4_STREAMSIZE     (LZ4_STREAMSIZE_U64 * sizeof(unsigned long long))
-union LZ4_stream_u {
-    unsigned long long table[LZ4_STREAMSIZE_U64];
-    LZ4_stream_t_internal internal_donotuse;
-} ;  /* previously typedef'd to LZ4_stream_t */
-

information structure to track an LZ4 stream. - init this structure before first use. - note : only use in association with static linking ! - this definition is not API/ABI safe, - it may change in a future version ! - -


- -
#define LZ4_STREAMDECODESIZE_U64  4
-#define LZ4_STREAMDECODESIZE     (LZ4_STREAMDECODESIZE_U64 * sizeof(unsigned long long))
-union LZ4_streamDecode_u {
-    unsigned long long table[LZ4_STREAMDECODESIZE_U64];
-    LZ4_streamDecode_t_internal internal_donotuse;
-} ;   /* previously typedef'd to LZ4_streamDecode_t */
-

information structure to track an LZ4 stream during decompression. - init this structure using LZ4_setStreamDecode (or memset()) before first use - note : only use in association with static linking ! - this definition is not API/ABI safe, - and may change in a future version ! - -


- -

Obsolete Functions


-
-
#ifdef LZ4_DISABLE_DEPRECATE_WARNINGS
-#  define LZ4_DEPRECATED(message)   /* disable deprecation warnings */
-#else
-#  define LZ4_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
-#  if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */
-#    define LZ4_DEPRECATED(message) [[deprecated(message)]]
-#  elif (LZ4_GCC_VERSION >= 405) || defined(__clang__)
-#    define LZ4_DEPRECATED(message) __attribute__((deprecated(message)))
-#  elif (LZ4_GCC_VERSION >= 301)
-#    define LZ4_DEPRECATED(message) __attribute__((deprecated))
-#  elif defined(_MSC_VER)
-#    define LZ4_DEPRECATED(message) __declspec(deprecated(message))
-#  else
-#    pragma message("WARNING: You need to implement LZ4_DEPRECATED for this compiler")
-#    define LZ4_DEPRECATED(message)
-#  endif
-#endif /* LZ4_DISABLE_DEPRECATE_WARNINGS */
-

Should deprecation warnings be a problem, - it is generally possible to disable them, - typically with -Wno-deprecated-declarations for gcc - or _CRT_SECURE_NO_WARNINGS in Visual. - Otherwise, it's also possible to define LZ4_DISABLE_DEPRECATE_WARNINGS -


- - - diff --git a/src/lz4/doc/lz4frame_manual.html b/src/lz4/doc/lz4frame_manual.html deleted file mode 100644 index 7529f6ea36..0000000000 --- a/src/lz4/doc/lz4frame_manual.html +++ /dev/null @@ -1,277 +0,0 @@ - - - -1.8.0 Manual - - -

1.8.0 Manual

-
-

Contents

-
    -
  1. Introduction
  2. -
  3. Compiler specifics
  4. -
  5. Error management
  6. -
  7. Frame compression types
  8. -
  9. Simple compression function
  10. -
  11. Advanced compression functions
  12. -
  13. Resource Management
  14. -
  15. Compression
  16. -
  17. Decompression functions
  18. -
  19. Streaming decompression functions
  20. -
-
-

Introduction

-  lz4frame.h implements LZ4 frame specification (doc/lz4_Frame_format.md).
-  lz4frame.h provides frame compression functions that take care
-  of encoding standard metadata alongside LZ4-compressed blocks.
-
- -

Compiler specifics


-
-

Error management


-
-
unsigned    LZ4F_isError(LZ4F_errorCode_t code);   /**< tells if a `LZ4F_errorCode_t` function result is an error code */
-

-
const char* LZ4F_getErrorName(LZ4F_errorCode_t code);   /**< return error code string; useful for debugging */
-

-

Frame compression types


-
-
typedef enum {
-    LZ4F_default=0,
-    LZ4F_max64KB=4,
-    LZ4F_max256KB=5,
-    LZ4F_max1MB=6,
-    LZ4F_max4MB=7
-    LZ4F_OBSOLETE_ENUM(max64KB)
-    LZ4F_OBSOLETE_ENUM(max256KB)
-    LZ4F_OBSOLETE_ENUM(max1MB)
-    LZ4F_OBSOLETE_ENUM(max4MB)
-} LZ4F_blockSizeID_t;
-

-
typedef enum {
-    LZ4F_blockLinked=0,
-    LZ4F_blockIndependent
-    LZ4F_OBSOLETE_ENUM(blockLinked)
-    LZ4F_OBSOLETE_ENUM(blockIndependent)
-} LZ4F_blockMode_t;
-

-
typedef enum {
-    LZ4F_noContentChecksum=0,
-    LZ4F_contentChecksumEnabled
-    LZ4F_OBSOLETE_ENUM(noContentChecksum)
-    LZ4F_OBSOLETE_ENUM(contentChecksumEnabled)
-} LZ4F_contentChecksum_t;
-

-
typedef enum {
-    LZ4F_noBlockChecksum=0,
-    LZ4F_blockChecksumEnabled
-} LZ4F_blockChecksum_t;
-

-
typedef enum {
-    LZ4F_frame=0,
-    LZ4F_skippableFrame
-    LZ4F_OBSOLETE_ENUM(skippableFrame)
-} LZ4F_frameType_t;
-

-
typedef struct {
-  LZ4F_blockSizeID_t     blockSizeID;          /* max64KB, max256KB, max1MB, max4MB ; 0 == default */
-  LZ4F_blockMode_t       blockMode;            /* LZ4F_blockLinked, LZ4F_blockIndependent ; 0 == default */
-  LZ4F_contentChecksum_t contentChecksumFlag;  /* if enabled, frame is terminated with a 32-bits checksum of decompressed data ; 0 == disabled (default)  */
-  LZ4F_frameType_t       frameType;            /* read-only field : LZ4F_frame or LZ4F_skippableFrame */
-  unsigned long long     contentSize;          /* Size of uncompressed content ; 0 == unknown */
-  unsigned               dictID;               /* Dictionary ID, sent by the compressor to help decoder select the correct dictionary; 0 == no dictID provided */
-  LZ4F_blockChecksum_t   blockChecksumFlag;    /* if enabled, each block is followed by a checksum of block's compressed data ; 0 == disabled (default)  */
-} LZ4F_frameInfo_t;
-

makes it possible to set or read frame parameters. - It's not required to set all fields, as long as the structure was initially memset() to zero. - For all fields, 0 sets it to default value -


- -
typedef struct {
-  LZ4F_frameInfo_t frameInfo;
-  int      compressionLevel;       /* 0 == default (fast mode); values above LZ4HC_CLEVEL_MAX count as LZ4HC_CLEVEL_MAX; values below 0 trigger "fast acceleration", proportional to value */
-  unsigned autoFlush;              /* 1 == always flush, to reduce usage of internal buffers */
-  unsigned reserved[4];            /* must be zero for forward compatibility */
-} LZ4F_preferences_t;
-

makes it possible to supply detailed compression parameters to the stream interface. - It's not required to set all fields, as long as the structure was initially memset() to zero. - All reserved fields must be set to zero. -


- -

Simple compression function


-
-
size_t LZ4F_compressFrameBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr);
-

Returns the maximum possible size of a frame compressed with LZ4F_compressFrame() given srcSize content and preferences. - Note : this result is only usable with LZ4F_compressFrame(), not with multi-segments compression. - -


- -
size_t LZ4F_compressFrame(void* dstBuffer, size_t dstCapacity,
-                                const void* srcBuffer, size_t srcSize,
-                                const LZ4F_preferences_t* preferencesPtr);
-

Compress an entire srcBuffer into a valid LZ4 frame. - dstCapacity MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr). - The LZ4F_preferences_t structure is optional : you can provide NULL as argument. All preferences will be set to default. - @return : number of bytes written into dstBuffer. - or an error code if it fails (can be tested using LZ4F_isError()) - -


- -

Advanced compression functions


-
-
typedef struct {
-  unsigned stableSrc;    /* 1 == src content will remain present on future calls to LZ4F_compress(); skip copying src content within tmp buffer */
-  unsigned reserved[3];
-} LZ4F_compressOptions_t;
-

-

Resource Management


-
-
LZ4F_errorCode_t LZ4F_createCompressionContext(LZ4F_cctx** cctxPtr, unsigned version);
-LZ4F_errorCode_t LZ4F_freeCompressionContext(LZ4F_cctx* cctx);
-

The first thing to do is to create a compressionContext object, which will be used in all compression operations. - This is achieved using LZ4F_createCompressionContext(), which takes as argument a version. - The version provided MUST be LZ4F_VERSION. It is intended to track potential version mismatch, notably when using DLL. - The function will provide a pointer to a fully allocated LZ4F_cctx object. - If @return != zero, there was an error during context creation. - Object can release its memory using LZ4F_freeCompressionContext(); - -


- -

Compression


-
-
size_t LZ4F_compressBegin(LZ4F_cctx* cctx,
-                                      void* dstBuffer, size_t dstCapacity,
-                                      const LZ4F_preferences_t* prefsPtr);
-

will write the frame header into dstBuffer. - dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes. - `prefsPtr` is optional : you can provide NULL as argument, all preferences will then be set to default. - @return : number of bytes written into dstBuffer for the header - or an error code (which can be tested using LZ4F_isError()) - -


- -
size_t LZ4F_compressBound(size_t srcSize, const LZ4F_preferences_t* prefsPtr);
-

Provides dstCapacity given a srcSize to guarantee operation success in worst case situations. - prefsPtr is optional : you can provide NULL as argument, preferences will be set to cover worst case scenario. - Result is always the same for a srcSize and prefsPtr, so it can be trusted to size reusable buffers. - When srcSize==0, LZ4F_compressBound() provides an upper bound for LZ4F_flush() and LZ4F_compressEnd() operations. - -


- -
size_t LZ4F_compressUpdate(LZ4F_cctx* cctx, void* dstBuffer, size_t dstCapacity, const void* srcBuffer, size_t srcSize, const LZ4F_compressOptions_t* cOptPtr);
-

LZ4F_compressUpdate() can be called repetitively to compress as much data as necessary. - An important rule is that dstCapacity MUST be large enough to ensure operation success even in worst case situations. - This value is provided by LZ4F_compressBound(). - If this condition is not respected, LZ4F_compress() will fail (result is an errorCode). - LZ4F_compressUpdate() doesn't guarantee error recovery. When an error occurs, compression context must be freed or resized. - `cOptPtr` is optional : NULL can be provided, in which case all options are set to default. - @return : number of bytes written into `dstBuffer` (it can be zero, meaning input data was just buffered). - or an error code if it fails (which can be tested using LZ4F_isError()) - -


- -
size_t LZ4F_flush(LZ4F_cctx* cctx, void* dstBuffer, size_t dstCapacity, const LZ4F_compressOptions_t* cOptPtr);
-

When data must be generated and sent immediately, without waiting for a block to be completely filled, - it's possible to call LZ4_flush(). It will immediately compress any data buffered within cctx. - `dstCapacity` must be large enough to ensure the operation will be successful. - `cOptPtr` is optional : it's possible to provide NULL, all options will be set to default. - @return : number of bytes written into dstBuffer (it can be zero, which means there was no data stored within cctx) - or an error code if it fails (which can be tested using LZ4F_isError()) - -


- -
size_t LZ4F_compressEnd(LZ4F_cctx* cctx, void* dstBuffer, size_t dstCapacity, const LZ4F_compressOptions_t* cOptPtr);
-

To properly finish an LZ4 frame, invoke LZ4F_compressEnd(). - It will flush whatever data remained within `cctx` (like LZ4_flush()) - and properly finalize the frame, with an endMark and a checksum. - `cOptPtr` is optional : NULL can be provided, in which case all options will be set to default. - @return : number of bytes written into dstBuffer (necessarily >= 4 (endMark), or 8 if optional frame checksum is enabled) - or an error code if it fails (which can be tested using LZ4F_isError()) - A successful call to LZ4F_compressEnd() makes `cctx` available again for another compression task. - -


- -

Decompression functions


-
-
typedef struct {
-  unsigned stableDst;    /* pledge that at least 64KB+64Bytes of previously decompressed data remain unmodifed where it was decoded. This optimization skips storage operations in tmp buffers */
-  unsigned reserved[3];  /* must be set to zero for forward compatibility */
-} LZ4F_decompressOptions_t;
-

-
LZ4F_errorCode_t LZ4F_createDecompressionContext(LZ4F_dctx** dctxPtr, unsigned version);
-LZ4F_errorCode_t LZ4F_freeDecompressionContext(LZ4F_dctx* dctx);
-

Create an LZ4F_dctx object, to track all decompression operations. - The version provided MUST be LZ4F_VERSION. - The function provides a pointer to an allocated and initialized LZ4F_dctx object. - The result is an errorCode, which can be tested using LZ4F_isError(). - dctx memory can be released using LZ4F_freeDecompressionContext(); - The result of LZ4F_freeDecompressionContext() is indicative of the current state of decompressionContext when being released. - That is, it should be == 0 if decompression has been completed fully and correctly. - -


- -

Streaming decompression functions


-
-
size_t LZ4F_getFrameInfo(LZ4F_dctx* dctx,
-                                     LZ4F_frameInfo_t* frameInfoPtr,
-                                     const void* srcBuffer, size_t* srcSizePtr);
-

This function extracts frame parameters (max blockSize, dictID, etc.). - Its usage is optional. - Extracted information is typically useful for allocation and dictionary. - This function works in 2 situations : - - At the beginning of a new frame, in which case - it will decode information from `srcBuffer`, starting the decoding process. - Input size must be large enough to successfully decode the entire frame header. - Frame header size is variable, but is guaranteed to be <= LZ4F_HEADER_SIZE_MAX bytes. - It's allowed to provide more input data than this minimum. - - After decoding has been started. - In which case, no input is read, frame parameters are extracted from dctx. - - If decoding has barely started, but not yet extracted information from header, - LZ4F_getFrameInfo() will fail. - The number of bytes consumed from srcBuffer will be updated within *srcSizePtr (necessarily <= original value). - Decompression must resume from (srcBuffer + *srcSizePtr). - @return : an hint about how many srcSize bytes LZ4F_decompress() expects for next call, - or an error code which can be tested using LZ4F_isError(). - note 1 : in case of error, dctx is not modified. Decoding operation can resume from beginning safely. - note 2 : frame parameters are *copied into* an already allocated LZ4F_frameInfo_t structure. - -


- -
size_t LZ4F_decompress(LZ4F_dctx* dctx,
-                                   void* dstBuffer, size_t* dstSizePtr,
-                                   const void* srcBuffer, size_t* srcSizePtr,
-                                   const LZ4F_decompressOptions_t* dOptPtr);
-

Call this function repetitively to regenerate compressed data from `srcBuffer`. - The function will attempt to decode up to *srcSizePtr bytes from srcBuffer, into dstBuffer of capacity *dstSizePtr. - - The number of bytes regenerated into dstBuffer is provided within *dstSizePtr (necessarily <= original value). - - The number of bytes consumed from srcBuffer is provided within *srcSizePtr (necessarily <= original value). - Number of bytes consumed can be < number of bytes provided. - It typically happens when dstBuffer is not large enough to contain all decoded data. - Unconsumed source data must be presented again in subsequent invocations. - - `dstBuffer` content is expected to be flushed between each invocation, as its content will be overwritten. - `dstBuffer` itself can be changed at will between each consecutive function invocation. - - @return : an hint of how many `srcSize` bytes LZ4F_decompress() expects for next call. - Schematically, it's the size of the current (or remaining) compressed block + header of next block. - Respecting the hint provides some small speed benefit, because it skips intermediate buffers. - This is just a hint though, it's always possible to provide any srcSize. - When a frame is fully decoded, @return will be 0 (no more data expected). - If decompression failed, @return is an error code, which can be tested using LZ4F_isError(). - - After a frame is fully decoded, dctx can be used again to decompress another frame. - After a decompression error, use LZ4F_resetDecompressionContext() before re-using dctx, to return to clean state. - -


- -
void LZ4F_resetDecompressionContext(LZ4F_dctx* dctx);   /* always successful */
-

In case of an error, the context is left in "undefined" state. - In which case, it's necessary to reset it, before re-using it. - This method can also be used to abruptly stop an unfinished decompression, - and start a new one using the same context. -


- - - diff --git a/src/lz4/examples/.gitignore b/src/lz4/examples/.gitignore deleted file mode 100644 index 5abeef6220..0000000000 --- a/src/lz4/examples/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -/Makefile.lz4* -/printVersion -/doubleBuffer -/dictionaryRandomAccess -/ringBuffer -/ringBufferHC -/lineCompress -/frameCompress -/simpleBuffer -/*.exe diff --git a/src/lz4/examples/COPYING b/src/lz4/examples/COPYING deleted file mode 100644 index d159169d10..0000000000 --- a/src/lz4/examples/COPYING +++ /dev/null @@ -1,339 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 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. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, 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 or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -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 give any other recipients of the Program a copy of this License -along with the Program. - -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 Program or any portion -of it, thus forming a work based on the Program, 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) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -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 Program, 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 Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) 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; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, 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 executable. However, as a -special exception, the source code 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. - -If distribution of executable or 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 counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program 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. - - 5. 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 Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program 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 to -this License. - - 7. 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 Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program 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 Program. - -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. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program 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. - - 9. The Free Software Foundation may publish revised and/or new versions -of the 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 Program -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 Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, 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 - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "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 PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. 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 PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), 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 Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. 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 program is free software; 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-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. diff --git a/src/lz4/examples/HCStreaming_ringBuffer.c b/src/lz4/examples/HCStreaming_ringBuffer.c deleted file mode 100644 index d49b267858..0000000000 --- a/src/lz4/examples/HCStreaming_ringBuffer.c +++ /dev/null @@ -1,229 +0,0 @@ -// LZ4 HC streaming API example : ring buffer -// Based on previous work from Takayuki Matsuoka - - -/************************************** - * Compiler Options - **************************************/ -#ifdef _MSC_VER /* Visual Studio */ -# define _CRT_SECURE_NO_WARNINGS /* for MSVC */ -# define snprintf sprintf_s -#endif - -#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) -#ifdef __GNUC__ -# pragma GCC diagnostic ignored "-Wmissing-braces" /* GCC bug 53119 : doesn't accept { 0 } as initializer (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53119) */ -#endif - - -/************************************** - * Includes - **************************************/ -#include "lz4hc.h" -#include "lz4.h" - -#include -#include -#include -#include - -enum { - MESSAGE_MAX_BYTES = 1024, - RING_BUFFER_BYTES = 1024 * 8 + MESSAGE_MAX_BYTES, - DEC_BUFFER_BYTES = RING_BUFFER_BYTES + MESSAGE_MAX_BYTES // Intentionally larger to test unsynchronized ring buffers -}; - - -size_t write_int32(FILE* fp, int32_t i) { - return fwrite(&i, sizeof(i), 1, fp); -} - -size_t write_bin(FILE* fp, const void* array, int arrayBytes) { - return fwrite(array, 1, arrayBytes, fp); -} - -size_t read_int32(FILE* fp, int32_t* i) { - return fread(i, sizeof(*i), 1, fp); -} - -size_t read_bin(FILE* fp, void* array, int arrayBytes) { - return fread(array, 1, arrayBytes, fp); -} - - -void test_compress(FILE* outFp, FILE* inpFp) -{ - LZ4_streamHC_t lz4Stream_body = { 0 }; - LZ4_streamHC_t* lz4Stream = &lz4Stream_body; - - static char inpBuf[RING_BUFFER_BYTES]; - int inpOffset = 0; - - for(;;) { - // Read random length ([1,MESSAGE_MAX_BYTES]) data to the ring buffer. - char* const inpPtr = &inpBuf[inpOffset]; - const int randomLength = (rand() % MESSAGE_MAX_BYTES) + 1; - const int inpBytes = (int) read_bin(inpFp, inpPtr, randomLength); - if (0 == inpBytes) break; - -#define CMPBUFSIZE (LZ4_COMPRESSBOUND(MESSAGE_MAX_BYTES)) - { char cmpBuf[CMPBUFSIZE]; - const int cmpBytes = LZ4_compress_HC_continue(lz4Stream, inpPtr, cmpBuf, inpBytes, CMPBUFSIZE); - - if(cmpBytes <= 0) break; - write_int32(outFp, cmpBytes); - write_bin(outFp, cmpBuf, cmpBytes); - - inpOffset += inpBytes; - - // Wraparound the ringbuffer offset - if(inpOffset >= RING_BUFFER_BYTES - MESSAGE_MAX_BYTES) - inpOffset = 0; - } - } - - write_int32(outFp, 0); -} - - -void test_decompress(FILE* outFp, FILE* inpFp) -{ - static char decBuf[DEC_BUFFER_BYTES]; - int decOffset = 0; - LZ4_streamDecode_t lz4StreamDecode_body = { 0 }; - LZ4_streamDecode_t* lz4StreamDecode = &lz4StreamDecode_body; - - for(;;) { - int cmpBytes = 0; - char cmpBuf[CMPBUFSIZE]; - - { const size_t r0 = read_int32(inpFp, &cmpBytes); - size_t r1; - if(r0 != 1 || cmpBytes <= 0) - break; - - r1 = read_bin(inpFp, cmpBuf, cmpBytes); - if(r1 != (size_t) cmpBytes) - break; - } - - { char* const decPtr = &decBuf[decOffset]; - const int decBytes = LZ4_decompress_safe_continue( - lz4StreamDecode, cmpBuf, decPtr, cmpBytes, MESSAGE_MAX_BYTES); - if(decBytes <= 0) - break; - - decOffset += decBytes; - write_bin(outFp, decPtr, decBytes); - - // Wraparound the ringbuffer offset - if(decOffset >= DEC_BUFFER_BYTES - MESSAGE_MAX_BYTES) - decOffset = 0; - } - } -} - - -// Compare 2 files content -// return 0 if identical -// return ByteNb>0 if different -size_t compare(FILE* f0, FILE* f1) -{ - size_t result = 1; - - for (;;) { - char b0[65536]; - char b1[65536]; - const size_t r0 = fread(b0, 1, sizeof(b0), f0); - const size_t r1 = fread(b1, 1, sizeof(b1), f1); - - if ((r0==0) && (r1==0)) return 0; // success - - if (r0 != r1) { - size_t smallest = r0; - if (r1 -#include -#include -#include - -enum { - BLOCK_BYTES = 1024 * 8, -// BLOCK_BYTES = 1024 * 64, -}; - - -size_t write_int(FILE* fp, int i) { - return fwrite(&i, sizeof(i), 1, fp); -} - -size_t write_bin(FILE* fp, const void* array, size_t arrayBytes) { - return fwrite(array, 1, arrayBytes, fp); -} - -size_t read_int(FILE* fp, int* i) { - return fread(i, sizeof(*i), 1, fp); -} - -size_t read_bin(FILE* fp, void* array, size_t arrayBytes) { - return fread(array, 1, arrayBytes, fp); -} - - -void test_compress(FILE* outFp, FILE* inpFp) -{ - LZ4_stream_t lz4Stream_body; - LZ4_stream_t* lz4Stream = &lz4Stream_body; - - char inpBuf[2][BLOCK_BYTES]; - int inpBufIndex = 0; - - LZ4_resetStream(lz4Stream); - - for(;;) { - char* const inpPtr = inpBuf[inpBufIndex]; - const int inpBytes = (int) read_bin(inpFp, inpPtr, BLOCK_BYTES); - if(0 == inpBytes) { - break; - } - - { - char cmpBuf[LZ4_COMPRESSBOUND(BLOCK_BYTES)]; - const int cmpBytes = LZ4_compress_fast_continue( - lz4Stream, inpPtr, cmpBuf, inpBytes, sizeof(cmpBuf), 1); - if(cmpBytes <= 0) { - break; - } - write_int(outFp, cmpBytes); - write_bin(outFp, cmpBuf, (size_t) cmpBytes); - } - - inpBufIndex = (inpBufIndex + 1) % 2; - } - - write_int(outFp, 0); -} - - -void test_decompress(FILE* outFp, FILE* inpFp) -{ - LZ4_streamDecode_t lz4StreamDecode_body; - LZ4_streamDecode_t* lz4StreamDecode = &lz4StreamDecode_body; - - char decBuf[2][BLOCK_BYTES]; - int decBufIndex = 0; - - LZ4_setStreamDecode(lz4StreamDecode, NULL, 0); - - for(;;) { - char cmpBuf[LZ4_COMPRESSBOUND(BLOCK_BYTES)]; - int cmpBytes = 0; - - { - const size_t readCount0 = read_int(inpFp, &cmpBytes); - if(readCount0 != 1 || cmpBytes <= 0) { - break; - } - - const size_t readCount1 = read_bin(inpFp, cmpBuf, (size_t) cmpBytes); - if(readCount1 != (size_t) cmpBytes) { - break; - } - } - - { - char* const decPtr = decBuf[decBufIndex]; - const int decBytes = LZ4_decompress_safe_continue( - lz4StreamDecode, cmpBuf, decPtr, cmpBytes, BLOCK_BYTES); - if(decBytes <= 0) { - break; - } - write_bin(outFp, decPtr, (size_t) decBytes); - } - - decBufIndex = (decBufIndex + 1) % 2; - } -} - - -int compare(FILE* fp0, FILE* fp1) -{ - int result = 0; - - while(0 == result) { - char b0[65536]; - char b1[65536]; - const size_t r0 = read_bin(fp0, b0, sizeof(b0)); - const size_t r1 = read_bin(fp1, b1, sizeof(b1)); - - result = (int) r0 - (int) r1; - - if(0 == r0 || 0 == r1) { - break; - } - if(0 == result) { - result = memcmp(b0, b1, r0); - } - } - - return result; -} - - -int main(int argc, char* argv[]) -{ - char inpFilename[256] = { 0 }; - char lz4Filename[256] = { 0 }; - char decFilename[256] = { 0 }; - - if(argc < 2) { - printf("Please specify input filename\n"); - return 0; - } - - snprintf(inpFilename, 256, "%s", argv[1]); - snprintf(lz4Filename, 256, "%s.lz4s-%d", argv[1], BLOCK_BYTES); - snprintf(decFilename, 256, "%s.lz4s-%d.dec", argv[1], BLOCK_BYTES); - - printf("inp = [%s]\n", inpFilename); - printf("lz4 = [%s]\n", lz4Filename); - printf("dec = [%s]\n", decFilename); - - // compress - { - FILE* inpFp = fopen(inpFilename, "rb"); - FILE* outFp = fopen(lz4Filename, "wb"); - - printf("compress : %s -> %s\n", inpFilename, lz4Filename); - test_compress(outFp, inpFp); - printf("compress : done\n"); - - fclose(outFp); - fclose(inpFp); - } - - // decompress - { - FILE* inpFp = fopen(lz4Filename, "rb"); - FILE* outFp = fopen(decFilename, "wb"); - - printf("decompress : %s -> %s\n", lz4Filename, decFilename); - test_decompress(outFp, inpFp); - printf("decompress : done\n"); - - fclose(outFp); - fclose(inpFp); - } - - // verify - { - FILE* inpFp = fopen(inpFilename, "rb"); - FILE* decFp = fopen(decFilename, "rb"); - - printf("verify : %s <-> %s\n", inpFilename, decFilename); - const int cmp = compare(inpFp, decFp); - if(0 == cmp) { - printf("verify : OK\n"); - } else { - printf("verify : NG\n"); - } - - fclose(decFp); - fclose(inpFp); - } - - return 0; -} diff --git a/src/lz4/examples/blockStreaming_doubleBuffer.md b/src/lz4/examples/blockStreaming_doubleBuffer.md deleted file mode 100644 index 3027ea3a7c..0000000000 --- a/src/lz4/examples/blockStreaming_doubleBuffer.md +++ /dev/null @@ -1,100 +0,0 @@ -# LZ4 Streaming API Example : Double Buffer -by *Takayuki Matsuoka* - -`blockStreaming_doubleBuffer.c` is LZ4 Straming API example which implements double buffer (de)compression. - -Please note : - - - Firstly, read "LZ4 Streaming API Basics". - - This is relatively advanced application example. - - Output file is not compatible with lz4frame and platform dependent. - - -## What's the point of this example ? - - - Handle huge file in small amount of memory - - Always better compression ratio than Block API - - Uniform block size - - -## How the compression works - -First of all, allocate "Double Buffer" for input and LZ4 compressed data buffer for output. -Double buffer has two pages, "first" page (Page#1) and "second" page (Page#2). - -``` - Double Buffer - - Page#1 Page#2 - +---------+---------+ - | Block#1 | | - +----+----+---------+ - | - v - {Out#1} - - - Prefix Dependency - +---------+ - | | - v | - +---------+----+----+ - | Block#1 | Block#2 | - +---------+----+----+ - | - v - {Out#2} - - - External Dictionary Mode - +---------+ - | | - | v - +----+----+---------+ - | Block#3 | Block#2 | - +----+----+---------+ - | - v - {Out#3} - - - Prefix Dependency - +---------+ - | | - v | - +---------+----+----+ - | Block#3 | Block#4 | - +---------+----+----+ - | - v - {Out#4} -``` - -Next, read first block to double buffer's first page. And compress it by `LZ4_compress_continue()`. -For the first time, LZ4 doesn't know any previous dependencies, -so it just compress the line without dependencies and generates compressed block {Out#1} to LZ4 compressed data buffer. -After that, write {Out#1} to the file. - -Next, read second block to double buffer's second page. And compress it. -In this time, LZ4 can use dependency to Block#1 to improve compression ratio. -This dependency is called "Prefix mode". - -Next, read third block to double buffer's *first* page. And compress it. -Also this time, LZ4 can use dependency to Block#2. -This dependency is called "External Dictonaly mode". - -Continue these procedure to the end of the file. - - -## How the decompression works - -Decompression will do reverse order. - - - Read first compressed block. - - Decompress it to the first page and write that page to the file. - - Read second compressed block. - - Decompress it to the second page and write that page to the file. - - Read third compressed block. - - Decompress it to the *first* page and write that page to the file. - -Continue these procedure to the end of the compressed file. diff --git a/src/lz4/examples/blockStreaming_lineByLine.c b/src/lz4/examples/blockStreaming_lineByLine.c deleted file mode 100644 index f449aa32fb..0000000000 --- a/src/lz4/examples/blockStreaming_lineByLine.c +++ /dev/null @@ -1,211 +0,0 @@ -// LZ4 streaming API example : line-by-line logfile compression -// Copyright : Takayuki Matsuoka - - -#ifdef _MSC_VER /* Visual Studio */ -# define _CRT_SECURE_NO_WARNINGS -# define snprintf sprintf_s -#endif -#include "lz4.h" - -#include -#include -#include -#include - -static size_t write_uint16(FILE* fp, uint16_t i) -{ - return fwrite(&i, sizeof(i), 1, fp); -} - -static size_t write_bin(FILE* fp, const void* array, int arrayBytes) -{ - return fwrite(array, 1, arrayBytes, fp); -} - -static size_t read_uint16(FILE* fp, uint16_t* i) -{ - return fread(i, sizeof(*i), 1, fp); -} - -static size_t read_bin(FILE* fp, void* array, int arrayBytes) -{ - return fread(array, 1, arrayBytes, fp); -} - - -static void test_compress( - FILE* outFp, - FILE* inpFp, - size_t messageMaxBytes, - size_t ringBufferBytes) -{ - LZ4_stream_t* const lz4Stream = LZ4_createStream(); - const size_t cmpBufBytes = LZ4_COMPRESSBOUND(messageMaxBytes); - char* const cmpBuf = (char*) malloc(cmpBufBytes); - char* const inpBuf = (char*) malloc(ringBufferBytes); - int inpOffset = 0; - - for ( ; ; ) - { - char* const inpPtr = &inpBuf[inpOffset]; - -#if 0 - // Read random length data to the ring buffer. - const int randomLength = (rand() % messageMaxBytes) + 1; - const int inpBytes = (int) read_bin(inpFp, inpPtr, randomLength); - if (0 == inpBytes) break; -#else - // Read line to the ring buffer. - int inpBytes = 0; - if (!fgets(inpPtr, (int) messageMaxBytes, inpFp)) - break; - inpBytes = (int) strlen(inpPtr); -#endif - - { - const int cmpBytes = LZ4_compress_fast_continue( - lz4Stream, inpPtr, cmpBuf, inpBytes, cmpBufBytes, 1); - if (cmpBytes <= 0) break; - write_uint16(outFp, (uint16_t) cmpBytes); - write_bin(outFp, cmpBuf, cmpBytes); - - // Add and wraparound the ringbuffer offset - inpOffset += inpBytes; - if ((size_t)inpOffset >= ringBufferBytes - messageMaxBytes) inpOffset = 0; - } - } - write_uint16(outFp, 0); - - free(inpBuf); - free(cmpBuf); - LZ4_freeStream(lz4Stream); -} - - -static void test_decompress( - FILE* outFp, - FILE* inpFp, - size_t messageMaxBytes, - size_t ringBufferBytes) -{ - LZ4_streamDecode_t* const lz4StreamDecode = LZ4_createStreamDecode(); - char* const cmpBuf = (char*) malloc(LZ4_COMPRESSBOUND(messageMaxBytes)); - char* const decBuf = (char*) malloc(ringBufferBytes); - int decOffset = 0; - - for ( ; ; ) - { - uint16_t cmpBytes = 0; - - if (read_uint16(inpFp, &cmpBytes) != 1) break; - if (cmpBytes <= 0) break; - if (read_bin(inpFp, cmpBuf, cmpBytes) != cmpBytes) break; - - { - char* const decPtr = &decBuf[decOffset]; - const int decBytes = LZ4_decompress_safe_continue( - lz4StreamDecode, cmpBuf, decPtr, cmpBytes, (int) messageMaxBytes); - if (decBytes <= 0) break; - write_bin(outFp, decPtr, decBytes); - - // Add and wraparound the ringbuffer offset - decOffset += decBytes; - if ((size_t)decOffset >= ringBufferBytes - messageMaxBytes) decOffset = 0; - } - } - - free(decBuf); - free(cmpBuf); - LZ4_freeStreamDecode(lz4StreamDecode); -} - - -static int compare(FILE* f0, FILE* f1) -{ - int result = 0; - const size_t tempBufferBytes = 65536; - char* const b0 = (char*) malloc(tempBufferBytes); - char* const b1 = (char*) malloc(tempBufferBytes); - - while(0 == result) - { - const size_t r0 = fread(b0, 1, tempBufferBytes, f0); - const size_t r1 = fread(b1, 1, tempBufferBytes, f1); - - result = (int) r0 - (int) r1; - - if (0 == r0 || 0 == r1) break; - if (0 == result) result = memcmp(b0, b1, r0); - } - - free(b1); - free(b0); - return result; -} - - -int main(int argc, char* argv[]) -{ - enum { - MESSAGE_MAX_BYTES = 1024, - RING_BUFFER_BYTES = 1024 * 256 + MESSAGE_MAX_BYTES, - }; - - char inpFilename[256] = { 0 }; - char lz4Filename[256] = { 0 }; - char decFilename[256] = { 0 }; - - if (argc < 2) - { - printf("Please specify input filename\n"); - return 0; - } - - snprintf(inpFilename, 256, "%s", argv[1]); - snprintf(lz4Filename, 256, "%s.lz4s", argv[1]); - snprintf(decFilename, 256, "%s.lz4s.dec", argv[1]); - - printf("inp = [%s]\n", inpFilename); - printf("lz4 = [%s]\n", lz4Filename); - printf("dec = [%s]\n", decFilename); - - // compress - { - FILE* inpFp = fopen(inpFilename, "rb"); - FILE* outFp = fopen(lz4Filename, "wb"); - - test_compress(outFp, inpFp, MESSAGE_MAX_BYTES, RING_BUFFER_BYTES); - - fclose(outFp); - fclose(inpFp); - } - - // decompress - { - FILE* inpFp = fopen(lz4Filename, "rb"); - FILE* outFp = fopen(decFilename, "wb"); - - test_decompress(outFp, inpFp, MESSAGE_MAX_BYTES, RING_BUFFER_BYTES); - - fclose(outFp); - fclose(inpFp); - } - - // verify - { - FILE* inpFp = fopen(inpFilename, "rb"); - FILE* decFp = fopen(decFilename, "rb"); - - const int cmp = compare(inpFp, decFp); - if (0 == cmp) - printf("Verify : OK\n"); - else - printf("Verify : NG\n"); - - fclose(decFp); - fclose(inpFp); - } - - return 0; -} diff --git a/src/lz4/examples/blockStreaming_lineByLine.md b/src/lz4/examples/blockStreaming_lineByLine.md deleted file mode 100644 index 4735f927f3..0000000000 --- a/src/lz4/examples/blockStreaming_lineByLine.md +++ /dev/null @@ -1,122 +0,0 @@ -# LZ4 Streaming API Example : Line by Line Text Compression -by *Takayuki Matsuoka* - -`blockStreaming_lineByLine.c` is LZ4 Straming API example which implements line by line incremental (de)compression. - -Please note the following restrictions : - - - Firstly, read "LZ4 Streaming API Basics". - - This is relatively advanced application example. - - Output file is not compatible with lz4frame and platform dependent. - - -## What's the point of this example ? - - - Line by line incremental (de)compression. - - Handle huge file in small amount of memory - - Generally better compression ratio than Block API - - Non-uniform block size - - -## How the compression works - -First of all, allocate "Ring Buffer" for input and LZ4 compressed data buffer for output. - -``` -(1) - Ring Buffer - - +--------+ - | Line#1 | - +---+----+ - | - v - {Out#1} - - -(2) - Prefix Mode Dependency - +----+ - | | - v | - +--------+-+------+ - | Line#1 | Line#2 | - +--------+---+----+ - | - v - {Out#2} - - -(3) - Prefix Prefix - +----+ +----+ - | | | | - v | v | - +--------+-+------+-+------+ - | Line#1 | Line#2 | Line#3 | - +--------+--------+---+----+ - | - v - {Out#3} - - -(4) - External Dictionary Mode - +----+ +----+ - | | | | - v | v | - ------+--------+-+------+-+--------+ - | .... | Line#X | Line#X+1 | - ------+--------+--------+-----+----+ - ^ | - | v - | {Out#X+1} - | - Reset - - -(5) - Prefix - +-----+ - | | - v | - ------+--------+--------+----------+--+-------+ - | .... | Line#X | Line#X+1 | Line#X+2 | - ------+--------+--------+----------+-----+----+ - ^ | - | v - | {Out#X+2} - | - Reset -``` - -Next (see (1)), read first line to ringbuffer and compress it by `LZ4_compress_continue()`. -For the first time, LZ4 doesn't know any previous dependencies, -so it just compress the line without dependencies and generates compressed line {Out#1} to LZ4 compressed data buffer. -After that, write {Out#1} to the file and forward ringbuffer offset. - -Do the same things to second line (see (2)). -But in this time, LZ4 can use dependency to Line#1 to improve compression ratio. -This dependency is called "Prefix mode". - -Eventually, we'll reach end of ringbuffer at Line#X (see (4)). -This time, we should reset ringbuffer offset. -After resetting, at Line#X+1 pointer is not adjacent, but LZ4 still maintain its memory. -This is called "External Dictionary Mode". - -In Line#X+2 (see (5)), finally LZ4 forget almost all memories but still remains Line#X+1. -This is the same situation as Line#2. - -Continue these procedure to the end of text file. - - -## How the decompression works - -Decompression will do reverse order. - - - Read compressed line from the file to buffer. - - Decompress it to the ringbuffer. - - Output decompressed plain text line to the file. - - Forward ringbuffer offset. If offset exceedes end of the ringbuffer, reset it. - -Continue these procedure to the end of the compressed file. diff --git a/src/lz4/examples/blockStreaming_ringBuffer.c b/src/lz4/examples/blockStreaming_ringBuffer.c deleted file mode 100644 index 697d342c82..0000000000 --- a/src/lz4/examples/blockStreaming_ringBuffer.c +++ /dev/null @@ -1,201 +0,0 @@ -// LZ4 streaming API example : ring buffer -// Based on sample code from Takayuki Matsuoka - - -/************************************** - * Compiler Options - **************************************/ -#ifdef _MSC_VER /* Visual Studio */ -# define _CRT_SECURE_NO_WARNINGS // for MSVC -# define snprintf sprintf_s -#endif -#ifdef __GNUC__ -# pragma GCC diagnostic ignored "-Wmissing-braces" /* GCC bug 53119 : doesn't accept { 0 } as initializer (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53119) */ -#endif - - -/************************************** - * Includes - **************************************/ -#include -#include -#include -#include -#include "lz4.h" - - -enum { - MESSAGE_MAX_BYTES = 1024, - RING_BUFFER_BYTES = 1024 * 8 + MESSAGE_MAX_BYTES, - DECODE_RING_BUFFER = RING_BUFFER_BYTES + MESSAGE_MAX_BYTES // Intentionally larger, to test unsynchronized ring buffers -}; - - -size_t write_int32(FILE* fp, int32_t i) { - return fwrite(&i, sizeof(i), 1, fp); -} - -size_t write_bin(FILE* fp, const void* array, int arrayBytes) { - return fwrite(array, 1, arrayBytes, fp); -} - -size_t read_int32(FILE* fp, int32_t* i) { - return fread(i, sizeof(*i), 1, fp); -} - -size_t read_bin(FILE* fp, void* array, int arrayBytes) { - return fread(array, 1, arrayBytes, fp); -} - - -void test_compress(FILE* outFp, FILE* inpFp) -{ - LZ4_stream_t lz4Stream_body = { 0 }; - LZ4_stream_t* lz4Stream = &lz4Stream_body; - - static char inpBuf[RING_BUFFER_BYTES]; - int inpOffset = 0; - - for(;;) { - // Read random length ([1,MESSAGE_MAX_BYTES]) data to the ring buffer. - char* const inpPtr = &inpBuf[inpOffset]; - const int randomLength = (rand() % MESSAGE_MAX_BYTES) + 1; - const int inpBytes = (int) read_bin(inpFp, inpPtr, randomLength); - if (0 == inpBytes) break; - - { -#define CMPBUFSIZE (LZ4_COMPRESSBOUND(MESSAGE_MAX_BYTES)) - char cmpBuf[CMPBUFSIZE]; - const int cmpBytes = LZ4_compress_fast_continue(lz4Stream, inpPtr, cmpBuf, inpBytes, CMPBUFSIZE, 0); - if(cmpBytes <= 0) break; - write_int32(outFp, cmpBytes); - write_bin(outFp, cmpBuf, cmpBytes); - - inpOffset += inpBytes; - - // Wraparound the ringbuffer offset - if(inpOffset >= RING_BUFFER_BYTES - MESSAGE_MAX_BYTES) inpOffset = 0; - } - } - - write_int32(outFp, 0); -} - - -void test_decompress(FILE* outFp, FILE* inpFp) -{ - static char decBuf[DECODE_RING_BUFFER]; - int decOffset = 0; - LZ4_streamDecode_t lz4StreamDecode_body = { 0 }; - LZ4_streamDecode_t* lz4StreamDecode = &lz4StreamDecode_body; - - for(;;) { - int cmpBytes = 0; - char cmpBuf[CMPBUFSIZE]; - - { - const size_t r0 = read_int32(inpFp, &cmpBytes); - if(r0 != 1 || cmpBytes <= 0) break; - - const size_t r1 = read_bin(inpFp, cmpBuf, cmpBytes); - if(r1 != (size_t) cmpBytes) break; - } - - { - char* const decPtr = &decBuf[decOffset]; - const int decBytes = LZ4_decompress_safe_continue( - lz4StreamDecode, cmpBuf, decPtr, cmpBytes, MESSAGE_MAX_BYTES); - if(decBytes <= 0) break; - decOffset += decBytes; - write_bin(outFp, decPtr, decBytes); - - // Wraparound the ringbuffer offset - if(decOffset >= DECODE_RING_BUFFER - MESSAGE_MAX_BYTES) decOffset = 0; - } - } -} - - -int compare(FILE* f0, FILE* f1) -{ - int result = 0; - - while(0 == result) { - char b0[65536]; - char b1[65536]; - const size_t r0 = fread(b0, 1, sizeof(b0), f0); - const size_t r1 = fread(b1, 1, sizeof(b1), f1); - - result = (int) r0 - (int) r1; - - if(0 == r0 || 0 == r1) { - break; - } - if(0 == result) { - result = memcmp(b0, b1, r0); - } - } - - return result; -} - - -int main(int argc, char** argv) -{ - char inpFilename[256] = { 0 }; - char lz4Filename[256] = { 0 }; - char decFilename[256] = { 0 }; - - if(argc < 2) { - printf("Please specify input filename\n"); - return 0; - } - - snprintf(inpFilename, 256, "%s", argv[1]); - snprintf(lz4Filename, 256, "%s.lz4s-%d", argv[1], 0); - snprintf(decFilename, 256, "%s.lz4s-%d.dec", argv[1], 0); - - printf("inp = [%s]\n", inpFilename); - printf("lz4 = [%s]\n", lz4Filename); - printf("dec = [%s]\n", decFilename); - - // compress - { - FILE* inpFp = fopen(inpFilename, "rb"); - FILE* outFp = fopen(lz4Filename, "wb"); - - test_compress(outFp, inpFp); - - fclose(outFp); - fclose(inpFp); - } - - // decompress - { - FILE* inpFp = fopen(lz4Filename, "rb"); - FILE* outFp = fopen(decFilename, "wb"); - - test_decompress(outFp, inpFp); - - fclose(outFp); - fclose(inpFp); - } - - // verify - { - FILE* inpFp = fopen(inpFilename, "rb"); - FILE* decFp = fopen(decFilename, "rb"); - - const int cmp = compare(inpFp, decFp); - if(0 == cmp) { - printf("Verify : OK\n"); - } else { - printf("Verify : NG\n"); - } - - fclose(decFp); - fclose(inpFp); - } - - return 0; -} diff --git a/src/lz4/examples/compress_functions.c b/src/lz4/examples/compress_functions.c deleted file mode 100644 index d0dca13a1c..0000000000 --- a/src/lz4/examples/compress_functions.c +++ /dev/null @@ -1,363 +0,0 @@ -/* - * compress_functions.c - * Copyright : Kyle Harper - * License : Follows same licensing as the lz4.c/lz4.h program at any given time. Currently, BSD 2. - * Description: A program to demonstrate the various compression functions involved in when using LZ4_compress_default(). The idea - * is to show how each step in the call stack can be used directly, if desired. There is also some benchmarking for - * each function to demonstrate the (probably lack of) performance difference when jumping the stack. - * (If you're new to lz4, please read simple_buffer.c to understand the fundamentals) - * - * The call stack (before theoretical compiler optimizations) for LZ4_compress_default is as follows: - * LZ4_compress_default - * LZ4_compress_fast - * LZ4_compress_fast_extState - * LZ4_compress_generic - * - * LZ4_compress_default() - * This is the recommended function for compressing data. It will serve as the baseline for comparison. - * LZ4_compress_fast() - * Despite its name, it's not a "fast" version of compression. It simply decides if HEAPMODE is set and either - * allocates memory on the heap for a struct or creates the struct directly on the stack. Stack access is generally - * faster but this function itself isn't giving that advantage, it's just some logic for compile time. - * LZ4_compress_fast_extState() - * This simply accepts all the pointers and values collected thus far and adds logic to determine how - * LZ4_compress_generic should be invoked; specifically: can the source fit into a single pass as determined by - * LZ4_64Klimit. - * LZ4_compress_generic() - * As the name suggests, this is the generic function that ultimately does most of the heavy lifting. Calling this - * directly can help avoid some test cases and branching which might be useful in some implementation-specific - * situations, but you really need to know what you're doing AND what you're asking lz4 to do! You also need a - * wrapper function because this function isn't exposed with lz4.h. - * - * The call stack for decompression functions is shallow. There are 2 options: - * LZ4_decompress_safe || LZ4_decompress_fast - * LZ4_decompress_generic - * - * LZ4_decompress_safe - * This is the recommended function for decompressing data. It is considered safe because the caller specifies - * both the size of the compresssed buffer to read as well as the maximum size of the output (decompressed) buffer - * instead of just the latter. - * LZ4_decompress_fast - * Again, despite its name it's not a "fast" version of decompression. It simply frees the caller of sending the - * size of the compressed buffer (it will simply be read-to-end, hence it's non-safety). - * LZ4_decompress_generic - * This is the generic function that both of the LZ4_decompress_* functions above end up calling. Calling this - * directly is not advised, period. Furthermore, it is a static inline function in lz4.c, so there isn't a symbol - * exposed for anyone using lz4.h to utilize. - * - * Special Note About Decompression: - * Using the LZ4_decompress_safe() function protects against malicious (user) input. If you are using data from a - * trusted source, or if your program is the producer (P) as well as its consumer (C) in a PC or MPMC setup, you can - * safely use the LZ4_decompress_fast function - */ - -/* Since lz4 compiles with c99 and not gnu/std99 we need to enable POSIX linking for time.h structs and functions. */ -#if __STDC_VERSION__ >= 199901L -#define _XOPEN_SOURCE 600 -#else -#define _XOPEN_SOURCE 500 -#endif -#define _POSIX_C_SOURCE 199309L - -/* Includes, for Power! */ -#include "lz4.h" -#include /* for printf() */ -#include /* for exit() */ -#include /* for atoi() memcmp() */ -#include /* for uint_types */ -#include /* for PRIu64 */ -#include /* for clock_gettime() */ -#include /* for setlocale() */ - -/* We need to know what one billion is for clock timing. */ -#define BILLION 1000000000L - -/* Create a crude set of test IDs so we can switch on them later (Can't switch() on a char[] or char*). */ -#define ID__LZ4_COMPRESS_DEFAULT 1 -#define ID__LZ4_COMPRESS_FAST 2 -#define ID__LZ4_COMPRESS_FAST_EXTSTATE 3 -#define ID__LZ4_COMPRESS_GENERIC 4 -#define ID__LZ4_DECOMPRESS_SAFE 5 -#define ID__LZ4_DECOMPRESS_FAST 6 - - - -/* - * Easy show-error-and-bail function. - */ -void run_screaming(const char *message, const int code) { - printf("%s\n", message); - exit(code); - return; -} - - -/* - * Centralize the usage function to keep main cleaner. - */ -void usage(const char *message) { - printf("Usage: ./argPerformanceTesting \n"); - run_screaming(message, 1); - return; -} - - - -/* - * Runs the benchmark for LZ4_compress_* based on function_id. - */ -uint64_t bench( - const char *known_good_dst, - const int function_id, - const int iterations, - const char *src, - char *dst, - const size_t src_size, - const size_t max_dst_size, - const size_t comp_size - ) { - uint64_t time_taken = 0; - int rv = 0; - const int warm_up = 5000; - struct timespec start, end; - const int acceleration = 1; - LZ4_stream_t state; - - // Select the right function to perform the benchmark on. We perform 5000 initial loops to warm the cache and ensure that dst - // remains matching to known_good_dst between successive calls. - switch(function_id) { - case ID__LZ4_COMPRESS_DEFAULT: - printf("Starting benchmark for function: LZ4_compress_default()\n"); - for(int junk=0; junk 1) - iterations = atoi(argv[1]); - if (iterations < 1) - usage("Argument 1 (iterations) must be > 0."); - - // First we will create 2 sources (char *) of 2000 bytes each. One normal text, the other highly-compressible text. - const char *src = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed luctus purus et risus vulputate, et mollis orci ullamcorper. Nulla facilisi. Fusce in ligula sed purus varius aliquet interdum vitae justo. Proin quis diam velit. Nulla varius iaculis auctor. Cras volutpat, justo eu dictum pulvinar, elit sem porttitor metus, et imperdiet metus sapien et ante. Nullam nisi nulla, ornare eu tristique eu, dignissim vitae diam. Nulla sagittis porta libero, a accumsan felis sagittis scelerisque. Integer laoreet eleifend congue. Etiam rhoncus leo vel dolor fermentum, quis luctus nisl iaculis. Praesent a erat sapien. Aliquam semper mi in lorem ultrices ultricies. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In feugiat risus sed enim ultrices, at sodales nulla tristique. Maecenas eget pellentesque justo, sed pellentesque lectus. Fusce sagittis sit amet elit vel varius. Donec sed ligula nec ligula vulputate rutrum sed ut lectus. Etiam congue pharetra leo vitae cursus. Morbi enim ante, porttitor ut varius vel, tincidunt quis justo. Nunc iaculis, risus id ultrices semper, metus est efficitur ligula, vel posuere risus nunc eget purus. Ut lorem turpis, condimentum at sem sed, porta aliquam turpis. In ut sapien a nulla dictum tincidunt quis sit amet lorem. Fusce at est egestas, luctus neque eu, consectetur tortor. Phasellus eleifend ultricies nulla ac lobortis. Morbi maximus quam cursus vehicula iaculis. Maecenas cursus vel justo ut rutrum. Curabitur magna orci, dignissim eget dapibus vitae, finibus id lacus. Praesent rhoncus mattis augue vitae bibendum. Praesent porta mauris non ultrices fermentum. Quisque vulputate ipsum in sodales pulvinar. Aliquam nec mollis felis. Donec vitae augue pulvinar, congue nisl sed, pretium purus. Fusce lobortis mi ac neque scelerisque semper. Pellentesque vel est vitae magna aliquet aliquet. Nam non dolor. Nulla facilisi. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Morbi ac lacinia felis metus."; - const char *hc_src = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa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aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; - // Set and derive sizes. Since we're using strings, use strlen() + 1 for \0. - const size_t src_size = strlen(src) + 1; - const size_t max_dst_size = LZ4_compressBound(src_size); - int bytes_returned = 0; - // Now build allocations for the data we'll be playing with. - char *dst = calloc(1, max_dst_size); - char *known_good_dst = calloc(1, max_dst_size); - char *known_good_hc_dst = calloc(1, max_dst_size); - if (dst == NULL || known_good_dst == NULL || known_good_hc_dst == NULL) - run_screaming("Couldn't allocate memory for the destination buffers. Sad :(", 1); - - // Create known-good buffers to verify our tests with other functions will produce the same results. - bytes_returned = LZ4_compress_default(src, known_good_dst, src_size, max_dst_size); - if (bytes_returned < 1) - run_screaming("Couldn't create a known-good destination buffer for comparison... this is bad.", 1); - const size_t src_comp_size = bytes_returned; - bytes_returned = LZ4_compress_default(hc_src, known_good_hc_dst, src_size, max_dst_size); - if (bytes_returned < 1) - run_screaming("Couldn't create a known-good (highly compressible) destination buffer for comparison... this is bad.", 1); - const size_t hc_src_comp_size = bytes_returned; - - - /* LZ4_compress_default() */ - // This is the default function so we don't need to demonstrate how to use it. See basics.c if you need more basal information. - - /* LZ4_compress_fast() */ - // Using this function is identical to LZ4_compress_default except we need to specify an "acceleration" value. Defaults to 1. - memset(dst, 0, max_dst_size); - bytes_returned = LZ4_compress_fast(src, dst, src_size, max_dst_size, 1); - if (bytes_returned < 1) - run_screaming("Failed to compress src using LZ4_compress_fast. echo $? for return code.", bytes_returned); - if (memcmp(dst, known_good_dst, bytes_returned) != 0) - run_screaming("According to memcmp(), the value we got in dst from LZ4_compress_fast doesn't match the known-good value. This is bad.", 1); - - /* LZ4_compress_fast_extState() */ - // Using this function directly requires that we build an LZ4_stream_t struct ourselves. We do NOT have to reset it ourselves. - memset(dst, 0, max_dst_size); - LZ4_stream_t state; - bytes_returned = LZ4_compress_fast_extState(&state, src, dst, src_size, max_dst_size, 1); - if (bytes_returned < 1) - run_screaming("Failed to compress src using LZ4_compress_fast_extState. echo $? for return code.", bytes_returned); - if (memcmp(dst, known_good_dst, bytes_returned) != 0) - run_screaming("According to memcmp(), the value we got in dst from LZ4_compress_fast_extState doesn't match the known-good value. This is bad.", 1); - - /* LZ4_compress_generic */ - // When you can exactly control the inputs and options of your LZ4 needs, you can use LZ4_compress_generic and fixed (const) - // values for the enum types such as dictionary and limitations. Any other direct-use is probably a bad idea. - // - // That said, the LZ4_compress_generic() function is 'static inline' and does not have a prototype in lz4.h to expose a symbol - // for it. In other words: we can't access it directly. I don't want to submit a PR that modifies lz4.c/h. Yann and others can - // do that if they feel it's worth expanding this example. - // - // I will, however, leave a skeleton of what would be required to use it directly: - /* - memset(dst, 0, max_dst_size); - // LZ4_stream_t state: is already declared above. We can reuse it BUT we have to reset the stream ourselves between each call. - LZ4_resetStream((LZ4_stream_t *)&state); - // Since src size is small we know the following enums will be used: notLimited (0), byU16 (2), noDict (0), noDictIssue (0). - bytes_returned = LZ4_compress_generic(&state, src, dst, src_size, max_dst_size, notLimited, byU16, noDict, noDictIssue, 1); - if (bytes_returned < 1) - run_screaming("Failed to compress src using LZ4_compress_generic. echo $? for return code.", bytes_returned); - if (memcmp(dst, known_good_dst, bytes_returned) != 0) - run_screaming("According to memcmp(), the value we got in dst from LZ4_compress_generic doesn't match the known-good value. This is bad.", 1); - */ - - - /* Benchmarking */ - /* Now we'll run a few rudimentary benchmarks with each function to demonstrate differences in speed based on the function used. - * Remember, we cannot call LZ4_compress_generic() directly (yet) so it's disabled. - */ - // Suite A - Normal Compressibility - char *dst_d = calloc(1, src_size); - memset(dst, 0, max_dst_size); - printf("\nStarting suite A: Normal compressible text.\n"); - uint64_t time_taken__default = bench(known_good_dst, ID__LZ4_COMPRESS_DEFAULT, iterations, src, dst, src_size, max_dst_size, src_comp_size); - uint64_t time_taken__fast = bench(known_good_dst, ID__LZ4_COMPRESS_FAST, iterations, src, dst, src_size, max_dst_size, src_comp_size); - uint64_t time_taken__fast_extstate = bench(known_good_dst, ID__LZ4_COMPRESS_FAST_EXTSTATE, iterations, src, dst, src_size, max_dst_size, src_comp_size); - //uint64_t time_taken__generic = bench(known_good_dst, ID__LZ4_COMPRESS_GENERIC, iterations, src, dst, src_size, max_dst_size, src_comp_size); - uint64_t time_taken__decomp_safe = bench(src, ID__LZ4_DECOMPRESS_SAFE, iterations, known_good_dst, dst_d, src_size, max_dst_size, src_comp_size); - uint64_t time_taken__decomp_fast = bench(src, ID__LZ4_DECOMPRESS_FAST, iterations, known_good_dst, dst_d, src_size, max_dst_size, src_comp_size); - // Suite B - Highly Compressible - memset(dst, 0, max_dst_size); - printf("\nStarting suite B: Highly compressible text.\n"); - uint64_t time_taken_hc__default = bench(known_good_hc_dst, ID__LZ4_COMPRESS_DEFAULT, iterations, hc_src, dst, src_size, max_dst_size, hc_src_comp_size); - uint64_t time_taken_hc__fast = bench(known_good_hc_dst, ID__LZ4_COMPRESS_FAST, iterations, hc_src, dst, src_size, max_dst_size, hc_src_comp_size); - uint64_t time_taken_hc__fast_extstate = bench(known_good_hc_dst, ID__LZ4_COMPRESS_FAST_EXTSTATE, iterations, hc_src, dst, src_size, max_dst_size, hc_src_comp_size); - //uint64_t time_taken_hc__generic = bench(known_good_hc_dst, ID__LZ4_COMPRESS_GENERIC, iterations, hc_src, dst, src_size, max_dst_size, hc_src_comp_size); - uint64_t time_taken_hc__decomp_safe = bench(hc_src, ID__LZ4_DECOMPRESS_SAFE, iterations, known_good_hc_dst, dst_d, src_size, max_dst_size, hc_src_comp_size); - uint64_t time_taken_hc__decomp_fast = bench(hc_src, ID__LZ4_DECOMPRESS_FAST, iterations, known_good_hc_dst, dst_d, src_size, max_dst_size, hc_src_comp_size); - - // Report and leave. - setlocale(LC_ALL, ""); - const char *format = "|%-14s|%-30s|%'14.9f|%'16d|%'14d|%'13.2f%%|\n"; - const char *header_format = "|%-14s|%-30s|%14s|%16s|%14s|%14s|\n"; - const char *separator = "+--------------+------------------------------+--------------+----------------+--------------+--------------+\n"; - printf("\n"); - printf("%s", separator); - printf(header_format, "Source", "Function Benchmarked", "Total Seconds", "Iterations/sec", "ns/Iteration", "% of default"); - printf("%s", separator); - printf(format, "Normal Text", "LZ4_compress_default()", (double)time_taken__default / BILLION, (int)(iterations / ((double)time_taken__default /BILLION)), time_taken__default / iterations, (double)time_taken__default * 100 / time_taken__default); - printf(format, "Normal Text", "LZ4_compress_fast()", (double)time_taken__fast / BILLION, (int)(iterations / ((double)time_taken__fast /BILLION)), time_taken__fast / iterations, (double)time_taken__fast * 100 / time_taken__default); - printf(format, "Normal Text", "LZ4_compress_fast_extState()", (double)time_taken__fast_extstate / BILLION, (int)(iterations / ((double)time_taken__fast_extstate /BILLION)), time_taken__fast_extstate / iterations, (double)time_taken__fast_extstate * 100 / time_taken__default); - //printf(format, "Normal Text", "LZ4_compress_generic()", (double)time_taken__generic / BILLION, (int)(iterations / ((double)time_taken__generic /BILLION)), time_taken__generic / iterations, (double)time_taken__generic * 100 / time_taken__default); - printf(format, "Normal Text", "LZ4_decompress_safe()", (double)time_taken__decomp_safe / BILLION, (int)(iterations / ((double)time_taken__decomp_safe /BILLION)), time_taken__decomp_safe / iterations, (double)time_taken__decomp_safe * 100 / time_taken__default); - printf(format, "Normal Text", "LZ4_decompress_fast()", (double)time_taken__decomp_fast / BILLION, (int)(iterations / ((double)time_taken__decomp_fast /BILLION)), time_taken__decomp_fast / iterations, (double)time_taken__decomp_fast * 100 / time_taken__default); - printf(header_format, "", "", "", "", "", ""); - printf(format, "Compressible", "LZ4_compress_default()", (double)time_taken_hc__default / BILLION, (int)(iterations / ((double)time_taken_hc__default /BILLION)), time_taken_hc__default / iterations, (double)time_taken_hc__default * 100 / time_taken_hc__default); - printf(format, "Compressible", "LZ4_compress_fast()", (double)time_taken_hc__fast / BILLION, (int)(iterations / ((double)time_taken_hc__fast /BILLION)), time_taken_hc__fast / iterations, (double)time_taken_hc__fast * 100 / time_taken_hc__default); - printf(format, "Compressible", "LZ4_compress_fast_extState()", (double)time_taken_hc__fast_extstate / BILLION, (int)(iterations / ((double)time_taken_hc__fast_extstate /BILLION)), time_taken_hc__fast_extstate / iterations, (double)time_taken_hc__fast_extstate * 100 / time_taken_hc__default); - //printf(format, "Compressible", "LZ4_compress_generic()", (double)time_taken_hc__generic / BILLION, (int)(iterations / ((double)time_taken_hc__generic /BILLION)), time_taken_hc__generic / iterations, (double)time_taken_hc__generic * 100 / time_taken_hc__default); - printf(format, "Compressible", "LZ4_decompress_safe()", (double)time_taken_hc__decomp_safe / BILLION, (int)(iterations / ((double)time_taken_hc__decomp_safe /BILLION)), time_taken_hc__decomp_safe / iterations, (double)time_taken_hc__decomp_safe * 100 / time_taken_hc__default); - printf(format, "Compressible", "LZ4_decompress_fast()", (double)time_taken_hc__decomp_fast / BILLION, (int)(iterations / ((double)time_taken_hc__decomp_fast /BILLION)), time_taken_hc__decomp_fast / iterations, (double)time_taken_hc__decomp_fast * 100 / time_taken_hc__default); - printf("%s", separator); - printf("\n"); - printf("All done, ran %d iterations per test.\n", iterations); - return 0; -} diff --git a/src/lz4/examples/dictionaryRandomAccess.c b/src/lz4/examples/dictionaryRandomAccess.c deleted file mode 100644 index 6acf99b44e..0000000000 --- a/src/lz4/examples/dictionaryRandomAccess.c +++ /dev/null @@ -1,280 +0,0 @@ -// LZ4 API example : Dictionary Random Access - -#ifdef _MSC_VER /* Visual Studio */ -# define _CRT_SECURE_NO_WARNINGS -# define snprintf sprintf_s -#endif -#include "lz4.h" - -#include -#include -#include -#include - -#define MIN(x, y) (x) < (y) ? (x) : (y) - -enum { - BLOCK_BYTES = 1024, /* 1 KiB of uncompressed data in a block */ - DICTIONARY_BYTES = 1024, /* Load a 1 KiB dictionary */ - MAX_BLOCKS = 1024 /* For simplicity of implementation */ -}; - -/** - * Magic bytes for this test case. - * This is not a great magic number because it is a common word in ASCII. - * However, it is important to have some versioning system in your format. - */ -const char kTestMagic[] = { 'T', 'E', 'S', 'T' }; - - -void write_int(FILE* fp, int i) { - size_t written = fwrite(&i, sizeof(i), 1, fp); - if (written != 1) { exit(10); } -} - -void write_bin(FILE* fp, const void* array, size_t arrayBytes) { - size_t written = fwrite(array, 1, arrayBytes, fp); - if (written != arrayBytes) { exit(11); } -} - -void read_int(FILE* fp, int* i) { - size_t read = fread(i, sizeof(*i), 1, fp); - if (read != 1) { exit(12); } -} - -size_t read_bin(FILE* fp, void* array, size_t arrayBytes) { - size_t read = fread(array, 1, arrayBytes, fp); - if (ferror(fp)) { exit(12); } - return read; -} - -void seek_bin(FILE* fp, long offset, int origin) { - if (fseek(fp, offset, origin)) { exit(14); } -} - - -void test_compress(FILE* outFp, FILE* inpFp, void *dict, int dictSize) -{ - LZ4_stream_t lz4Stream_body; - LZ4_stream_t* lz4Stream = &lz4Stream_body; - - char inpBuf[BLOCK_BYTES]; - int offsets[MAX_BLOCKS]; - int *offsetsEnd = offsets; - - - LZ4_resetStream(lz4Stream); - - /* Write header magic */ - write_bin(outFp, kTestMagic, sizeof(kTestMagic)); - - *offsetsEnd++ = sizeof(kTestMagic); - /* Write compressed data blocks. Each block contains BLOCK_BYTES of plain - data except possibly the last. */ - for(;;) { - const int inpBytes = (int) read_bin(inpFp, inpBuf, BLOCK_BYTES); - if(0 == inpBytes) { - break; - } - - /* Forget previously compressed data and load the dictionary */ - LZ4_loadDict(lz4Stream, dict, dictSize); - { - char cmpBuf[LZ4_COMPRESSBOUND(BLOCK_BYTES)]; - const int cmpBytes = LZ4_compress_fast_continue( - lz4Stream, inpBuf, cmpBuf, inpBytes, sizeof(cmpBuf), 1); - if(cmpBytes <= 0) { exit(1); } - write_bin(outFp, cmpBuf, (size_t)cmpBytes); - /* Keep track of the offsets */ - *offsetsEnd = *(offsetsEnd - 1) + cmpBytes; - ++offsetsEnd; - } - if (offsetsEnd - offsets > MAX_BLOCKS) { exit(2); } - } - /* Write the tailing jump table */ - { - int *ptr = offsets; - while (ptr != offsetsEnd) { - write_int(outFp, *ptr++); - } - write_int(outFp, offsetsEnd - offsets); - } -} - - -void test_decompress(FILE* outFp, FILE* inpFp, void *dict, int dictSize, int offset, int length) -{ - LZ4_streamDecode_t lz4StreamDecode_body; - LZ4_streamDecode_t* lz4StreamDecode = &lz4StreamDecode_body; - - /* The blocks [currentBlock, endBlock) contain the data we want */ - int currentBlock = offset / BLOCK_BYTES; - int endBlock = ((offset + length - 1) / BLOCK_BYTES) + 1; - - char decBuf[BLOCK_BYTES]; - int offsets[MAX_BLOCKS]; - - /* Special cases */ - if (length == 0) { return; } - - /* Read the magic bytes */ - { - char magic[sizeof(kTestMagic)]; - size_t read = read_bin(inpFp, magic, sizeof(magic)); - if (read != sizeof(magic)) { exit(1); } - if (memcmp(kTestMagic, magic, sizeof(magic))) { exit(2); } - } - - /* Read the offsets tail */ - { - int numOffsets; - int block; - int *offsetsPtr = offsets; - seek_bin(inpFp, -4, SEEK_END); - read_int(inpFp, &numOffsets); - if (numOffsets <= endBlock) { exit(3); } - seek_bin(inpFp, -4 * (numOffsets + 1), SEEK_END); - for (block = 0; block <= endBlock; ++block) { - read_int(inpFp, offsetsPtr++); - } - } - /* Seek to the first block to read */ - seek_bin(inpFp, offsets[currentBlock], SEEK_SET); - offset = offset % BLOCK_BYTES; - - /* Start decoding */ - for(; currentBlock < endBlock; ++currentBlock) { - char cmpBuf[LZ4_COMPRESSBOUND(BLOCK_BYTES)]; - /* The difference in offsets is the size of the block */ - int cmpBytes = offsets[currentBlock + 1] - offsets[currentBlock]; - { - const size_t read = read_bin(inpFp, cmpBuf, (size_t)cmpBytes); - if(read != (size_t)cmpBytes) { exit(4); } - } - - /* Load the dictionary */ - LZ4_setStreamDecode(lz4StreamDecode, dict, dictSize); - { - const int decBytes = LZ4_decompress_safe_continue( - lz4StreamDecode, cmpBuf, decBuf, cmpBytes, BLOCK_BYTES); - if(decBytes <= 0) { exit(5); } - { - /* Write out the part of the data we care about */ - int blockLength = MIN(length, (decBytes - offset)); - write_bin(outFp, decBuf + offset, (size_t)blockLength); - offset = 0; - length -= blockLength; - } - } - } -} - - -int compare(FILE* fp0, FILE* fp1, int length) -{ - int result = 0; - - while(0 == result) { - char b0[4096]; - char b1[4096]; - const size_t r0 = read_bin(fp0, b0, MIN(length, (int)sizeof(b0))); - const size_t r1 = read_bin(fp1, b1, MIN(length, (int)sizeof(b1))); - - result = (int) r0 - (int) r1; - - if(0 == r0 || 0 == r1) { - break; - } - if(0 == result) { - result = memcmp(b0, b1, r0); - } - length -= r0; - } - - return result; -} - - -int main(int argc, char* argv[]) -{ - char inpFilename[256] = { 0 }; - char lz4Filename[256] = { 0 }; - char decFilename[256] = { 0 }; - char dictFilename[256] = { 0 }; - int offset; - int length; - char dict[DICTIONARY_BYTES]; - int dictSize; - - if(argc < 5) { - printf("Usage: %s input dictionary offset length", argv[0]); - return 0; - } - - snprintf(inpFilename, 256, "%s", argv[1]); - snprintf(lz4Filename, 256, "%s.lz4s-%d", argv[1], BLOCK_BYTES); - snprintf(decFilename, 256, "%s.lz4s-%d.dec", argv[1], BLOCK_BYTES); - snprintf(dictFilename, 256, "%s", argv[2]); - offset = atoi(argv[3]); - length = atoi(argv[4]); - - printf("inp = [%s]\n", inpFilename); - printf("lz4 = [%s]\n", lz4Filename); - printf("dec = [%s]\n", decFilename); - printf("dict = [%s]\n", dictFilename); - printf("offset = [%d]\n", offset); - printf("length = [%d]\n", length); - - /* Load dictionary */ - { - FILE* dictFp = fopen(dictFilename, "rb"); - dictSize = (int)read_bin(dictFp, dict, DICTIONARY_BYTES); - fclose(dictFp); - } - - /* compress */ - { - FILE* inpFp = fopen(inpFilename, "rb"); - FILE* outFp = fopen(lz4Filename, "wb"); - - printf("compress : %s -> %s\n", inpFilename, lz4Filename); - test_compress(outFp, inpFp, dict, dictSize); - printf("compress : done\n"); - - fclose(outFp); - fclose(inpFp); - } - - /* decompress */ - { - FILE* inpFp = fopen(lz4Filename, "rb"); - FILE* outFp = fopen(decFilename, "wb"); - - printf("decompress : %s -> %s\n", lz4Filename, decFilename); - test_decompress(outFp, inpFp, dict, DICTIONARY_BYTES, offset, length); - printf("decompress : done\n"); - - fclose(outFp); - fclose(inpFp); - } - - /* verify */ - { - FILE* inpFp = fopen(inpFilename, "rb"); - FILE* decFp = fopen(decFilename, "rb"); - seek_bin(inpFp, offset, SEEK_SET); - - printf("verify : %s <-> %s\n", inpFilename, decFilename); - const int cmp = compare(inpFp, decFp, length); - if(0 == cmp) { - printf("verify : OK\n"); - } else { - printf("verify : NG\n"); - } - - fclose(decFp); - fclose(inpFp); - } - - return 0; -} diff --git a/src/lz4/examples/dictionaryRandomAccess.md b/src/lz4/examples/dictionaryRandomAccess.md deleted file mode 100644 index 53d825deca..0000000000 --- a/src/lz4/examples/dictionaryRandomAccess.md +++ /dev/null @@ -1,67 +0,0 @@ -# LZ4 API Example : Dictionary Random Access - -`dictionaryRandomAccess.c` is LZ4 API example which implements dictionary compression and random access decompression. - -Please note that the output file is not compatible with lz4frame and is platform dependent. - - -## What's the point of this example ? - - - Dictionary based compression for homogenous files. - - Random access to compressed blocks. - - -## How the compression works - -Reads the dictionary from a file, and uses it as the history for each block. -This allows each block to be independent, but maintains compression ratio. - -``` - Dictionary - + - | - v - +---------+ - | Block#1 | - +----+----+ - | - v - {Out#1} - - - Dictionary - + - | - v - +---------+ - | Block#2 | - +----+----+ - | - v - {Out#2} -``` - -After writing the magic bytes `TEST` and then the compressed blocks, write out the jump table. -The last 4 bytes is an integer containing the number of blocks in the stream. -If there are `N` blocks, then just before the last 4 bytes is `N + 1` 4 byte integers containing the offsets at the beginning and end of each block. -Let `Offset#K` be the total number of bytes written after writing out `Block#K` *including* the magic bytes for simplicity. - -``` -+------+---------+ +---------+---+----------+ +----------+-----+ -| TEST | Block#1 | ... | Block#N | 4 | Offset#1 | ... | Offset#N | N+1 | -+------+---------+ +---------+---+----------+ +----------+-----+ -``` - -## How the decompression works - -Decompression will do reverse order. - - - Seek to the last 4 bytes of the file and read the number of offsets. - - Read each offset into an array. - - Seek to the first block containing data we want to read. - We know where to look because we know each block contains a fixed amount of uncompressed data, except possibly the last. - - Decompress it and write what data we need from it to the file. - - Read the next block. - - Decompress it and write that page to the file. - -Continue these procedure until all the required data has been read. diff --git a/src/lz4/examples/frameCompress.c b/src/lz4/examples/frameCompress.c deleted file mode 100644 index 8712725e41..0000000000 --- a/src/lz4/examples/frameCompress.c +++ /dev/null @@ -1,312 +0,0 @@ -// LZ4frame API example : compress a file -// Based on sample code from Zbigniew Jędrzejewski-Szmek - -#include -#include -#include -#include - -#include - -#define BUF_SIZE 16*1024 -#define LZ4_HEADER_SIZE 19 -#define LZ4_FOOTER_SIZE 4 - -static const LZ4F_preferences_t lz4_preferences = { - { LZ4F_max256KB, LZ4F_blockLinked, LZ4F_noContentChecksum, LZ4F_frame, - 0 /* content size unknown */, 0 /* no dictID */ , LZ4F_noBlockChecksum }, - 0, /* compression level */ - 0, /* autoflush */ - { 0, 0, 0, 0 }, /* reserved, must be set to 0 */ -}; - -static size_t compress_file(FILE *in, FILE *out, size_t *size_in, size_t *size_out) { - LZ4F_errorCode_t r; - LZ4F_compressionContext_t ctx; - char *src, *buf = NULL; - size_t size, n, k, count_in = 0, count_out, offset = 0, frame_size; - - r = LZ4F_createCompressionContext(&ctx, LZ4F_VERSION); - if (LZ4F_isError(r)) { - printf("Failed to create context: error %zu\n", r); - return 1; - } - r = 1; /* function result; 1 == error, by default (early exit) */ - - src = malloc(BUF_SIZE); - if (!src) { - printf("Not enough memory\n"); - goto cleanup; - } - - frame_size = LZ4F_compressBound(BUF_SIZE, &lz4_preferences); - size = frame_size + LZ4_HEADER_SIZE + LZ4_FOOTER_SIZE; - buf = malloc(size); - if (!buf) { - printf("Not enough memory\n"); - goto cleanup; - } - - n = offset = count_out = LZ4F_compressBegin(ctx, buf, size, &lz4_preferences); - if (LZ4F_isError(n)) { - printf("Failed to start compression: error %zu\n", n); - goto cleanup; - } - - printf("Buffer size is %zu bytes, header size %zu bytes\n", size, n); - - for (;;) { - k = fread(src, 1, BUF_SIZE, in); - if (k == 0) - break; - count_in += k; - - n = LZ4F_compressUpdate(ctx, buf + offset, size - offset, src, k, NULL); - if (LZ4F_isError(n)) { - printf("Compression failed: error %zu\n", n); - goto cleanup; - } - - offset += n; - count_out += n; - if (size - offset < frame_size + LZ4_FOOTER_SIZE) { - printf("Writing %zu bytes\n", offset); - - k = fwrite(buf, 1, offset, out); - if (k < offset) { - if (ferror(out)) - printf("Write failed\n"); - else - printf("Short write\n"); - goto cleanup; - } - - offset = 0; - } - } - - n = LZ4F_compressEnd(ctx, buf + offset, size - offset, NULL); - if (LZ4F_isError(n)) { - printf("Failed to end compression: error %zu\n", n); - goto cleanup; - } - - offset += n; - count_out += n; - printf("Writing %zu bytes\n", offset); - - k = fwrite(buf, 1, offset, out); - if (k < offset) { - if (ferror(out)) - printf("Write failed\n"); - else - printf("Short write\n"); - goto cleanup; - } - - *size_in = count_in; - *size_out = count_out; - r = 0; - cleanup: - if (ctx) - LZ4F_freeCompressionContext(ctx); - free(src); - free(buf); - return r; -} - -static size_t get_block_size(const LZ4F_frameInfo_t* info) { - switch (info->blockSizeID) { - case LZ4F_default: - case LZ4F_max64KB: return 1 << 16; - case LZ4F_max256KB: return 1 << 18; - case LZ4F_max1MB: return 1 << 20; - case LZ4F_max4MB: return 1 << 22; - default: - printf("Impossible unless more block sizes are allowed\n"); - exit(1); - } -} - -static size_t decompress_file(FILE *in, FILE *out) { - void* const src = malloc(BUF_SIZE); - void* dst = NULL; - size_t dstCapacity = 0; - LZ4F_dctx *dctx = NULL; - size_t ret; - - /* Initialization */ - if (!src) { perror("decompress_file(src)"); goto cleanup; } - ret = LZ4F_createDecompressionContext(&dctx, 100); - if (LZ4F_isError(ret)) { - printf("LZ4F_dctx creation error: %s\n", LZ4F_getErrorName(ret)); - goto cleanup; - } - - /* Decompression */ - ret = 1; - while (ret != 0) { - /* Load more input */ - size_t srcSize = fread(src, 1, BUF_SIZE, in); - void* srcPtr = src; - void* srcEnd = srcPtr + srcSize; - if (srcSize == 0 || ferror(in)) { - printf("Decompress: not enough input or error reading file\n"); - goto cleanup; - } - /* Allocate destination buffer if it isn't already */ - if (!dst) { - LZ4F_frameInfo_t info; - ret = LZ4F_getFrameInfo(dctx, &info, src, &srcSize); - if (LZ4F_isError(ret)) { - printf("LZ4F_getFrameInfo error: %s\n", LZ4F_getErrorName(ret)); - goto cleanup; - } - /* Allocating enough space for an entire block isn't necessary for - * correctness, but it allows some memcpy's to be elided. - */ - dstCapacity = get_block_size(&info); - dst = malloc(dstCapacity); - if (!dst) { perror("decompress_file(dst)"); goto cleanup; } - srcPtr += srcSize; - srcSize = srcEnd - srcPtr; - } - /* Decompress: - * Continue while there is more input to read and the frame isn't over. - * If srcPtr == srcEnd then we know that there is no more output left in the - * internal buffer left to flush. - */ - while (srcPtr != srcEnd && ret != 0) { - /* INVARIANT: Any data left in dst has already been written */ - size_t dstSize = dstCapacity; - ret = LZ4F_decompress(dctx, dst, &dstSize, srcPtr, &srcSize, /* LZ4F_decompressOptions_t */ NULL); - if (LZ4F_isError(ret)) { - printf("Decompression error: %s\n", LZ4F_getErrorName(ret)); - goto cleanup; - } - /* Flush output */ - if (dstSize != 0){ - size_t written = fwrite(dst, 1, dstSize, out); - printf("Writing %zu bytes\n", dstSize); - if (written != dstSize) { - printf("Decompress: Failed to write to file\n"); - goto cleanup; - } - } - /* Update input */ - srcPtr += srcSize; - srcSize = srcEnd - srcPtr; - } - } - /* Check that there isn't trailing input data after the frame. - * It is valid to have multiple frames in the same file, but this example - * doesn't support it. - */ - ret = fread(src, 1, 1, in); - if (ret != 0 || !feof(in)) { - printf("Decompress: Trailing data left in file after frame\n"); - goto cleanup; - } - -cleanup: - free(src); - free(dst); - return LZ4F_freeDecompressionContext(dctx); /* note : free works on NULL */ -} - -int compare(FILE* fp0, FILE* fp1) -{ - int result = 0; - - while(0 == result) { - char b0[1024]; - char b1[1024]; - const size_t r0 = fread(b0, 1, sizeof(b0), fp0); - const size_t r1 = fread(b1, 1, sizeof(b1), fp1); - - result = (int) r0 - (int) r1; - - if (0 == r0 || 0 == r1) { - break; - } - if (0 == result) { - result = memcmp(b0, b1, r0); - } - } - - return result; -} - -int main(int argc, const char **argv) { - char inpFilename[256] = { 0 }; - char lz4Filename[256] = { 0 }; - char decFilename[256] = { 0 }; - - if(argc < 2) { - printf("Please specify input filename\n"); - return 0; - } - - snprintf(inpFilename, 256, "%s", argv[1]); - snprintf(lz4Filename, 256, "%s.lz4", argv[1]); - snprintf(decFilename, 256, "%s.lz4.dec", argv[1]); - - printf("inp = [%s]\n", inpFilename); - printf("lz4 = [%s]\n", lz4Filename); - printf("dec = [%s]\n", decFilename); - - /* compress */ - { FILE* const inpFp = fopen(inpFilename, "rb"); - FILE* const outFp = fopen(lz4Filename, "wb"); - size_t sizeIn = 0; - size_t sizeOut = 0; - size_t ret; - - printf("compress : %s -> %s\n", inpFilename, lz4Filename); - ret = compress_file(inpFp, outFp, &sizeIn, &sizeOut); - if (ret) { - printf("compress : failed with code %zu\n", ret); - return (int)ret; - } - printf("%s: %zu → %zu bytes, %.1f%%\n", - inpFilename, sizeIn, sizeOut, - (double)sizeOut / sizeIn * 100); - printf("compress : done\n"); - - fclose(outFp); - fclose(inpFp); - } - - /* decompress */ - { FILE* const inpFp = fopen(lz4Filename, "rb"); - FILE* const outFp = fopen(decFilename, "wb"); - size_t ret; - - printf("decompress : %s -> %s\n", lz4Filename, decFilename); - ret = decompress_file(inpFp, outFp); - if (ret) { - printf("decompress : failed with code %zu\n", ret); - return (int)ret; - } - printf("decompress : done\n"); - - fclose(outFp); - fclose(inpFp); - } - - /* verify */ - { FILE* const inpFp = fopen(inpFilename, "rb"); - FILE* const decFp = fopen(decFilename, "rb"); - - printf("verify : %s <-> %s\n", inpFilename, decFilename); - const int cmp = compare(inpFp, decFp); - if(0 == cmp) { - printf("verify : OK\n"); - } else { - printf("verify : NG\n"); - } - - fclose(decFp); - fclose(inpFp); - } -} diff --git a/src/lz4/examples/printVersion.c b/src/lz4/examples/printVersion.c deleted file mode 100644 index 86071397c8..0000000000 --- a/src/lz4/examples/printVersion.c +++ /dev/null @@ -1,13 +0,0 @@ -// LZ4 trivial example : print Library version number -// Copyright : Takayuki Matsuoka & Yann Collet - - -#include -#include "lz4.h" - -int main(int argc, char** argv) -{ - (void)argc; (void)argv; - printf("Hello World ! LZ4 Library version = %d\n", LZ4_versionNumber()); - return 0; -} diff --git a/src/lz4/examples/simple_buffer.c b/src/lz4/examples/simple_buffer.c deleted file mode 100644 index 403d9e87ca..0000000000 --- a/src/lz4/examples/simple_buffer.c +++ /dev/null @@ -1,94 +0,0 @@ -/* - * simple_buffer.c - * Copyright : Kyle Harper - * License : Follows same licensing as the lz4.c/lz4.h program at any given time. Currently, BSD 2. - * Description: Example program to demonstrate the basic usage of the compress/decompress functions within lz4.c/lz4.h. - * The functions you'll likely want are LZ4_compress_default and LZ4_decompress_safe. Both of these are documented in - * the lz4.h header file; I recommend reading them. - */ - -/* Includes, for Power! */ -#include "lz4.h" // This is all that is required to expose the prototypes for basic compression and decompression. -#include // For printf() -#include // For memcmp() -#include // For exit() - -/* - * Easy show-error-and-bail function. - */ -void run_screaming(const char *message, const int code) { - printf("%s\n", message); - exit(code); - return; -} - - -/* - * main - */ -int main(void) { - /* Introduction */ - // Below we will have a Compression and Decompression section to demonstrate. - // There are a few important notes before we start: - // 1) The return codes of LZ4_ functions are important. - // Read lz4.h if you're unsure what a given code means. - // 2) LZ4 uses char* pointers in all LZ4_ functions. - // This is baked into the API and probably not going to change. - // If your program uses pointers that are unsigned char*, void*, or otherwise different, - // you may need to do some casting or set the right -W compiler flags to ignore those warnings (e.g.: -Wno-pointer-sign). - - /* Compression */ - // We'll store some text into a variable pointed to by *src to be compressed later. - const char* const src = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; - // The compression function needs to know how many bytes exist. Since we're using a string, we can use strlen() + 1 (for \0). - const int src_size = (int)(strlen(src) + 1); - // LZ4 provides a function that will tell you the maximum size of compressed output based on input data via LZ4_compressBound(). - const int max_dst_size = LZ4_compressBound(src_size); - // We will use that size for our destination boundary when allocating space. - char* compressed_data = malloc(max_dst_size); - if (compressed_data == NULL) - run_screaming("Failed to allocate memory for *compressed_data.", 1); - // That's all the information and preparation LZ4 needs to compress *src into *compressed_data. - // Invoke LZ4_compress_default now with our size values and pointers to our memory locations. - // Save the return value for error checking. - const int compressed_data_size = LZ4_compress_default(src, compressed_data, src_size, max_dst_size); - // Check return_value to determine what happened. - if (compressed_data_size < 0) - run_screaming("A negative result from LZ4_compress_default indicates a failure trying to compress the data. See exit code (echo $?) for value returned.", compressed_data_size); - if (compressed_data_size == 0) - run_screaming("A result of 0 means compression worked, but was stopped because the destination buffer couldn't hold all the information.", 1); - if (compressed_data_size > 0) - printf("We successfully compressed some data!\n"); - // Not only does a positive return_value mean success, the value returned == the number of bytes required. - // You can use this to realloc() *compress_data to free up memory, if desired. We'll do so just to demonstrate the concept. - compressed_data = (char *)realloc(compressed_data, compressed_data_size); - if (compressed_data == NULL) - run_screaming("Failed to re-alloc memory for compressed_data. Sad :(", 1); - - /* Decompression */ - // Now that we've successfully compressed the information from *src to *compressed_data, let's do the opposite! We'll create a - // *new_src location of size src_size since we know that value. - char* const regen_buffer = malloc(src_size); - if (regen_buffer == NULL) - run_screaming("Failed to allocate memory for *regen_buffer.", 1); - // The LZ4_decompress_safe function needs to know where the compressed data is, how many bytes long it is, - // where the regen_buffer memory location is, and how large regen_buffer (uncompressed) output will be. - // Again, save the return_value. - const int decompressed_size = LZ4_decompress_safe(compressed_data, regen_buffer, compressed_data_size, src_size); - free(compressed_data); /* no longer useful */ - if (decompressed_size < 0) - run_screaming("A negative result from LZ4_decompress_safe indicates a failure trying to decompress the data. See exit code (echo $?) for value returned.", decompressed_size); - if (decompressed_size == 0) - run_screaming("I'm not sure this function can ever return 0. Documentation in lz4.h doesn't indicate so.", 1); - if (decompressed_size > 0) - printf("We successfully decompressed some data!\n"); - // Not only does a positive return value mean success, - // value returned == number of bytes regenerated from compressed_data stream. - - /* Validation */ - // We should be able to compare our original *src with our *new_src and be byte-for-byte identical. - if (memcmp(src, regen_buffer, src_size) != 0) - run_screaming("Validation failed. *src and *new_src are not identical.", 1); - printf("Validation done. The string we ended up with is:\n%s\n", regen_buffer); - return 0; -} diff --git a/src/lz4/examples/streaming_api_basics.md b/src/lz4/examples/streaming_api_basics.md deleted file mode 100644 index 90065e42af..0000000000 --- a/src/lz4/examples/streaming_api_basics.md +++ /dev/null @@ -1,87 +0,0 @@ -# LZ4 Streaming API Basics -by *Takayuki Matsuoka* -## LZ4 API sets - -LZ4 has the following API sets : - - - "Auto Framing" API (lz4frame.h) : - This is most recommended API for usual application. - It guarantees interoperability with other LZ4 framing format compliant tools/libraries - such as LZ4 command line utility, node-lz4, etc. - - "Block" API : This is recommended for simple purpose. - It compress single raw memory block to LZ4 memory block and vice versa. - - "Streaming" API : This is designed for complex thing. - For example, compress huge stream data in restricted memory environment. - -Basically, you should use "Auto Framing" API. -But if you want to write advanced application, it's time to use Block or Streaming APIs. - - -## What is difference between Block and Streaming API ? - -Block API (de)compresses single contiguous memory block. -In other words, LZ4 library find redundancy from single contiguous memory block. -Streaming API does same thing but (de)compress multiple adjacent contiguous memory block. -So LZ4 library could find more redundancy than Block API. - -The following figure shows difference between API and block sizes. -In these figures, original data is splitted to 4KiBytes contiguous chunks. - -``` -Original Data - +---------------+---------------+----+----+----+ - | 4KiB Chunk A | 4KiB Chunk B | C | D |... | - +---------------+---------------+----+----+----+ - -Example (1) : Block API, 4KiB Block - +---------------+---------------+----+----+----+ - | 4KiB Chunk A | 4KiB Chunk B | C | D |... | - +---------------+---------------+----+----+----+ - | Block #1 | Block #2 | #3 | #4 |... | - +---------------+---------------+----+----+----+ - - (No Dependency) - - -Example (2) : Block API, 8KiB Block - +---------------+---------------+----+----+----+ - | 4KiB Chunk A | 4KiB Chunk B | C | D |... | - +---------------+---------------+----+----+----+ - | Block #1 |Block #2 |... | - +--------------------+----------+-------+-+----+ - ^ | ^ | - | | | | - +--------------+ +----+ - Internal Dependency Internal Dependency - - -Example (3) : Streaming API, 4KiB Block - +---------------+---------------+-----+----+----+ - | 4KiB Chunk A | 4KiB Chunk B | C | D |... | - +---------------+---------------+-----+----+----+ - | Block #1 | Block #2 | #3 | #4 |... | - +---------------+----+----------+-+---+-+--+----+ - ^ | ^ | ^ | - | | | | | | - +--------------+ +--------+ +---+ - Dependency Dependency Dependency -``` - - - In example (1), there is no dependency. - All blocks are compressed independently. - - In example (2), naturally 8KiBytes block has internal dependency. - But still block #1 and #2 are compressed independently. - - In example (3), block #2 has dependency to #1, - also #3 has dependency to #2 and #1, #4 has #3, #2 and #1, and so on. - -Here, we can observe difference between example (2) and (3). -In (2), there's no dependency between chunk B and C, but (3) has dependency between B and C. -This dependency improves compression ratio. - - -## Restriction of Streaming API - -For the efficiency, Streaming API doesn't keep mirror copy of dependent (de)compressed memory. -This means users should keep these dependent (de)compressed memory explicitly. -Usually, "Dependent memory" is previous adjacent contiguous memory up to 64KiBytes. -LZ4 will not access further memories. diff --git a/src/lz4/lib/.gitignore b/src/lz4/lib/.gitignore deleted file mode 100644 index 5d6f134c53..0000000000 --- a/src/lz4/lib/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -# make install artefact -liblz4.pc diff --git a/src/lz4/lib/LICENSE b/src/lz4/lib/LICENSE deleted file mode 100644 index 74c2cdd7d5..0000000000 --- a/src/lz4/lib/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -LZ4 Library -Copyright (c) 2011-2016, Yann Collet -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/lz4/lib/Makefile b/src/lz4/lib/Makefile deleted file mode 100644 index 9abb6994a6..0000000000 --- a/src/lz4/lib/Makefile +++ /dev/null @@ -1,180 +0,0 @@ -# ################################################################ -# LZ4 library - Makefile -# Copyright (C) Yann Collet 2011-2016 -# All rights reserved. -# -# This Makefile is validated for Linux, macOS, *BSD, Hurd, Solaris, MSYS2 targets -# -# BSD license -# Redistribution and use in source and binary forms, with or without modification, -# are permitted provided that the following conditions are met: -# -# * Redistributions of source code must retain the above copyright notice, this -# list of conditions and the following disclaimer. -# -# * Redistributions in binary form must reproduce the above copyright notice, this -# list of conditions and the following disclaimer in the documentation and/or -# other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# -# You can contact the author at : -# - LZ4 source repository : https://github.com/Cyan4973/lz4 -# - LZ4 forum froup : https://groups.google.com/forum/#!forum/lz4c -# ################################################################ - -# Version numbers -LIBVER_MAJOR_SCRIPT:=`sed -n '/define LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ./lz4.h` -LIBVER_MINOR_SCRIPT:=`sed -n '/define LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ./lz4.h` -LIBVER_PATCH_SCRIPT:=`sed -n '/define LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ./lz4.h` -LIBVER_SCRIPT:= $(LIBVER_MAJOR_SCRIPT).$(LIBVER_MINOR_SCRIPT).$(LIBVER_PATCH_SCRIPT) -LIBVER_MAJOR := $(shell echo $(LIBVER_MAJOR_SCRIPT)) -LIBVER_MINOR := $(shell echo $(LIBVER_MINOR_SCRIPT)) -LIBVER_PATCH := $(shell echo $(LIBVER_PATCH_SCRIPT)) -LIBVER := $(shell echo $(LIBVER_SCRIPT)) - -BUILD_STATIC:=yes - -CPPFLAGS+= -DXXH_NAMESPACE=LZ4_ -CFLAGS ?= -O3 -DEBUGFLAGS:= -Wall -Wextra -Wcast-qual -Wcast-align -Wshadow \ - -Wswitch-enum -Wdeclaration-after-statement -Wstrict-prototypes -Wundef \ - -Wpointer-arith -Wstrict-aliasing=1 -CFLAGS += $(DEBUGFLAGS) $(MOREFLAGS) -FLAGS = $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) - - - -# OS X linker doesn't support -soname, and use different extension -# see : https://developer.apple.com/library/mac/documentation/DeveloperTools/Conceptual/DynamicLibraries/100-Articles/DynamicLibraryDesignGuidelines.html -ifeq ($(shell uname), Darwin) - SHARED_EXT = dylib - SHARED_EXT_MAJOR = $(LIBVER_MAJOR).$(SHARED_EXT) - SHARED_EXT_VER = $(LIBVER).$(SHARED_EXT) - SONAME_FLAGS = -install_name $(LIBDIR)/liblz4.$(SHARED_EXT_MAJOR) -compatibility_version $(LIBVER_MAJOR) -current_version $(LIBVER) -else - SONAME_FLAGS = -Wl,-soname=liblz4.$(SHARED_EXT).$(LIBVER_MAJOR) - SHARED_EXT = so - SHARED_EXT_MAJOR = $(SHARED_EXT).$(LIBVER_MAJOR) - SHARED_EXT_VER = $(SHARED_EXT).$(LIBVER) -endif - -LIBLZ4 = liblz4.$(SHARED_EXT_VER) - -.PHONY: default -default: lib-release - -lib-release: DEBUGFLAGS := -lib-release: lib - -lib: liblz4.a liblz4 - -all: lib - -all32: CFLAGS+=-m32 -all32: all - -liblz4.a: *.c -ifeq ($(BUILD_STATIC),yes) # can be disabled on command line - @echo compiling static library - @$(CC) $(CPPFLAGS) $(CFLAGS) -c $^ - @$(AR) rcs $@ *.o -endif - -$(LIBLZ4): *.c - @echo compiling dynamic library $(LIBVER) -ifneq (,$(filter Windows%,$(OS))) - @$(CC) $(FLAGS) -DLZ4_DLL_EXPORT=1 -shared $^ -o dll\$@.dll - dlltool -D dll\liblz4.dll -d dll\liblz4.def -l dll\liblz4.lib -else - @$(CC) $(FLAGS) -shared $^ -fPIC -fvisibility=hidden $(SONAME_FLAGS) -o $@ - @echo creating versioned links - @ln -sf $@ liblz4.$(SHARED_EXT_MAJOR) - @ln -sf $@ liblz4.$(SHARED_EXT) -endif - -liblz4: $(LIBLZ4) - -clean: - @$(RM) core *.o liblz4.pc dll/liblz4.dll dll/liblz4.lib - @$(RM) *.a *.$(SHARED_EXT) *.$(SHARED_EXT_MAJOR) *.$(SHARED_EXT_VER) - @echo Cleaning library completed - - -#----------------------------------------------------------------------------- -# make install is validated only for Linux, OSX, BSD, Hurd and Solaris targets -#----------------------------------------------------------------------------- -ifneq (,$(filter $(shell uname),Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD NetBSD DragonFly SunOS)) - -DESTDIR ?= -# directory variables : GNU convention prefers lowercase -# support both lower and uppercase (BSD), use uppercase in script -prefix ?= /usr/local -PREFIX ?= $(prefix) -exec_prefix ?= $(PREFIX) -libdir ?= $(exec_prefix)/lib -LIBDIR ?= $(libdir) -includedir ?= $(PREFIX)/include -INCLUDEDIR ?= $(includedir) - -ifneq (,$(filter $(shell uname),OpenBSD FreeBSD NetBSD DragonFly)) -PKGCONFIGDIR ?= $(PREFIX)/libdata/pkgconfig -else -PKGCONFIGDIR ?= $(LIBDIR)/pkgconfig -endif - -ifneq (,$(filter $(shell uname),SunOS)) -INSTALL ?= ginstall -else -INSTALL ?= install -endif - -INSTALL_PROGRAM ?= $(INSTALL) -INSTALL_DATA ?= $(INSTALL) -m 644 - -liblz4.pc: liblz4.pc.in Makefile - @echo creating pkgconfig - @sed -e 's|@PREFIX@|$(PREFIX)|' \ - -e 's|@LIBDIR@|$(LIBDIR)|' \ - -e 's|@INCLUDEDIR@|$(INCLUDEDIR)|' \ - -e 's|@VERSION@|$(LIBVER)|' \ - $< >$@ - -install: lib liblz4.pc - @$(INSTALL) -d -m 755 $(DESTDIR)$(PKGCONFIGDIR)/ $(DESTDIR)$(INCLUDEDIR)/ $(DESTDIR)$(LIBDIR)/ - @$(INSTALL_DATA) liblz4.pc $(DESTDIR)$(PKGCONFIGDIR)/ - @echo Installing libraries -ifeq ($(BUILD_STATIC),yes) - @$(INSTALL_DATA) liblz4.a $(DESTDIR)$(LIBDIR)/liblz4.a - @$(INSTALL_DATA) lz4frame_static.h $(DESTDIR)$(INCLUDEDIR)/lz4frame_static.h -endif - @$(INSTALL_PROGRAM) liblz4.$(SHARED_EXT_VER) $(DESTDIR)$(LIBDIR) - @ln -sf liblz4.$(SHARED_EXT_VER) $(DESTDIR)$(LIBDIR)/liblz4.$(SHARED_EXT_MAJOR) - @ln -sf liblz4.$(SHARED_EXT_VER) $(DESTDIR)$(LIBDIR)/liblz4.$(SHARED_EXT) - @echo Installing headers in $(INCLUDEDIR) - @$(INSTALL_DATA) lz4.h $(DESTDIR)$(INCLUDEDIR)/lz4.h - @$(INSTALL_DATA) lz4hc.h $(DESTDIR)$(INCLUDEDIR)/lz4hc.h - @$(INSTALL_DATA) lz4frame.h $(DESTDIR)$(INCLUDEDIR)/lz4frame.h - @echo lz4 libraries installed - -uninstall: - @$(RM) $(DESTDIR)$(LIBDIR)/pkgconfig/liblz4.pc - @$(RM) $(DESTDIR)$(LIBDIR)/liblz4.$(SHARED_EXT) - @$(RM) $(DESTDIR)$(LIBDIR)/liblz4.$(SHARED_EXT_MAJOR) - @$(RM) $(DESTDIR)$(LIBDIR)/liblz4.$(SHARED_EXT_VER) - @$(RM) $(DESTDIR)$(LIBDIR)/liblz4.a - @$(RM) $(DESTDIR)$(INCLUDEDIR)/lz4.h - @$(RM) $(DESTDIR)$(INCLUDEDIR)/lz4hc.h - @$(RM) $(DESTDIR)$(INCLUDEDIR)/lz4frame.h - @echo lz4 libraries successfully uninstalled - -endif diff --git a/src/lz4/lib/README.md b/src/lz4/lib/README.md deleted file mode 100644 index b40442c4d3..0000000000 --- a/src/lz4/lib/README.md +++ /dev/null @@ -1,73 +0,0 @@ -LZ4 - Library Files -================================ - -The directory contains many files, but depending on project's objectives, -not all of them are necessary. - -#### Minimal LZ4 build - -The minimum required is **`lz4.c`** and **`lz4.h`**, -which will provide the fast compression and decompression algorithm. - - -#### The High Compression variant of LZ4 - -For more compression at the cost of compression speed, -the High Compression variant **lz4hc** is available. -It's necessary to add **`lz4hc.c`** and **`lz4hc.h`**. -The variant still depends on regular `lz4` source files. -In particular, the decompression is still provided by `lz4.c`. - - -#### Compatibility issues - -In order to produce files or streams compatible with `lz4` command line utility, -it's necessary to encode lz4-compressed blocks using the [official interoperable frame format]. -This format is generated and decoded automatically by the **lz4frame** library. -In order to work properly, lz4frame needs lz4 and lz4hc, and also **xxhash**, -which provides error detection. -(_Advanced stuff_ : It's possible to hide xxhash symbols into a local namespace. -This is what `liblz4` does, to avoid symbol duplication -in case a user program would link to several libraries containing xxhash symbols.) - - -#### Advanced API - -A more complex `lz4frame_static.h` is also provided. -It contains definitions which are not guaranteed to remain stable within future versions. -It must be used with static linking ***only***. - - -#### Using MinGW+MSYS to create DLL - -DLL can be created using MinGW+MSYS with the `make liblz4` command. -This command creates `dll\liblz4.dll` and the import library `dll\liblz4.lib`. -The import library is only required with Visual C++. -The header files `lz4.h`, `lz4hc.h`, `lz4frame.h` and the dynamic library -`dll\liblz4.dll` are required to compile a project using gcc/MinGW. -The dynamic library has to be added to linking options. -It means that if a project that uses LZ4 consists of a single `test-dll.c` -file it should be linked with `dll\liblz4.dll`. For example: -``` - gcc $(CFLAGS) -Iinclude/ test-dll.c -o test-dll dll\liblz4.dll -``` -The compiled executable will require LZ4 DLL which is available at `dll\liblz4.dll`. - - -#### Miscellaneous - -Other files present in the directory are not source code. There are : - - - LICENSE : contains the BSD license text - - Makefile : script to compile or install lz4 library (static or dynamic) - - liblz4.pc.in : for pkg-config (make install) - - README.md : this file - -[official interoperable frame format]: ../doc/lz4_Frame_format.md - - -#### License - -All source material within __lib__ directory are BSD 2-Clause licensed. -See [LICENSE](LICENSE) for details. -The license is also repeated at the top of each source file. diff --git a/src/lz4/lib/dll/example/Makefile b/src/lz4/lib/dll/example/Makefile deleted file mode 100644 index e9879568da..0000000000 --- a/src/lz4/lib/dll/example/Makefile +++ /dev/null @@ -1,63 +0,0 @@ -# ########################################################################## -# LZ4 programs - Makefile -# Copyright (C) Yann Collet 2016 -# -# GPL v2 License -# -# This program is free software; 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-1301 USA. -# -# You can contact the author at : -# - LZ4 homepage : http://www.lz4.org -# - LZ4 source repository : https://github.com/lz4/lz4 -# ########################################################################## - -VOID := /dev/null -LZ4DIR := ../include -LIBDIR := ../static -DLLDIR := ../dll - -CFLAGS ?= -O3 # can select custom flags. For example : CFLAGS="-O2 -g" make -CFLAGS += -Wall -Wextra -Wundef -Wcast-qual -Wcast-align -Wshadow -Wswitch-enum \ - -Wdeclaration-after-statement -Wstrict-prototypes \ - -Wpointer-arith -Wstrict-aliasing=1 -CFLAGS += $(MOREFLAGS) -CPPFLAGS:= -I$(LZ4DIR) -DXXH_NAMESPACE=LZ4_ -FLAGS := $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) - - -# Define *.exe as extension for Windows systems -ifneq (,$(filter Windows%,$(OS))) -EXT =.exe -else -EXT = -endif - -.PHONY: default fullbench-dll fullbench-lib - - -default: all - -all: fullbench-dll fullbench-lib - - -fullbench-lib: fullbench.c xxhash.c - $(CC) $(FLAGS) $^ -o $@$(EXT) $(LIBDIR)/liblz4_static.lib - -fullbench-dll: fullbench.c xxhash.c - $(CC) $(FLAGS) $^ -o $@$(EXT) -DLZ4_DLL_IMPORT=1 $(DLLDIR)/liblz4.dll - -clean: - @$(RM) fullbench-dll$(EXT) fullbench-lib$(EXT) \ - @echo Cleaning completed diff --git a/src/lz4/lib/dll/example/README.md b/src/lz4/lib/dll/example/README.md deleted file mode 100644 index 223e4738a0..0000000000 --- a/src/lz4/lib/dll/example/README.md +++ /dev/null @@ -1,69 +0,0 @@ -LZ4 Windows binary package -==================================== - -#### The package contents - -- `lz4.exe` : Command Line Utility, supporting gzip-like arguments -- `dll\liblz4.dll` : The DLL of LZ4 library -- `dll\liblz4.lib` : The import library of LZ4 library for Visual C++ -- `example\` : The example of usage of LZ4 library -- `include\` : Header files required with LZ4 library -- `static\liblz4_static.lib` : The static LZ4 library - - -#### Usage of Command Line Interface - -Command Line Interface (CLI) supports gzip-like arguments. -By default CLI takes an input file and compresses it to an output file: -``` - Usage: lz4 [arg] [input] [output] -``` -The full list of commands for CLI can be obtained with `-h` or `-H`. The ratio can -be improved with commands from `-3` to `-16` but higher levels also have slower -compression. CLI includes in-memory compression benchmark module with compression -levels starting from `-b` and ending with `-e` with iteration time of `-i` seconds. -CLI supports aggregation of parameters i.e. `-b1`, `-e18`, and `-i1` can be joined -into `-b1e18i1`. - - -#### The example of usage of static and dynamic LZ4 libraries with gcc/MinGW - -Use `cd example` and `make` to build `fullbench-dll` and `fullbench-lib`. -`fullbench-dll` uses a dynamic LZ4 library from the `dll` directory. -`fullbench-lib` uses a static LZ4 library from the `lib` directory. - - -#### Using LZ4 DLL with gcc/MinGW - -The header files from `include\` and the dynamic library `dll\liblz4.dll` -are required to compile a project using gcc/MinGW. -The dynamic library has to be added to linking options. -It means that if a project that uses LZ4 consists of a single `test-dll.c` -file it should be linked with `dll\liblz4.dll`. For example: -``` - gcc $(CFLAGS) -Iinclude\ test-dll.c -o test-dll dll\liblz4.dll -``` -The compiled executable will require LZ4 DLL which is available at `dll\liblz4.dll`. - - -#### The example of usage of static and dynamic LZ4 libraries with Visual C++ - -Open `example\fullbench-dll.sln` to compile `fullbench-dll` that uses a -dynamic LZ4 library from the `dll` directory. The solution works with Visual C++ -2010 or newer. When one will open the solution with Visual C++ newer than 2010 -then the solution will upgraded to the current version. - - -#### Using LZ4 DLL with Visual C++ - -The header files from `include\` and the import library `dll\liblz4.lib` -are required to compile a project using Visual C++. - -1. The header files should be added to `Additional Include Directories` that can - be found in project properties `C/C++` then `General`. -2. The import library has to be added to `Additional Dependencies` that can - be found in project properties `Linker` then `Input`. - If one will provide only the name `liblz4.lib` without a full path to the library - the directory has to be added to `Linker\General\Additional Library Directories`. - -The compiled executable will require LZ4 DLL which is available at `dll\liblz4.dll`. diff --git a/src/lz4/lib/dll/example/fullbench-dll.sln b/src/lz4/lib/dll/example/fullbench-dll.sln deleted file mode 100644 index 72e302e7f5..0000000000 --- a/src/lz4/lib/dll/example/fullbench-dll.sln +++ /dev/null @@ -1,25 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Express 2012 for Windows Desktop -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fullbench-dll", "fullbench-dll.vcxproj", "{13992FD2-077E-4954-B065-A428198201A9}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - Release|Win32 = Release|Win32 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {13992FD2-077E-4954-B065-A428198201A9}.Debug|Win32.ActiveCfg = Debug|Win32 - {13992FD2-077E-4954-B065-A428198201A9}.Debug|Win32.Build.0 = Debug|Win32 - {13992FD2-077E-4954-B065-A428198201A9}.Debug|x64.ActiveCfg = Debug|x64 - {13992FD2-077E-4954-B065-A428198201A9}.Debug|x64.Build.0 = Debug|x64 - {13992FD2-077E-4954-B065-A428198201A9}.Release|Win32.ActiveCfg = Release|Win32 - {13992FD2-077E-4954-B065-A428198201A9}.Release|Win32.Build.0 = Release|Win32 - {13992FD2-077E-4954-B065-A428198201A9}.Release|x64.ActiveCfg = Release|x64 - {13992FD2-077E-4954-B065-A428198201A9}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/src/lz4/lib/dll/example/fullbench-dll.vcxproj b/src/lz4/lib/dll/example/fullbench-dll.vcxproj deleted file mode 100644 index cdb553422a..0000000000 --- a/src/lz4/lib/dll/example/fullbench-dll.vcxproj +++ /dev/null @@ -1,182 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {13992FD2-077E-4954-B065-A428198201A9} - Win32Proj - fullbench-dll - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - true - Unicode - - - Application - false - true - Unicode - - - - - - - - - - - - - - - - - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions) - true - false - ..\include - - - Console - true - $(SolutionDir)..\dll;%(AdditionalLibraryDirectories) - liblz4.lib;%(AdditionalDependencies) - false - - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - ..\include - - - Console - true - $(SolutionDir)..\dll;%(AdditionalLibraryDirectories) - liblz4.lib;%(AdditionalDependencies) - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions) - false - false - ..\include - - - Console - true - true - true - $(SolutionDir)..\dll;%(AdditionalLibraryDirectories) - liblz4.lib;%(AdditionalDependencies) - false - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - ..\include - - - Console - true - true - true - $(SolutionDir)..\dll;%(AdditionalLibraryDirectories) - liblz4.lib;%(AdditionalDependencies) - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/lz4/lib/dll/liblz4.def b/src/lz4/lib/dll/liblz4.def deleted file mode 100644 index 0ace2235a3..0000000000 --- a/src/lz4/lib/dll/liblz4.def +++ /dev/null @@ -1,62 +0,0 @@ -LIBRARY liblz4.dll -EXPORTS - LZ4F_compressBegin - LZ4F_compressBound - LZ4F_compressEnd - LZ4F_compressFrame - LZ4F_compressFrameBound - LZ4F_compressUpdate - LZ4F_createCompressionContext - LZ4F_createDecompressionContext - LZ4F_decompress - LZ4F_flush - LZ4F_freeCompressionContext - LZ4F_freeDecompressionContext - LZ4F_getErrorName - LZ4F_getFrameInfo - LZ4F_getVersion - LZ4F_isError - LZ4_compress - LZ4_compressBound - LZ4_compressHC - LZ4_compressHC_continue - LZ4_compressHC_limitedOutput - LZ4_compressHC_limitedOutput_continue - LZ4_compressHC_limitedOutput_withStateHC - LZ4_compressHC_withStateHC - LZ4_compress_HC - LZ4_compress_HC_continue - LZ4_compress_HC_extStateHC - LZ4_compress_continue - LZ4_compress_default - LZ4_compress_destSize - LZ4_compress_fast - LZ4_compress_fast_continue - LZ4_compress_fast_extState - LZ4_compress_limitedOutput - LZ4_compress_limitedOutput_continue - LZ4_compress_limitedOutput_withState - LZ4_compress_withState - LZ4_createStream - LZ4_createStreamDecode - LZ4_createStreamHC - LZ4_decompress_fast - LZ4_decompress_fast_continue - LZ4_decompress_fast_usingDict - LZ4_decompress_safe - LZ4_decompress_safe_continue - LZ4_decompress_safe_partial - LZ4_decompress_safe_usingDict - LZ4_freeStream - LZ4_freeStreamDecode - LZ4_freeStreamHC - LZ4_loadDict - LZ4_loadDictHC - LZ4_resetStream - LZ4_resetStreamHC - LZ4_saveDict - LZ4_saveDictHC - LZ4_setStreamDecode - LZ4_sizeofState - LZ4_sizeofStateHC - LZ4_versionNumber diff --git a/src/lz4/lib/liblz4.pc.in b/src/lz4/lib/liblz4.pc.in deleted file mode 100644 index cb31cd78a0..0000000000 --- a/src/lz4/lib/liblz4.pc.in +++ /dev/null @@ -1,14 +0,0 @@ -# LZ4 - Fast LZ compression algorithm -# Copyright (C) 2011-2014, Yann Collet. -# BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - -prefix=@PREFIX@ -libdir=@LIBDIR@ -includedir=@INCLUDEDIR@ - -Name: lz4 -Description: extremely fast lossless compression algorithm library -URL: http://www.lz4.org/ -Version: @VERSION@ -Libs: -L@LIBDIR@ -llz4 -Cflags: -I@INCLUDEDIR@ diff --git a/src/lz4/lib/lz4.c b/src/lz4/lib/lz4.c deleted file mode 100644 index 41c0a28baa..0000000000 --- a/src/lz4/lib/lz4.c +++ /dev/null @@ -1,1478 +0,0 @@ -/* - LZ4 - Fast LZ compression algorithm - Copyright (C) 2011-2017, Yann Collet. - - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - LZ4 homepage : http://www.lz4.org - - LZ4 source repository : https://github.com/lz4/lz4 -*/ - - -/*-************************************ -* Tuning parameters -**************************************/ -/* - * LZ4_HEAPMODE : - * Select how default compression functions will allocate memory for their hash table, - * in memory stack (0:default, fastest), or in memory heap (1:requires malloc()). - */ -#ifndef LZ4_HEAPMODE -# define LZ4_HEAPMODE 0 -#endif - -/* - * ACCELERATION_DEFAULT : - * Select "acceleration" for LZ4_compress_fast() when parameter value <= 0 - */ -#define ACCELERATION_DEFAULT 1 - - -/*-************************************ -* CPU Feature Detection -**************************************/ -/* LZ4_FORCE_MEMORY_ACCESS - * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable. - * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal. - * The below switch allow to select different access method for improved performance. - * Method 0 (default) : use `memcpy()`. Safe and portable. - * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable). - * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`. - * Method 2 : direct access. This method is portable but violate C standard. - * It can generate buggy code on targets which assembly generation depends on alignment. - * But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6) - * See https://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details. - * Prefer these methods in priority order (0 > 1 > 2) - */ -#ifndef LZ4_FORCE_MEMORY_ACCESS /* can be defined externally */ -# if defined(__GNUC__) && ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) ) -# define LZ4_FORCE_MEMORY_ACCESS 2 -# elif defined(__INTEL_COMPILER) || defined(__GNUC__) -# define LZ4_FORCE_MEMORY_ACCESS 1 -# endif -#endif - -/* - * LZ4_FORCE_SW_BITCOUNT - * Define this parameter if your target system or compiler does not support hardware bit count - */ -#if defined(_MSC_VER) && defined(_WIN32_WCE) /* Visual Studio for Windows CE does not support Hardware bit count */ -# define LZ4_FORCE_SW_BITCOUNT -#endif - - -/*-************************************ -* Dependency -**************************************/ -#include "lz4.h" -/* see also "memory routines" below */ - - -/*-************************************ -* Compiler Options -**************************************/ -#ifdef _MSC_VER /* Visual Studio */ -# include -# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ -# pragma warning(disable : 4293) /* disable: C4293: too large shift (32-bits) */ -#endif /* _MSC_VER */ - -#ifndef FORCE_INLINE -# ifdef _MSC_VER /* Visual Studio */ -# define FORCE_INLINE static __forceinline -# else -# if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */ -# ifdef __GNUC__ -# define FORCE_INLINE static inline __attribute__((always_inline)) -# else -# define FORCE_INLINE static inline -# endif -# else -# define FORCE_INLINE static -# endif /* __STDC_VERSION__ */ -# endif /* _MSC_VER */ -#endif /* FORCE_INLINE */ - -#if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__) -# define expect(expr,value) (__builtin_expect ((expr),(value)) ) -#else -# define expect(expr,value) (expr) -#endif - -#define likely(expr) expect((expr) != 0, 1) -#define unlikely(expr) expect((expr) != 0, 0) - - -/*-************************************ -* Memory routines -**************************************/ -#include /* malloc, calloc, free */ -#define ALLOCATOR(n,s) calloc(n,s) -#define FREEMEM free -#include /* memset, memcpy */ -#define MEM_INIT memset - - -/*-************************************ -* Basic Types -**************************************/ -#if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) -# include - typedef uint8_t BYTE; - typedef uint16_t U16; - typedef uint32_t U32; - typedef int32_t S32; - typedef uint64_t U64; - typedef uintptr_t uptrval; -#else - typedef unsigned char BYTE; - typedef unsigned short U16; - typedef unsigned int U32; - typedef signed int S32; - typedef unsigned long long U64; - typedef size_t uptrval; /* generally true, except OpenVMS-64 */ -#endif - -#if defined(__x86_64__) - typedef U64 reg_t; /* 64-bits in x32 mode */ -#else - typedef size_t reg_t; /* 32-bits in x32 mode */ -#endif - -/*-************************************ -* Reading and writing into memory -**************************************/ -static unsigned LZ4_isLittleEndian(void) -{ - const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */ - return one.c[0]; -} - - -#if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2) -/* lie to the compiler about data alignment; use with caution */ - -static U16 LZ4_read16(const void* memPtr) { return *(const U16*) memPtr; } -static U32 LZ4_read32(const void* memPtr) { return *(const U32*) memPtr; } -static reg_t LZ4_read_ARCH(const void* memPtr) { return *(const reg_t*) memPtr; } - -static void LZ4_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; } -static void LZ4_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; } - -#elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==1) - -/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */ -/* currently only defined for gcc and icc */ -typedef union { U16 u16; U32 u32; reg_t uArch; } __attribute__((packed)) unalign; - -static U16 LZ4_read16(const void* ptr) { return ((const unalign*)ptr)->u16; } -static U32 LZ4_read32(const void* ptr) { return ((const unalign*)ptr)->u32; } -static reg_t LZ4_read_ARCH(const void* ptr) { return ((const unalign*)ptr)->uArch; } - -static void LZ4_write16(void* memPtr, U16 value) { ((unalign*)memPtr)->u16 = value; } -static void LZ4_write32(void* memPtr, U32 value) { ((unalign*)memPtr)->u32 = value; } - -#else /* safe and portable access through memcpy() */ - -static U16 LZ4_read16(const void* memPtr) -{ - U16 val; memcpy(&val, memPtr, sizeof(val)); return val; -} - -static U32 LZ4_read32(const void* memPtr) -{ - U32 val; memcpy(&val, memPtr, sizeof(val)); return val; -} - -static reg_t LZ4_read_ARCH(const void* memPtr) -{ - reg_t val; memcpy(&val, memPtr, sizeof(val)); return val; -} - -static void LZ4_write16(void* memPtr, U16 value) -{ - memcpy(memPtr, &value, sizeof(value)); -} - -static void LZ4_write32(void* memPtr, U32 value) -{ - memcpy(memPtr, &value, sizeof(value)); -} - -#endif /* LZ4_FORCE_MEMORY_ACCESS */ - - -static U16 LZ4_readLE16(const void* memPtr) -{ - if (LZ4_isLittleEndian()) { - return LZ4_read16(memPtr); - } else { - const BYTE* p = (const BYTE*)memPtr; - return (U16)((U16)p[0] + (p[1]<<8)); - } -} - -static void LZ4_writeLE16(void* memPtr, U16 value) -{ - if (LZ4_isLittleEndian()) { - LZ4_write16(memPtr, value); - } else { - BYTE* p = (BYTE*)memPtr; - p[0] = (BYTE) value; - p[1] = (BYTE)(value>>8); - } -} - -static void LZ4_copy8(void* dst, const void* src) -{ - memcpy(dst,src,8); -} - -/* customized variant of memcpy, which can overwrite up to 8 bytes beyond dstEnd */ -static void LZ4_wildCopy(void* dstPtr, const void* srcPtr, void* dstEnd) -{ - BYTE* d = (BYTE*)dstPtr; - const BYTE* s = (const BYTE*)srcPtr; - BYTE* const e = (BYTE*)dstEnd; - - do { LZ4_copy8(d,s); d+=8; s+=8; } while (d=2) -# include -# define DEBUGLOG(l, ...) { \ - if (l<=LZ4_DEBUG) { \ - fprintf(stderr, __FILE__ ": "); \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stderr, " \n"); \ - } } -#else -# define DEBUGLOG(l, ...) {} /* disabled */ -#endif - - -/*-************************************ -* Common functions -**************************************/ -static unsigned LZ4_NbCommonBytes (register reg_t val) -{ - if (LZ4_isLittleEndian()) { - if (sizeof(val)==8) { -# if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) - unsigned long r = 0; - _BitScanForward64( &r, (U64)val ); - return (int)(r>>3); -# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) - return (__builtin_ctzll((U64)val) >> 3); -# else - static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 }; - return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58]; -# endif - } else /* 32 bits */ { -# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT) - unsigned long r; - _BitScanForward( &r, (U32)val ); - return (int)(r>>3); -# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) - return (__builtin_ctz((U32)val) >> 3); -# else - static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 }; - return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27]; -# endif - } - } else /* Big Endian CPU */ { - if (sizeof(val)==8) { -# if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) - unsigned long r = 0; - _BitScanReverse64( &r, val ); - return (unsigned)(r>>3); -# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) - return (__builtin_clzll((U64)val) >> 3); -# else - unsigned r; - if (!(val>>32)) { r=4; } else { r=0; val>>=32; } - if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; } - r += (!val); - return r; -# endif - } else /* 32 bits */ { -# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT) - unsigned long r = 0; - _BitScanReverse( &r, (unsigned long)val ); - return (unsigned)(r>>3); -# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) - return (__builtin_clz((U32)val) >> 3); -# else - unsigned r; - if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; } - r += (!val); - return r; -# endif - } - } -} - -#define STEPSIZE sizeof(reg_t) -static unsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit) -{ - const BYTE* const pStart = pIn; - - while (likely(pIn compression run slower on incompressible data */ - - -/*-************************************ -* Local Structures and types -**************************************/ -typedef enum { notLimited = 0, limitedOutput = 1 } limitedOutput_directive; -typedef enum { byPtr, byU32, byU16 } tableType_t; - -typedef enum { noDict = 0, withPrefix64k, usingExtDict } dict_directive; -typedef enum { noDictIssue = 0, dictSmall } dictIssue_directive; - -typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive; -typedef enum { full = 0, partial = 1 } earlyEnd_directive; - - -/*-************************************ -* Local Utils -**************************************/ -int LZ4_versionNumber (void) { return LZ4_VERSION_NUMBER; } -const char* LZ4_versionString(void) { return LZ4_VERSION_STRING; } -int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); } -int LZ4_sizeofState() { return LZ4_STREAMSIZE; } - - -/*-****************************** -* Compression functions -********************************/ -static U32 LZ4_hash4(U32 sequence, tableType_t const tableType) -{ - if (tableType == byU16) - return ((sequence * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1))); - else - return ((sequence * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG)); -} - -static U32 LZ4_hash5(U64 sequence, tableType_t const tableType) -{ - static const U64 prime5bytes = 889523592379ULL; - static const U64 prime8bytes = 11400714785074694791ULL; - const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG+1 : LZ4_HASHLOG; - if (LZ4_isLittleEndian()) - return (U32)(((sequence << 24) * prime5bytes) >> (64 - hashLog)); - else - return (U32)(((sequence >> 24) * prime8bytes) >> (64 - hashLog)); -} - -FORCE_INLINE U32 LZ4_hashPosition(const void* const p, tableType_t const tableType) -{ - if ((sizeof(reg_t)==8) && (tableType != byU16)) return LZ4_hash5(LZ4_read_ARCH(p), tableType); - return LZ4_hash4(LZ4_read32(p), tableType); -} - -static void LZ4_putPositionOnHash(const BYTE* p, U32 h, void* tableBase, tableType_t const tableType, const BYTE* srcBase) -{ - switch (tableType) - { - case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = p; return; } - case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = (U32)(p-srcBase); return; } - case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = (U16)(p-srcBase); return; } - } -} - -FORCE_INLINE void LZ4_putPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase) -{ - U32 const h = LZ4_hashPosition(p, tableType); - LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase); -} - -static const BYTE* LZ4_getPositionOnHash(U32 h, void* tableBase, tableType_t tableType, const BYTE* srcBase) -{ - if (tableType == byPtr) { const BYTE** hashTable = (const BYTE**) tableBase; return hashTable[h]; } - if (tableType == byU32) { const U32* const hashTable = (U32*) tableBase; return hashTable[h] + srcBase; } - { const U16* const hashTable = (U16*) tableBase; return hashTable[h] + srcBase; } /* default, to ensure a return */ -} - -FORCE_INLINE const BYTE* LZ4_getPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase) -{ - U32 const h = LZ4_hashPosition(p, tableType); - return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase); -} - - -/** LZ4_compress_generic() : - inlined, to ensure branches are decided at compilation time */ -FORCE_INLINE int LZ4_compress_generic( - LZ4_stream_t_internal* const cctx, - const char* const source, - char* const dest, - const int inputSize, - const int maxOutputSize, - const limitedOutput_directive outputLimited, - const tableType_t tableType, - const dict_directive dict, - const dictIssue_directive dictIssue, - const U32 acceleration) -{ - const BYTE* ip = (const BYTE*) source; - const BYTE* base; - const BYTE* lowLimit; - const BYTE* const lowRefLimit = ip - cctx->dictSize; - const BYTE* const dictionary = cctx->dictionary; - const BYTE* const dictEnd = dictionary + cctx->dictSize; - const ptrdiff_t dictDelta = dictEnd - (const BYTE*)source; - const BYTE* anchor = (const BYTE*) source; - const BYTE* const iend = ip + inputSize; - const BYTE* const mflimit = iend - MFLIMIT; - const BYTE* const matchlimit = iend - LASTLITERALS; - - BYTE* op = (BYTE*) dest; - BYTE* const olimit = op + maxOutputSize; - - U32 forwardH; - - /* Init conditions */ - if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported inputSize, too large (or negative) */ - switch(dict) - { - case noDict: - default: - base = (const BYTE*)source; - lowLimit = (const BYTE*)source; - break; - case withPrefix64k: - base = (const BYTE*)source - cctx->currentOffset; - lowLimit = (const BYTE*)source - cctx->dictSize; - break; - case usingExtDict: - base = (const BYTE*)source - cctx->currentOffset; - lowLimit = (const BYTE*)source; - break; - } - if ((tableType == byU16) && (inputSize>=LZ4_64Klimit)) return 0; /* Size too large (not within 64K limit) */ - if (inputSizehashTable, tableType, base); - ip++; forwardH = LZ4_hashPosition(ip, tableType); - - /* Main Loop */ - for ( ; ; ) { - ptrdiff_t refDelta = 0; - const BYTE* match; - BYTE* token; - - /* Find a match */ - { const BYTE* forwardIp = ip; - unsigned step = 1; - unsigned searchMatchNb = acceleration << LZ4_skipTrigger; - do { - U32 const h = forwardH; - ip = forwardIp; - forwardIp += step; - step = (searchMatchNb++ >> LZ4_skipTrigger); - - if (unlikely(forwardIp > mflimit)) goto _last_literals; - - match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType, base); - if (dict==usingExtDict) { - if (match < (const BYTE*)source) { - refDelta = dictDelta; - lowLimit = dictionary; - } else { - refDelta = 0; - lowLimit = (const BYTE*)source; - } } - forwardH = LZ4_hashPosition(forwardIp, tableType); - LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType, base); - - } while ( ((dictIssue==dictSmall) ? (match < lowRefLimit) : 0) - || ((tableType==byU16) ? 0 : (match + MAX_DISTANCE < ip)) - || (LZ4_read32(match+refDelta) != LZ4_read32(ip)) ); - } - - /* Catch up */ - while (((ip>anchor) & (match+refDelta > lowLimit)) && (unlikely(ip[-1]==match[refDelta-1]))) { ip--; match--; } - - /* Encode Literals */ - { unsigned const litLength = (unsigned)(ip - anchor); - token = op++; - if ((outputLimited) && /* Check output buffer overflow */ - (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength/255) > olimit))) - return 0; - if (litLength >= RUN_MASK) { - int len = (int)litLength-RUN_MASK; - *token = (RUN_MASK<= 255 ; len-=255) *op++ = 255; - *op++ = (BYTE)len; - } - else *token = (BYTE)(litLength< matchlimit) limit = matchlimit; - matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, limit); - ip += MINMATCH + matchCode; - if (ip==limit) { - unsigned const more = LZ4_count(ip, (const BYTE*)source, matchlimit); - matchCode += more; - ip += more; - } - } else { - matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit); - ip += MINMATCH + matchCode; - } - - if ( outputLimited && /* Check output buffer overflow */ - (unlikely(op + (1 + LASTLITERALS) + (matchCode>>8) > olimit)) ) - return 0; - if (matchCode >= ML_MASK) { - *token += ML_MASK; - matchCode -= ML_MASK; - LZ4_write32(op, 0xFFFFFFFF); - while (matchCode >= 4*255) op+=4, LZ4_write32(op, 0xFFFFFFFF), matchCode -= 4*255; - op += matchCode / 255; - *op++ = (BYTE)(matchCode % 255); - } else - *token += (BYTE)(matchCode); - } - - anchor = ip; - - /* Test end of chunk */ - if (ip > mflimit) break; - - /* Fill table */ - LZ4_putPosition(ip-2, cctx->hashTable, tableType, base); - - /* Test next position */ - match = LZ4_getPosition(ip, cctx->hashTable, tableType, base); - if (dict==usingExtDict) { - if (match < (const BYTE*)source) { - refDelta = dictDelta; - lowLimit = dictionary; - } else { - refDelta = 0; - lowLimit = (const BYTE*)source; - } } - LZ4_putPosition(ip, cctx->hashTable, tableType, base); - if ( ((dictIssue==dictSmall) ? (match>=lowRefLimit) : 1) - && (match+MAX_DISTANCE>=ip) - && (LZ4_read32(match+refDelta)==LZ4_read32(ip)) ) - { token=op++; *token=0; goto _next_match; } - - /* Prepare next loop */ - forwardH = LZ4_hashPosition(++ip, tableType); - } - -_last_literals: - /* Encode Last Literals */ - { size_t const lastRun = (size_t)(iend - anchor); - if ( (outputLimited) && /* Check output buffer overflow */ - ((op - (BYTE*)dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize) ) - return 0; - if (lastRun >= RUN_MASK) { - size_t accumulator = lastRun - RUN_MASK; - *op++ = RUN_MASK << ML_BITS; - for(; accumulator >= 255 ; accumulator-=255) *op++ = 255; - *op++ = (BYTE) accumulator; - } else { - *op++ = (BYTE)(lastRun<internal_donotuse; - LZ4_resetStream((LZ4_stream_t*)state); - if (acceleration < 1) acceleration = ACCELERATION_DEFAULT; - - if (maxOutputSize >= LZ4_compressBound(inputSize)) { - if (inputSize < LZ4_64Klimit) - return LZ4_compress_generic(ctx, source, dest, inputSize, 0, notLimited, byU16, noDict, noDictIssue, acceleration); - else - return LZ4_compress_generic(ctx, source, dest, inputSize, 0, notLimited, (sizeof(void*)==8) ? byU32 : byPtr, noDict, noDictIssue, acceleration); - } else { - if (inputSize < LZ4_64Klimit) - return LZ4_compress_generic(ctx, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration); - else - return LZ4_compress_generic(ctx, source, dest, inputSize, maxOutputSize, limitedOutput, (sizeof(void*)==8) ? byU32 : byPtr, noDict, noDictIssue, acceleration); - } -} - - -int LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) -{ -#if (LZ4_HEAPMODE) - void* ctxPtr = ALLOCATOR(1, sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */ -#else - LZ4_stream_t ctx; - void* const ctxPtr = &ctx; -#endif - - int const result = LZ4_compress_fast_extState(ctxPtr, source, dest, inputSize, maxOutputSize, acceleration); - -#if (LZ4_HEAPMODE) - FREEMEM(ctxPtr); -#endif - return result; -} - - -int LZ4_compress_default(const char* source, char* dest, int inputSize, int maxOutputSize) -{ - return LZ4_compress_fast(source, dest, inputSize, maxOutputSize, 1); -} - - -/* hidden debug function */ -/* strangely enough, gcc generates faster code when this function is uncommented, even if unused */ -int LZ4_compress_fast_force(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) -{ - LZ4_stream_t ctx; - LZ4_resetStream(&ctx); - - if (inputSize < LZ4_64Klimit) - return LZ4_compress_generic(&ctx.internal_donotuse, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration); - else - return LZ4_compress_generic(&ctx.internal_donotuse, source, dest, inputSize, maxOutputSize, limitedOutput, sizeof(void*)==8 ? byU32 : byPtr, noDict, noDictIssue, acceleration); -} - - -/*-****************************** -* *_destSize() variant -********************************/ - -static int LZ4_compress_destSize_generic( - LZ4_stream_t_internal* const ctx, - const char* const src, - char* const dst, - int* const srcSizePtr, - const int targetDstSize, - const tableType_t tableType) -{ - const BYTE* ip = (const BYTE*) src; - const BYTE* base = (const BYTE*) src; - const BYTE* lowLimit = (const BYTE*) src; - const BYTE* anchor = ip; - const BYTE* const iend = ip + *srcSizePtr; - const BYTE* const mflimit = iend - MFLIMIT; - const BYTE* const matchlimit = iend - LASTLITERALS; - - BYTE* op = (BYTE*) dst; - BYTE* const oend = op + targetDstSize; - BYTE* const oMaxLit = op + targetDstSize - 2 /* offset */ - 8 /* because 8+MINMATCH==MFLIMIT */ - 1 /* token */; - BYTE* const oMaxMatch = op + targetDstSize - (LASTLITERALS + 1 /* token */); - BYTE* const oMaxSeq = oMaxLit - 1 /* token */; - - U32 forwardH; - - - /* Init conditions */ - if (targetDstSize < 1) return 0; /* Impossible to store anything */ - if ((U32)*srcSizePtr > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported input size, too large (or negative) */ - if ((tableType == byU16) && (*srcSizePtr>=LZ4_64Klimit)) return 0; /* Size too large (not within 64K limit) */ - if (*srcSizePtrhashTable, tableType, base); - ip++; forwardH = LZ4_hashPosition(ip, tableType); - - /* Main Loop */ - for ( ; ; ) { - const BYTE* match; - BYTE* token; - - /* Find a match */ - { const BYTE* forwardIp = ip; - unsigned step = 1; - unsigned searchMatchNb = 1 << LZ4_skipTrigger; - - do { - U32 h = forwardH; - ip = forwardIp; - forwardIp += step; - step = (searchMatchNb++ >> LZ4_skipTrigger); - - if (unlikely(forwardIp > mflimit)) goto _last_literals; - - match = LZ4_getPositionOnHash(h, ctx->hashTable, tableType, base); - forwardH = LZ4_hashPosition(forwardIp, tableType); - LZ4_putPositionOnHash(ip, h, ctx->hashTable, tableType, base); - - } while ( ((tableType==byU16) ? 0 : (match + MAX_DISTANCE < ip)) - || (LZ4_read32(match) != LZ4_read32(ip)) ); - } - - /* Catch up */ - while ((ip>anchor) && (match > lowLimit) && (unlikely(ip[-1]==match[-1]))) { ip--; match--; } - - /* Encode Literal length */ - { unsigned litLength = (unsigned)(ip - anchor); - token = op++; - if (op + ((litLength+240)/255) + litLength > oMaxLit) { - /* Not enough space for a last match */ - op--; - goto _last_literals; - } - if (litLength>=RUN_MASK) { - unsigned len = litLength - RUN_MASK; - *token=(RUN_MASK<= 255 ; len-=255) *op++ = 255; - *op++ = (BYTE)len; - } - else *token = (BYTE)(litLength< oMaxMatch) { - /* Match description too long : reduce it */ - matchLength = (15-1) + (oMaxMatch-op) * 255; - } - ip += MINMATCH + matchLength; - - if (matchLength>=ML_MASK) { - *token += ML_MASK; - matchLength -= ML_MASK; - while (matchLength >= 255) { matchLength-=255; *op++ = 255; } - *op++ = (BYTE)matchLength; - } - else *token += (BYTE)(matchLength); - } - - anchor = ip; - - /* Test end of block */ - if (ip > mflimit) break; - if (op > oMaxSeq) break; - - /* Fill table */ - LZ4_putPosition(ip-2, ctx->hashTable, tableType, base); - - /* Test next position */ - match = LZ4_getPosition(ip, ctx->hashTable, tableType, base); - LZ4_putPosition(ip, ctx->hashTable, tableType, base); - if ( (match+MAX_DISTANCE>=ip) - && (LZ4_read32(match)==LZ4_read32(ip)) ) - { token=op++; *token=0; goto _next_match; } - - /* Prepare next loop */ - forwardH = LZ4_hashPosition(++ip, tableType); - } - -_last_literals: - /* Encode Last Literals */ - { size_t lastRunSize = (size_t)(iend - anchor); - if (op + 1 /* token */ + ((lastRunSize+240)/255) /* litLength */ + lastRunSize /* literals */ > oend) { - /* adapt lastRunSize to fill 'dst' */ - lastRunSize = (oend-op) - 1; - lastRunSize -= (lastRunSize+240)/255; - } - ip = anchor + lastRunSize; - - if (lastRunSize >= RUN_MASK) { - size_t accumulator = lastRunSize - RUN_MASK; - *op++ = RUN_MASK << ML_BITS; - for(; accumulator >= 255 ; accumulator-=255) *op++ = 255; - *op++ = (BYTE) accumulator; - } else { - *op++ = (BYTE)(lastRunSize<= LZ4_compressBound(*srcSizePtr)) { /* compression success is guaranteed */ - return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, targetDstSize, 1); - } else { - if (*srcSizePtr < LZ4_64Klimit) - return LZ4_compress_destSize_generic(&state->internal_donotuse, src, dst, srcSizePtr, targetDstSize, byU16); - else - return LZ4_compress_destSize_generic(&state->internal_donotuse, src, dst, srcSizePtr, targetDstSize, sizeof(void*)==8 ? byU32 : byPtr); - } -} - - -int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targetDstSize) -{ -#if (LZ4_HEAPMODE) - LZ4_stream_t* ctx = (LZ4_stream_t*)ALLOCATOR(1, sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */ -#else - LZ4_stream_t ctxBody; - LZ4_stream_t* ctx = &ctxBody; -#endif - - int result = LZ4_compress_destSize_extState(ctx, src, dst, srcSizePtr, targetDstSize); - -#if (LZ4_HEAPMODE) - FREEMEM(ctx); -#endif - return result; -} - - - -/*-****************************** -* Streaming functions -********************************/ - -LZ4_stream_t* LZ4_createStream(void) -{ - LZ4_stream_t* lz4s = (LZ4_stream_t*)ALLOCATOR(8, LZ4_STREAMSIZE_U64); - LZ4_STATIC_ASSERT(LZ4_STREAMSIZE >= sizeof(LZ4_stream_t_internal)); /* A compilation error here means LZ4_STREAMSIZE is not large enough */ - LZ4_resetStream(lz4s); - return lz4s; -} - -void LZ4_resetStream (LZ4_stream_t* LZ4_stream) -{ - MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t)); -} - -int LZ4_freeStream (LZ4_stream_t* LZ4_stream) -{ - if (!LZ4_stream) return 0; /* support free on NULL */ - FREEMEM(LZ4_stream); - return (0); -} - - -#define HASH_UNIT sizeof(reg_t) -int LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize) -{ - LZ4_stream_t_internal* dict = &LZ4_dict->internal_donotuse; - const BYTE* p = (const BYTE*)dictionary; - const BYTE* const dictEnd = p + dictSize; - const BYTE* base; - - if ((dict->initCheck) || (dict->currentOffset > 1 GB)) /* Uninitialized structure, or reuse overflow */ - LZ4_resetStream(LZ4_dict); - - if (dictSize < (int)HASH_UNIT) { - dict->dictionary = NULL; - dict->dictSize = 0; - return 0; - } - - if ((dictEnd - p) > 64 KB) p = dictEnd - 64 KB; - dict->currentOffset += 64 KB; - base = p - dict->currentOffset; - dict->dictionary = p; - dict->dictSize = (U32)(dictEnd - p); - dict->currentOffset += dict->dictSize; - - while (p <= dictEnd-HASH_UNIT) { - LZ4_putPosition(p, dict->hashTable, byU32, base); - p+=3; - } - - return dict->dictSize; -} - - -static void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, const BYTE* src) -{ - if ((LZ4_dict->currentOffset > 0x80000000) || - ((uptrval)LZ4_dict->currentOffset > (uptrval)src)) { /* address space overflow */ - /* rescale hash table */ - U32 const delta = LZ4_dict->currentOffset - 64 KB; - const BYTE* dictEnd = LZ4_dict->dictionary + LZ4_dict->dictSize; - int i; - for (i=0; ihashTable[i] < delta) LZ4_dict->hashTable[i]=0; - else LZ4_dict->hashTable[i] -= delta; - } - LZ4_dict->currentOffset = 64 KB; - if (LZ4_dict->dictSize > 64 KB) LZ4_dict->dictSize = 64 KB; - LZ4_dict->dictionary = dictEnd - LZ4_dict->dictSize; - } -} - - -int LZ4_compress_fast_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) -{ - LZ4_stream_t_internal* streamPtr = &LZ4_stream->internal_donotuse; - const BYTE* const dictEnd = streamPtr->dictionary + streamPtr->dictSize; - - const BYTE* smallest = (const BYTE*) source; - if (streamPtr->initCheck) return 0; /* Uninitialized structure detected */ - if ((streamPtr->dictSize>0) && (smallest>dictEnd)) smallest = dictEnd; - LZ4_renormDictT(streamPtr, smallest); - if (acceleration < 1) acceleration = ACCELERATION_DEFAULT; - - /* Check overlapping input/dictionary space */ - { const BYTE* sourceEnd = (const BYTE*) source + inputSize; - if ((sourceEnd > streamPtr->dictionary) && (sourceEnd < dictEnd)) { - streamPtr->dictSize = (U32)(dictEnd - sourceEnd); - if (streamPtr->dictSize > 64 KB) streamPtr->dictSize = 64 KB; - if (streamPtr->dictSize < 4) streamPtr->dictSize = 0; - streamPtr->dictionary = dictEnd - streamPtr->dictSize; - } - } - - /* prefix mode : source data follows dictionary */ - if (dictEnd == (const BYTE*)source) { - int result; - if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) - result = LZ4_compress_generic(streamPtr, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, withPrefix64k, dictSmall, acceleration); - else - result = LZ4_compress_generic(streamPtr, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, withPrefix64k, noDictIssue, acceleration); - streamPtr->dictSize += (U32)inputSize; - streamPtr->currentOffset += (U32)inputSize; - return result; - } - - /* external dictionary mode */ - { int result; - if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) - result = LZ4_compress_generic(streamPtr, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, usingExtDict, dictSmall, acceleration); - else - result = LZ4_compress_generic(streamPtr, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, usingExtDict, noDictIssue, acceleration); - streamPtr->dictionary = (const BYTE*)source; - streamPtr->dictSize = (U32)inputSize; - streamPtr->currentOffset += (U32)inputSize; - return result; - } -} - - -/* Hidden debug function, to force external dictionary mode */ -int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int inputSize) -{ - LZ4_stream_t_internal* streamPtr = &LZ4_dict->internal_donotuse; - int result; - const BYTE* const dictEnd = streamPtr->dictionary + streamPtr->dictSize; - - const BYTE* smallest = dictEnd; - if (smallest > (const BYTE*) source) smallest = (const BYTE*) source; - LZ4_renormDictT(streamPtr, smallest); - - result = LZ4_compress_generic(streamPtr, source, dest, inputSize, 0, notLimited, byU32, usingExtDict, noDictIssue, 1); - - streamPtr->dictionary = (const BYTE*)source; - streamPtr->dictSize = (U32)inputSize; - streamPtr->currentOffset += (U32)inputSize; - - return result; -} - - -/*! LZ4_saveDict() : - * If previously compressed data block is not guaranteed to remain available at its memory location, - * save it into a safer place (char* safeBuffer). - * Note : you don't need to call LZ4_loadDict() afterwards, - * dictionary is immediately usable, you can therefore call LZ4_compress_fast_continue(). - * Return : saved dictionary size in bytes (necessarily <= dictSize), or 0 if error. - */ -int LZ4_saveDict (LZ4_stream_t* LZ4_dict, char* safeBuffer, int dictSize) -{ - LZ4_stream_t_internal* const dict = &LZ4_dict->internal_donotuse; - const BYTE* const previousDictEnd = dict->dictionary + dict->dictSize; - - if ((U32)dictSize > 64 KB) dictSize = 64 KB; /* useless to define a dictionary > 64 KB */ - if ((U32)dictSize > dict->dictSize) dictSize = dict->dictSize; - - memmove(safeBuffer, previousDictEnd - dictSize, dictSize); - - dict->dictionary = (const BYTE*)safeBuffer; - dict->dictSize = (U32)dictSize; - - return dictSize; -} - - - -/*-***************************** -* Decompression functions -*******************************/ -/*! LZ4_decompress_generic() : - * This generic decompression function cover all use cases. - * It shall be instantiated several times, using different sets of directives - * Note that it is important this generic function is really inlined, - * in order to remove useless branches during compilation optimization. - */ -FORCE_INLINE int LZ4_decompress_generic( - const char* const source, - char* const dest, - int inputSize, - int outputSize, /* If endOnInput==endOnInputSize, this value is the max size of Output Buffer. */ - - int endOnInput, /* endOnOutputSize, endOnInputSize */ - int partialDecoding, /* full, partial */ - int targetOutputSize, /* only used if partialDecoding==partial */ - int dict, /* noDict, withPrefix64k, usingExtDict */ - const BYTE* const lowPrefix, /* == dest when no prefix */ - const BYTE* const dictStart, /* only if dict==usingExtDict */ - const size_t dictSize /* note : = 0 if noDict */ - ) -{ - /* Local Variables */ - const BYTE* ip = (const BYTE*) source; - const BYTE* const iend = ip + inputSize; - - BYTE* op = (BYTE*) dest; - BYTE* const oend = op + outputSize; - BYTE* cpy; - BYTE* oexit = op + targetOutputSize; - const BYTE* const lowLimit = lowPrefix - dictSize; - - const BYTE* const dictEnd = (const BYTE*)dictStart + dictSize; - const unsigned dec32table[] = {0, 1, 2, 1, 4, 4, 4, 4}; - const int dec64table[] = {0, 0, 0, -1, 0, 1, 2, 3}; - - const int safeDecode = (endOnInput==endOnInputSize); - const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB))); - - - /* Special cases */ - if ((partialDecoding) && (oexit > oend-MFLIMIT)) oexit = oend-MFLIMIT; /* targetOutputSize too high => decode everything */ - if ((endOnInput) && (unlikely(outputSize==0))) return ((inputSize==1) && (*ip==0)) ? 0 : -1; /* Empty output buffer */ - if ((!endOnInput) && (unlikely(outputSize==0))) return (*ip==0?1:-1); - - /* Main Loop : decode sequences */ - while (1) { - size_t length; - const BYTE* match; - size_t offset; - - /* get literal length */ - unsigned const token = *ip++; - if ((length=(token>>ML_BITS)) == RUN_MASK) { - unsigned s; - do { - s = *ip++; - length += s; - } while ( likely(endOnInput ? ip(partialDecoding?oexit:oend-MFLIMIT)) || (ip+length>iend-(2+1+LASTLITERALS))) ) - || ((!endOnInput) && (cpy>oend-WILDCOPYLENGTH)) ) - { - if (partialDecoding) { - if (cpy > oend) goto _output_error; /* Error : write attempt beyond end of output buffer */ - if ((endOnInput) && (ip+length > iend)) goto _output_error; /* Error : read attempt beyond end of input buffer */ - } else { - if ((!endOnInput) && (cpy != oend)) goto _output_error; /* Error : block decoding must stop exactly there */ - if ((endOnInput) && ((ip+length != iend) || (cpy > oend))) goto _output_error; /* Error : input must be consumed */ - } - memcpy(op, ip, length); - ip += length; - op += length; - break; /* Necessarily EOF, due to parsing restrictions */ - } - LZ4_wildCopy(op, ip, cpy); - ip += length; op = cpy; - - /* get offset */ - offset = LZ4_readLE16(ip); ip+=2; - match = op - offset; - if ((checkOffset) && (unlikely(match < lowLimit))) goto _output_error; /* Error : offset outside buffers */ - LZ4_write32(op, (U32)offset); /* costs ~1%; silence an msan warning when offset==0 */ - - /* get matchlength */ - length = token & ML_MASK; - if (length == ML_MASK) { - unsigned s; - do { - s = *ip++; - if ((endOnInput) && (ip > iend-LASTLITERALS)) goto _output_error; - length += s; - } while (s==255); - if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) goto _output_error; /* overflow detection */ - } - length += MINMATCH; - - /* check external dictionary */ - if ((dict==usingExtDict) && (match < lowPrefix)) { - if (unlikely(op+length > oend-LASTLITERALS)) goto _output_error; /* doesn't respect parsing restriction */ - - if (length <= (size_t)(lowPrefix-match)) { - /* match can be copied as a single segment from external dictionary */ - memmove(op, dictEnd - (lowPrefix-match), length); - op += length; - } else { - /* match encompass external dictionary and current block */ - size_t const copySize = (size_t)(lowPrefix-match); - size_t const restSize = length - copySize; - memcpy(op, dictEnd - copySize, copySize); - op += copySize; - if (restSize > (size_t)(op-lowPrefix)) { /* overlap copy */ - BYTE* const endOfMatch = op + restSize; - const BYTE* copyFrom = lowPrefix; - while (op < endOfMatch) *op++ = *copyFrom++; - } else { - memcpy(op, lowPrefix, restSize); - op += restSize; - } } - continue; - } - - /* copy match within block */ - cpy = op + length; - if (unlikely(offset<8)) { - const int dec64 = dec64table[offset]; - op[0] = match[0]; - op[1] = match[1]; - op[2] = match[2]; - op[3] = match[3]; - match += dec32table[offset]; - memcpy(op+4, match, 4); - match -= dec64; - } else { LZ4_copy8(op, match); match+=8; } - op += 8; - - if (unlikely(cpy>oend-12)) { - BYTE* const oCopyLimit = oend-(WILDCOPYLENGTH-1); - if (cpy > oend-LASTLITERALS) goto _output_error; /* Error : last LASTLITERALS bytes must be literals (uncompressed) */ - if (op < oCopyLimit) { - LZ4_wildCopy(op, match, oCopyLimit); - match += oCopyLimit - op; - op = oCopyLimit; - } - while (op16) LZ4_wildCopy(op+8, match+8, cpy); - } - op=cpy; /* correction */ - } - - /* end of decoding */ - if (endOnInput) - return (int) (((char*)op)-dest); /* Nb of output bytes decoded */ - else - return (int) (((const char*)ip)-source); /* Nb of input bytes read */ - - /* Overflow error detected */ -_output_error: - return (int) (-(((const char*)ip)-source))-1; -} - - -int LZ4_decompress_safe(const char* source, char* dest, int compressedSize, int maxDecompressedSize) -{ - return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize, endOnInputSize, full, 0, noDict, (BYTE*)dest, NULL, 0); -} - -int LZ4_decompress_safe_partial(const char* source, char* dest, int compressedSize, int targetOutputSize, int maxDecompressedSize) -{ - return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize, endOnInputSize, partial, targetOutputSize, noDict, (BYTE*)dest, NULL, 0); -} - -int LZ4_decompress_fast(const char* source, char* dest, int originalSize) -{ - return LZ4_decompress_generic(source, dest, 0, originalSize, endOnOutputSize, full, 0, withPrefix64k, (BYTE*)(dest - 64 KB), NULL, 64 KB); -} - - -/*===== streaming decompression functions =====*/ - -LZ4_streamDecode_t* LZ4_createStreamDecode(void) -{ - LZ4_streamDecode_t* lz4s = (LZ4_streamDecode_t*) ALLOCATOR(1, sizeof(LZ4_streamDecode_t)); - return lz4s; -} - -int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream) -{ - if (!LZ4_stream) return 0; /* support free on NULL */ - FREEMEM(LZ4_stream); - return 0; -} - -/*! - * LZ4_setStreamDecode() : - * Use this function to instruct where to find the dictionary. - * This function is not necessary if previous data is still available where it was decoded. - * Loading a size of 0 is allowed (same effect as no dictionary). - * Return : 1 if OK, 0 if error - */ -int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize) -{ - LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse; - lz4sd->prefixSize = (size_t) dictSize; - lz4sd->prefixEnd = (const BYTE*) dictionary + dictSize; - lz4sd->externalDict = NULL; - lz4sd->extDictSize = 0; - return 1; -} - -/* -*_continue() : - These decoding functions allow decompression of multiple blocks in "streaming" mode. - Previously decoded blocks must still be available at the memory position where they were decoded. - If it's not possible, save the relevant part of decoded data into a safe buffer, - and indicate where it stands using LZ4_setStreamDecode() -*/ -int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxOutputSize) -{ - LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse; - int result; - - if (lz4sd->prefixEnd == (BYTE*)dest) { - result = LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, - endOnInputSize, full, 0, - usingExtDict, lz4sd->prefixEnd - lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize); - if (result <= 0) return result; - lz4sd->prefixSize += result; - lz4sd->prefixEnd += result; - } else { - lz4sd->extDictSize = lz4sd->prefixSize; - lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize; - result = LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, - endOnInputSize, full, 0, - usingExtDict, (BYTE*)dest, lz4sd->externalDict, lz4sd->extDictSize); - if (result <= 0) return result; - lz4sd->prefixSize = result; - lz4sd->prefixEnd = (BYTE*)dest + result; - } - - return result; -} - -int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize) -{ - LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse; - int result; - - if (lz4sd->prefixEnd == (BYTE*)dest) { - result = LZ4_decompress_generic(source, dest, 0, originalSize, - endOnOutputSize, full, 0, - usingExtDict, lz4sd->prefixEnd - lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize); - if (result <= 0) return result; - lz4sd->prefixSize += originalSize; - lz4sd->prefixEnd += originalSize; - } else { - lz4sd->extDictSize = lz4sd->prefixSize; - lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize; - result = LZ4_decompress_generic(source, dest, 0, originalSize, - endOnOutputSize, full, 0, - usingExtDict, (BYTE*)dest, lz4sd->externalDict, lz4sd->extDictSize); - if (result <= 0) return result; - lz4sd->prefixSize = originalSize; - lz4sd->prefixEnd = (BYTE*)dest + originalSize; - } - - return result; -} - - -/* -Advanced decoding functions : -*_usingDict() : - These decoding functions work the same as "_continue" ones, - the dictionary must be explicitly provided within parameters -*/ - -FORCE_INLINE int LZ4_decompress_usingDict_generic(const char* source, char* dest, int compressedSize, int maxOutputSize, int safe, const char* dictStart, int dictSize) -{ - if (dictSize==0) - return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, noDict, (BYTE*)dest, NULL, 0); - if (dictStart+dictSize == dest) { - if (dictSize >= (int)(64 KB - 1)) - return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, withPrefix64k, (BYTE*)dest-64 KB, NULL, 0); - return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, noDict, (BYTE*)dest-dictSize, NULL, 0); - } - return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, usingExtDict, (BYTE*)dest, (const BYTE*)dictStart, dictSize); -} - -int LZ4_decompress_safe_usingDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize) -{ - return LZ4_decompress_usingDict_generic(source, dest, compressedSize, maxOutputSize, 1, dictStart, dictSize); -} - -int LZ4_decompress_fast_usingDict(const char* source, char* dest, int originalSize, const char* dictStart, int dictSize) -{ - return LZ4_decompress_usingDict_generic(source, dest, 0, originalSize, 0, dictStart, dictSize); -} - -/* debug function */ -int LZ4_decompress_safe_forceExtDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize) -{ - return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, full, 0, usingExtDict, (BYTE*)dest, (const BYTE*)dictStart, dictSize); -} - - -/*=************************************************* -* Obsolete Functions -***************************************************/ -/* obsolete compression functions */ -int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize) { return LZ4_compress_default(source, dest, inputSize, maxOutputSize); } -int LZ4_compress(const char* source, char* dest, int inputSize) { return LZ4_compress_default(source, dest, inputSize, LZ4_compressBound(inputSize)); } -int LZ4_compress_limitedOutput_withState (void* state, const char* src, char* dst, int srcSize, int dstSize) { return LZ4_compress_fast_extState(state, src, dst, srcSize, dstSize, 1); } -int LZ4_compress_withState (void* state, const char* src, char* dst, int srcSize) { return LZ4_compress_fast_extState(state, src, dst, srcSize, LZ4_compressBound(srcSize), 1); } -int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_fast_continue(LZ4_stream, src, dst, srcSize, maxDstSize, 1); } -int LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize) { return LZ4_compress_fast_continue(LZ4_stream, source, dest, inputSize, LZ4_compressBound(inputSize), 1); } - -/* -These function names are deprecated and should no longer be used. -They are only provided here for compatibility with older user programs. -- LZ4_uncompress is totally equivalent to LZ4_decompress_fast -- LZ4_uncompress_unknownOutputSize is totally equivalent to LZ4_decompress_safe -*/ -int LZ4_uncompress (const char* source, char* dest, int outputSize) { return LZ4_decompress_fast(source, dest, outputSize); } -int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize) { return LZ4_decompress_safe(source, dest, isize, maxOutputSize); } - - -/* Obsolete Streaming functions */ - -int LZ4_sizeofStreamState() { return LZ4_STREAMSIZE; } - -static void LZ4_init(LZ4_stream_t* lz4ds, BYTE* base) -{ - MEM_INIT(lz4ds, 0, sizeof(LZ4_stream_t)); - lz4ds->internal_donotuse.bufferStart = base; -} - -int LZ4_resetStreamState(void* state, char* inputBuffer) -{ - if ((((uptrval)state) & 3) != 0) return 1; /* Error : pointer is not aligned on 4-bytes boundary */ - LZ4_init((LZ4_stream_t*)state, (BYTE*)inputBuffer); - return 0; -} - -void* LZ4_create (char* inputBuffer) -{ - LZ4_stream_t* lz4ds = (LZ4_stream_t*)ALLOCATOR(8, sizeof(LZ4_stream_t)); - LZ4_init (lz4ds, (BYTE*)inputBuffer); - return lz4ds; -} - -char* LZ4_slideInputBuffer (void* LZ4_Data) -{ - LZ4_stream_t_internal* ctx = &((LZ4_stream_t*)LZ4_Data)->internal_donotuse; - int dictSize = LZ4_saveDict((LZ4_stream_t*)LZ4_Data, (char*)ctx->bufferStart, 64 KB); - return (char*)(ctx->bufferStart + dictSize); -} - -/* Obsolete streaming decompression functions */ - -int LZ4_decompress_safe_withPrefix64k(const char* source, char* dest, int compressedSize, int maxOutputSize) -{ - return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, full, 0, withPrefix64k, (BYTE*)dest - 64 KB, NULL, 64 KB); -} - -int LZ4_decompress_fast_withPrefix64k(const char* source, char* dest, int originalSize) -{ - return LZ4_decompress_generic(source, dest, 0, originalSize, endOnOutputSize, full, 0, withPrefix64k, (BYTE*)dest - 64 KB, NULL, 64 KB); -} - -#endif /* LZ4_COMMONDEFS_ONLY */ diff --git a/src/lz4/lib/lz4.h b/src/lz4/lib/lz4.h deleted file mode 100644 index 86ca0d59c1..0000000000 --- a/src/lz4/lib/lz4.h +++ /dev/null @@ -1,463 +0,0 @@ -/* - * LZ4 - Fast LZ compression algorithm - * Header File - * Copyright (C) 2011-2017, Yann Collet. - - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - LZ4 homepage : http://www.lz4.org - - LZ4 source repository : https://github.com/lz4/lz4 -*/ -#if defined (__cplusplus) -extern "C" { -#endif - -#ifndef LZ4_H_2983827168210 -#define LZ4_H_2983827168210 - -/* --- Dependency --- */ -#include /* size_t */ - - -/** - Introduction - - LZ4 is lossless compression algorithm, providing compression speed at 400 MB/s per core, - scalable with multi-cores CPU. It features an extremely fast decoder, with speed in - multiple GB/s per core, typically reaching RAM speed limits on multi-core systems. - - The LZ4 compression library provides in-memory compression and decompression functions. - Compression can be done in: - - a single step (described as Simple Functions) - - a single step, reusing a context (described in Advanced Functions) - - unbounded multiple steps (described as Streaming compression) - - lz4.h provides block compression functions. It gives full buffer control to user. - Decompressing an lz4-compressed block also requires metadata (such as compressed size). - Each application is free to encode such metadata in whichever way it wants. - - An additional format, called LZ4 frame specification (doc/lz4_Frame_format.md), - take care of encoding standard metadata alongside LZ4-compressed blocks. - If your application requires interoperability, it's recommended to use it. - A library is provided to take care of it, see lz4frame.h. -*/ - -/*^*************************************************************** -* Export parameters -*****************************************************************/ -/* -* LZ4_DLL_EXPORT : -* Enable exporting of functions when building a Windows DLL -* LZ4LIB_API : -* Control library symbols visibility. -*/ -#if defined(LZ4_DLL_EXPORT) && (LZ4_DLL_EXPORT==1) -# define LZ4LIB_API __declspec(dllexport) -#elif defined(LZ4_DLL_IMPORT) && (LZ4_DLL_IMPORT==1) -# define LZ4LIB_API __declspec(dllimport) /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/ -#elif defined(__GNUC__) && (__GNUC__ >= 4) -# define LZ4LIB_API __attribute__ ((__visibility__ ("default"))) -#else -# define LZ4LIB_API -#endif - - -/*------ Version ------*/ -#define LZ4_VERSION_MAJOR 1 /* for breaking interface changes */ -#define LZ4_VERSION_MINOR 8 /* for new (non-breaking) interface capabilities */ -#define LZ4_VERSION_RELEASE 0 /* for tweaks, bug-fixes, or development */ - -#define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE) - -#define LZ4_LIB_VERSION LZ4_VERSION_MAJOR.LZ4_VERSION_MINOR.LZ4_VERSION_RELEASE -#define LZ4_QUOTE(str) #str -#define LZ4_EXPAND_AND_QUOTE(str) LZ4_QUOTE(str) -#define LZ4_VERSION_STRING LZ4_EXPAND_AND_QUOTE(LZ4_LIB_VERSION) - -LZ4LIB_API int LZ4_versionNumber (void); /**< library version number; to be used when checking dll version */ -LZ4LIB_API const char* LZ4_versionString (void); /**< library version string; to be used when checking dll version */ - - -/*-************************************ -* Tuning parameter -**************************************/ -/*! - * LZ4_MEMORY_USAGE : - * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.) - * Increasing memory usage improves compression ratio - * Reduced memory usage can improve speed, due to cache effect - * Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache - */ -#ifndef LZ4_MEMORY_USAGE -# define LZ4_MEMORY_USAGE 14 -#endif - -/*-************************************ -* Simple Functions -**************************************/ -/*! LZ4_compress_default() : - Compresses 'sourceSize' bytes from buffer 'source' - into already allocated 'dest' buffer of size 'maxDestSize'. - Compression is guaranteed to succeed if 'maxDestSize' >= LZ4_compressBound(sourceSize). - It also runs faster, so it's a recommended setting. - If the function cannot compress 'source' into a more limited 'dest' budget, - compression stops *immediately*, and the function result is zero. - As a consequence, 'dest' content is not valid. - This function never writes outside 'dest' buffer, nor read outside 'source' buffer. - sourceSize : Max supported value is LZ4_MAX_INPUT_VALUE - maxDestSize : full or partial size of buffer 'dest' (which must be already allocated) - return : the number of bytes written into buffer 'dest' (necessarily <= maxOutputSize) - or 0 if compression fails */ -LZ4LIB_API int LZ4_compress_default(const char* source, char* dest, int sourceSize, int maxDestSize); - -/*! LZ4_decompress_safe() : - compressedSize : is the precise full size of the compressed block. - maxDecompressedSize : is the size of destination buffer, which must be already allocated. - return : the number of bytes decompressed into destination buffer (necessarily <= maxDecompressedSize) - If destination buffer is not large enough, decoding will stop and output an error code (<0). - If the source stream is detected malformed, the function will stop decoding and return a negative result. - This function is protected against buffer overflow exploits, including malicious data packets. - It never writes outside output buffer, nor reads outside input buffer. -*/ -LZ4LIB_API int LZ4_decompress_safe (const char* source, char* dest, int compressedSize, int maxDecompressedSize); - - -/*-************************************ -* Advanced Functions -**************************************/ -#define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */ -#define LZ4_COMPRESSBOUND(isize) ((unsigned)(isize) > (unsigned)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16) - -/*! -LZ4_compressBound() : - Provides the maximum size that LZ4 compression may output in a "worst case" scenario (input data not compressible) - This function is primarily useful for memory allocation purposes (destination buffer size). - Macro LZ4_COMPRESSBOUND() is also provided for compilation-time evaluation (stack memory allocation for example). - Note that LZ4_compress_default() compress faster when dest buffer size is >= LZ4_compressBound(srcSize) - inputSize : max supported value is LZ4_MAX_INPUT_SIZE - return : maximum output size in a "worst case" scenario - or 0, if input size is too large ( > LZ4_MAX_INPUT_SIZE) -*/ -LZ4LIB_API int LZ4_compressBound(int inputSize); - -/*! -LZ4_compress_fast() : - Same as LZ4_compress_default(), but allows to select an "acceleration" factor. - The larger the acceleration value, the faster the algorithm, but also the lesser the compression. - It's a trade-off. It can be fine tuned, with each successive value providing roughly +~3% to speed. - An acceleration value of "1" is the same as regular LZ4_compress_default() - Values <= 0 will be replaced by ACCELERATION_DEFAULT (see lz4.c), which is 1. -*/ -LZ4LIB_API int LZ4_compress_fast (const char* source, char* dest, int sourceSize, int maxDestSize, int acceleration); - - -/*! -LZ4_compress_fast_extState() : - Same compression function, just using an externally allocated memory space to store compression state. - Use LZ4_sizeofState() to know how much memory must be allocated, - and allocate it on 8-bytes boundaries (using malloc() typically). - Then, provide it as 'void* state' to compression function. -*/ -LZ4LIB_API int LZ4_sizeofState(void); -LZ4LIB_API int LZ4_compress_fast_extState (void* state, const char* source, char* dest, int inputSize, int maxDestSize, int acceleration); - - -/*! -LZ4_compress_destSize() : - Reverse the logic, by compressing as much data as possible from 'source' buffer - into already allocated buffer 'dest' of size 'targetDestSize'. - This function either compresses the entire 'source' content into 'dest' if it's large enough, - or fill 'dest' buffer completely with as much data as possible from 'source'. - *sourceSizePtr : will be modified to indicate how many bytes where read from 'source' to fill 'dest'. - New value is necessarily <= old value. - return : Nb bytes written into 'dest' (necessarily <= targetDestSize) - or 0 if compression fails -*/ -LZ4LIB_API int LZ4_compress_destSize (const char* source, char* dest, int* sourceSizePtr, int targetDestSize); - - -/*! -LZ4_decompress_fast() : - originalSize : is the original and therefore uncompressed size - return : the number of bytes read from the source buffer (in other words, the compressed size) - If the source stream is detected malformed, the function will stop decoding and return a negative result. - Destination buffer must be already allocated. Its size must be a minimum of 'originalSize' bytes. - note : This function fully respect memory boundaries for properly formed compressed data. - It is a bit faster than LZ4_decompress_safe(). - However, it does not provide any protection against intentionally modified data stream (malicious input). - Use this function in trusted environment only (data to decode comes from a trusted source). -*/ -LZ4LIB_API int LZ4_decompress_fast (const char* source, char* dest, int originalSize); - -/*! -LZ4_decompress_safe_partial() : - This function decompress a compressed block of size 'compressedSize' at position 'source' - into destination buffer 'dest' of size 'maxDecompressedSize'. - The function tries to stop decompressing operation as soon as 'targetOutputSize' has been reached, - reducing decompression time. - return : the number of bytes decoded in the destination buffer (necessarily <= maxDecompressedSize) - Note : this number can be < 'targetOutputSize' should the compressed block to decode be smaller. - Always control how many bytes were decoded. - If the source stream is detected malformed, the function will stop decoding and return a negative result. - This function never writes outside of output buffer, and never reads outside of input buffer. It is therefore protected against malicious data packets -*/ -LZ4LIB_API int LZ4_decompress_safe_partial (const char* source, char* dest, int compressedSize, int targetOutputSize, int maxDecompressedSize); - - -/*-********************************************* -* Streaming Compression Functions -***********************************************/ -typedef union LZ4_stream_u LZ4_stream_t; /* incomplete type (defined later) */ - -/*! LZ4_createStream() and LZ4_freeStream() : - * LZ4_createStream() will allocate and initialize an `LZ4_stream_t` structure. - * LZ4_freeStream() releases its memory. - */ -LZ4LIB_API LZ4_stream_t* LZ4_createStream(void); -LZ4LIB_API int LZ4_freeStream (LZ4_stream_t* streamPtr); - -/*! LZ4_resetStream() : - * An LZ4_stream_t structure can be allocated once and re-used multiple times. - * Use this function to init an allocated `LZ4_stream_t` structure and start a new compression. - */ -LZ4LIB_API void LZ4_resetStream (LZ4_stream_t* streamPtr); - -/*! LZ4_loadDict() : - * Use this function to load a static dictionary into LZ4_stream. - * Any previous data will be forgotten, only 'dictionary' will remain in memory. - * Loading a size of 0 is allowed. - * Return : dictionary size, in bytes (necessarily <= 64 KB) - */ -LZ4LIB_API int LZ4_loadDict (LZ4_stream_t* streamPtr, const char* dictionary, int dictSize); - -/*! LZ4_compress_fast_continue() : - * Compress buffer content 'src', using data from previously compressed blocks as dictionary to improve compression ratio. - * Important : Previous data blocks are assumed to remain present and unmodified ! - * 'dst' buffer must be already allocated. - * If dstCapacity >= LZ4_compressBound(srcSize), compression is guaranteed to succeed, and runs faster. - * If not, and if compressed data cannot fit into 'dst' buffer size, compression stops, and function @return==0. - * After an error, the stream status is invalid, it can only be reset or freed. - */ -LZ4LIB_API int LZ4_compress_fast_continue (LZ4_stream_t* streamPtr, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration); - -/*! LZ4_saveDict() : - * If previously compressed data block is not guaranteed to remain available at its current memory location, - * save it into a safer place (char* safeBuffer). - * Note : it's not necessary to call LZ4_loadDict() after LZ4_saveDict(), dictionary is immediately usable. - * @return : saved dictionary size in bytes (necessarily <= dictSize), or 0 if error. - */ -LZ4LIB_API int LZ4_saveDict (LZ4_stream_t* streamPtr, char* safeBuffer, int dictSize); - - -/*-********************************************** -* Streaming Decompression Functions -* Bufferless synchronous API -************************************************/ -typedef union LZ4_streamDecode_u LZ4_streamDecode_t; /* incomplete type (defined later) */ - -/*! LZ4_createStreamDecode() and LZ4_freeStreamDecode() : - * creation / destruction of streaming decompression tracking structure */ -LZ4LIB_API LZ4_streamDecode_t* LZ4_createStreamDecode(void); -LZ4LIB_API int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream); - -/*! LZ4_setStreamDecode() : - * Use this function to instruct where to find the dictionary. - * Setting a size of 0 is allowed (same effect as reset). - * @return : 1 if OK, 0 if error - */ -LZ4LIB_API int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize); - -/*! LZ4_decompress_*_continue() : - * These decoding functions allow decompression of multiple blocks in "streaming" mode. - * Previously decoded blocks *must* remain available at the memory position where they were decoded (up to 64 KB) - * In the case of a ring buffers, decoding buffer must be either : - * - Exactly same size as encoding buffer, with same update rule (block boundaries at same positions) - * In which case, the decoding & encoding ring buffer can have any size, including very small ones ( < 64 KB). - * - Larger than encoding buffer, by a minimum of maxBlockSize more bytes. - * maxBlockSize is implementation dependent. It's the maximum size you intend to compress into a single block. - * In which case, encoding and decoding buffers do not need to be synchronized, - * and encoding ring buffer can have any size, including small ones ( < 64 KB). - * - _At least_ 64 KB + 8 bytes + maxBlockSize. - * In which case, encoding and decoding buffers do not need to be synchronized, - * and encoding ring buffer can have any size, including larger than decoding buffer. - * Whenever these conditions are not possible, save the last 64KB of decoded data into a safe buffer, - * and indicate where it is saved using LZ4_setStreamDecode() -*/ -LZ4LIB_API int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxDecompressedSize); -LZ4LIB_API int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize); - - -/*! LZ4_decompress_*_usingDict() : - * These decoding functions work the same as - * a combination of LZ4_setStreamDecode() followed by LZ4_decompress_*_continue() - * They are stand-alone, and don't need an LZ4_streamDecode_t structure. - */ -LZ4LIB_API int LZ4_decompress_safe_usingDict (const char* source, char* dest, int compressedSize, int maxDecompressedSize, const char* dictStart, int dictSize); -LZ4LIB_API int LZ4_decompress_fast_usingDict (const char* source, char* dest, int originalSize, const char* dictStart, int dictSize); - - -/*^********************************************** - * !!!!!! STATIC LINKING ONLY !!!!!! - ***********************************************/ -/*-************************************ - * Private definitions - ************************************** - * Do not use these definitions. - * They are exposed to allow static allocation of `LZ4_stream_t` and `LZ4_streamDecode_t`. - * Using these definitions will expose code to API and/or ABI break in future versions of the library. - **************************************/ -#define LZ4_HASHLOG (LZ4_MEMORY_USAGE-2) -#define LZ4_HASHTABLESIZE (1 << LZ4_MEMORY_USAGE) -#define LZ4_HASH_SIZE_U32 (1 << LZ4_HASHLOG) /* required as macro for static allocation */ - -#if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) -#include - -typedef struct { - uint32_t hashTable[LZ4_HASH_SIZE_U32]; - uint32_t currentOffset; - uint32_t initCheck; - const uint8_t* dictionary; - uint8_t* bufferStart; /* obsolete, used for slideInputBuffer */ - uint32_t dictSize; -} LZ4_stream_t_internal; - -typedef struct { - const uint8_t* externalDict; - size_t extDictSize; - const uint8_t* prefixEnd; - size_t prefixSize; -} LZ4_streamDecode_t_internal; - -#else - -typedef struct { - unsigned int hashTable[LZ4_HASH_SIZE_U32]; - unsigned int currentOffset; - unsigned int initCheck; - const unsigned char* dictionary; - unsigned char* bufferStart; /* obsolete, used for slideInputBuffer */ - unsigned int dictSize; -} LZ4_stream_t_internal; - -typedef struct { - const unsigned char* externalDict; - size_t extDictSize; - const unsigned char* prefixEnd; - size_t prefixSize; -} LZ4_streamDecode_t_internal; - -#endif - -/*! - * LZ4_stream_t : - * information structure to track an LZ4 stream. - * init this structure before first use. - * note : only use in association with static linking ! - * this definition is not API/ABI safe, - * it may change in a future version ! - */ -#define LZ4_STREAMSIZE_U64 ((1 << (LZ4_MEMORY_USAGE-3)) + 4) -#define LZ4_STREAMSIZE (LZ4_STREAMSIZE_U64 * sizeof(unsigned long long)) -union LZ4_stream_u { - unsigned long long table[LZ4_STREAMSIZE_U64]; - LZ4_stream_t_internal internal_donotuse; -} ; /* previously typedef'd to LZ4_stream_t */ - - -/*! - * LZ4_streamDecode_t : - * information structure to track an LZ4 stream during decompression. - * init this structure using LZ4_setStreamDecode (or memset()) before first use - * note : only use in association with static linking ! - * this definition is not API/ABI safe, - * and may change in a future version ! - */ -#define LZ4_STREAMDECODESIZE_U64 4 -#define LZ4_STREAMDECODESIZE (LZ4_STREAMDECODESIZE_U64 * sizeof(unsigned long long)) -union LZ4_streamDecode_u { - unsigned long long table[LZ4_STREAMDECODESIZE_U64]; - LZ4_streamDecode_t_internal internal_donotuse; -} ; /* previously typedef'd to LZ4_streamDecode_t */ - - -/*-************************************ -* Obsolete Functions -**************************************/ - -/*! Deprecation warnings - Should deprecation warnings be a problem, - it is generally possible to disable them, - typically with -Wno-deprecated-declarations for gcc - or _CRT_SECURE_NO_WARNINGS in Visual. - Otherwise, it's also possible to define LZ4_DISABLE_DEPRECATE_WARNINGS */ -#ifdef LZ4_DISABLE_DEPRECATE_WARNINGS -# define LZ4_DEPRECATED(message) /* disable deprecation warnings */ -#else -# define LZ4_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) -# if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */ -# define LZ4_DEPRECATED(message) [[deprecated(message)]] -# elif (LZ4_GCC_VERSION >= 405) || defined(__clang__) -# define LZ4_DEPRECATED(message) __attribute__((deprecated(message))) -# elif (LZ4_GCC_VERSION >= 301) -# define LZ4_DEPRECATED(message) __attribute__((deprecated)) -# elif defined(_MSC_VER) -# define LZ4_DEPRECATED(message) __declspec(deprecated(message)) -# else -# pragma message("WARNING: You need to implement LZ4_DEPRECATED for this compiler") -# define LZ4_DEPRECATED(message) -# endif -#endif /* LZ4_DISABLE_DEPRECATE_WARNINGS */ - -/* Obsolete compression functions */ -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_default() instead") int LZ4_compress (const char* source, char* dest, int sourceSize); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_default() instead") int LZ4_compress_limitedOutput (const char* source, char* dest, int sourceSize, int maxOutputSize); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") int LZ4_compress_withState (void* state, const char* source, char* dest, int inputSize); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") int LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") int LZ4_compress_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize, int maxOutputSize); - -/* Obsolete decompression functions */ -LZ4LIB_API LZ4_DEPRECATED("use LZ4_decompress_fast() instead") int LZ4_uncompress (const char* source, char* dest, int outputSize); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_decompress_safe() instead") int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize); - -/* Obsolete streaming functions; use new streaming interface whenever possible */ -LZ4LIB_API LZ4_DEPRECATED("use LZ4_createStream() instead") void* LZ4_create (char* inputBuffer); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_createStream() instead") int LZ4_sizeofStreamState(void); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_resetStream() instead") int LZ4_resetStreamState(void* state, char* inputBuffer); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_saveDict() instead") char* LZ4_slideInputBuffer (void* state); - -/* Obsolete streaming decoding functions */ -LZ4LIB_API LZ4_DEPRECATED("use LZ4_decompress_safe_usingDict() instead") int LZ4_decompress_safe_withPrefix64k (const char* src, char* dst, int compressedSize, int maxDstSize); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_decompress_fast_usingDict() instead") int LZ4_decompress_fast_withPrefix64k (const char* src, char* dst, int originalSize); - -#endif /* LZ4_H_2983827168210 */ - - -#if defined (__cplusplus) -} -#endif diff --git a/src/lz4/lib/lz4frame.c b/src/lz4/lib/lz4frame.c deleted file mode 100644 index 340870877e..0000000000 --- a/src/lz4/lib/lz4frame.c +++ /dev/null @@ -1,1669 +0,0 @@ -/* -LZ4 auto-framing library -Copyright (C) 2011-2016, Yann Collet. - -BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -* Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -You can contact the author at : -- LZ4 homepage : http://www.lz4.org -- LZ4 source repository : https://github.com/lz4/lz4 -*/ - -/* LZ4F is a stand-alone API to create LZ4-compressed Frames -* in full conformance with specification v1.5.0 -* All related operations, including memory management, are handled by the library. -* */ - - -/*-************************************ -* Compiler Options -**************************************/ -#ifdef _MSC_VER /* Visual Studio */ -# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ -#endif - - -/*-************************************ -* Memory routines -**************************************/ -#include /* malloc, calloc, free */ -#define ALLOCATOR(s) calloc(1,s) -#define FREEMEM free -#include /* memset, memcpy, memmove */ -#define MEM_INIT memset - - -/*-************************************ -* Includes -**************************************/ -#include "lz4frame_static.h" -#include "lz4.h" -#define LZ4_HC_STATIC_LINKING_ONLY -#include "lz4hc.h" -#define XXH_STATIC_LINKING_ONLY -#include "xxhash.h" - - -/*-************************************ -* Debug -**************************************/ -#define LZ4F_STATIC_ASSERT(c) { enum { LZ4F_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */ - - -/*-************************************ -* Basic Types -**************************************/ -#if !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) -# include - typedef uint8_t BYTE; - typedef uint16_t U16; - typedef uint32_t U32; - typedef int32_t S32; - typedef uint64_t U64; -#else - typedef unsigned char BYTE; - typedef unsigned short U16; - typedef unsigned int U32; - typedef signed int S32; - typedef unsigned long long U64; -#endif - - -/* unoptimized version; solves endianess & alignment issues */ -static U32 LZ4F_readLE32 (const void* src) -{ - const BYTE* const srcPtr = (const BYTE*)src; - U32 value32 = srcPtr[0]; - value32 += (srcPtr[1]<<8); - value32 += (srcPtr[2]<<16); - value32 += ((U32)srcPtr[3])<<24; - return value32; -} - -static void LZ4F_writeLE32 (void* dst, U32 value32) -{ - BYTE* const dstPtr = (BYTE*)dst; - dstPtr[0] = (BYTE)value32; - dstPtr[1] = (BYTE)(value32 >> 8); - dstPtr[2] = (BYTE)(value32 >> 16); - dstPtr[3] = (BYTE)(value32 >> 24); -} - -static U64 LZ4F_readLE64 (const void* src) -{ - const BYTE* const srcPtr = (const BYTE*)src; - U64 value64 = srcPtr[0]; - value64 += ((U64)srcPtr[1]<<8); - value64 += ((U64)srcPtr[2]<<16); - value64 += ((U64)srcPtr[3]<<24); - value64 += ((U64)srcPtr[4]<<32); - value64 += ((U64)srcPtr[5]<<40); - value64 += ((U64)srcPtr[6]<<48); - value64 += ((U64)srcPtr[7]<<56); - return value64; -} - -static void LZ4F_writeLE64 (void* dst, U64 value64) -{ - BYTE* const dstPtr = (BYTE*)dst; - dstPtr[0] = (BYTE)value64; - dstPtr[1] = (BYTE)(value64 >> 8); - dstPtr[2] = (BYTE)(value64 >> 16); - dstPtr[3] = (BYTE)(value64 >> 24); - dstPtr[4] = (BYTE)(value64 >> 32); - dstPtr[5] = (BYTE)(value64 >> 40); - dstPtr[6] = (BYTE)(value64 >> 48); - dstPtr[7] = (BYTE)(value64 >> 56); -} - - -/*-************************************ -* Constants -**************************************/ -#define KB *(1<<10) -#define MB *(1<<20) -#define GB *(1<<30) - -#define _1BIT 0x01 -#define _2BITS 0x03 -#define _3BITS 0x07 -#define _4BITS 0x0F -#define _8BITS 0xFF - -#define LZ4F_MAGIC_SKIPPABLE_START 0x184D2A50U -#define LZ4F_MAGICNUMBER 0x184D2204U -#define LZ4F_BLOCKUNCOMPRESSED_FLAG 0x80000000U -#define LZ4F_BLOCKSIZEID_DEFAULT LZ4F_max64KB - -static const size_t minFHSize = 7; -static const size_t maxFHSize = LZ4F_HEADER_SIZE_MAX; /* 19 */ -static const size_t BHSize = 4; - - -/*-************************************ -* Structures and local types -**************************************/ -typedef struct LZ4F_cctx_s -{ - LZ4F_preferences_t prefs; - U32 version; - U32 cStage; - const LZ4F_CDict* cdict; - size_t maxBlockSize; - size_t maxBufferSize; - BYTE* tmpBuff; - BYTE* tmpIn; - size_t tmpInSize; - U64 totalInSize; - XXH32_state_t xxh; - void* lz4CtxPtr; - U32 lz4CtxLevel; /* 0: unallocated; 1: LZ4_stream_t; 3: LZ4_streamHC_t */ -} LZ4F_cctx_t; - - -/*-************************************ -* Error management -**************************************/ -#define LZ4F_GENERATE_STRING(STRING) #STRING, -static const char* LZ4F_errorStrings[] = { LZ4F_LIST_ERRORS(LZ4F_GENERATE_STRING) }; - - -unsigned LZ4F_isError(LZ4F_errorCode_t code) -{ - return (code > (LZ4F_errorCode_t)(-LZ4F_ERROR_maxCode)); -} - -const char* LZ4F_getErrorName(LZ4F_errorCode_t code) -{ - static const char* codeError = "Unspecified error code"; - if (LZ4F_isError(code)) return LZ4F_errorStrings[-(int)(code)]; - return codeError; -} - -LZ4F_errorCodes LZ4F_getErrorCode(size_t functionResult) -{ - if (!LZ4F_isError(functionResult)) return LZ4F_OK_NoError; - return (LZ4F_errorCodes)(-(ptrdiff_t)functionResult); -} - -static LZ4F_errorCode_t err0r(LZ4F_errorCodes code) -{ - /* A compilation error here means sizeof(ptrdiff_t) is not large enough */ - LZ4F_STATIC_ASSERT(sizeof(ptrdiff_t) >= sizeof(size_t)); - return (LZ4F_errorCode_t)-(ptrdiff_t)code; -} - -unsigned LZ4F_getVersion(void) { return LZ4F_VERSION; } - -int LZ4F_compressionLevel_max(void) { return LZ4HC_CLEVEL_MAX; } - - -/*-************************************ -* Private functions -**************************************/ -#define MIN(a,b) ( (a) < (b) ? (a) : (b) ) - -static size_t LZ4F_getBlockSize(unsigned blockSizeID) -{ - static const size_t blockSizes[4] = { 64 KB, 256 KB, 1 MB, 4 MB }; - - if (blockSizeID == 0) blockSizeID = LZ4F_BLOCKSIZEID_DEFAULT; - blockSizeID -= 4; - if (blockSizeID > 3) return err0r(LZ4F_ERROR_maxBlockSize_invalid); - return blockSizes[blockSizeID]; -} - -static BYTE LZ4F_headerChecksum (const void* header, size_t length) -{ - U32 const xxh = XXH32(header, length, 0); - return (BYTE)(xxh >> 8); -} - - -/*-************************************ -* Simple-pass compression functions -**************************************/ -static LZ4F_blockSizeID_t LZ4F_optimalBSID(const LZ4F_blockSizeID_t requestedBSID, - const size_t srcSize) -{ - LZ4F_blockSizeID_t proposedBSID = LZ4F_max64KB; - size_t maxBlockSize = 64 KB; - while (requestedBSID > proposedBSID) { - if (srcSize <= maxBlockSize) - return proposedBSID; - proposedBSID = (LZ4F_blockSizeID_t)((int)proposedBSID + 1); - maxBlockSize <<= 2; - } - return requestedBSID; -} - -/*! LZ4F_compressBound_internal() : - * Provides dstCapacity given a srcSize to guarantee operation success in worst case situations. - * prefsPtr is optional : if NULL is provided, preferences will be set to cover worst case scenario. - * @return is always the same for a srcSize and prefsPtr, so it can be relied upon to size reusable buffers. - * When srcSize==0, LZ4F_compressBound() provides an upper bound for LZ4F_flush() and LZ4F_compressEnd() operations. - */ -static size_t LZ4F_compressBound_internal(size_t srcSize, - const LZ4F_preferences_t* preferencesPtr, - size_t alreadyBuffered) -{ - LZ4F_preferences_t prefsNull; - memset(&prefsNull, 0, sizeof(prefsNull)); - prefsNull.frameInfo.contentChecksumFlag = LZ4F_contentChecksumEnabled; /* worst case */ - { const LZ4F_preferences_t* const prefsPtr = (preferencesPtr==NULL) ? &prefsNull : preferencesPtr; - U32 const flush = prefsPtr->autoFlush | (srcSize==0); - LZ4F_blockSizeID_t const blockID = prefsPtr->frameInfo.blockSizeID; - size_t const blockSize = LZ4F_getBlockSize(blockID); - size_t const maxBuffered = blockSize - 1; - size_t const bufferedSize = MIN(alreadyBuffered, maxBuffered); - size_t const maxSrcSize = srcSize + bufferedSize; - unsigned const nbFullBlocks = (unsigned)(maxSrcSize / blockSize); - size_t const partialBlockSize = (srcSize - (srcSize==0)) & (blockSize-1); /* 0 => -1 == MAX => blockSize-1 */ - size_t const lastBlockSize = flush ? partialBlockSize : 0; - unsigned const nbBlocks = nbFullBlocks + (lastBlockSize>0); - - size_t const blockHeaderSize = 4; - size_t const blockCRCSize = 4 * prefsPtr->frameInfo.blockChecksumFlag; - size_t const frameEnd = 4 + (prefsPtr->frameInfo.contentChecksumFlag*4); - - return ((blockHeaderSize + blockCRCSize) * nbBlocks) + - (blockSize * nbFullBlocks) + lastBlockSize + frameEnd; - } -} - -size_t LZ4F_compressFrameBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr) -{ - LZ4F_preferences_t prefs; - size_t const headerSize = maxFHSize; /* max header size, including optional fields */ - - if (preferencesPtr!=NULL) prefs = *preferencesPtr; - else memset(&prefs, 0, sizeof(prefs)); - prefs.autoFlush = 1; - - return headerSize + LZ4F_compressBound_internal(srcSize, &prefs, 0);; -} - - -/*! LZ4F_compressFrame_usingCDict() : - * Compress srcBuffer using a dictionary, in a single step. - * cdict can be NULL, in which case, no dictionary is used. - * dstBuffer MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr). - * The LZ4F_preferences_t structure is optional : you may provide NULL as argument, - * however, it's the only way to provide a dictID, so it's not recommended. - * @return : number of bytes written into dstBuffer, - * or an error code if it fails (can be tested using LZ4F_isError()) - */ -size_t LZ4F_compressFrame_usingCDict(void* dstBuffer, size_t dstCapacity, - const void* srcBuffer, size_t srcSize, - const LZ4F_CDict* cdict, - const LZ4F_preferences_t* preferencesPtr) -{ - LZ4F_cctx_t cctxI; - LZ4_stream_t lz4ctx; - LZ4F_preferences_t prefs; - LZ4F_compressOptions_t options; - BYTE* const dstStart = (BYTE*) dstBuffer; - BYTE* dstPtr = dstStart; - BYTE* const dstEnd = dstStart + dstCapacity; - - memset(&cctxI, 0, sizeof(cctxI)); - cctxI.version = LZ4F_VERSION; - cctxI.maxBufferSize = 5 MB; /* mess with real buffer size to prevent dynamic allocation; works only because autoflush==1 & stableSrc==1 */ - - if (preferencesPtr!=NULL) - prefs = *preferencesPtr; - else - memset(&prefs, 0, sizeof(prefs)); - if (prefs.frameInfo.contentSize != 0) - prefs.frameInfo.contentSize = (U64)srcSize; /* auto-correct content size if selected (!=0) */ - - prefs.frameInfo.blockSizeID = LZ4F_optimalBSID(prefs.frameInfo.blockSizeID, srcSize); - prefs.autoFlush = 1; - if (srcSize <= LZ4F_getBlockSize(prefs.frameInfo.blockSizeID)) - prefs.frameInfo.blockMode = LZ4F_blockIndependent; /* only one block => no need for inter-block link */ - - if (prefs.compressionLevel < LZ4HC_CLEVEL_MIN) { - cctxI.lz4CtxPtr = &lz4ctx; - cctxI.lz4CtxLevel = 1; - } /* fast compression context pre-created on stack */ - - memset(&options, 0, sizeof(options)); - options.stableSrc = 1; - - if (dstCapacity < LZ4F_compressFrameBound(srcSize, &prefs)) /* condition to guarantee success */ - return err0r(LZ4F_ERROR_dstMaxSize_tooSmall); - - { size_t const headerSize = LZ4F_compressBegin_usingCDict(&cctxI, dstBuffer, dstCapacity, cdict, &prefs); /* write header */ - if (LZ4F_isError(headerSize)) return headerSize; - dstPtr += headerSize; /* header size */ } - - { size_t const cSize = LZ4F_compressUpdate(&cctxI, dstPtr, dstEnd-dstPtr, srcBuffer, srcSize, &options); - if (LZ4F_isError(cSize)) return cSize; - dstPtr += cSize; } - - { size_t const tailSize = LZ4F_compressEnd(&cctxI, dstPtr, dstEnd-dstPtr, &options); /* flush last block, and generate suffix */ - if (LZ4F_isError(tailSize)) return tailSize; - dstPtr += tailSize; } - - if (prefs.compressionLevel >= LZ4HC_CLEVEL_MIN) /* Ctx allocation only for lz4hc */ - FREEMEM(cctxI.lz4CtxPtr); - - return (dstPtr - dstStart); -} - - -/*! LZ4F_compressFrame() : - * Compress an entire srcBuffer into a valid LZ4 frame, in a single step. - * dstBuffer MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr). - * The LZ4F_preferences_t structure is optional : you can provide NULL as argument. All preferences will be set to default. - * @return : number of bytes written into dstBuffer. - * or an error code if it fails (can be tested using LZ4F_isError()) - */ -size_t LZ4F_compressFrame(void* dstBuffer, size_t dstCapacity, - const void* srcBuffer, size_t srcSize, - const LZ4F_preferences_t* preferencesPtr) -{ - return LZ4F_compressFrame_usingCDict(dstBuffer, dstCapacity, - srcBuffer, srcSize, - NULL, preferencesPtr); -} - - -/*-*************************************************** -* Dictionary compression -*****************************************************/ - -struct LZ4F_CDict_s { - void* dictContent; - LZ4_stream_t* fastCtx; - LZ4_streamHC_t* HCCtx; -}; /* typedef'd to LZ4F_CDict within lz4frame_static.h */ - -/*! LZ4F_createCDict() : - * When compressing multiple messages / blocks with the same dictionary, it's recommended to load it just once. - * LZ4F_createCDict() will create a digested dictionary, ready to start future compression operations without startup delay. - * LZ4F_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only. - * `dictBuffer` can be released after LZ4F_CDict creation, since its content is copied within CDict - * @return : digested dictionary for compression, or NULL if failed */ -LZ4F_CDict* LZ4F_createCDict(const void* dictBuffer, size_t dictSize) -{ - const char* dictStart = (const char*)dictBuffer; - LZ4F_CDict* cdict = (LZ4F_CDict*) malloc(sizeof(*cdict)); - if (!cdict) return NULL; - if (dictSize > 64 KB) { - dictStart += dictSize - 64 KB; - dictSize = 64 KB; - } - cdict->dictContent = ALLOCATOR(dictSize); - cdict->fastCtx = LZ4_createStream(); - cdict->HCCtx = LZ4_createStreamHC(); - if (!cdict->dictContent || !cdict->fastCtx || !cdict->HCCtx) { - LZ4F_freeCDict(cdict); - return NULL; - } - memcpy(cdict->dictContent, dictStart, dictSize); - LZ4_resetStream(cdict->fastCtx); - LZ4_loadDict (cdict->fastCtx, (const char*)cdict->dictContent, (int)dictSize); - LZ4_resetStreamHC(cdict->HCCtx, LZ4HC_CLEVEL_DEFAULT); - LZ4_loadDictHC(cdict->HCCtx, (const char*)cdict->dictContent, (int)dictSize); - return cdict; -} - -void LZ4F_freeCDict(LZ4F_CDict* cdict) -{ - if (cdict==NULL) return; /* support free on NULL */ - FREEMEM(cdict->dictContent); - LZ4_freeStream(cdict->fastCtx); - LZ4_freeStreamHC(cdict->HCCtx); - FREEMEM(cdict); -} - - -/*-********************************* -* Advanced compression functions -***********************************/ - -/*! LZ4F_createCompressionContext() : - * The first thing to do is to create a compressionContext object, which will be used in all compression operations. - * This is achieved using LZ4F_createCompressionContext(), which takes as argument a version and an LZ4F_preferences_t structure. - * The version provided MUST be LZ4F_VERSION. It is intended to track potential incompatible differences between different binaries. - * The function will provide a pointer to an allocated LZ4F_compressionContext_t object. - * If the result LZ4F_errorCode_t is not OK_NoError, there was an error during context creation. - * Object can release its memory using LZ4F_freeCompressionContext(); - */ -LZ4F_errorCode_t LZ4F_createCompressionContext(LZ4F_compressionContext_t* LZ4F_compressionContextPtr, unsigned version) -{ - LZ4F_cctx_t* const cctxPtr = (LZ4F_cctx_t*)ALLOCATOR(sizeof(LZ4F_cctx_t)); - if (cctxPtr==NULL) return err0r(LZ4F_ERROR_allocation_failed); - - cctxPtr->version = version; - cctxPtr->cStage = 0; /* Next stage : init stream */ - - *LZ4F_compressionContextPtr = (LZ4F_compressionContext_t)cctxPtr; - - return LZ4F_OK_NoError; -} - - -LZ4F_errorCode_t LZ4F_freeCompressionContext(LZ4F_compressionContext_t LZ4F_compressionContext) -{ - LZ4F_cctx_t* const cctxPtr = (LZ4F_cctx_t*)LZ4F_compressionContext; - - if (cctxPtr != NULL) { /* support free on NULL */ - FREEMEM(cctxPtr->lz4CtxPtr); /* works because LZ4_streamHC_t and LZ4_stream_t are simple POD types */ - FREEMEM(cctxPtr->tmpBuff); - FREEMEM(LZ4F_compressionContext); - } - - return LZ4F_OK_NoError; -} - - -/*! LZ4F_compressBegin_usingCDict() : - * init streaming compression and writes frame header into dstBuffer. - * dstBuffer must be >= LZ4F_HEADER_SIZE_MAX bytes. - * @return : number of bytes written into dstBuffer for the header - * or an error code (can be tested using LZ4F_isError()) - */ -size_t LZ4F_compressBegin_usingCDict(LZ4F_cctx* cctxPtr, - void* dstBuffer, size_t dstCapacity, - const LZ4F_CDict* cdict, - const LZ4F_preferences_t* preferencesPtr) -{ - LZ4F_preferences_t prefNull; - BYTE* const dstStart = (BYTE*)dstBuffer; - BYTE* dstPtr = dstStart; - BYTE* headerStart; - - if (dstCapacity < maxFHSize) return err0r(LZ4F_ERROR_dstMaxSize_tooSmall); - memset(&prefNull, 0, sizeof(prefNull)); - if (preferencesPtr == NULL) preferencesPtr = &prefNull; - cctxPtr->prefs = *preferencesPtr; - - /* Ctx Management */ - { U32 const tableID = (cctxPtr->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) ? 1 : 2; /* 0:nothing ; 1:LZ4 table ; 2:HC tables */ - if (cctxPtr->lz4CtxLevel < tableID) { - FREEMEM(cctxPtr->lz4CtxPtr); - if (cctxPtr->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) - cctxPtr->lz4CtxPtr = (void*)LZ4_createStream(); - else - cctxPtr->lz4CtxPtr = (void*)LZ4_createStreamHC(); - if (cctxPtr->lz4CtxPtr == NULL) return err0r(LZ4F_ERROR_allocation_failed); - cctxPtr->lz4CtxLevel = tableID; - } } - - /* Buffer Management */ - if (cctxPtr->prefs.frameInfo.blockSizeID == 0) - cctxPtr->prefs.frameInfo.blockSizeID = LZ4F_BLOCKSIZEID_DEFAULT; - cctxPtr->maxBlockSize = LZ4F_getBlockSize(cctxPtr->prefs.frameInfo.blockSizeID); - - { size_t const requiredBuffSize = preferencesPtr->autoFlush ? - (cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked) * 64 KB : /* only needs windows size */ - cctxPtr->maxBlockSize + ((cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked) * 128 KB); - - if (cctxPtr->maxBufferSize < requiredBuffSize) { - cctxPtr->maxBufferSize = 0; - FREEMEM(cctxPtr->tmpBuff); - cctxPtr->tmpBuff = (BYTE*)ALLOCATOR(requiredBuffSize); - if (cctxPtr->tmpBuff == NULL) return err0r(LZ4F_ERROR_allocation_failed); - cctxPtr->maxBufferSize = requiredBuffSize; - } } - cctxPtr->tmpIn = cctxPtr->tmpBuff; - cctxPtr->tmpInSize = 0; - XXH32_reset(&(cctxPtr->xxh), 0); - - /* context init */ - cctxPtr->cdict = cdict; - if (cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked) { - /* frame init only for blockLinked : blockIndependent will be init at each block */ - if (cdict) { - if (cctxPtr->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) { - memcpy(cctxPtr->lz4CtxPtr, cdict->fastCtx, sizeof(*cdict->fastCtx)); - } else { - memcpy(cctxPtr->lz4CtxPtr, cdict->HCCtx, sizeof(*cdict->HCCtx)); - LZ4_setCompressionLevel((LZ4_streamHC_t*)cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel); - } - } else { - if (cctxPtr->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) - LZ4_resetStream((LZ4_stream_t*)(cctxPtr->lz4CtxPtr)); - else - LZ4_resetStreamHC((LZ4_streamHC_t*)(cctxPtr->lz4CtxPtr), cctxPtr->prefs.compressionLevel); - } - } - - /* Magic Number */ - LZ4F_writeLE32(dstPtr, LZ4F_MAGICNUMBER); - dstPtr += 4; - headerStart = dstPtr; - - /* FLG Byte */ - *dstPtr++ = (BYTE)(((1 & _2BITS) << 6) /* Version('01') */ - + ((cctxPtr->prefs.frameInfo.blockMode & _1BIT ) << 5) - + ((cctxPtr->prefs.frameInfo.blockChecksumFlag & _1BIT ) << 4) - + ((cctxPtr->prefs.frameInfo.contentSize > 0) << 3) - + ((cctxPtr->prefs.frameInfo.contentChecksumFlag & _1BIT ) << 2) - + (cctxPtr->prefs.frameInfo.dictID > 0) ); - /* BD Byte */ - *dstPtr++ = (BYTE)((cctxPtr->prefs.frameInfo.blockSizeID & _3BITS) << 4); - /* Optional Frame content size field */ - if (cctxPtr->prefs.frameInfo.contentSize) { - LZ4F_writeLE64(dstPtr, cctxPtr->prefs.frameInfo.contentSize); - dstPtr += 8; - cctxPtr->totalInSize = 0; - } - /* Optional dictionary ID field */ - if (cctxPtr->prefs.frameInfo.dictID) { - LZ4F_writeLE32(dstPtr, cctxPtr->prefs.frameInfo.dictID); - dstPtr += 4; - } - /* Header CRC Byte */ - *dstPtr = LZ4F_headerChecksum(headerStart, dstPtr - headerStart); - dstPtr++; - - cctxPtr->cStage = 1; /* header written, now request input data block */ - return (dstPtr - dstStart); -} - - -/*! LZ4F_compressBegin() : - * init streaming compression and writes frame header into dstBuffer. - * dstBuffer must be >= LZ4F_HEADER_SIZE_MAX bytes. - * preferencesPtr can be NULL, in which case default parameters are selected. - * @return : number of bytes written into dstBuffer for the header - * or an error code (can be tested using LZ4F_isError()) - */ -size_t LZ4F_compressBegin(LZ4F_cctx* cctxPtr, - void* dstBuffer, size_t dstCapacity, - const LZ4F_preferences_t* preferencesPtr) -{ - return LZ4F_compressBegin_usingCDict(cctxPtr, dstBuffer, dstCapacity, - NULL, preferencesPtr); -} - - -/* LZ4F_compressBound() : - * @ return size of Dst buffer given a srcSize to handle worst case situations. - * The LZ4F_frameInfo_t structure is optional : if NULL, preferences will be set to cover worst case situations. - * This function cannot fail. - */ -size_t LZ4F_compressBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr) -{ - return LZ4F_compressBound_internal(srcSize, preferencesPtr, (size_t)-1); -} - - -typedef int (*compressFunc_t)(void* ctx, const char* src, char* dst, int srcSize, int dstSize, int level, const LZ4F_CDict* cdict); - - -/*! LZ4F_makeBlock(): - * compress a single block, add header and checksum - * assumption : dst buffer capacity is >= srcSize */ -static size_t LZ4F_makeBlock(void* dst, const void* src, size_t srcSize, - compressFunc_t compress, void* lz4ctx, int level, - const LZ4F_CDict* cdict, LZ4F_blockChecksum_t crcFlag) -{ - BYTE* const cSizePtr = (BYTE*)dst; - U32 cSize = (U32)compress(lz4ctx, (const char*)src, (char*)(cSizePtr+4), - (int)(srcSize), (int)(srcSize-1), - level, cdict); - LZ4F_writeLE32(cSizePtr, cSize); - if (cSize == 0) { /* compression failed */ - cSize = (U32)srcSize; - LZ4F_writeLE32(cSizePtr, cSize | LZ4F_BLOCKUNCOMPRESSED_FLAG); - memcpy(cSizePtr+4, src, srcSize); - } - if (crcFlag) { - U32 const crc32 = XXH32(cSizePtr+4, cSize, 0); /* checksum of compressed data */ - LZ4F_writeLE32(cSizePtr+4+cSize, crc32); - } - return 4 + cSize + ((U32)crcFlag)*4; -} - - -static int LZ4F_compressBlock(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict) -{ - int const acceleration = (level < -1) ? -level : 1; - if (cdict) { - memcpy(ctx, cdict->fastCtx, sizeof(*cdict->fastCtx)); - return LZ4_compress_fast_continue((LZ4_stream_t*)ctx, src, dst, srcSize, dstCapacity, acceleration); - } - return LZ4_compress_fast_extState(ctx, src, dst, srcSize, dstCapacity, acceleration); -} - -static int LZ4F_compressBlock_continue(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict) -{ - int const acceleration = (level < -1) ? -level : 1; - (void)cdict; /* init once at beginning of frame */ - return LZ4_compress_fast_continue((LZ4_stream_t*)ctx, src, dst, srcSize, dstCapacity, acceleration); -} - -static int LZ4F_compressBlockHC(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict) -{ - if (cdict) { - memcpy(ctx, cdict->HCCtx, sizeof(*cdict->HCCtx)); - LZ4_setCompressionLevel((LZ4_streamHC_t*)ctx, level); - return LZ4_compress_HC_continue((LZ4_streamHC_t*)ctx, src, dst, srcSize, dstCapacity); - } - return LZ4_compress_HC_extStateHC(ctx, src, dst, srcSize, dstCapacity, level); -} - -static int LZ4F_compressBlockHC_continue(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict) -{ - (void)level; (void)cdict; /* init once at beginning of frame */ - return LZ4_compress_HC_continue((LZ4_streamHC_t*)ctx, src, dst, srcSize, dstCapacity); -} - -static compressFunc_t LZ4F_selectCompression(LZ4F_blockMode_t blockMode, int level) -{ - if (level < LZ4HC_CLEVEL_MIN) { - if (blockMode == LZ4F_blockIndependent) return LZ4F_compressBlock; - return LZ4F_compressBlock_continue; - } - if (blockMode == LZ4F_blockIndependent) return LZ4F_compressBlockHC; - return LZ4F_compressBlockHC_continue; -} - -static int LZ4F_localSaveDict(LZ4F_cctx_t* cctxPtr) -{ - if (cctxPtr->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) - return LZ4_saveDict ((LZ4_stream_t*)(cctxPtr->lz4CtxPtr), (char*)(cctxPtr->tmpBuff), 64 KB); - return LZ4_saveDictHC ((LZ4_streamHC_t*)(cctxPtr->lz4CtxPtr), (char*)(cctxPtr->tmpBuff), 64 KB); -} - -typedef enum { notDone, fromTmpBuffer, fromSrcBuffer } LZ4F_lastBlockStatus; - -/*! LZ4F_compressUpdate() : - * LZ4F_compressUpdate() can be called repetitively to compress as much data as necessary. - * dstBuffer MUST be >= LZ4F_compressBound(srcSize, preferencesPtr). - * LZ4F_compressOptions_t structure is optional : you can provide NULL as argument. - * @return : the number of bytes written into dstBuffer. It can be zero, meaning input data was just buffered. - * or an error code if it fails (which can be tested using LZ4F_isError()) - */ -size_t LZ4F_compressUpdate(LZ4F_cctx* cctxPtr, - void* dstBuffer, size_t dstCapacity, - const void* srcBuffer, size_t srcSize, - const LZ4F_compressOptions_t* compressOptionsPtr) -{ - LZ4F_compressOptions_t cOptionsNull; - size_t const blockSize = cctxPtr->maxBlockSize; - const BYTE* srcPtr = (const BYTE*)srcBuffer; - const BYTE* const srcEnd = srcPtr + srcSize; - BYTE* const dstStart = (BYTE*)dstBuffer; - BYTE* dstPtr = dstStart; - LZ4F_lastBlockStatus lastBlockCompressed = notDone; - compressFunc_t const compress = LZ4F_selectCompression(cctxPtr->prefs.frameInfo.blockMode, cctxPtr->prefs.compressionLevel); - - - if (cctxPtr->cStage != 1) return err0r(LZ4F_ERROR_GENERIC); - if (dstCapacity < LZ4F_compressBound_internal(srcSize, &(cctxPtr->prefs), cctxPtr->tmpInSize)) return err0r(LZ4F_ERROR_dstMaxSize_tooSmall); - memset(&cOptionsNull, 0, sizeof(cOptionsNull)); - if (compressOptionsPtr == NULL) compressOptionsPtr = &cOptionsNull; - - /* complete tmp buffer */ - if (cctxPtr->tmpInSize > 0) { /* some data already within tmp buffer */ - size_t const sizeToCopy = blockSize - cctxPtr->tmpInSize; - if (sizeToCopy > srcSize) { - /* add src to tmpIn buffer */ - memcpy(cctxPtr->tmpIn + cctxPtr->tmpInSize, srcBuffer, srcSize); - srcPtr = srcEnd; - cctxPtr->tmpInSize += srcSize; - /* still needs some CRC */ - } else { - /* complete tmpIn block and then compress it */ - lastBlockCompressed = fromTmpBuffer; - memcpy(cctxPtr->tmpIn + cctxPtr->tmpInSize, srcBuffer, sizeToCopy); - srcPtr += sizeToCopy; - - dstPtr += LZ4F_makeBlock(dstPtr, cctxPtr->tmpIn, blockSize, - compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel, - cctxPtr->cdict, cctxPtr->prefs.frameInfo.blockChecksumFlag); - - if (cctxPtr->prefs.frameInfo.blockMode==LZ4F_blockLinked) cctxPtr->tmpIn += blockSize; - cctxPtr->tmpInSize = 0; - } - } - - while ((size_t)(srcEnd - srcPtr) >= blockSize) { - /* compress full blocks */ - lastBlockCompressed = fromSrcBuffer; - dstPtr += LZ4F_makeBlock(dstPtr, srcPtr, blockSize, - compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel, - cctxPtr->cdict, cctxPtr->prefs.frameInfo.blockChecksumFlag); - srcPtr += blockSize; - } - - if ((cctxPtr->prefs.autoFlush) && (srcPtr < srcEnd)) { - /* compress remaining input < blockSize */ - lastBlockCompressed = fromSrcBuffer; - dstPtr += LZ4F_makeBlock(dstPtr, srcPtr, srcEnd - srcPtr, - compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel, - cctxPtr->cdict, cctxPtr->prefs.frameInfo.blockChecksumFlag); - srcPtr = srcEnd; - } - - /* preserve dictionary if necessary */ - if ((cctxPtr->prefs.frameInfo.blockMode==LZ4F_blockLinked) && (lastBlockCompressed==fromSrcBuffer)) { - if (compressOptionsPtr->stableSrc) { - cctxPtr->tmpIn = cctxPtr->tmpBuff; - } else { - int const realDictSize = LZ4F_localSaveDict(cctxPtr); - if (realDictSize==0) return err0r(LZ4F_ERROR_GENERIC); - cctxPtr->tmpIn = cctxPtr->tmpBuff + realDictSize; - } - } - - /* keep tmpIn within limits */ - if ((cctxPtr->tmpIn + blockSize) > (cctxPtr->tmpBuff + cctxPtr->maxBufferSize) /* necessarily LZ4F_blockLinked && lastBlockCompressed==fromTmpBuffer */ - && !(cctxPtr->prefs.autoFlush)) - { - int const realDictSize = LZ4F_localSaveDict(cctxPtr); - cctxPtr->tmpIn = cctxPtr->tmpBuff + realDictSize; - } - - /* some input data left, necessarily < blockSize */ - if (srcPtr < srcEnd) { - /* fill tmp buffer */ - size_t const sizeToCopy = srcEnd - srcPtr; - memcpy(cctxPtr->tmpIn, srcPtr, sizeToCopy); - cctxPtr->tmpInSize = sizeToCopy; - } - - if (cctxPtr->prefs.frameInfo.contentChecksumFlag == LZ4F_contentChecksumEnabled) - XXH32_update(&(cctxPtr->xxh), srcBuffer, srcSize); - - cctxPtr->totalInSize += srcSize; - return dstPtr - dstStart; -} - - -/*! LZ4F_flush() : - * Should you need to create compressed data immediately, without waiting for a block to be filled, - * you can call LZ4_flush(), which will immediately compress any remaining data stored within compressionContext. - * The result of the function is the number of bytes written into dstBuffer - * (it can be zero, this means there was no data left within compressionContext) - * The function outputs an error code if it fails (can be tested using LZ4F_isError()) - * The LZ4F_compressOptions_t structure is optional : you can provide NULL as argument. - */ -size_t LZ4F_flush(LZ4F_cctx* cctxPtr, void* dstBuffer, size_t dstCapacity, const LZ4F_compressOptions_t* compressOptionsPtr) -{ - BYTE* const dstStart = (BYTE*)dstBuffer; - BYTE* dstPtr = dstStart; - compressFunc_t compress; - - if (cctxPtr->tmpInSize == 0) return 0; /* nothing to flush */ - if (cctxPtr->cStage != 1) return err0r(LZ4F_ERROR_GENERIC); - if (dstCapacity < (cctxPtr->tmpInSize + 4)) return err0r(LZ4F_ERROR_dstMaxSize_tooSmall); /* +4 : block header(4) */ - (void)compressOptionsPtr; /* not yet useful */ - - /* select compression function */ - compress = LZ4F_selectCompression(cctxPtr->prefs.frameInfo.blockMode, cctxPtr->prefs.compressionLevel); - - /* compress tmp buffer */ - dstPtr += LZ4F_makeBlock(dstPtr, cctxPtr->tmpIn, cctxPtr->tmpInSize, - compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel, - cctxPtr->cdict, cctxPtr->prefs.frameInfo.blockChecksumFlag); - if (cctxPtr->prefs.frameInfo.blockMode==LZ4F_blockLinked) cctxPtr->tmpIn += cctxPtr->tmpInSize; - cctxPtr->tmpInSize = 0; - - /* keep tmpIn within limits */ - if ((cctxPtr->tmpIn + cctxPtr->maxBlockSize) > (cctxPtr->tmpBuff + cctxPtr->maxBufferSize)) { /* necessarily LZ4F_blockLinked */ - int realDictSize = LZ4F_localSaveDict(cctxPtr); - cctxPtr->tmpIn = cctxPtr->tmpBuff + realDictSize; - } - - return dstPtr - dstStart; -} - - -/*! LZ4F_compressEnd() : - * When you want to properly finish the compressed frame, just call LZ4F_compressEnd(). - * It will flush whatever data remained within compressionContext (like LZ4_flush()) - * but also properly finalize the frame, with an endMark and a checksum. - * The result of the function is the number of bytes written into dstBuffer (necessarily >= 4 (endMark size)) - * The function outputs an error code if it fails (can be tested using LZ4F_isError()) - * The LZ4F_compressOptions_t structure is optional : you can provide NULL as argument. - * compressionContext can then be used again, starting with LZ4F_compressBegin(). The preferences will remain the same. - */ -size_t LZ4F_compressEnd(LZ4F_cctx* cctxPtr, void* dstBuffer, size_t dstMaxSize, const LZ4F_compressOptions_t* compressOptionsPtr) -{ - BYTE* const dstStart = (BYTE*)dstBuffer; - BYTE* dstPtr = dstStart; - - size_t const flushSize = LZ4F_flush(cctxPtr, dstBuffer, dstMaxSize, compressOptionsPtr); - if (LZ4F_isError(flushSize)) return flushSize; - dstPtr += flushSize; - - LZ4F_writeLE32(dstPtr, 0); - dstPtr+=4; /* endMark */ - - if (cctxPtr->prefs.frameInfo.contentChecksumFlag == LZ4F_contentChecksumEnabled) { - U32 const xxh = XXH32_digest(&(cctxPtr->xxh)); - LZ4F_writeLE32(dstPtr, xxh); - dstPtr+=4; /* content Checksum */ - } - - cctxPtr->cStage = 0; /* state is now re-usable (with identical preferences) */ - cctxPtr->maxBufferSize = 0; /* reuse HC context */ - - if (cctxPtr->prefs.frameInfo.contentSize) { - if (cctxPtr->prefs.frameInfo.contentSize != cctxPtr->totalInSize) - return err0r(LZ4F_ERROR_frameSize_wrong); - } - - return dstPtr - dstStart; -} - - -/*-*************************************************** -* Frame Decompression -*****************************************************/ - -typedef enum { - dstage_getFrameHeader=0, dstage_storeFrameHeader, - dstage_init, - dstage_getBlockHeader, dstage_storeBlockHeader, - dstage_copyDirect, dstage_getBlockChecksum, - dstage_getCBlock, dstage_storeCBlock, - dstage_decodeCBlock, dstage_decodeCBlock_intoDst, - dstage_decodeCBlock_intoTmp, dstage_flushOut, - dstage_getSuffix, dstage_storeSuffix, - dstage_getSFrameSize, dstage_storeSFrameSize, - dstage_skipSkippable -} dStage_t; - -struct LZ4F_dctx_s { - LZ4F_frameInfo_t frameInfo; - U32 version; - dStage_t dStage; - U64 frameRemainingSize; - size_t maxBlockSize; - size_t maxBufferSize; - BYTE* tmpIn; - size_t tmpInSize; - size_t tmpInTarget; - BYTE* tmpOutBuffer; - const BYTE* dict; - size_t dictSize; - BYTE* tmpOut; - size_t tmpOutSize; - size_t tmpOutStart; - XXH32_state_t xxh; - XXH32_state_t blockChecksum; - BYTE header[LZ4F_HEADER_SIZE_MAX]; -}; /* typedef'd to LZ4F_dctx in lz4frame.h */ - - -/*! LZ4F_createDecompressionContext() : - * Create a decompressionContext object, which will track all decompression operations. - * Provides a pointer to a fully allocated and initialized LZ4F_decompressionContext object. - * Object can later be released using LZ4F_freeDecompressionContext(). - * @return : if != 0, there was an error during context creation. - */ -LZ4F_errorCode_t LZ4F_createDecompressionContext(LZ4F_dctx** LZ4F_decompressionContextPtr, unsigned versionNumber) -{ - LZ4F_dctx* const dctx = (LZ4F_dctx*)ALLOCATOR(sizeof(LZ4F_dctx)); - if (dctx==NULL) return err0r(LZ4F_ERROR_GENERIC); - - dctx->version = versionNumber; - *LZ4F_decompressionContextPtr = dctx; - return LZ4F_OK_NoError; -} - -LZ4F_errorCode_t LZ4F_freeDecompressionContext(LZ4F_dctx* dctx) -{ - LZ4F_errorCode_t result = LZ4F_OK_NoError; - if (dctx != NULL) { /* can accept NULL input, like free() */ - result = (LZ4F_errorCode_t)dctx->dStage; - FREEMEM(dctx->tmpIn); - FREEMEM(dctx->tmpOutBuffer); - FREEMEM(dctx); - } - return result; -} - - -/*==--- Streaming Decompression operations ---==*/ - -void LZ4F_resetDecompressionContext(LZ4F_dctx* dctx) -{ - dctx->dStage = dstage_getFrameHeader; - dctx->dict = NULL; - dctx->dictSize = 0; -} - - -/*! LZ4F_headerSize() : - * @return : size of frame header - * or an error code, which can be tested using LZ4F_isError() - */ -static size_t LZ4F_headerSize(const void* src, size_t srcSize) -{ - /* minimal srcSize to determine header size */ - if (srcSize < 5) return err0r(LZ4F_ERROR_frameHeader_incomplete); - - /* special case : skippable frames */ - if ((LZ4F_readLE32(src) & 0xFFFFFFF0U) == LZ4F_MAGIC_SKIPPABLE_START) return 8; - - /* control magic number */ - if (LZ4F_readLE32(src) != LZ4F_MAGICNUMBER) - return err0r(LZ4F_ERROR_frameType_unknown); - - /* Frame Header Size */ - { BYTE const FLG = ((const BYTE*)src)[4]; - U32 const contentSizeFlag = (FLG>>3) & _1BIT; - U32 const dictIDFlag = FLG & _1BIT; - return minFHSize + (contentSizeFlag*8) + (dictIDFlag*4); - } -} - - -/*! LZ4F_decodeHeader() : - * input : `src` points at the **beginning of the frame** - * output : set internal values of dctx, such as - * dctx->frameInfo and dctx->dStage. - * Also allocates internal buffers. - * @return : nb Bytes read from src (necessarily <= srcSize) - * or an error code (testable with LZ4F_isError()) - */ -static size_t LZ4F_decodeHeader(LZ4F_dctx* dctx, const void* src, size_t srcSize) -{ - unsigned blockMode, blockChecksumFlag, contentSizeFlag, contentChecksumFlag, dictIDFlag, blockSizeID; - size_t frameHeaderSize; - const BYTE* srcPtr = (const BYTE*)src; - - /* need to decode header to get frameInfo */ - if (srcSize < minFHSize) return err0r(LZ4F_ERROR_frameHeader_incomplete); /* minimal frame header size */ - memset(&(dctx->frameInfo), 0, sizeof(dctx->frameInfo)); - - /* special case : skippable frames */ - if ((LZ4F_readLE32(srcPtr) & 0xFFFFFFF0U) == LZ4F_MAGIC_SKIPPABLE_START) { - dctx->frameInfo.frameType = LZ4F_skippableFrame; - if (src == (void*)(dctx->header)) { - dctx->tmpInSize = srcSize; - dctx->tmpInTarget = 8; - dctx->dStage = dstage_storeSFrameSize; - return srcSize; - } else { - dctx->dStage = dstage_getSFrameSize; - return 4; - } - } - - /* control magic number */ - if (LZ4F_readLE32(srcPtr) != LZ4F_MAGICNUMBER) - return err0r(LZ4F_ERROR_frameType_unknown); - dctx->frameInfo.frameType = LZ4F_frame; - - /* Flags */ - { U32 const FLG = srcPtr[4]; - U32 const version = (FLG>>6) & _2BITS; - blockChecksumFlag = (FLG>>4) & _1BIT; - blockMode = (FLG>>5) & _1BIT; - contentSizeFlag = (FLG>>3) & _1BIT; - contentChecksumFlag = (FLG>>2) & _1BIT; - dictIDFlag = FLG & _1BIT; - /* validate */ - if (((FLG>>1)&_1BIT) != 0) return err0r(LZ4F_ERROR_reservedFlag_set); /* Reserved bit */ - if (version != 1) return err0r(LZ4F_ERROR_headerVersion_wrong); /* Version Number, only supported value */ - } - - /* Frame Header Size */ - frameHeaderSize = minFHSize + (contentSizeFlag*8) + (dictIDFlag*4); - - if (srcSize < frameHeaderSize) { - /* not enough input to fully decode frame header */ - if (srcPtr != dctx->header) - memcpy(dctx->header, srcPtr, srcSize); - dctx->tmpInSize = srcSize; - dctx->tmpInTarget = frameHeaderSize; - dctx->dStage = dstage_storeFrameHeader; - return srcSize; - } - - { U32 const BD = srcPtr[5]; - blockSizeID = (BD>>4) & _3BITS; - /* validate */ - if (((BD>>7)&_1BIT) != 0) return err0r(LZ4F_ERROR_reservedFlag_set); /* Reserved bit */ - if (blockSizeID < 4) return err0r(LZ4F_ERROR_maxBlockSize_invalid); /* 4-7 only supported values for the time being */ - if (((BD>>0)&_4BITS) != 0) return err0r(LZ4F_ERROR_reservedFlag_set); /* Reserved bits */ - } - - /* check header */ - { BYTE const HC = LZ4F_headerChecksum(srcPtr+4, frameHeaderSize-5); - if (HC != srcPtr[frameHeaderSize-1]) - return err0r(LZ4F_ERROR_headerChecksum_invalid); - } - - /* save */ - dctx->frameInfo.blockMode = (LZ4F_blockMode_t)blockMode; - dctx->frameInfo.blockChecksumFlag = (LZ4F_blockChecksum_t)blockChecksumFlag; - dctx->frameInfo.contentChecksumFlag = (LZ4F_contentChecksum_t)contentChecksumFlag; - dctx->frameInfo.blockSizeID = (LZ4F_blockSizeID_t)blockSizeID; - dctx->maxBlockSize = LZ4F_getBlockSize(blockSizeID); - if (contentSizeFlag) - dctx->frameRemainingSize = - dctx->frameInfo.contentSize = LZ4F_readLE64(srcPtr+6); - if (dictIDFlag) - dctx->frameInfo.dictID = LZ4F_readLE32(srcPtr + frameHeaderSize - 5); - - dctx->dStage = dstage_init; - - return frameHeaderSize; -} - - -/*! LZ4F_getFrameInfo() : - * This function extracts frame parameters (max blockSize, frame checksum, etc.). - * Usage is optional. Objective is to provide relevant information for allocation purposes. - * This function works in 2 situations : - * - At the beginning of a new frame, in which case it will decode this information from `srcBuffer`, and start the decoding process. - * Amount of input data provided must be large enough to successfully decode the frame header. - * A header size is variable, but is guaranteed to be <= LZ4F_HEADER_SIZE_MAX bytes. It's possible to provide more input data than this minimum. - * - After decoding has been started. In which case, no input is read, frame parameters are extracted from dctx. - * The number of bytes consumed from srcBuffer will be updated within *srcSizePtr (necessarily <= original value). - * Decompression must resume from (srcBuffer + *srcSizePtr). - * @return : an hint about how many srcSize bytes LZ4F_decompress() expects for next call, - * or an error code which can be tested using LZ4F_isError() - * note 1 : in case of error, dctx is not modified. Decoding operations can resume from where they stopped. - * note 2 : frame parameters are *copied into* an already allocated LZ4F_frameInfo_t structure. - */ -LZ4F_errorCode_t LZ4F_getFrameInfo(LZ4F_dctx* dctx, LZ4F_frameInfo_t* frameInfoPtr, - const void* srcBuffer, size_t* srcSizePtr) -{ - if (dctx->dStage > dstage_storeFrameHeader) { /* assumption : dstage_* header enum at beginning of range */ - /* frameInfo already decoded */ - size_t o=0, i=0; - *srcSizePtr = 0; - *frameInfoPtr = dctx->frameInfo; - /* returns : recommended nb of bytes for LZ4F_decompress() */ - return LZ4F_decompress(dctx, NULL, &o, NULL, &i, NULL); - } else { - if (dctx->dStage == dstage_storeFrameHeader) { - /* frame decoding already started, in the middle of header => automatic fail */ - *srcSizePtr = 0; - return err0r(LZ4F_ERROR_frameDecoding_alreadyStarted); - } else { - size_t decodeResult; - size_t const hSize = LZ4F_headerSize(srcBuffer, *srcSizePtr); - if (LZ4F_isError(hSize)) { *srcSizePtr=0; return hSize; } - if (*srcSizePtr < hSize) { - *srcSizePtr=0; - return err0r(LZ4F_ERROR_frameHeader_incomplete); - } - - decodeResult = LZ4F_decodeHeader(dctx, srcBuffer, hSize); - if (LZ4F_isError(decodeResult)) { - *srcSizePtr = 0; - } else { - *srcSizePtr = decodeResult; - decodeResult = BHSize; /* block header size */ - } - *frameInfoPtr = dctx->frameInfo; - return decodeResult; - } } -} - - -/* LZ4F_updateDict() : - * only used for LZ4F_blockLinked mode */ -static void LZ4F_updateDict(LZ4F_dctx* dctx, const BYTE* dstPtr, size_t dstSize, const BYTE* dstPtr0, unsigned withinTmp) -{ - if (dctx->dictSize==0) - dctx->dict = (const BYTE*)dstPtr; /* priority to dictionary continuity */ - - if (dctx->dict + dctx->dictSize == dstPtr) { /* dictionary continuity */ - dctx->dictSize += dstSize; - return; - } - - if (dstPtr - dstPtr0 + dstSize >= 64 KB) { /* dstBuffer large enough to become dictionary */ - dctx->dict = (const BYTE*)dstPtr0; - dctx->dictSize = dstPtr - dstPtr0 + dstSize; - return; - } - - if ((withinTmp) && (dctx->dict == dctx->tmpOutBuffer)) { - /* assumption : dctx->dict + dctx->dictSize == dctx->tmpOut + dctx->tmpOutStart */ - dctx->dictSize += dstSize; - return; - } - - if (withinTmp) { /* copy relevant dict portion in front of tmpOut within tmpOutBuffer */ - size_t const preserveSize = dctx->tmpOut - dctx->tmpOutBuffer; - size_t copySize = 64 KB - dctx->tmpOutSize; - const BYTE* const oldDictEnd = dctx->dict + dctx->dictSize - dctx->tmpOutStart; - if (dctx->tmpOutSize > 64 KB) copySize = 0; - if (copySize > preserveSize) copySize = preserveSize; - - memcpy(dctx->tmpOutBuffer + preserveSize - copySize, oldDictEnd - copySize, copySize); - - dctx->dict = dctx->tmpOutBuffer; - dctx->dictSize = preserveSize + dctx->tmpOutStart + dstSize; - return; - } - - if (dctx->dict == dctx->tmpOutBuffer) { /* copy dst into tmp to complete dict */ - if (dctx->dictSize + dstSize > dctx->maxBufferSize) { /* tmp buffer not large enough */ - size_t const preserveSize = 64 KB - dstSize; /* note : dstSize < 64 KB */ - memcpy(dctx->tmpOutBuffer, dctx->dict + dctx->dictSize - preserveSize, preserveSize); - dctx->dictSize = preserveSize; - } - memcpy(dctx->tmpOutBuffer + dctx->dictSize, dstPtr, dstSize); - dctx->dictSize += dstSize; - return; - } - - /* join dict & dest into tmp */ - { size_t preserveSize = 64 KB - dstSize; /* note : dstSize < 64 KB */ - if (preserveSize > dctx->dictSize) preserveSize = dctx->dictSize; - memcpy(dctx->tmpOutBuffer, dctx->dict + dctx->dictSize - preserveSize, preserveSize); - memcpy(dctx->tmpOutBuffer + preserveSize, dstPtr, dstSize); - dctx->dict = dctx->tmpOutBuffer; - dctx->dictSize = preserveSize + dstSize; - } -} - - - -/*! LZ4F_decompress() : - * Call this function repetitively to regenerate compressed data in srcBuffer. - * The function will attempt to decode up to *srcSizePtr bytes from srcBuffer - * into dstBuffer of capacity *dstSizePtr. - * - * The number of bytes regenerated into dstBuffer will be provided within *dstSizePtr (necessarily <= original value). - * - * The number of bytes effectively read from srcBuffer will be provided within *srcSizePtr (necessarily <= original value). - * If number of bytes read is < number of bytes provided, then decompression operation is not complete. - * Remaining data will have to be presented again in a subsequent invocation. - * - * The function result is an hint of the better srcSize to use for next call to LZ4F_decompress. - * Schematically, it's the size of the current (or remaining) compressed block + header of next block. - * Respecting the hint provides a small boost to performance, since it allows less buffer shuffling. - * Note that this is just a hint, and it's always possible to any srcSize value. - * When a frame is fully decoded, @return will be 0. - * If decompression failed, @return is an error code which can be tested using LZ4F_isError(). - */ -size_t LZ4F_decompress(LZ4F_dctx* dctx, - void* dstBuffer, size_t* dstSizePtr, - const void* srcBuffer, size_t* srcSizePtr, - const LZ4F_decompressOptions_t* decompressOptionsPtr) -{ - LZ4F_decompressOptions_t optionsNull; - const BYTE* const srcStart = (const BYTE*)srcBuffer; - const BYTE* const srcEnd = srcStart + *srcSizePtr; - const BYTE* srcPtr = srcStart; - BYTE* const dstStart = (BYTE*)dstBuffer; - BYTE* const dstEnd = dstStart + *dstSizePtr; - BYTE* dstPtr = dstStart; - const BYTE* selectedIn = NULL; - unsigned doAnotherStage = 1; - size_t nextSrcSizeHint = 1; - - - memset(&optionsNull, 0, sizeof(optionsNull)); - if (decompressOptionsPtr==NULL) decompressOptionsPtr = &optionsNull; - *srcSizePtr = 0; - *dstSizePtr = 0; - - /* behaves as a state machine */ - - while (doAnotherStage) { - - switch(dctx->dStage) - { - - case dstage_getFrameHeader: - if ((size_t)(srcEnd-srcPtr) >= maxFHSize) { /* enough to decode - shortcut */ - size_t const hSize = LZ4F_decodeHeader(dctx, srcPtr, srcEnd-srcPtr); /* will update dStage appropriately */ - if (LZ4F_isError(hSize)) return hSize; - srcPtr += hSize; - break; - } - dctx->tmpInSize = 0; - if (srcEnd-srcPtr == 0) return minFHSize; /* 0-size input */ - dctx->tmpInTarget = minFHSize; /* minimum to attempt decode */ - dctx->dStage = dstage_storeFrameHeader; - /* fall-through */ - - case dstage_storeFrameHeader: - { size_t const sizeToCopy = MIN(dctx->tmpInTarget - dctx->tmpInSize, (size_t)(srcEnd - srcPtr)); - memcpy(dctx->header + dctx->tmpInSize, srcPtr, sizeToCopy); - dctx->tmpInSize += sizeToCopy; - srcPtr += sizeToCopy; - if (dctx->tmpInSize < dctx->tmpInTarget) { - nextSrcSizeHint = (dctx->tmpInTarget - dctx->tmpInSize) + BHSize; /* rest of header + nextBlockHeader */ - doAnotherStage = 0; /* not enough src data, ask for some more */ - break; - } - { size_t const hSize = LZ4F_decodeHeader(dctx, dctx->header, dctx->tmpInTarget); /* will update dStage appropriately */ - if (LZ4F_isError(hSize)) return hSize; - } - break; - } - - case dstage_init: - if (dctx->frameInfo.contentChecksumFlag) XXH32_reset(&(dctx->xxh), 0); - /* internal buffers allocation */ - { size_t const bufferNeeded = dctx->maxBlockSize + ((dctx->frameInfo.blockMode==LZ4F_blockLinked) * 128 KB) + 4 /* block checksum */; - if (bufferNeeded > dctx->maxBufferSize) { /* tmp buffers too small */ - dctx->maxBufferSize = 0; /* ensure allocation will be re-attempted on next entry*/ - FREEMEM(dctx->tmpIn); - dctx->tmpIn = (BYTE*)ALLOCATOR(dctx->maxBlockSize); - if (dctx->tmpIn == NULL) return err0r(LZ4F_ERROR_allocation_failed); - FREEMEM(dctx->tmpOutBuffer); - dctx->tmpOutBuffer= (BYTE*)ALLOCATOR(bufferNeeded); - if (dctx->tmpOutBuffer== NULL) return err0r(LZ4F_ERROR_allocation_failed); - dctx->maxBufferSize = bufferNeeded; - } } - dctx->tmpInSize = 0; - dctx->tmpInTarget = 0; - dctx->tmpOut = dctx->tmpOutBuffer; - dctx->tmpOutStart = 0; - dctx->tmpOutSize = 0; - - dctx->dStage = dstage_getBlockHeader; - /* fall-through */ - - case dstage_getBlockHeader: - if ((size_t)(srcEnd - srcPtr) >= BHSize) { - selectedIn = srcPtr; - srcPtr += BHSize; - } else { - /* not enough input to read cBlockSize field */ - dctx->tmpInSize = 0; - dctx->dStage = dstage_storeBlockHeader; - } - - if (dctx->dStage == dstage_storeBlockHeader) /* can be skipped */ - case dstage_storeBlockHeader: - { size_t sizeToCopy = BHSize - dctx->tmpInSize; - if (sizeToCopy > (size_t)(srcEnd - srcPtr)) sizeToCopy = srcEnd - srcPtr; - memcpy(dctx->tmpIn + dctx->tmpInSize, srcPtr, sizeToCopy); - srcPtr += sizeToCopy; - dctx->tmpInSize += sizeToCopy; - if (dctx->tmpInSize < BHSize) { /* not enough input for cBlockSize */ - nextSrcSizeHint = BHSize - dctx->tmpInSize; - doAnotherStage = 0; - break; - } - selectedIn = dctx->tmpIn; - } - - /* decode block header */ - { size_t const nextCBlockSize = LZ4F_readLE32(selectedIn) & 0x7FFFFFFFU; - size_t const crcSize = dctx->frameInfo.blockChecksumFlag * 4; - if (nextCBlockSize==0) { /* frameEnd signal, no more block */ - dctx->dStage = dstage_getSuffix; - break; - } - if (nextCBlockSize > dctx->maxBlockSize) - return err0r(LZ4F_ERROR_maxBlockSize_invalid); - if (LZ4F_readLE32(selectedIn) & LZ4F_BLOCKUNCOMPRESSED_FLAG) { - /* next block is uncompressed */ - dctx->tmpInTarget = nextCBlockSize; - if (dctx->frameInfo.blockChecksumFlag) { - XXH32_reset(&dctx->blockChecksum, 0); - } - dctx->dStage = dstage_copyDirect; - break; - } - /* next block is a compressed block */ - dctx->tmpInTarget = nextCBlockSize + crcSize; - dctx->dStage = dstage_getCBlock; - if (dstPtr==dstEnd) { - nextSrcSizeHint = nextCBlockSize + crcSize + BHSize; - doAnotherStage = 0; - } - break; - } - - case dstage_copyDirect: /* uncompressed block */ - { size_t const minBuffSize = MIN((size_t)(srcEnd-srcPtr), (size_t)(dstEnd-dstPtr)); - size_t const sizeToCopy = MIN(dctx->tmpInTarget, minBuffSize); - memcpy(dstPtr, srcPtr, sizeToCopy); - if (dctx->frameInfo.blockChecksumFlag) { - XXH32_update(&dctx->blockChecksum, srcPtr, sizeToCopy); - } - if (dctx->frameInfo.contentChecksumFlag) - XXH32_update(&dctx->xxh, srcPtr, sizeToCopy); - if (dctx->frameInfo.contentSize) - dctx->frameRemainingSize -= sizeToCopy; - - /* history management (linked blocks only)*/ - if (dctx->frameInfo.blockMode == LZ4F_blockLinked) - LZ4F_updateDict(dctx, dstPtr, sizeToCopy, dstStart, 0); - - srcPtr += sizeToCopy; - dstPtr += sizeToCopy; - if (sizeToCopy == dctx->tmpInTarget) { /* all done */ - if (dctx->frameInfo.blockChecksumFlag) { - dctx->tmpInSize = 0; - dctx->dStage = dstage_getBlockChecksum; - } else - dctx->dStage = dstage_getBlockHeader; /* new block */ - break; - } - dctx->tmpInTarget -= sizeToCopy; /* need to copy more */ - nextSrcSizeHint = dctx->tmpInTarget + - + dctx->frameInfo.contentChecksumFlag * 4 /* block checksum */ - + BHSize /* next header size */; - doAnotherStage = 0; - break; - } - - /* check block checksum for recently transferred uncompressed block */ - case dstage_getBlockChecksum: - { const void* crcSrc; - if ((srcEnd-srcPtr >= 4) && (dctx->tmpInSize==0)) { - crcSrc = srcPtr; - srcPtr += 4; - } else { - size_t const stillToCopy = 4 - dctx->tmpInSize; - size_t const sizeToCopy = MIN(stillToCopy, (size_t)(srcEnd-srcPtr)); - memcpy(dctx->header + dctx->tmpInSize, srcPtr, sizeToCopy); - dctx->tmpInSize += sizeToCopy; - srcPtr += sizeToCopy; - if (dctx->tmpInSize < 4) { /* all input consumed */ - doAnotherStage = 0; - break; - } - crcSrc = dctx->header; - } - { U32 const readCRC = LZ4F_readLE32(crcSrc); - U32 const calcCRC = XXH32_digest(&dctx->blockChecksum); - if (readCRC != calcCRC) - return err0r(LZ4F_ERROR_blockChecksum_invalid); - } - } - dctx->dStage = dstage_getBlockHeader; /* new block */ - break; - - case dstage_getCBlock: /* entry from dstage_decodeCBlockSize */ - if ((size_t)(srcEnd-srcPtr) < dctx->tmpInTarget) { - dctx->tmpInSize = 0; - dctx->dStage = dstage_storeCBlock; - break; - } - /* input large enough to read full block directly */ - selectedIn = srcPtr; - srcPtr += dctx->tmpInTarget; - dctx->dStage = dstage_decodeCBlock; - break; - - case dstage_storeCBlock: - { size_t const sizeToCopy = MIN(dctx->tmpInTarget - dctx->tmpInSize, (size_t)(srcEnd-srcPtr)); - memcpy(dctx->tmpIn + dctx->tmpInSize, srcPtr, sizeToCopy); - dctx->tmpInSize += sizeToCopy; - srcPtr += sizeToCopy; - if (dctx->tmpInSize < dctx->tmpInTarget) { /* need more input */ - nextSrcSizeHint = (dctx->tmpInTarget - dctx->tmpInSize) + BHSize; - doAnotherStage=0; - break; - } - selectedIn = dctx->tmpIn; - dctx->dStage = dstage_decodeCBlock; - } - /* fall-through */ - - /* At this stage, input is large enough to decode a block */ - case dstage_decodeCBlock: - if (dctx->frameInfo.blockChecksumFlag) { - dctx->tmpInTarget -= 4; - { U32 const readBlockCrc = LZ4F_readLE32(selectedIn + dctx->tmpInTarget); - U32 const calcBlockCrc = XXH32(selectedIn, dctx->tmpInTarget, 0); - if (readBlockCrc != calcBlockCrc) - return err0r(LZ4F_ERROR_blockChecksum_invalid); - } } - if ((size_t)(dstEnd-dstPtr) < dctx->maxBlockSize) /* not enough place into dst : decode into tmpOut */ - dctx->dStage = dstage_decodeCBlock_intoTmp; - else - dctx->dStage = dstage_decodeCBlock_intoDst; - break; - - case dstage_decodeCBlock_intoDst: - { int const decodedSize = LZ4_decompress_safe_usingDict( - (const char*)selectedIn, (char*)dstPtr, - (int)dctx->tmpInTarget, (int)dctx->maxBlockSize, - (const char*)dctx->dict, (int)dctx->dictSize); - if (decodedSize < 0) return err0r(LZ4F_ERROR_GENERIC); /* decompression failed */ - if (dctx->frameInfo.contentChecksumFlag) - XXH32_update(&(dctx->xxh), dstPtr, decodedSize); - if (dctx->frameInfo.contentSize) - dctx->frameRemainingSize -= decodedSize; - - /* dictionary management */ - if (dctx->frameInfo.blockMode==LZ4F_blockLinked) - LZ4F_updateDict(dctx, dstPtr, decodedSize, dstStart, 0); - - dstPtr += decodedSize; - dctx->dStage = dstage_getBlockHeader; - break; - } - - case dstage_decodeCBlock_intoTmp: - /* not enough place into dst : decode into tmpOut */ - - /* ensure enough place for tmpOut */ - if (dctx->frameInfo.blockMode == LZ4F_blockLinked) { - if (dctx->dict == dctx->tmpOutBuffer) { - if (dctx->dictSize > 128 KB) { - memcpy(dctx->tmpOutBuffer, dctx->dict + dctx->dictSize - 64 KB, 64 KB); - dctx->dictSize = 64 KB; - } - dctx->tmpOut = dctx->tmpOutBuffer + dctx->dictSize; - } else { /* dict not within tmp */ - size_t const reservedDictSpace = MIN(dctx->dictSize, 64 KB); - dctx->tmpOut = dctx->tmpOutBuffer + reservedDictSpace; - } - } - - /* Decode block */ - { int const decodedSize = LZ4_decompress_safe_usingDict( - (const char*)selectedIn, (char*)dctx->tmpOut, - (int)dctx->tmpInTarget, (int)dctx->maxBlockSize, - (const char*)dctx->dict, (int)dctx->dictSize); - if (decodedSize < 0) /* decompression failed */ - return err0r(LZ4F_ERROR_decompressionFailed); - if (dctx->frameInfo.contentChecksumFlag) - XXH32_update(&(dctx->xxh), dctx->tmpOut, decodedSize); - if (dctx->frameInfo.contentSize) - dctx->frameRemainingSize -= decodedSize; - dctx->tmpOutSize = decodedSize; - dctx->tmpOutStart = 0; - dctx->dStage = dstage_flushOut; - } - /* fall-through */ - - case dstage_flushOut: /* flush decoded data from tmpOut to dstBuffer */ - { size_t const sizeToCopy = MIN(dctx->tmpOutSize - dctx->tmpOutStart, (size_t)(dstEnd-dstPtr)); - memcpy(dstPtr, dctx->tmpOut + dctx->tmpOutStart, sizeToCopy); - - /* dictionary management */ - if (dctx->frameInfo.blockMode==LZ4F_blockLinked) - LZ4F_updateDict(dctx, dstPtr, sizeToCopy, dstStart, 1); - - dctx->tmpOutStart += sizeToCopy; - dstPtr += sizeToCopy; - - if (dctx->tmpOutStart == dctx->tmpOutSize) { /* all flushed */ - dctx->dStage = dstage_getBlockHeader; /* get next block */ - break; - } - nextSrcSizeHint = BHSize; - doAnotherStage = 0; /* still some data to flush */ - break; - } - - case dstage_getSuffix: - { size_t const suffixSize = dctx->frameInfo.contentChecksumFlag * 4; - if (dctx->frameRemainingSize) - return err0r(LZ4F_ERROR_frameSize_wrong); /* incorrect frame size decoded */ - if (suffixSize == 0) { /* frame completed */ - nextSrcSizeHint = 0; - LZ4F_resetDecompressionContext(dctx); - doAnotherStage = 0; - break; - } - if ((srcEnd - srcPtr) < 4) { /* not enough size for entire CRC */ - dctx->tmpInSize = 0; - dctx->dStage = dstage_storeSuffix; - } else { - selectedIn = srcPtr; - srcPtr += 4; - } - } - - if (dctx->dStage == dstage_storeSuffix) /* can be skipped */ - case dstage_storeSuffix: - { - size_t sizeToCopy = 4 - dctx->tmpInSize; - if (sizeToCopy > (size_t)(srcEnd - srcPtr)) sizeToCopy = srcEnd - srcPtr; - memcpy(dctx->tmpIn + dctx->tmpInSize, srcPtr, sizeToCopy); - srcPtr += sizeToCopy; - dctx->tmpInSize += sizeToCopy; - if (dctx->tmpInSize < 4) { /* not enough input to read complete suffix */ - nextSrcSizeHint = 4 - dctx->tmpInSize; - doAnotherStage=0; - break; - } - selectedIn = dctx->tmpIn; - } - - /* case dstage_checkSuffix: */ /* no direct call, avoid scan-build warning */ - { U32 const readCRC = LZ4F_readLE32(selectedIn); - U32 const resultCRC = XXH32_digest(&(dctx->xxh)); - if (readCRC != resultCRC) - return err0r(LZ4F_ERROR_contentChecksum_invalid); - nextSrcSizeHint = 0; - LZ4F_resetDecompressionContext(dctx); - doAnotherStage = 0; - break; - } - - case dstage_getSFrameSize: - if ((srcEnd - srcPtr) >= 4) { - selectedIn = srcPtr; - srcPtr += 4; - } else { - /* not enough input to read cBlockSize field */ - dctx->tmpInSize = 4; - dctx->tmpInTarget = 8; - dctx->dStage = dstage_storeSFrameSize; - } - - if (dctx->dStage == dstage_storeSFrameSize) - case dstage_storeSFrameSize: - { - size_t const sizeToCopy = MIN(dctx->tmpInTarget - dctx->tmpInSize, - (size_t)(srcEnd - srcPtr) ); - memcpy(dctx->header + dctx->tmpInSize, srcPtr, sizeToCopy); - srcPtr += sizeToCopy; - dctx->tmpInSize += sizeToCopy; - if (dctx->tmpInSize < dctx->tmpInTarget) { - /* not enough input to get full sBlockSize; wait for more */ - nextSrcSizeHint = dctx->tmpInTarget - dctx->tmpInSize; - doAnotherStage = 0; - break; - } - selectedIn = dctx->header + 4; - } - - /* case dstage_decodeSFrameSize: */ /* no direct access */ - { size_t const SFrameSize = LZ4F_readLE32(selectedIn); - dctx->frameInfo.contentSize = SFrameSize; - dctx->tmpInTarget = SFrameSize; - dctx->dStage = dstage_skipSkippable; - break; - } - - case dstage_skipSkippable: - { size_t const skipSize = MIN(dctx->tmpInTarget, (size_t)(srcEnd-srcPtr)); - srcPtr += skipSize; - dctx->tmpInTarget -= skipSize; - doAnotherStage = 0; - nextSrcSizeHint = dctx->tmpInTarget; - if (nextSrcSizeHint) break; /* still more to skip */ - LZ4F_resetDecompressionContext(dctx); - break; - } - } - } - - /* preserve history within tmp if necessary */ - if ( (dctx->frameInfo.blockMode==LZ4F_blockLinked) - && (dctx->dict != dctx->tmpOutBuffer) - && (dctx->dStage != dstage_getFrameHeader) - && (!decompressOptionsPtr->stableDst) - && ((unsigned)(dctx->dStage-1) < (unsigned)(dstage_getSuffix-1)) ) - { - if (dctx->dStage == dstage_flushOut) { - size_t preserveSize = dctx->tmpOut - dctx->tmpOutBuffer; - size_t copySize = 64 KB - dctx->tmpOutSize; - const BYTE* oldDictEnd = dctx->dict + dctx->dictSize - dctx->tmpOutStart; - if (dctx->tmpOutSize > 64 KB) copySize = 0; - if (copySize > preserveSize) copySize = preserveSize; - - memcpy(dctx->tmpOutBuffer + preserveSize - copySize, oldDictEnd - copySize, copySize); - - dctx->dict = dctx->tmpOutBuffer; - dctx->dictSize = preserveSize + dctx->tmpOutStart; - } else { - size_t newDictSize = dctx->dictSize; - const BYTE* oldDictEnd = dctx->dict + dctx->dictSize; - if ((newDictSize) > 64 KB) newDictSize = 64 KB; - - memcpy(dctx->tmpOutBuffer, oldDictEnd - newDictSize, newDictSize); - - dctx->dict = dctx->tmpOutBuffer; - dctx->dictSize = newDictSize; - dctx->tmpOut = dctx->tmpOutBuffer + newDictSize; - } - } - - *srcSizePtr = (srcPtr - srcStart); - *dstSizePtr = (dstPtr - dstStart); - return nextSrcSizeHint; -} - -/*! LZ4F_decompress_usingDict() : - * Same as LZ4F_decompress(), using a predefined dictionary. - * Dictionary is used "in place", without any preprocessing. - * It must remain accessible throughout the entire frame decoding. - */ -size_t LZ4F_decompress_usingDict(LZ4F_dctx* dctx, - void* dstBuffer, size_t* dstSizePtr, - const void* srcBuffer, size_t* srcSizePtr, - const void* dict, size_t dictSize, - const LZ4F_decompressOptions_t* decompressOptionsPtr) -{ - if (dctx->dStage <= dstage_init) { - dctx->dict = (const BYTE*)dict; - dctx->dictSize = dictSize; - } - return LZ4F_decompress(dctx, dstBuffer, dstSizePtr, - srcBuffer, srcSizePtr, - decompressOptionsPtr); -} diff --git a/src/lz4/lib/lz4frame.h b/src/lz4/lib/lz4frame.h deleted file mode 100644 index 88a6513c42..0000000000 --- a/src/lz4/lib/lz4frame.h +++ /dev/null @@ -1,391 +0,0 @@ -/* - LZ4 auto-framing library - Header File - Copyright (C) 2011-2017, Yann Collet. - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - LZ4 source repository : https://github.com/lz4/lz4 - - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c -*/ - -/* LZ4F is a stand-alone API to create LZ4-compressed frames - * conformant with specification v1.5.1. - * It also offers streaming capabilities. - * lz4.h is not required when using lz4frame.h. - * */ - -#ifndef LZ4F_H_09782039843 -#define LZ4F_H_09782039843 - -#if defined (__cplusplus) -extern "C" { -#endif - -/* --- Dependency --- */ -#include /* size_t */ - - -/** - Introduction - - lz4frame.h implements LZ4 frame specification (doc/lz4_Frame_format.md). - lz4frame.h provides frame compression functions that take care - of encoding standard metadata alongside LZ4-compressed blocks. -*/ - -/*-*************************************************************** - * Compiler specifics - *****************************************************************/ -/* LZ4_DLL_EXPORT : - * Enable exporting of functions when building a Windows DLL - * LZ4FLIB_API : - * Control library symbols visibility. - */ -#if defined(LZ4_DLL_EXPORT) && (LZ4_DLL_EXPORT==1) -# define LZ4FLIB_API __declspec(dllexport) -#elif defined(LZ4_DLL_IMPORT) && (LZ4_DLL_IMPORT==1) -# define LZ4FLIB_API __declspec(dllimport) -#elif defined(__GNUC__) && (__GNUC__ >= 4) -# define LZ4FLIB_API __attribute__ ((__visibility__ ("default"))) -#else -# define LZ4FLIB_API -#endif - -#ifdef LZ4F_DISABLE_DEPRECATE_WARNINGS -# define LZ4F_DEPRECATE(x) x -#else -# if defined(_MSC_VER) -# define LZ4F_DEPRECATE(x) x /* __declspec(deprecated) x - only works with C++ */ -# elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 6)) -# define LZ4F_DEPRECATE(x) x __attribute__((deprecated)) -# else -# define LZ4F_DEPRECATE(x) x /* no deprecation warning for this compiler */ -# endif -#endif - - -/*-************************************ - * Error management - **************************************/ -typedef size_t LZ4F_errorCode_t; - -LZ4FLIB_API unsigned LZ4F_isError(LZ4F_errorCode_t code); /**< tells if a `LZ4F_errorCode_t` function result is an error code */ -LZ4FLIB_API const char* LZ4F_getErrorName(LZ4F_errorCode_t code); /**< return error code string; useful for debugging */ - - -/*-************************************ - * Frame compression types - **************************************/ -/* #define LZ4F_ENABLE_OBSOLETE_ENUMS // uncomment to enable obsolete enums */ -#ifdef LZ4F_ENABLE_OBSOLETE_ENUMS -# define LZ4F_OBSOLETE_ENUM(x) , LZ4F_DEPRECATE(x) = LZ4F_##x -#else -# define LZ4F_OBSOLETE_ENUM(x) -#endif - -/* The larger the block size, the (slightly) better the compression ratio, - * though there are diminishing returns. - * Larger blocks also increase memory usage on both compression and decompression sides. */ -typedef enum { - LZ4F_default=0, - LZ4F_max64KB=4, - LZ4F_max256KB=5, - LZ4F_max1MB=6, - LZ4F_max4MB=7 - LZ4F_OBSOLETE_ENUM(max64KB) - LZ4F_OBSOLETE_ENUM(max256KB) - LZ4F_OBSOLETE_ENUM(max1MB) - LZ4F_OBSOLETE_ENUM(max4MB) -} LZ4F_blockSizeID_t; - -/* Linked blocks sharply reduce inefficiencies when using small blocks, - * they compress better. - * However, some LZ4 decoders are only compatible with independent blocks */ -typedef enum { - LZ4F_blockLinked=0, - LZ4F_blockIndependent - LZ4F_OBSOLETE_ENUM(blockLinked) - LZ4F_OBSOLETE_ENUM(blockIndependent) -} LZ4F_blockMode_t; - -typedef enum { - LZ4F_noContentChecksum=0, - LZ4F_contentChecksumEnabled - LZ4F_OBSOLETE_ENUM(noContentChecksum) - LZ4F_OBSOLETE_ENUM(contentChecksumEnabled) -} LZ4F_contentChecksum_t; - -typedef enum { - LZ4F_noBlockChecksum=0, - LZ4F_blockChecksumEnabled -} LZ4F_blockChecksum_t; - -typedef enum { - LZ4F_frame=0, - LZ4F_skippableFrame - LZ4F_OBSOLETE_ENUM(skippableFrame) -} LZ4F_frameType_t; - -#ifdef LZ4F_ENABLE_OBSOLETE_ENUMS -typedef LZ4F_blockSizeID_t blockSizeID_t; -typedef LZ4F_blockMode_t blockMode_t; -typedef LZ4F_frameType_t frameType_t; -typedef LZ4F_contentChecksum_t contentChecksum_t; -#endif - -/*! LZ4F_frameInfo_t : - * makes it possible to set or read frame parameters. - * It's not required to set all fields, as long as the structure was initially memset() to zero. - * For all fields, 0 sets it to default value */ -typedef struct { - LZ4F_blockSizeID_t blockSizeID; /* max64KB, max256KB, max1MB, max4MB ; 0 == default */ - LZ4F_blockMode_t blockMode; /* LZ4F_blockLinked, LZ4F_blockIndependent ; 0 == default */ - LZ4F_contentChecksum_t contentChecksumFlag; /* if enabled, frame is terminated with a 32-bits checksum of decompressed data ; 0 == disabled (default) */ - LZ4F_frameType_t frameType; /* read-only field : LZ4F_frame or LZ4F_skippableFrame */ - unsigned long long contentSize; /* Size of uncompressed content ; 0 == unknown */ - unsigned dictID; /* Dictionary ID, sent by the compressor to help decoder select the correct dictionary; 0 == no dictID provided */ - LZ4F_blockChecksum_t blockChecksumFlag; /* if enabled, each block is followed by a checksum of block's compressed data ; 0 == disabled (default) */ -} LZ4F_frameInfo_t; - -/*! LZ4F_preferences_t : - * makes it possible to supply detailed compression parameters to the stream interface. - * It's not required to set all fields, as long as the structure was initially memset() to zero. - * All reserved fields must be set to zero. */ -typedef struct { - LZ4F_frameInfo_t frameInfo; - int compressionLevel; /* 0 == default (fast mode); values above LZ4HC_CLEVEL_MAX count as LZ4HC_CLEVEL_MAX; values below 0 trigger "fast acceleration", proportional to value */ - unsigned autoFlush; /* 1 == always flush, to reduce usage of internal buffers */ - unsigned reserved[4]; /* must be zero for forward compatibility */ -} LZ4F_preferences_t; - -LZ4FLIB_API int LZ4F_compressionLevel_max(void); - - -/*-********************************* -* Simple compression function -***********************************/ -/*! LZ4F_compressFrameBound() : - * Returns the maximum possible size of a frame compressed with LZ4F_compressFrame() given srcSize content and preferences. - * Note : this result is only usable with LZ4F_compressFrame(), not with multi-segments compression. - */ -LZ4FLIB_API size_t LZ4F_compressFrameBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr); - -/*! LZ4F_compressFrame() : - * Compress an entire srcBuffer into a valid LZ4 frame. - * dstCapacity MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr). - * The LZ4F_preferences_t structure is optional : you can provide NULL as argument. All preferences will be set to default. - * @return : number of bytes written into dstBuffer. - * or an error code if it fails (can be tested using LZ4F_isError()) - */ -LZ4FLIB_API size_t LZ4F_compressFrame(void* dstBuffer, size_t dstCapacity, - const void* srcBuffer, size_t srcSize, - const LZ4F_preferences_t* preferencesPtr); - - -/*-*********************************** -* Advanced compression functions -*************************************/ -typedef struct LZ4F_cctx_s LZ4F_cctx; /* incomplete type */ -typedef LZ4F_cctx* LZ4F_compressionContext_t; /* for compatibility with previous API version */ - -typedef struct { - unsigned stableSrc; /* 1 == src content will remain present on future calls to LZ4F_compress(); skip copying src content within tmp buffer */ - unsigned reserved[3]; -} LZ4F_compressOptions_t; - -/*--- Resource Management ---*/ - -#define LZ4F_VERSION 100 -LZ4FLIB_API unsigned LZ4F_getVersion(void); -/*! LZ4F_createCompressionContext() : - * The first thing to do is to create a compressionContext object, which will be used in all compression operations. - * This is achieved using LZ4F_createCompressionContext(), which takes as argument a version. - * The version provided MUST be LZ4F_VERSION. It is intended to track potential version mismatch, notably when using DLL. - * The function will provide a pointer to a fully allocated LZ4F_cctx object. - * If @return != zero, there was an error during context creation. - * Object can release its memory using LZ4F_freeCompressionContext(); - */ -LZ4FLIB_API LZ4F_errorCode_t LZ4F_createCompressionContext(LZ4F_cctx** cctxPtr, unsigned version); -LZ4FLIB_API LZ4F_errorCode_t LZ4F_freeCompressionContext(LZ4F_cctx* cctx); - - -/*---- Compression ----*/ - -#define LZ4F_HEADER_SIZE_MAX 19 -/*! LZ4F_compressBegin() : - * will write the frame header into dstBuffer. - * dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes. - * `prefsPtr` is optional : you can provide NULL as argument, all preferences will then be set to default. - * @return : number of bytes written into dstBuffer for the header - * or an error code (which can be tested using LZ4F_isError()) - */ -LZ4FLIB_API size_t LZ4F_compressBegin(LZ4F_cctx* cctx, - void* dstBuffer, size_t dstCapacity, - const LZ4F_preferences_t* prefsPtr); - -/*! LZ4F_compressBound() : - * Provides dstCapacity given a srcSize to guarantee operation success in worst case situations. - * prefsPtr is optional : you can provide NULL as argument, preferences will be set to cover worst case scenario. - * Result is always the same for a srcSize and prefsPtr, so it can be trusted to size reusable buffers. - * When srcSize==0, LZ4F_compressBound() provides an upper bound for LZ4F_flush() and LZ4F_compressEnd() operations. - */ -LZ4FLIB_API size_t LZ4F_compressBound(size_t srcSize, const LZ4F_preferences_t* prefsPtr); - -/*! LZ4F_compressUpdate() : - * LZ4F_compressUpdate() can be called repetitively to compress as much data as necessary. - * An important rule is that dstCapacity MUST be large enough to ensure operation success even in worst case situations. - * This value is provided by LZ4F_compressBound(). - * If this condition is not respected, LZ4F_compress() will fail (result is an errorCode). - * LZ4F_compressUpdate() doesn't guarantee error recovery. When an error occurs, compression context must be freed or resized. - * `cOptPtr` is optional : NULL can be provided, in which case all options are set to default. - * @return : number of bytes written into `dstBuffer` (it can be zero, meaning input data was just buffered). - * or an error code if it fails (which can be tested using LZ4F_isError()) - */ -LZ4FLIB_API size_t LZ4F_compressUpdate(LZ4F_cctx* cctx, void* dstBuffer, size_t dstCapacity, const void* srcBuffer, size_t srcSize, const LZ4F_compressOptions_t* cOptPtr); - -/*! LZ4F_flush() : - * When data must be generated and sent immediately, without waiting for a block to be completely filled, - * it's possible to call LZ4_flush(). It will immediately compress any data buffered within cctx. - * `dstCapacity` must be large enough to ensure the operation will be successful. - * `cOptPtr` is optional : it's possible to provide NULL, all options will be set to default. - * @return : number of bytes written into dstBuffer (it can be zero, which means there was no data stored within cctx) - * or an error code if it fails (which can be tested using LZ4F_isError()) - */ -LZ4FLIB_API size_t LZ4F_flush(LZ4F_cctx* cctx, void* dstBuffer, size_t dstCapacity, const LZ4F_compressOptions_t* cOptPtr); - -/*! LZ4F_compressEnd() : - * To properly finish an LZ4 frame, invoke LZ4F_compressEnd(). - * It will flush whatever data remained within `cctx` (like LZ4_flush()) - * and properly finalize the frame, with an endMark and a checksum. - * `cOptPtr` is optional : NULL can be provided, in which case all options will be set to default. - * @return : number of bytes written into dstBuffer (necessarily >= 4 (endMark), or 8 if optional frame checksum is enabled) - * or an error code if it fails (which can be tested using LZ4F_isError()) - * A successful call to LZ4F_compressEnd() makes `cctx` available again for another compression task. - */ -LZ4FLIB_API size_t LZ4F_compressEnd(LZ4F_cctx* cctx, void* dstBuffer, size_t dstCapacity, const LZ4F_compressOptions_t* cOptPtr); - - -/*-********************************* -* Decompression functions -***********************************/ -typedef struct LZ4F_dctx_s LZ4F_dctx; /* incomplete type */ -typedef LZ4F_dctx* LZ4F_decompressionContext_t; /* compatibility with previous API versions */ - -typedef struct { - unsigned stableDst; /* pledge that at least 64KB+64Bytes of previously decompressed data remain unmodifed where it was decoded. This optimization skips storage operations in tmp buffers */ - unsigned reserved[3]; /* must be set to zero for forward compatibility */ -} LZ4F_decompressOptions_t; - - -/* Resource management */ - -/*!LZ4F_createDecompressionContext() : - * Create an LZ4F_dctx object, to track all decompression operations. - * The version provided MUST be LZ4F_VERSION. - * The function provides a pointer to an allocated and initialized LZ4F_dctx object. - * The result is an errorCode, which can be tested using LZ4F_isError(). - * dctx memory can be released using LZ4F_freeDecompressionContext(); - * The result of LZ4F_freeDecompressionContext() is indicative of the current state of decompressionContext when being released. - * That is, it should be == 0 if decompression has been completed fully and correctly. - */ -LZ4FLIB_API LZ4F_errorCode_t LZ4F_createDecompressionContext(LZ4F_dctx** dctxPtr, unsigned version); -LZ4FLIB_API LZ4F_errorCode_t LZ4F_freeDecompressionContext(LZ4F_dctx* dctx); - - -/*-*********************************** -* Streaming decompression functions -*************************************/ - -/*! LZ4F_getFrameInfo() : - * This function extracts frame parameters (max blockSize, dictID, etc.). - * Its usage is optional. - * Extracted information is typically useful for allocation and dictionary. - * This function works in 2 situations : - * - At the beginning of a new frame, in which case - * it will decode information from `srcBuffer`, starting the decoding process. - * Input size must be large enough to successfully decode the entire frame header. - * Frame header size is variable, but is guaranteed to be <= LZ4F_HEADER_SIZE_MAX bytes. - * It's allowed to provide more input data than this minimum. - * - After decoding has been started. - * In which case, no input is read, frame parameters are extracted from dctx. - * - If decoding has barely started, but not yet extracted information from header, - * LZ4F_getFrameInfo() will fail. - * The number of bytes consumed from srcBuffer will be updated within *srcSizePtr (necessarily <= original value). - * Decompression must resume from (srcBuffer + *srcSizePtr). - * @return : an hint about how many srcSize bytes LZ4F_decompress() expects for next call, - * or an error code which can be tested using LZ4F_isError(). - * note 1 : in case of error, dctx is not modified. Decoding operation can resume from beginning safely. - * note 2 : frame parameters are *copied into* an already allocated LZ4F_frameInfo_t structure. - */ -LZ4FLIB_API size_t LZ4F_getFrameInfo(LZ4F_dctx* dctx, - LZ4F_frameInfo_t* frameInfoPtr, - const void* srcBuffer, size_t* srcSizePtr); - -/*! LZ4F_decompress() : - * Call this function repetitively to regenerate compressed data from `srcBuffer`. - * The function will attempt to decode up to *srcSizePtr bytes from srcBuffer, into dstBuffer of capacity *dstSizePtr. - * - * The number of bytes regenerated into dstBuffer is provided within *dstSizePtr (necessarily <= original value). - * - * The number of bytes consumed from srcBuffer is provided within *srcSizePtr (necessarily <= original value). - * Number of bytes consumed can be < number of bytes provided. - * It typically happens when dstBuffer is not large enough to contain all decoded data. - * Unconsumed source data must be presented again in subsequent invocations. - * - * `dstBuffer` content is expected to be flushed between each invocation, as its content will be overwritten. - * `dstBuffer` itself can be changed at will between each consecutive function invocation. - * - * @return : an hint of how many `srcSize` bytes LZ4F_decompress() expects for next call. - * Schematically, it's the size of the current (or remaining) compressed block + header of next block. - * Respecting the hint provides some small speed benefit, because it skips intermediate buffers. - * This is just a hint though, it's always possible to provide any srcSize. - * When a frame is fully decoded, @return will be 0 (no more data expected). - * If decompression failed, @return is an error code, which can be tested using LZ4F_isError(). - * - * After a frame is fully decoded, dctx can be used again to decompress another frame. - * After a decompression error, use LZ4F_resetDecompressionContext() before re-using dctx, to return to clean state. - */ -LZ4FLIB_API size_t LZ4F_decompress(LZ4F_dctx* dctx, - void* dstBuffer, size_t* dstSizePtr, - const void* srcBuffer, size_t* srcSizePtr, - const LZ4F_decompressOptions_t* dOptPtr); - - -/*! LZ4F_resetDecompressionContext() : v1.8.0 - * In case of an error, the context is left in "undefined" state. - * In which case, it's necessary to reset it, before re-using it. - * This method can also be used to abruptly stop an unfinished decompression, - * and start a new one using the same context. */ -LZ4FLIB_API void LZ4F_resetDecompressionContext(LZ4F_dctx* dctx); /* always successful */ - - - -#if defined (__cplusplus) -} -#endif - -#endif /* LZ4F_H_09782039843 */ diff --git a/src/lz4/lib/lz4frame_static.h b/src/lz4/lib/lz4frame_static.h deleted file mode 100644 index 1899f8e466..0000000000 --- a/src/lz4/lib/lz4frame_static.h +++ /dev/null @@ -1,143 +0,0 @@ -/* - LZ4 auto-framing library - Header File for static linking only - Copyright (C) 2011-2016, Yann Collet. - - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - LZ4 source repository : https://github.com/lz4/lz4 - - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c -*/ - -#ifndef LZ4FRAME_STATIC_H_0398209384 -#define LZ4FRAME_STATIC_H_0398209384 - -#if defined (__cplusplus) -extern "C" { -#endif - -/* lz4frame_static.h should be used solely in the context of static linking. - * It contains definitions which are not stable and may change in the future. - * Never use it in the context of DLL linking. - */ - - -/* --- Dependency --- */ -#include "lz4frame.h" - - -/* --- Error List --- */ -#define LZ4F_LIST_ERRORS(ITEM) \ - ITEM(OK_NoError) \ - ITEM(ERROR_GENERIC) \ - ITEM(ERROR_maxBlockSize_invalid) \ - ITEM(ERROR_blockMode_invalid) \ - ITEM(ERROR_contentChecksumFlag_invalid) \ - ITEM(ERROR_compressionLevel_invalid) \ - ITEM(ERROR_headerVersion_wrong) \ - ITEM(ERROR_blockChecksum_invalid) \ - ITEM(ERROR_reservedFlag_set) \ - ITEM(ERROR_allocation_failed) \ - ITEM(ERROR_srcSize_tooLarge) \ - ITEM(ERROR_dstMaxSize_tooSmall) \ - ITEM(ERROR_frameHeader_incomplete) \ - ITEM(ERROR_frameType_unknown) \ - ITEM(ERROR_frameSize_wrong) \ - ITEM(ERROR_srcPtr_wrong) \ - ITEM(ERROR_decompressionFailed) \ - ITEM(ERROR_headerChecksum_invalid) \ - ITEM(ERROR_contentChecksum_invalid) \ - ITEM(ERROR_frameDecoding_alreadyStarted) \ - ITEM(ERROR_maxCode) - -#define LZ4F_GENERATE_ENUM(ENUM) LZ4F_##ENUM, - -/* enum list is exposed, to handle specific errors */ -typedef enum { LZ4F_LIST_ERRORS(LZ4F_GENERATE_ENUM) } LZ4F_errorCodes; - -LZ4F_errorCodes LZ4F_getErrorCode(size_t functionResult); - - - -/********************************** - * Bulk processing dictionary API - *********************************/ -typedef struct LZ4F_CDict_s LZ4F_CDict; - -/*! LZ4_createCDict() : - * When compressing multiple messages / blocks with the same dictionary, it's recommended to load it just once. - * LZ4_createCDict() will create a digested dictionary, ready to start future compression operations without startup delay. - * LZ4_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only. - * `dictBuffer` can be released after LZ4_CDict creation, since its content is copied within CDict */ -LZ4F_CDict* LZ4F_createCDict(const void* dictBuffer, size_t dictSize); -void LZ4F_freeCDict(LZ4F_CDict* CDict); - - -/*! LZ4_compressFrame_usingCDict() : - * Compress an entire srcBuffer into a valid LZ4 frame using a digested Dictionary. - * If cdict==NULL, compress without a dictionary. - * dstBuffer MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr). - * If this condition is not respected, function will fail (@return an errorCode). - * The LZ4F_preferences_t structure is optional : you may provide NULL as argument, - * but it's not recommended, as it's the only way to provide dictID in the frame header. - * @return : number of bytes written into dstBuffer. - * or an error code if it fails (can be tested using LZ4F_isError()) */ -size_t LZ4F_compressFrame_usingCDict(void* dst, size_t dstCapacity, - const void* src, size_t srcSize, - const LZ4F_CDict* cdict, - const LZ4F_preferences_t* preferencesPtr); - - -/*! LZ4F_compressBegin_usingCDict() : - * Inits streaming dictionary compression, and writes the frame header into dstBuffer. - * dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes. - * `prefsPtr` is optional : you may provide NULL as argument, - * however, it's the only way to provide dictID in the frame header. - * @return : number of bytes written into dstBuffer for the header, - * or an error code (which can be tested using LZ4F_isError()) */ -size_t LZ4F_compressBegin_usingCDict(LZ4F_cctx* cctx, - void* dstBuffer, size_t dstCapacity, - const LZ4F_CDict* cdict, - const LZ4F_preferences_t* prefsPtr); - - -/*! LZ4F_decompress_usingDict() : - * Same as LZ4F_decompress(), using a predefined dictionary. - * Dictionary is used "in place", without any preprocessing. - * It must remain accessible throughout the entire frame decoding. */ -size_t LZ4F_decompress_usingDict(LZ4F_dctx* dctxPtr, - void* dstBuffer, size_t* dstSizePtr, - const void* srcBuffer, size_t* srcSizePtr, - const void* dict, size_t dictSize, - const LZ4F_decompressOptions_t* decompressOptionsPtr); - - -#if defined (__cplusplus) -} -#endif - -#endif /* LZ4FRAME_STATIC_H_0398209384 */ diff --git a/src/lz4/lib/lz4hc.c b/src/lz4/lib/lz4hc.c deleted file mode 100644 index 22eb071e9c..0000000000 --- a/src/lz4/lib/lz4hc.c +++ /dev/null @@ -1,807 +0,0 @@ -/* - LZ4 HC - High Compression Mode of LZ4 - Copyright (C) 2011-2017, Yann Collet. - - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - LZ4 source repository : https://github.com/lz4/lz4 - - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c -*/ -/* note : lz4hc is not an independent module, it requires lz4.h/lz4.c for proper compilation */ - - -/* ************************************* -* Tuning Parameter -***************************************/ - -/*! HEAPMODE : - * Select how default compression function will allocate workplace memory, - * in stack (0:fastest), or in heap (1:requires malloc()). - * Since workplace is rather large, heap mode is recommended. - */ -#ifndef LZ4HC_HEAPMODE -# define LZ4HC_HEAPMODE 1 -#endif - - -/*=== Dependency ===*/ -#include "lz4hc.h" - - -/*=== Common LZ4 definitions ===*/ -#if defined(__GNUC__) -# pragma GCC diagnostic ignored "-Wunused-function" -#endif -#if defined (__clang__) -# pragma clang diagnostic ignored "-Wunused-function" -#endif - -#define LZ4_COMMONDEFS_ONLY -#include "lz4.c" /* LZ4_count, constants, mem */ - - -/*=== Constants ===*/ -#define OPTIMAL_ML (int)((ML_MASK-1)+MINMATCH) - - -/*=== Macros ===*/ -#define MIN(a,b) ( (a) < (b) ? (a) : (b) ) -#define MAX(a,b) ( (a) > (b) ? (a) : (b) ) -#define HASH_FUNCTION(i) (((i) * 2654435761U) >> ((MINMATCH*8)-LZ4HC_HASH_LOG)) -#define DELTANEXTMAXD(p) chainTable[(p) & LZ4HC_MAXD_MASK] /* flexible, LZ4HC_MAXD dependent */ -#define DELTANEXTU16(table, pos) table[(U16)(pos)] /* faster */ - -static U32 LZ4HC_hashPtr(const void* ptr) { return HASH_FUNCTION(LZ4_read32(ptr)); } - - - -/************************************** -* HC Compression -**************************************/ -static void LZ4HC_init (LZ4HC_CCtx_internal* hc4, const BYTE* start) -{ - MEM_INIT((void*)hc4->hashTable, 0, sizeof(hc4->hashTable)); - MEM_INIT(hc4->chainTable, 0xFF, sizeof(hc4->chainTable)); - hc4->nextToUpdate = 64 KB; - hc4->base = start - 64 KB; - hc4->end = start; - hc4->dictBase = start - 64 KB; - hc4->dictLimit = 64 KB; - hc4->lowLimit = 64 KB; -} - - -/* Update chains up to ip (excluded) */ -FORCE_INLINE void LZ4HC_Insert (LZ4HC_CCtx_internal* hc4, const BYTE* ip) -{ - U16* const chainTable = hc4->chainTable; - U32* const hashTable = hc4->hashTable; - const BYTE* const base = hc4->base; - U32 const target = (U32)(ip - base); - U32 idx = hc4->nextToUpdate; - - while (idx < target) { - U32 const h = LZ4HC_hashPtr(base+idx); - size_t delta = idx - hashTable[h]; - if (delta>MAX_DISTANCE) delta = MAX_DISTANCE; - DELTANEXTU16(chainTable, idx) = (U16)delta; - hashTable[h] = idx; - idx++; - } - - hc4->nextToUpdate = target; -} - - -FORCE_INLINE int LZ4HC_InsertAndFindBestMatch (LZ4HC_CCtx_internal* const hc4, /* Index table will be updated */ - const BYTE* const ip, const BYTE* const iLimit, - const BYTE** matchpos, - const int maxNbAttempts) -{ - U16* const chainTable = hc4->chainTable; - U32* const HashTable = hc4->hashTable; - const BYTE* const base = hc4->base; - const BYTE* const dictBase = hc4->dictBase; - const U32 dictLimit = hc4->dictLimit; - const U32 lowLimit = (hc4->lowLimit + 64 KB > (U32)(ip-base)) ? hc4->lowLimit : (U32)(ip - base) - (64 KB - 1); - U32 matchIndex; - int nbAttempts = maxNbAttempts; - size_t ml = 0; - - /* HC4 match finder */ - LZ4HC_Insert(hc4, ip); - matchIndex = HashTable[LZ4HC_hashPtr(ip)]; - - while ((matchIndex>=lowLimit) && (nbAttempts)) { - nbAttempts--; - if (matchIndex >= dictLimit) { - const BYTE* const match = base + matchIndex; - if ( (*(match+ml) == *(ip+ml)) /* can be longer */ - && (LZ4_read32(match) == LZ4_read32(ip)) ) - { - size_t const mlt = LZ4_count(ip+MINMATCH, match+MINMATCH, iLimit) + MINMATCH; - if (mlt > ml) { ml = mlt; *matchpos = match; } - } - } else { - const BYTE* const match = dictBase + matchIndex; - if (LZ4_read32(match) == LZ4_read32(ip)) { - size_t mlt; - const BYTE* vLimit = ip + (dictLimit - matchIndex); - if (vLimit > iLimit) vLimit = iLimit; - mlt = LZ4_count(ip+MINMATCH, match+MINMATCH, vLimit) + MINMATCH; - if ((ip+mlt == vLimit) && (vLimit < iLimit)) - mlt += LZ4_count(ip+mlt, base+dictLimit, iLimit); - if (mlt > ml) { ml = mlt; *matchpos = base + matchIndex; } /* virtual matchpos */ - } - } - matchIndex -= DELTANEXTU16(chainTable, matchIndex); - } - - return (int)ml; -} - - -FORCE_INLINE int LZ4HC_InsertAndGetWiderMatch ( - LZ4HC_CCtx_internal* hc4, - const BYTE* const ip, - const BYTE* const iLowLimit, - const BYTE* const iHighLimit, - int longest, - const BYTE** matchpos, - const BYTE** startpos, - const int maxNbAttempts) -{ - U16* const chainTable = hc4->chainTable; - U32* const HashTable = hc4->hashTable; - const BYTE* const base = hc4->base; - const U32 dictLimit = hc4->dictLimit; - const BYTE* const lowPrefixPtr = base + dictLimit; - const U32 lowLimit = (hc4->lowLimit + 64 KB > (U32)(ip-base)) ? hc4->lowLimit : (U32)(ip - base) - (64 KB - 1); - const BYTE* const dictBase = hc4->dictBase; - int const delta = (int)(ip-iLowLimit); - int nbAttempts = maxNbAttempts; - U32 matchIndex; - - - /* First Match */ - LZ4HC_Insert(hc4, ip); - matchIndex = HashTable[LZ4HC_hashPtr(ip)]; - - while ((matchIndex>=lowLimit) && (nbAttempts)) { - nbAttempts--; - if (matchIndex >= dictLimit) { - const BYTE* const matchPtr = base + matchIndex; - if (*(iLowLimit + longest) == *(matchPtr - delta + longest)) { - if (LZ4_read32(matchPtr) == LZ4_read32(ip)) { - int mlt = MINMATCH + LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, iHighLimit); - int back = 0; - - while ( (ip+back > iLowLimit) - && (matchPtr+back > lowPrefixPtr) - && (ip[back-1] == matchPtr[back-1])) { - back--; - } - - mlt -= back; - - if (mlt > longest) { - longest = mlt; - *matchpos = matchPtr+back; - *startpos = ip+back; - } } } - } else { - const BYTE* const matchPtr = dictBase + matchIndex; - if (LZ4_read32(matchPtr) == LZ4_read32(ip)) { - int mlt; - int back=0; - const BYTE* vLimit = ip + (dictLimit - matchIndex); - if (vLimit > iHighLimit) vLimit = iHighLimit; - mlt = LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, vLimit) + MINMATCH; - if ((ip+mlt == vLimit) && (vLimit < iHighLimit)) - mlt += LZ4_count(ip+mlt, base+dictLimit, iHighLimit); - while ((ip+back > iLowLimit) && (matchIndex+back > lowLimit) && (ip[back-1] == matchPtr[back-1])) back--; - mlt -= back; - if (mlt > longest) { longest = mlt; *matchpos = base + matchIndex + back; *startpos = ip+back; } - } - } - matchIndex -= DELTANEXTU16(chainTable, matchIndex); - } - - return longest; -} - - -typedef enum { - noLimit = 0, - limitedOutput = 1, - limitedDestSize = 2, -} limitedOutput_directive; - -#ifndef LZ4HC_DEBUG -# define LZ4HC_DEBUG 0 -#endif - -/* LZ4HC_encodeSequence() : - * @return : 0 if ok, - * 1 if buffer issue detected */ -FORCE_INLINE int LZ4HC_encodeSequence ( - const BYTE** ip, - BYTE** op, - const BYTE** anchor, - int matchLength, - const BYTE* const match, - limitedOutput_directive limit, - BYTE* oend) -{ - size_t length; - BYTE* const token = (*op)++; - -#if LZ4HC_DEBUG - printf("literal : %u -- match : %u -- offset : %u\n", - (U32)(*ip - *anchor), (U32)matchLength, (U32)(*ip-match)); -#endif - - /* Encode Literal length */ - length = (size_t)(*ip - *anchor); - if ((limit) && ((*op + (length >> 8) + length + (2 + 1 + LASTLITERALS)) > oend)) return 1; /* Check output limit */ - if (length >= RUN_MASK) { - size_t len = length - RUN_MASK; - *token = (RUN_MASK << ML_BITS); - for(; len >= 255 ; len -= 255) *(*op)++ = 255; - *(*op)++ = (BYTE)len; - } else { - *token = (BYTE)(length << ML_BITS); - } - - /* Copy Literals */ - LZ4_wildCopy(*op, *anchor, (*op) + length); - *op += length; - - /* Encode Offset */ - LZ4_writeLE16(*op, (U16)(*ip-match)); *op += 2; - - /* Encode MatchLength */ - length = (size_t)(matchLength - MINMATCH); - if ((limit) && (*op + (length >> 8) + (1 + LASTLITERALS) > oend)) return 1; /* Check output limit */ - if (length >= ML_MASK) { - *token += ML_MASK; - length -= ML_MASK; - for(; length >= 510 ; length -= 510) { *(*op)++ = 255; *(*op)++ = 255; } - if (length >= 255) { length -= 255; *(*op)++ = 255; } - *(*op)++ = (BYTE)length; - } else { - *token += (BYTE)(length); - } - - /* Prepare next loop */ - *ip += matchLength; - *anchor = *ip; - - return 0; -} - -/* btopt */ -#include "lz4opt.h" - - -static int LZ4HC_compress_hashChain ( - LZ4HC_CCtx_internal* const ctx, - const char* const source, - char* const dest, - int* srcSizePtr, - int const maxOutputSize, - unsigned maxNbAttempts, - limitedOutput_directive limit - ) -{ - const int inputSize = *srcSizePtr; - - const BYTE* ip = (const BYTE*) source; - const BYTE* anchor = ip; - const BYTE* const iend = ip + inputSize; - const BYTE* const mflimit = iend - MFLIMIT; - const BYTE* const matchlimit = (iend - LASTLITERALS); - - BYTE* optr = (BYTE*) dest; - BYTE* op = (BYTE*) dest; - BYTE* oend = op + maxOutputSize; - - int ml, ml2, ml3, ml0; - const BYTE* ref = NULL; - const BYTE* start2 = NULL; - const BYTE* ref2 = NULL; - const BYTE* start3 = NULL; - const BYTE* ref3 = NULL; - const BYTE* start0; - const BYTE* ref0; - - /* init */ - *srcSizePtr = 0; - if (limit == limitedDestSize && maxOutputSize < 1) return 0; /* Impossible to store anything */ - if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported input size, too large (or negative) */ - - ctx->end += inputSize; - if (limit == limitedDestSize) oend -= LASTLITERALS; /* Hack for support limitations LZ4 decompressor */ - if (inputSize < LZ4_minLength) goto _last_literals; /* Input too small, no compression (all literals) */ - - ip++; - - /* Main Loop */ - while (ip < mflimit) { - ml = LZ4HC_InsertAndFindBestMatch (ctx, ip, matchlimit, (&ref), maxNbAttempts); - if (!ml) { ip++; continue; } - - /* saved, in case we would skip too much */ - start0 = ip; - ref0 = ref; - ml0 = ml; - -_Search2: - if (ip+ml < mflimit) - ml2 = LZ4HC_InsertAndGetWiderMatch(ctx, ip + ml - 2, ip + 0, matchlimit, ml, &ref2, &start2, maxNbAttempts); - else - ml2 = ml; - - if (ml2 == ml) { /* No better match */ - optr = op; - if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) goto _dest_overflow; - continue; - } - - if (start0 < ip) { - if (start2 < ip + ml0) { /* empirical */ - ip = start0; - ref = ref0; - ml = ml0; - } - } - - /* Here, start0==ip */ - if ((start2 - ip) < 3) { /* First Match too small : removed */ - ml = ml2; - ip = start2; - ref =ref2; - goto _Search2; - } - -_Search3: - /* At this stage, we have : - * ml2 > ml1, and - * ip1+3 <= ip2 (usually < ip1+ml1) */ - if ((start2 - ip) < OPTIMAL_ML) { - int correction; - int new_ml = ml; - if (new_ml > OPTIMAL_ML) new_ml = OPTIMAL_ML; - if (ip+new_ml > start2 + ml2 - MINMATCH) new_ml = (int)(start2 - ip) + ml2 - MINMATCH; - correction = new_ml - (int)(start2 - ip); - if (correction > 0) { - start2 += correction; - ref2 += correction; - ml2 -= correction; - } - } - /* Now, we have start2 = ip+new_ml, with new_ml = min(ml, OPTIMAL_ML=18) */ - - if (start2 + ml2 < mflimit) - ml3 = LZ4HC_InsertAndGetWiderMatch(ctx, start2 + ml2 - 3, start2, matchlimit, ml2, &ref3, &start3, maxNbAttempts); - else - ml3 = ml2; - - if (ml3 == ml2) { /* No better match : 2 sequences to encode */ - /* ip & ref are known; Now for ml */ - if (start2 < ip+ml) ml = (int)(start2 - ip); - /* Now, encode 2 sequences */ - optr = op; - if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) goto _dest_overflow; - ip = start2; - optr = op; - if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml2, ref2, limit, oend)) goto _dest_overflow; - continue; - } - - if (start3 < ip+ml+3) { /* Not enough space for match 2 : remove it */ - if (start3 >= (ip+ml)) { /* can write Seq1 immediately ==> Seq2 is removed, so Seq3 becomes Seq1 */ - if (start2 < ip+ml) { - int correction = (int)(ip+ml - start2); - start2 += correction; - ref2 += correction; - ml2 -= correction; - if (ml2 < MINMATCH) { - start2 = start3; - ref2 = ref3; - ml2 = ml3; - } - } - - optr = op; - if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) goto _dest_overflow; - ip = start3; - ref = ref3; - ml = ml3; - - start0 = start2; - ref0 = ref2; - ml0 = ml2; - goto _Search2; - } - - start2 = start3; - ref2 = ref3; - ml2 = ml3; - goto _Search3; - } - - /* - * OK, now we have 3 ascending matches; let's write at least the first one - * ip & ref are known; Now for ml - */ - if (start2 < ip+ml) { - if ((start2 - ip) < (int)ML_MASK) { - int correction; - if (ml > OPTIMAL_ML) ml = OPTIMAL_ML; - if (ip + ml > start2 + ml2 - MINMATCH) ml = (int)(start2 - ip) + ml2 - MINMATCH; - correction = ml - (int)(start2 - ip); - if (correction > 0) { - start2 += correction; - ref2 += correction; - ml2 -= correction; - } - } else { - ml = (int)(start2 - ip); - } - } - optr = op; - if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) goto _dest_overflow; - - ip = start2; - ref = ref2; - ml = ml2; - - start2 = start3; - ref2 = ref3; - ml2 = ml3; - - goto _Search3; - } - -_last_literals: - /* Encode Last Literals */ - { size_t lastRunSize = (size_t)(iend - anchor); /* literals */ - size_t litLength = (lastRunSize + 255 - RUN_MASK) / 255; - size_t const totalSize = 1 + litLength + lastRunSize; - if (limit == limitedDestSize) oend += LASTLITERALS; /* restore correct value */ - if (limit && (op + totalSize > oend)) { - if (limit == limitedOutput) return 0; /* Check output limit */ - /* adapt lastRunSize to fill 'dest' */ - lastRunSize = (size_t)(oend - op) - 1; - litLength = (lastRunSize + 255 - RUN_MASK) / 255; - lastRunSize -= litLength; - } - ip = anchor + lastRunSize; - - if (lastRunSize >= RUN_MASK) { - size_t accumulator = lastRunSize - RUN_MASK; - *op++ = (RUN_MASK << ML_BITS); - for(; accumulator >= 255 ; accumulator -= 255) *op++ = 255; - *op++ = (BYTE) accumulator; - } else { - *op++ = (BYTE)(lastRunSize << ML_BITS); - } - memcpy(op, anchor, lastRunSize); - op += lastRunSize; - } - - /* End */ - *srcSizePtr = (int) (((const char*)ip) - source); - return (int) (((char*)op)-dest); - -_dest_overflow: - if (limit == limitedDestSize) { - op = optr; /* restore correct out pointer */ - goto _last_literals; - } - return 0; -} - -static int LZ4HC_getSearchNum(int compressionLevel) -{ - switch (compressionLevel) { - default: return 0; /* unused */ - case 11: return 128; - case 12: return 1<<10; - } -} - -static int LZ4HC_compress_generic ( - LZ4HC_CCtx_internal* const ctx, - const char* const src, - char* const dst, - int* const srcSizePtr, - int const dstCapacity, - int cLevel, - limitedOutput_directive limit - ) -{ - if (cLevel < 1) cLevel = LZ4HC_CLEVEL_DEFAULT; /* note : convention is different from lz4frame, maybe to reconsider */ - if (cLevel > 9) { - if (limit == limitedDestSize) cLevel = 10; - switch (cLevel) { - case 10: - return LZ4HC_compress_hashChain(ctx, src, dst, srcSizePtr, dstCapacity, 1 << 12, limit); - case 11: - ctx->searchNum = LZ4HC_getSearchNum(cLevel); - return LZ4HC_compress_optimal(ctx, src, dst, *srcSizePtr, dstCapacity, limit, 128, 0); - default: - cLevel = 12; - /* fall-through */ - case 12: - ctx->searchNum = LZ4HC_getSearchNum(cLevel); - return LZ4HC_compress_optimal(ctx, src, dst, *srcSizePtr, dstCapacity, limit, LZ4_OPT_NUM, 1); - } - } - return LZ4HC_compress_hashChain(ctx, src, dst, srcSizePtr, dstCapacity, 1 << (cLevel-1), limit); /* levels 1-9 */ -} - - -int LZ4_sizeofStateHC(void) { return sizeof(LZ4_streamHC_t); } - -int LZ4_compress_HC_extStateHC (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel) -{ - LZ4HC_CCtx_internal* const ctx = &((LZ4_streamHC_t*)state)->internal_donotuse; - if (((size_t)(state)&(sizeof(void*)-1)) != 0) return 0; /* Error : state is not aligned for pointers (32 or 64 bits) */ - LZ4HC_init (ctx, (const BYTE*)src); - if (dstCapacity < LZ4_compressBound(srcSize)) - return LZ4HC_compress_generic (ctx, src, dst, &srcSize, dstCapacity, compressionLevel, limitedOutput); - else - return LZ4HC_compress_generic (ctx, src, dst, &srcSize, dstCapacity, compressionLevel, noLimit); -} - -int LZ4_compress_HC(const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel) -{ -#if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1 - LZ4_streamHC_t* const statePtr = (LZ4_streamHC_t*)malloc(sizeof(LZ4_streamHC_t)); -#else - LZ4_streamHC_t state; - LZ4_streamHC_t* const statePtr = &state; -#endif - int const cSize = LZ4_compress_HC_extStateHC(statePtr, src, dst, srcSize, dstCapacity, compressionLevel); -#if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1 - free(statePtr); -#endif - return cSize; -} - -/* LZ4_compress_HC_destSize() : - * currently, only compatible with Hash Chain implementation, - * hence limit compression level to LZ4HC_CLEVEL_OPT_MIN-1*/ -int LZ4_compress_HC_destSize(void* LZ4HC_Data, const char* source, char* dest, int* sourceSizePtr, int targetDestSize, int cLevel) -{ - LZ4HC_CCtx_internal* const ctx = &((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse; - LZ4HC_init(ctx, (const BYTE*) source); - return LZ4HC_compress_generic(ctx, source, dest, sourceSizePtr, targetDestSize, cLevel, limitedDestSize); -} - - - -/************************************** -* Streaming Functions -**************************************/ -/* allocation */ -LZ4_streamHC_t* LZ4_createStreamHC(void) { return (LZ4_streamHC_t*)malloc(sizeof(LZ4_streamHC_t)); } -int LZ4_freeStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr) { - if (!LZ4_streamHCPtr) return 0; /* support free on NULL */ - free(LZ4_streamHCPtr); - return 0; -} - - -/* initialization */ -void LZ4_resetStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel) -{ - LZ4_STATIC_ASSERT(sizeof(LZ4HC_CCtx_internal) <= sizeof(size_t) * LZ4_STREAMHCSIZE_SIZET); /* if compilation fails here, LZ4_STREAMHCSIZE must be increased */ - LZ4_streamHCPtr->internal_donotuse.base = NULL; - if (compressionLevel > LZ4HC_CLEVEL_MAX) compressionLevel = LZ4HC_CLEVEL_MAX; /* cap compression level */ - LZ4_streamHCPtr->internal_donotuse.compressionLevel = compressionLevel; - LZ4_streamHCPtr->internal_donotuse.searchNum = LZ4HC_getSearchNum(compressionLevel); -} - -void LZ4_setCompressionLevel(LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel) -{ - int const currentCLevel = LZ4_streamHCPtr->internal_donotuse.compressionLevel; - int const minCLevel = currentCLevel < LZ4HC_CLEVEL_OPT_MIN ? 1 : LZ4HC_CLEVEL_OPT_MIN; - int const maxCLevel = currentCLevel < LZ4HC_CLEVEL_OPT_MIN ? LZ4HC_CLEVEL_OPT_MIN-1 : LZ4HC_CLEVEL_MAX; - compressionLevel = MIN(compressionLevel, minCLevel); - compressionLevel = MAX(compressionLevel, maxCLevel); - LZ4_streamHCPtr->internal_donotuse.compressionLevel = compressionLevel; -} - -int LZ4_loadDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, const char* dictionary, int dictSize) -{ - LZ4HC_CCtx_internal* const ctxPtr = &LZ4_streamHCPtr->internal_donotuse; - if (dictSize > 64 KB) { - dictionary += dictSize - 64 KB; - dictSize = 64 KB; - } - LZ4HC_init (ctxPtr, (const BYTE*)dictionary); - ctxPtr->end = (const BYTE*)dictionary + dictSize; - if (ctxPtr->compressionLevel >= LZ4HC_CLEVEL_OPT_MIN) - LZ4HC_updateBinTree(ctxPtr, ctxPtr->end - MFLIMIT, ctxPtr->end - LASTLITERALS); - else - if (dictSize >= 4) LZ4HC_Insert (ctxPtr, ctxPtr->end-3); - return dictSize; -} - - -/* compression */ - -static void LZ4HC_setExternalDict(LZ4HC_CCtx_internal* ctxPtr, const BYTE* newBlock) -{ - if (ctxPtr->compressionLevel >= LZ4HC_CLEVEL_OPT_MIN) - LZ4HC_updateBinTree(ctxPtr, ctxPtr->end - MFLIMIT, ctxPtr->end - LASTLITERALS); - else - if (ctxPtr->end >= ctxPtr->base + 4) LZ4HC_Insert (ctxPtr, ctxPtr->end-3); /* Referencing remaining dictionary content */ - - /* Only one memory segment for extDict, so any previous extDict is lost at this stage */ - ctxPtr->lowLimit = ctxPtr->dictLimit; - ctxPtr->dictLimit = (U32)(ctxPtr->end - ctxPtr->base); - ctxPtr->dictBase = ctxPtr->base; - ctxPtr->base = newBlock - ctxPtr->dictLimit; - ctxPtr->end = newBlock; - ctxPtr->nextToUpdate = ctxPtr->dictLimit; /* match referencing will resume from there */ -} - -static int LZ4_compressHC_continue_generic (LZ4_streamHC_t* LZ4_streamHCPtr, - const char* src, char* dst, - int* srcSizePtr, int dstCapacity, - limitedOutput_directive limit) -{ - LZ4HC_CCtx_internal* const ctxPtr = &LZ4_streamHCPtr->internal_donotuse; - /* auto-init if forgotten */ - if (ctxPtr->base == NULL) LZ4HC_init (ctxPtr, (const BYTE*) src); - - /* Check overflow */ - if ((size_t)(ctxPtr->end - ctxPtr->base) > 2 GB) { - size_t dictSize = (size_t)(ctxPtr->end - ctxPtr->base) - ctxPtr->dictLimit; - if (dictSize > 64 KB) dictSize = 64 KB; - LZ4_loadDictHC(LZ4_streamHCPtr, (const char*)(ctxPtr->end) - dictSize, (int)dictSize); - } - - /* Check if blocks follow each other */ - if ((const BYTE*)src != ctxPtr->end) LZ4HC_setExternalDict(ctxPtr, (const BYTE*)src); - - /* Check overlapping input/dictionary space */ - { const BYTE* sourceEnd = (const BYTE*) src + *srcSizePtr; - const BYTE* const dictBegin = ctxPtr->dictBase + ctxPtr->lowLimit; - const BYTE* const dictEnd = ctxPtr->dictBase + ctxPtr->dictLimit; - if ((sourceEnd > dictBegin) && ((const BYTE*)src < dictEnd)) { - if (sourceEnd > dictEnd) sourceEnd = dictEnd; - ctxPtr->lowLimit = (U32)(sourceEnd - ctxPtr->dictBase); - if (ctxPtr->dictLimit - ctxPtr->lowLimit < 4) ctxPtr->lowLimit = ctxPtr->dictLimit; - } - } - - return LZ4HC_compress_generic (ctxPtr, src, dst, srcSizePtr, dstCapacity, ctxPtr->compressionLevel, limit); -} - -int LZ4_compress_HC_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* src, char* dst, int srcSize, int dstCapacity) -{ - if (dstCapacity < LZ4_compressBound(srcSize)) - return LZ4_compressHC_continue_generic (LZ4_streamHCPtr, src, dst, &srcSize, dstCapacity, limitedOutput); - else - return LZ4_compressHC_continue_generic (LZ4_streamHCPtr, src, dst, &srcSize, dstCapacity, noLimit); -} - -int LZ4_compress_HC_continue_destSize (LZ4_streamHC_t* LZ4_streamHCPtr, const char* src, char* dst, int* srcSizePtr, int targetDestSize) -{ - LZ4HC_CCtx_internal* const ctxPtr = &LZ4_streamHCPtr->internal_donotuse; - if (ctxPtr->compressionLevel >= LZ4HC_CLEVEL_OPT_MIN) LZ4HC_init(ctxPtr, (const BYTE*)src); /* not compatible with btopt implementation */ - return LZ4_compressHC_continue_generic(LZ4_streamHCPtr, src, dst, srcSizePtr, targetDestSize, limitedDestSize); -} - - - -/* dictionary saving */ - -int LZ4_saveDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, char* safeBuffer, int dictSize) -{ - LZ4HC_CCtx_internal* const streamPtr = &LZ4_streamHCPtr->internal_donotuse; - int const prefixSize = (int)(streamPtr->end - (streamPtr->base + streamPtr->dictLimit)); - if (dictSize > 64 KB) dictSize = 64 KB; - if (dictSize < 4) dictSize = 0; - if (dictSize > prefixSize) dictSize = prefixSize; - memmove(safeBuffer, streamPtr->end - dictSize, dictSize); - { U32 const endIndex = (U32)(streamPtr->end - streamPtr->base); - streamPtr->end = (const BYTE*)safeBuffer + dictSize; - streamPtr->base = streamPtr->end - endIndex; - streamPtr->dictLimit = endIndex - dictSize; - streamPtr->lowLimit = endIndex - dictSize; - if (streamPtr->nextToUpdate < streamPtr->dictLimit) streamPtr->nextToUpdate = streamPtr->dictLimit; - } - return dictSize; -} - - -/*********************************** -* Deprecated Functions -***********************************/ -/* These functions currently generate deprecation warnings */ -/* Deprecated compression functions */ -int LZ4_compressHC(const char* src, char* dst, int srcSize) { return LZ4_compress_HC (src, dst, srcSize, LZ4_compressBound(srcSize), 0); } -int LZ4_compressHC_limitedOutput(const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC(src, dst, srcSize, maxDstSize, 0); } -int LZ4_compressHC2(const char* src, char* dst, int srcSize, int cLevel) { return LZ4_compress_HC (src, dst, srcSize, LZ4_compressBound(srcSize), cLevel); } -int LZ4_compressHC2_limitedOutput(const char* src, char* dst, int srcSize, int maxDstSize, int cLevel) { return LZ4_compress_HC(src, dst, srcSize, maxDstSize, cLevel); } -int LZ4_compressHC_withStateHC (void* state, const char* src, char* dst, int srcSize) { return LZ4_compress_HC_extStateHC (state, src, dst, srcSize, LZ4_compressBound(srcSize), 0); } -int LZ4_compressHC_limitedOutput_withStateHC (void* state, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC_extStateHC (state, src, dst, srcSize, maxDstSize, 0); } -int LZ4_compressHC2_withStateHC (void* state, const char* src, char* dst, int srcSize, int cLevel) { return LZ4_compress_HC_extStateHC(state, src, dst, srcSize, LZ4_compressBound(srcSize), cLevel); } -int LZ4_compressHC2_limitedOutput_withStateHC (void* state, const char* src, char* dst, int srcSize, int maxDstSize, int cLevel) { return LZ4_compress_HC_extStateHC(state, src, dst, srcSize, maxDstSize, cLevel); } -int LZ4_compressHC_continue (LZ4_streamHC_t* ctx, const char* src, char* dst, int srcSize) { return LZ4_compress_HC_continue (ctx, src, dst, srcSize, LZ4_compressBound(srcSize)); } -int LZ4_compressHC_limitedOutput_continue (LZ4_streamHC_t* ctx, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC_continue (ctx, src, dst, srcSize, maxDstSize); } - - -/* Deprecated streaming functions */ -int LZ4_sizeofStreamStateHC(void) { return LZ4_STREAMHCSIZE; } - -int LZ4_resetStreamStateHC(void* state, char* inputBuffer) -{ - LZ4HC_CCtx_internal *ctx = &((LZ4_streamHC_t*)state)->internal_donotuse; - if ((((size_t)state) & (sizeof(void*)-1)) != 0) return 1; /* Error : pointer is not aligned for pointer (32 or 64 bits) */ - LZ4HC_init(ctx, (const BYTE*)inputBuffer); - ctx->inputBuffer = (BYTE*)inputBuffer; - return 0; -} - -void* LZ4_createHC (char* inputBuffer) -{ - LZ4_streamHC_t* hc4 = (LZ4_streamHC_t*)ALLOCATOR(1, sizeof(LZ4_streamHC_t)); - if (hc4 == NULL) return NULL; /* not enough memory */ - LZ4HC_init (&hc4->internal_donotuse, (const BYTE*)inputBuffer); - hc4->internal_donotuse.inputBuffer = (BYTE*)inputBuffer; - return hc4; -} - -int LZ4_freeHC (void* LZ4HC_Data) { - if (!LZ4HC_Data) return 0; /* support free on NULL */ - FREEMEM(LZ4HC_Data); - return 0; -} - -int LZ4_compressHC2_continue (void* LZ4HC_Data, const char* src, char* dst, int srcSize, int cLevel) -{ - return LZ4HC_compress_generic (&((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse, src, dst, &srcSize, 0, cLevel, noLimit); -} - -int LZ4_compressHC2_limitedOutput_continue (void* LZ4HC_Data, const char* src, char* dst, int srcSize, int dstCapacity, int cLevel) -{ - return LZ4HC_compress_generic (&((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse, src, dst, &srcSize, dstCapacity, cLevel, limitedOutput); -} - -char* LZ4_slideInputBufferHC(void* LZ4HC_Data) -{ - LZ4HC_CCtx_internal* const hc4 = &((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse; - int const dictSize = LZ4_saveDictHC((LZ4_streamHC_t*)LZ4HC_Data, (char*)(hc4->inputBuffer), 64 KB); - return (char*)(hc4->inputBuffer + dictSize); -} diff --git a/src/lz4/lib/lz4hc.h b/src/lz4/lib/lz4hc.h deleted file mode 100644 index 66d5636405..0000000000 --- a/src/lz4/lib/lz4hc.h +++ /dev/null @@ -1,278 +0,0 @@ -/* - LZ4 HC - High Compression Mode of LZ4 - Header File - Copyright (C) 2011-2017, Yann Collet. - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - LZ4 source repository : https://github.com/lz4/lz4 - - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c -*/ -#ifndef LZ4_HC_H_19834876238432 -#define LZ4_HC_H_19834876238432 - -#if defined (__cplusplus) -extern "C" { -#endif - -/* --- Dependency --- */ -/* note : lz4hc is not an independent module, it requires lz4.h/lz4.c for proper compilation */ -#include "lz4.h" /* stddef, LZ4LIB_API, LZ4_DEPRECATED */ - - -/* --- Useful constants --- */ -#define LZ4HC_CLEVEL_MIN 3 -#define LZ4HC_CLEVEL_DEFAULT 9 -#define LZ4HC_CLEVEL_OPT_MIN 11 -#define LZ4HC_CLEVEL_MAX 12 - - -/*-************************************ - * Block Compression - **************************************/ -/*! LZ4_compress_HC() : - * Compress data from `src` into `dst`, using the more powerful but slower "HC" algorithm. - * `dst` must be already allocated. - * Compression is guaranteed to succeed if `dstCapacity >= LZ4_compressBound(srcSize)` (see "lz4.h") - * Max supported `srcSize` value is LZ4_MAX_INPUT_SIZE (see "lz4.h") - * `compressionLevel` : Recommended values are between 4 and 9, although any value between 1 and LZ4HC_CLEVEL_MAX will work. - * Values >LZ4HC_CLEVEL_MAX behave the same as LZ4HC_CLEVEL_MAX. - * @return : the number of bytes written into 'dst' - * or 0 if compression fails. - */ -LZ4LIB_API int LZ4_compress_HC (const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel); - - -/* Note : - * Decompression functions are provided within "lz4.h" (BSD license) - */ - - -/*! LZ4_compress_HC_extStateHC() : - * Same as LZ4_compress_HC(), but using an externally allocated memory segment for `state`. - * `state` size is provided by LZ4_sizeofStateHC(). - * Memory segment must be aligned on 8-bytes boundaries (which a normal malloc() will do properly). - */ -LZ4LIB_API int LZ4_compress_HC_extStateHC(void* state, const char* src, char* dst, int srcSize, int maxDstSize, int compressionLevel); -LZ4LIB_API int LZ4_sizeofStateHC(void); - - -/*-************************************ - * Streaming Compression - * Bufferless synchronous API - **************************************/ - typedef union LZ4_streamHC_u LZ4_streamHC_t; /* incomplete type (defined later) */ - -/*! LZ4_createStreamHC() and LZ4_freeStreamHC() : - * These functions create and release memory for LZ4 HC streaming state. - * Newly created states are automatically initialized. - * Existing states can be re-used several times, using LZ4_resetStreamHC(). - * These methods are API and ABI stable, they can be used in combination with a DLL. - */ -LZ4LIB_API LZ4_streamHC_t* LZ4_createStreamHC(void); -LZ4LIB_API int LZ4_freeStreamHC (LZ4_streamHC_t* streamHCPtr); - -LZ4LIB_API void LZ4_resetStreamHC (LZ4_streamHC_t* streamHCPtr, int compressionLevel); -LZ4LIB_API int LZ4_loadDictHC (LZ4_streamHC_t* streamHCPtr, const char* dictionary, int dictSize); - -LZ4LIB_API int LZ4_compress_HC_continue (LZ4_streamHC_t* streamHCPtr, const char* src, char* dst, int srcSize, int maxDstSize); - -LZ4LIB_API int LZ4_saveDictHC (LZ4_streamHC_t* streamHCPtr, char* safeBuffer, int maxDictSize); - -/* - These functions compress data in successive blocks of any size, using previous blocks as dictionary. - One key assumption is that previous blocks (up to 64 KB) remain read-accessible while compressing next blocks. - There is an exception for ring buffers, which can be smaller than 64 KB. - Ring buffers scenario is automatically detected and handled by LZ4_compress_HC_continue(). - - Before starting compression, state must be properly initialized, using LZ4_resetStreamHC(). - A first "fictional block" can then be designated as initial dictionary, using LZ4_loadDictHC() (Optional). - - Then, use LZ4_compress_HC_continue() to compress each successive block. - Previous memory blocks (including initial dictionary when present) must remain accessible and unmodified during compression. - 'dst' buffer should be sized to handle worst case scenarios (see LZ4_compressBound()), to ensure operation success. - Because in case of failure, the API does not guarantee context recovery, and context will have to be reset. - If `dst` buffer budget cannot be >= LZ4_compressBound(), consider using LZ4_compress_HC_continue_destSize() instead. - - If, for any reason, previous data block can't be preserved unmodified in memory for next compression block, - you can save it to a more stable memory space, using LZ4_saveDictHC(). - Return value of LZ4_saveDictHC() is the size of dictionary effectively saved into 'safeBuffer'. -*/ - - - /*-************************************* - * PRIVATE DEFINITIONS : - * Do not use these definitions. - * They are exposed to allow static allocation of `LZ4_streamHC_t`. - * Using these definitions makes the code vulnerable to potential API break when upgrading LZ4 - **************************************/ -#define LZ4HC_DICTIONARY_LOGSIZE 17 /* because of btopt, hc would only need 16 */ -#define LZ4HC_MAXD (1<= 199901L) /* C99 */) -#include - -typedef struct -{ - uint32_t hashTable[LZ4HC_HASHTABLESIZE]; - uint16_t chainTable[LZ4HC_MAXD]; - const uint8_t* end; /* next block here to continue on current prefix */ - const uint8_t* base; /* All index relative to this position */ - const uint8_t* dictBase; /* alternate base for extDict */ - uint8_t* inputBuffer; /* deprecated */ - uint32_t dictLimit; /* below that point, need extDict */ - uint32_t lowLimit; /* below that point, no more dict */ - uint32_t nextToUpdate; /* index from which to continue dictionary update */ - uint32_t searchNum; /* only for optimal parser */ - uint32_t compressionLevel; -} LZ4HC_CCtx_internal; - -#else - -typedef struct -{ - unsigned int hashTable[LZ4HC_HASHTABLESIZE]; - unsigned short chainTable[LZ4HC_MAXD]; - const unsigned char* end; /* next block here to continue on current prefix */ - const unsigned char* base; /* All index relative to this position */ - const unsigned char* dictBase; /* alternate base for extDict */ - unsigned char* inputBuffer; /* deprecated */ - unsigned int dictLimit; /* below that point, need extDict */ - unsigned int lowLimit; /* below that point, no more dict */ - unsigned int nextToUpdate; /* index from which to continue dictionary update */ - unsigned int searchNum; /* only for optimal parser */ - int compressionLevel; -} LZ4HC_CCtx_internal; - -#endif - -#define LZ4_STREAMHCSIZE (4*LZ4HC_HASHTABLESIZE + 2*LZ4HC_MAXD + 56) /* 393268 */ -#define LZ4_STREAMHCSIZE_SIZET (LZ4_STREAMHCSIZE / sizeof(size_t)) -union LZ4_streamHC_u { - size_t table[LZ4_STREAMHCSIZE_SIZET]; - LZ4HC_CCtx_internal internal_donotuse; -}; /* previously typedef'd to LZ4_streamHC_t */ -/* - LZ4_streamHC_t : - This structure allows static allocation of LZ4 HC streaming state. - State must be initialized using LZ4_resetStreamHC() before first use. - - Static allocation shall only be used in combination with static linking. - When invoking LZ4 from a DLL, use create/free functions instead, which are API and ABI stable. -*/ - - -/*-************************************ -* Deprecated Functions -**************************************/ -/* see lz4.h LZ4_DISABLE_DEPRECATE_WARNINGS to turn off deprecation warnings */ - -/* deprecated compression functions */ -/* these functions will trigger warning messages in future releases */ -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_HC() instead") int LZ4_compressHC (const char* source, char* dest, int inputSize); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_HC() instead") int LZ4_compressHC_limitedOutput (const char* source, char* dest, int inputSize, int maxOutputSize); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_HC() instead") int LZ4_compressHC2 (const char* source, char* dest, int inputSize, int compressionLevel); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_HC() instead") int LZ4_compressHC2_limitedOutput (const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_HC_extStateHC() instead") int LZ4_compressHC_withStateHC (void* state, const char* source, char* dest, int inputSize); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_HC_extStateHC() instead") int LZ4_compressHC_limitedOutput_withStateHC (void* state, const char* source, char* dest, int inputSize, int maxOutputSize); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_HC_extStateHC() instead") int LZ4_compressHC2_withStateHC (void* state, const char* source, char* dest, int inputSize, int compressionLevel); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_HC_extStateHC() instead") int LZ4_compressHC2_limitedOutput_withStateHC(void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_HC_continue() instead") int LZ4_compressHC_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* source, char* dest, int inputSize); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_HC_continue() instead") int LZ4_compressHC_limitedOutput_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* source, char* dest, int inputSize, int maxOutputSize); - -/* Deprecated Streaming functions using older model; should no longer be used */ -LZ4LIB_API LZ4_DEPRECATED("use LZ4_createStreamHC() instead") void* LZ4_createHC (char* inputBuffer); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_saveDictHC() instead") char* LZ4_slideInputBufferHC (void* LZ4HC_Data); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_freeStreamHC() instead") int LZ4_freeHC (void* LZ4HC_Data); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_HC_continue() instead") int LZ4_compressHC2_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int compressionLevel); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_compress_HC_continue() instead") int LZ4_compressHC2_limitedOutput_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_createStreamHC() instead") int LZ4_sizeofStreamStateHC(void); -LZ4LIB_API LZ4_DEPRECATED("use LZ4_resetStreamHC() instead") int LZ4_resetStreamStateHC(void* state, char* inputBuffer); - - -#if defined (__cplusplus) -} -#endif - -#endif /* LZ4_HC_H_19834876238432 */ - -/*-************************************************ - * !!!!! STATIC LINKING ONLY !!!!! - * Following definitions are considered experimental. - * They should not be linked from DLL, - * as there is no guarantee of API stability yet. - * Prototypes will be promoted to "stable" status - * after successfull usage in real-life scenarios. - *************************************************/ -#ifdef LZ4_HC_STATIC_LINKING_ONLY /* protection macro */ -#ifndef LZ4_HC_SLO_098092834 -#define LZ4_HC_SLO_098092834 - -/*! LZ4_compress_HC_destSize() : v1.8.0 (experimental) - * Will try to compress as much data from `src` as possible - * that can fit into `targetDstSize` budget. - * Result is provided in 2 parts : - * @return : the number of bytes written into 'dst' - * or 0 if compression fails. - * `srcSizePtr` : value will be updated to indicate how much bytes were read from `src` - */ -int LZ4_compress_HC_destSize(void* LZ4HC_Data, - const char* src, char* dst, - int* srcSizePtr, int targetDstSize, - int compressionLevel); - -/*! LZ4_compress_HC_continue_destSize() : v1.8.0 (experimental) - * Similar as LZ4_compress_HC_continue(), - * but will read a variable nb of bytes from `src` - * to fit into `targetDstSize` budget. - * Result is provided in 2 parts : - * @return : the number of bytes written into 'dst' - * or 0 if compression fails. - * `srcSizePtr` : value will be updated to indicate how much bytes were read from `src`. - * Important : due to limitations, this prototype only works well up to cLevel < LZ4HC_CLEVEL_OPT_MIN - * beyond that level, compression performance will be much reduced due to internal incompatibilities - */ -int LZ4_compress_HC_continue_destSize(LZ4_streamHC_t* LZ4_streamHCPtr, - const char* src, char* dst, - int* srcSizePtr, int targetDstSize); - -/*! LZ4_setCompressionLevel() : v1.8.0 (experimental) - * It's possible to change compression level after LZ4_resetStreamHC(), between 2 invocations of LZ4_compress_HC_continue*(), - * but that requires to stay in the same mode (aka 1-10 or 11-12). - * This function ensures this condition. - */ -void LZ4_setCompressionLevel(LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel); - - - -#endif /* LZ4_HC_SLO_098092834 */ -#endif /* LZ4_HC_STATIC_LINKING_ONLY */ diff --git a/src/lz4/lib/lz4opt.h b/src/lz4/lib/lz4opt.h deleted file mode 100644 index e9e54d86c2..0000000000 --- a/src/lz4/lib/lz4opt.h +++ /dev/null @@ -1,366 +0,0 @@ -/* - lz4opt.h - Optimal Mode of LZ4 - Copyright (C) 2015-2017, Przemyslaw Skibinski - Note : this file is intended to be included within lz4hc.c - - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - LZ4 source repository : https://github.com/lz4/lz4 - - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c -*/ - -#define LZ4_OPT_NUM (1<<12) - - -typedef struct { - int off; - int len; -} LZ4HC_match_t; - -typedef struct { - int price; - int off; - int mlen; - int litlen; -} LZ4HC_optimal_t; - - -/* price in bytes */ -FORCE_INLINE size_t LZ4HC_literalsPrice(size_t litlen) -{ - size_t price = litlen; - if (litlen >= (size_t)RUN_MASK) - price += 1 + (litlen-RUN_MASK)/255; - return price; -} - - -/* requires mlen >= MINMATCH */ -FORCE_INLINE size_t LZ4HC_sequencePrice(size_t litlen, size_t mlen) -{ - size_t price = 2 + 1; /* 16-bit offset + token */ - - price += LZ4HC_literalsPrice(litlen); - - if (mlen >= (size_t)(ML_MASK+MINMATCH)) - price+= 1 + (mlen-(ML_MASK+MINMATCH))/255; - - return price; -} - - -/*-************************************* -* Binary Tree search -***************************************/ -FORCE_INLINE int LZ4HC_BinTree_InsertAndGetAllMatches ( - LZ4HC_CCtx_internal* ctx, - const BYTE* const ip, - const BYTE* const iHighLimit, - size_t best_mlen, - LZ4HC_match_t* matches, - int* matchNum) -{ - U16* const chainTable = ctx->chainTable; - U32* const HashTable = ctx->hashTable; - const BYTE* const base = ctx->base; - const U32 dictLimit = ctx->dictLimit; - const U32 current = (U32)(ip - base); - const U32 lowLimit = (ctx->lowLimit + MAX_DISTANCE > current) ? ctx->lowLimit : current - (MAX_DISTANCE - 1); - const BYTE* const dictBase = ctx->dictBase; - const BYTE* match; - int nbAttempts = ctx->searchNum; - int mnum = 0; - U16 *ptr0, *ptr1, delta0, delta1; - U32 matchIndex; - size_t matchLength = 0; - U32* HashPos; - - if (ip + MINMATCH > iHighLimit) return 1; - - /* HC4 match finder */ - HashPos = &HashTable[LZ4HC_hashPtr(ip)]; - matchIndex = *HashPos; - *HashPos = current; - - ptr0 = &DELTANEXTMAXD(current*2+1); - ptr1 = &DELTANEXTMAXD(current*2); - delta0 = delta1 = (U16)(current - matchIndex); - - while ((matchIndex < current) && (matchIndex>=lowLimit) && (nbAttempts)) { - nbAttempts--; - if (matchIndex >= dictLimit) { - match = base + matchIndex; - matchLength = LZ4_count(ip, match, iHighLimit); - } else { - const BYTE* vLimit = ip + (dictLimit - matchIndex); - match = dictBase + matchIndex; - if (vLimit > iHighLimit) vLimit = iHighLimit; - matchLength = LZ4_count(ip, match, vLimit); - if ((ip+matchLength == vLimit) && (vLimit < iHighLimit)) - matchLength += LZ4_count(ip+matchLength, base+dictLimit, iHighLimit); - if (matchIndex+matchLength >= dictLimit) - match = base + matchIndex; /* to prepare for next usage of match[matchLength] */ - } - - if (matchLength > best_mlen) { - best_mlen = matchLength; - if (matches) { - if (matchIndex >= dictLimit) - matches[mnum].off = (int)(ip - match); - else - matches[mnum].off = (int)(ip - (base + matchIndex)); /* virtual matchpos */ - matches[mnum].len = (int)matchLength; - mnum++; - } - if (best_mlen > LZ4_OPT_NUM) break; - } - - if (ip+matchLength >= iHighLimit) /* equal : no way to know if inf or sup */ - break; /* drop , to guarantee consistency ; miss a bit of compression, but other solutions can corrupt the tree */ - - DEBUGLOG(6, "ip :%016llX", (U64)ip); - DEBUGLOG(6, "match:%016llX", (U64)match); - if (*(ip+matchLength) < *(match+matchLength)) { - *ptr0 = delta0; - ptr0 = &DELTANEXTMAXD(matchIndex*2); - if (*ptr0 == (U16)-1) break; - delta0 = *ptr0; - delta1 += delta0; - matchIndex -= delta0; - } else { - *ptr1 = delta1; - ptr1 = &DELTANEXTMAXD(matchIndex*2+1); - if (*ptr1 == (U16)-1) break; - delta1 = *ptr1; - delta0 += delta1; - matchIndex -= delta1; - } - } - - *ptr0 = (U16)-1; - *ptr1 = (U16)-1; - if (matchNum) *matchNum = mnum; - /* if (best_mlen > 8) return best_mlen-8; */ - if (!matchNum) return 1; - return 1; -} - - -FORCE_INLINE void LZ4HC_updateBinTree(LZ4HC_CCtx_internal* ctx, const BYTE* const ip, const BYTE* const iHighLimit) -{ - const BYTE* const base = ctx->base; - const U32 target = (U32)(ip - base); - U32 idx = ctx->nextToUpdate; - while(idx < target) - idx += LZ4HC_BinTree_InsertAndGetAllMatches(ctx, base+idx, iHighLimit, 8, NULL, NULL); -} - - -/** Tree updater, providing best match */ -FORCE_INLINE int LZ4HC_BinTree_GetAllMatches ( - LZ4HC_CCtx_internal* ctx, - const BYTE* const ip, const BYTE* const iHighLimit, - size_t best_mlen, LZ4HC_match_t* matches, const int fullUpdate) -{ - int mnum = 0; - if (ip < ctx->base + ctx->nextToUpdate) return 0; /* skipped area */ - if (fullUpdate) LZ4HC_updateBinTree(ctx, ip, iHighLimit); - best_mlen = LZ4HC_BinTree_InsertAndGetAllMatches(ctx, ip, iHighLimit, best_mlen, matches, &mnum); - ctx->nextToUpdate = (U32)(ip - ctx->base + best_mlen); - return mnum; -} - - -#define SET_PRICE(pos, ml, offset, ll, cost) \ -{ \ - while (last_pos < pos) { opt[last_pos+1].price = 1<<30; last_pos++; } \ - opt[pos].mlen = (int)ml; \ - opt[pos].off = (int)offset; \ - opt[pos].litlen = (int)ll; \ - opt[pos].price = (int)cost; \ -} - - -static int LZ4HC_compress_optimal ( - LZ4HC_CCtx_internal* ctx, - const char* const source, - char* dest, - int inputSize, - int maxOutputSize, - limitedOutput_directive limit, - size_t sufficient_len, - const int fullUpdate - ) -{ - LZ4HC_optimal_t opt[LZ4_OPT_NUM + 1]; /* this uses a bit too much stack memory to my taste ... */ - LZ4HC_match_t matches[LZ4_OPT_NUM + 1]; - - const BYTE* ip = (const BYTE*) source; - const BYTE* anchor = ip; - const BYTE* const iend = ip + inputSize; - const BYTE* const mflimit = iend - MFLIMIT; - const BYTE* const matchlimit = (iend - LASTLITERALS); - BYTE* op = (BYTE*) dest; - BYTE* const oend = op + maxOutputSize; - - /* init */ - DEBUGLOG(5, "LZ4HC_compress_optimal"); - if (sufficient_len >= LZ4_OPT_NUM) sufficient_len = LZ4_OPT_NUM-1; - ctx->end += inputSize; - ip++; - - /* Main Loop */ - while (ip < mflimit) { - size_t const llen = ip - anchor; - size_t last_pos = 0; - size_t match_num, cur, best_mlen, best_off; - memset(opt, 0, sizeof(LZ4HC_optimal_t)); /* memset only the first one */ - - match_num = LZ4HC_BinTree_GetAllMatches(ctx, ip, matchlimit, MINMATCH-1, matches, fullUpdate); - if (!match_num) { ip++; continue; } - - if ((size_t)matches[match_num-1].len > sufficient_len) { - /* good enough solution : immediate encoding */ - best_mlen = matches[match_num-1].len; - best_off = matches[match_num-1].off; - cur = 0; - last_pos = 1; - goto encode; - } - - /* set prices using matches at position = 0 */ - { size_t matchNb; - for (matchNb = 0; matchNb < match_num; matchNb++) { - size_t mlen = (matchNb>0) ? (size_t)matches[matchNb-1].len+1 : MINMATCH; - best_mlen = matches[matchNb].len; /* necessarily < sufficient_len < LZ4_OPT_NUM */ - for ( ; mlen <= best_mlen ; mlen++) { - size_t const cost = LZ4HC_sequencePrice(llen, mlen) - LZ4HC_literalsPrice(llen); - SET_PRICE(mlen, mlen, matches[matchNb].off, 0, cost); /* updates last_pos and opt[pos] */ - } } } - - if (last_pos < MINMATCH) { ip++; continue; } /* note : on clang at least, this test improves performance */ - - /* check further positions */ - opt[0].mlen = opt[1].mlen = 1; - for (cur = 1; cur <= last_pos; cur++) { - const BYTE* const curPtr = ip + cur; - - /* establish baseline price if cur is literal */ - { size_t price, litlen; - if (opt[cur-1].mlen == 1) { - /* no match at previous position */ - litlen = opt[cur-1].litlen + 1; - if (cur > litlen) { - price = opt[cur - litlen].price + LZ4HC_literalsPrice(litlen); - } else { - price = LZ4HC_literalsPrice(llen + litlen) - LZ4HC_literalsPrice(llen); - } - } else { - litlen = 1; - price = opt[cur - 1].price + LZ4HC_literalsPrice(1); - } - - if (price < (size_t)opt[cur].price) - SET_PRICE(cur, 1 /*mlen*/, 0 /*off*/, litlen, price); /* note : increases last_pos */ - } - - if (cur == last_pos || curPtr >= mflimit) break; - - match_num = LZ4HC_BinTree_GetAllMatches(ctx, curPtr, matchlimit, MINMATCH-1, matches, fullUpdate); - if ((match_num > 0) && (size_t)matches[match_num-1].len > sufficient_len) { - /* immediate encoding */ - best_mlen = matches[match_num-1].len; - best_off = matches[match_num-1].off; - last_pos = cur + 1; - goto encode; - } - - /* set prices using matches at position = cur */ - { size_t matchNb; - for (matchNb = 0; matchNb < match_num; matchNb++) { - size_t ml = (matchNb>0) ? (size_t)matches[matchNb-1].len+1 : MINMATCH; - best_mlen = (cur + matches[matchNb].len < LZ4_OPT_NUM) ? - (size_t)matches[matchNb].len : LZ4_OPT_NUM - cur; - - for ( ; ml <= best_mlen ; ml++) { - size_t ll, price; - if (opt[cur].mlen == 1) { - ll = opt[cur].litlen; - if (cur > ll) - price = opt[cur - ll].price + LZ4HC_sequencePrice(ll, ml); - else - price = LZ4HC_sequencePrice(llen + ll, ml) - LZ4HC_literalsPrice(llen); - } else { - ll = 0; - price = opt[cur].price + LZ4HC_sequencePrice(0, ml); - } - - if (cur + ml > last_pos || price < (size_t)opt[cur + ml].price) { - SET_PRICE(cur + ml, ml, matches[matchNb].off, ll, price); - } } } } - } /* for (cur = 1; cur <= last_pos; cur++) */ - - best_mlen = opt[last_pos].mlen; - best_off = opt[last_pos].off; - cur = last_pos - best_mlen; - -encode: /* cur, last_pos, best_mlen, best_off must be set */ - opt[0].mlen = 1; - while (1) { /* from end to beginning */ - size_t const ml = opt[cur].mlen; - int const offset = opt[cur].off; - opt[cur].mlen = (int)best_mlen; - opt[cur].off = (int)best_off; - best_mlen = ml; - best_off = offset; - if (ml > cur) break; /* can this happen ? */ - cur -= ml; - } - - /* encode all recorded sequences */ - cur = 0; - while (cur < last_pos) { - int const ml = opt[cur].mlen; - int const offset = opt[cur].off; - if (ml == 1) { ip++; cur++; continue; } - cur += ml; - if ( LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ip - offset, limit, oend) ) return 0; - } - } /* while (ip < mflimit) */ - - /* Encode Last Literals */ - { int lastRun = (int)(iend - anchor); - if ((limit) && (((char*)op - dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize)) return 0; /* Check output limit */ - if (lastRun>=(int)RUN_MASK) { *op++=(RUN_MASK< 254 ; lastRun-=255) *op++ = 255; *op++ = (BYTE) lastRun; } - else *op++ = (BYTE)(lastRun< 1 > 2) - */ -#ifndef XXH_FORCE_MEMORY_ACCESS /* can be defined externally, on command line for example */ -# if defined(__GNUC__) && ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) ) -# define XXH_FORCE_MEMORY_ACCESS 2 -# elif defined(__INTEL_COMPILER) || \ - (defined(__GNUC__) && ( defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__) )) -# define XXH_FORCE_MEMORY_ACCESS 1 -# endif -#endif - -/*!XXH_ACCEPT_NULL_INPUT_POINTER : - * If the input pointer is a null pointer, xxHash default behavior is to trigger a memory access error, since it is a bad pointer. - * When this option is enabled, xxHash output for null input pointers will be the same as a null-length input. - * By default, this option is disabled. To enable it, uncomment below define : - */ -/* #define XXH_ACCEPT_NULL_INPUT_POINTER 1 */ - -/*!XXH_FORCE_NATIVE_FORMAT : - * By default, xxHash library provides endian-independent Hash values, based on little-endian convention. - * Results are therefore identical for little-endian and big-endian CPU. - * This comes at a performance cost for big-endian CPU, since some swapping is required to emulate little-endian format. - * Should endian-independence be of no importance for your application, you may set the #define below to 1, - * to improve speed for Big-endian CPU. - * This option has no impact on Little_Endian CPU. - */ -#ifndef XXH_FORCE_NATIVE_FORMAT /* can be defined externally */ -# define XXH_FORCE_NATIVE_FORMAT 0 -#endif - -/*!XXH_FORCE_ALIGN_CHECK : - * This is a minor performance trick, only useful with lots of very small keys. - * It means : check for aligned/unaligned input. - * The check costs one initial branch per hash; set to 0 when the input data - * is guaranteed to be aligned. - */ -#ifndef XXH_FORCE_ALIGN_CHECK /* can be defined externally */ -# if defined(__i386) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64) -# define XXH_FORCE_ALIGN_CHECK 0 -# else -# define XXH_FORCE_ALIGN_CHECK 1 -# endif -#endif - - -/* ************************************* -* Includes & Memory related functions -***************************************/ -/*! Modify the local functions below should you wish to use some other memory routines -* for malloc(), free() */ -#include -static void* XXH_malloc(size_t s) { return malloc(s); } -static void XXH_free (void* p) { free(p); } -/*! and for memcpy() */ -#include -static void* XXH_memcpy(void* dest, const void* src, size_t size) { return memcpy(dest,src,size); } - -#define XXH_STATIC_LINKING_ONLY -#include "xxhash.h" - - -/* ************************************* -* Compiler Specific Options -***************************************/ -#ifdef _MSC_VER /* Visual Studio */ -# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ -#endif - -#ifndef FORCE_INLINE -# ifdef _MSC_VER /* Visual Studio */ -# define FORCE_INLINE static __forceinline -# else -# if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */ -# ifdef __GNUC__ -# define FORCE_INLINE static inline __attribute__((always_inline)) -# else -# define FORCE_INLINE static inline -# endif -# else -# define FORCE_INLINE static -# endif /* __STDC_VERSION__ */ -# endif /* _MSC_VER */ -#endif /* FORCE_INLINE */ - - -/* ************************************* -* Basic Types -***************************************/ -#ifndef MEM_MODULE -# if !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) -# include - typedef uint8_t BYTE; - typedef uint16_t U16; - typedef uint32_t U32; - typedef int32_t S32; -# else - typedef unsigned char BYTE; - typedef unsigned short U16; - typedef unsigned int U32; - typedef signed int S32; -# endif -#endif - -#if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==2)) - -/* Force direct memory access. Only works on CPU which support unaligned memory access in hardware */ -static U32 XXH_read32(const void* memPtr) { return *(const U32*) memPtr; } - -#elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==1)) - -/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */ -/* currently only defined for gcc and icc */ -typedef union { U32 u32; } __attribute__((packed)) unalign; -static U32 XXH_read32(const void* ptr) { return ((const unalign*)ptr)->u32; } - -#else - -/* portable and safe solution. Generally efficient. - * see : http://stackoverflow.com/a/32095106/646947 - */ -static U32 XXH_read32(const void* memPtr) -{ - U32 val; - memcpy(&val, memPtr, sizeof(val)); - return val; -} - -#endif /* XXH_FORCE_DIRECT_MEMORY_ACCESS */ - - -/* **************************************** -* Compiler-specific Functions and Macros -******************************************/ -#define XXH_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) - -/* Note : although _rotl exists for minGW (GCC under windows), performance seems poor */ -#if defined(_MSC_VER) -# define XXH_rotl32(x,r) _rotl(x,r) -# define XXH_rotl64(x,r) _rotl64(x,r) -#else -# define XXH_rotl32(x,r) ((x << r) | (x >> (32 - r))) -# define XXH_rotl64(x,r) ((x << r) | (x >> (64 - r))) -#endif - -#if defined(_MSC_VER) /* Visual Studio */ -# define XXH_swap32 _byteswap_ulong -#elif XXH_GCC_VERSION >= 403 -# define XXH_swap32 __builtin_bswap32 -#else -static U32 XXH_swap32 (U32 x) -{ - return ((x << 24) & 0xff000000 ) | - ((x << 8) & 0x00ff0000 ) | - ((x >> 8) & 0x0000ff00 ) | - ((x >> 24) & 0x000000ff ); -} -#endif - - -/* ************************************* -* Architecture Macros -***************************************/ -typedef enum { XXH_bigEndian=0, XXH_littleEndian=1 } XXH_endianess; - -/* XXH_CPU_LITTLE_ENDIAN can be defined externally, for example on the compiler command line */ -#ifndef XXH_CPU_LITTLE_ENDIAN - static const int g_one = 1; -# define XXH_CPU_LITTLE_ENDIAN (*(const char*)(&g_one)) -#endif - - -/* *************************** -* Memory reads -*****************************/ -typedef enum { XXH_aligned, XXH_unaligned } XXH_alignment; - -FORCE_INLINE U32 XXH_readLE32_align(const void* ptr, XXH_endianess endian, XXH_alignment align) -{ - if (align==XXH_unaligned) - return endian==XXH_littleEndian ? XXH_read32(ptr) : XXH_swap32(XXH_read32(ptr)); - else - return endian==XXH_littleEndian ? *(const U32*)ptr : XXH_swap32(*(const U32*)ptr); -} - -FORCE_INLINE U32 XXH_readLE32(const void* ptr, XXH_endianess endian) -{ - return XXH_readLE32_align(ptr, endian, XXH_unaligned); -} - -static U32 XXH_readBE32(const void* ptr) -{ - return XXH_CPU_LITTLE_ENDIAN ? XXH_swap32(XXH_read32(ptr)) : XXH_read32(ptr); -} - - -/* ************************************* -* Macros -***************************************/ -#define XXH_STATIC_ASSERT(c) { enum { XXH_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */ -XXH_PUBLIC_API unsigned XXH_versionNumber (void) { return XXH_VERSION_NUMBER; } - - -/* ******************************************************************* -* 32-bits hash functions -*********************************************************************/ -static const U32 PRIME32_1 = 2654435761U; -static const U32 PRIME32_2 = 2246822519U; -static const U32 PRIME32_3 = 3266489917U; -static const U32 PRIME32_4 = 668265263U; -static const U32 PRIME32_5 = 374761393U; - -static U32 XXH32_round(U32 seed, U32 input) -{ - seed += input * PRIME32_2; - seed = XXH_rotl32(seed, 13); - seed *= PRIME32_1; - return seed; -} - -FORCE_INLINE U32 XXH32_endian_align(const void* input, size_t len, U32 seed, XXH_endianess endian, XXH_alignment align) -{ - const BYTE* p = (const BYTE*)input; - const BYTE* bEnd = p + len; - U32 h32; -#define XXH_get32bits(p) XXH_readLE32_align(p, endian, align) - -#ifdef XXH_ACCEPT_NULL_INPUT_POINTER - if (p==NULL) { - len=0; - bEnd=p=(const BYTE*)(size_t)16; - } -#endif - - if (len>=16) { - const BYTE* const limit = bEnd - 16; - U32 v1 = seed + PRIME32_1 + PRIME32_2; - U32 v2 = seed + PRIME32_2; - U32 v3 = seed + 0; - U32 v4 = seed - PRIME32_1; - - do { - v1 = XXH32_round(v1, XXH_get32bits(p)); p+=4; - v2 = XXH32_round(v2, XXH_get32bits(p)); p+=4; - v3 = XXH32_round(v3, XXH_get32bits(p)); p+=4; - v4 = XXH32_round(v4, XXH_get32bits(p)); p+=4; - } while (p<=limit); - - h32 = XXH_rotl32(v1, 1) + XXH_rotl32(v2, 7) + XXH_rotl32(v3, 12) + XXH_rotl32(v4, 18); - } else { - h32 = seed + PRIME32_5; - } - - h32 += (U32) len; - - while (p+4<=bEnd) { - h32 += XXH_get32bits(p) * PRIME32_3; - h32 = XXH_rotl32(h32, 17) * PRIME32_4 ; - p+=4; - } - - while (p> 15; - h32 *= PRIME32_2; - h32 ^= h32 >> 13; - h32 *= PRIME32_3; - h32 ^= h32 >> 16; - - return h32; -} - - -XXH_PUBLIC_API unsigned int XXH32 (const void* input, size_t len, unsigned int seed) -{ -#if 0 - /* Simple version, good for code maintenance, but unfortunately slow for small inputs */ - XXH32_state_t state; - XXH32_reset(&state, seed); - XXH32_update(&state, input, len); - return XXH32_digest(&state); -#else - XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; - - if (XXH_FORCE_ALIGN_CHECK) { - if ((((size_t)input) & 3) == 0) { /* Input is 4-bytes aligned, leverage the speed benefit */ - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned); - else - return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned); - } } - - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned); - else - return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned); -#endif -} - - - -/*====== Hash streaming ======*/ - -XXH_PUBLIC_API XXH32_state_t* XXH32_createState(void) -{ - return (XXH32_state_t*)XXH_malloc(sizeof(XXH32_state_t)); -} -XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr) -{ - XXH_free(statePtr); - return XXH_OK; -} - -XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* dstState, const XXH32_state_t* srcState) -{ - memcpy(dstState, srcState, sizeof(*dstState)); -} - -XXH_PUBLIC_API XXH_errorcode XXH32_reset(XXH32_state_t* statePtr, unsigned int seed) -{ - XXH32_state_t state; /* using a local state to memcpy() in order to avoid strict-aliasing warnings */ - memset(&state, 0, sizeof(state)-4); /* do not write into reserved, for future removal */ - state.v1 = seed + PRIME32_1 + PRIME32_2; - state.v2 = seed + PRIME32_2; - state.v3 = seed + 0; - state.v4 = seed - PRIME32_1; - memcpy(statePtr, &state, sizeof(state)); - return XXH_OK; -} - - -FORCE_INLINE XXH_errorcode XXH32_update_endian (XXH32_state_t* state, const void* input, size_t len, XXH_endianess endian) -{ - const BYTE* p = (const BYTE*)input; - const BYTE* const bEnd = p + len; - -#ifdef XXH_ACCEPT_NULL_INPUT_POINTER - if (input==NULL) return XXH_ERROR; -#endif - - state->total_len_32 += (unsigned)len; - state->large_len |= (len>=16) | (state->total_len_32>=16); - - if (state->memsize + len < 16) { /* fill in tmp buffer */ - XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, len); - state->memsize += (unsigned)len; - return XXH_OK; - } - - if (state->memsize) { /* some data left from previous update */ - XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, 16-state->memsize); - { const U32* p32 = state->mem32; - state->v1 = XXH32_round(state->v1, XXH_readLE32(p32, endian)); p32++; - state->v2 = XXH32_round(state->v2, XXH_readLE32(p32, endian)); p32++; - state->v3 = XXH32_round(state->v3, XXH_readLE32(p32, endian)); p32++; - state->v4 = XXH32_round(state->v4, XXH_readLE32(p32, endian)); p32++; - } - p += 16-state->memsize; - state->memsize = 0; - } - - if (p <= bEnd-16) { - const BYTE* const limit = bEnd - 16; - U32 v1 = state->v1; - U32 v2 = state->v2; - U32 v3 = state->v3; - U32 v4 = state->v4; - - do { - v1 = XXH32_round(v1, XXH_readLE32(p, endian)); p+=4; - v2 = XXH32_round(v2, XXH_readLE32(p, endian)); p+=4; - v3 = XXH32_round(v3, XXH_readLE32(p, endian)); p+=4; - v4 = XXH32_round(v4, XXH_readLE32(p, endian)); p+=4; - } while (p<=limit); - - state->v1 = v1; - state->v2 = v2; - state->v3 = v3; - state->v4 = v4; - } - - if (p < bEnd) { - XXH_memcpy(state->mem32, p, (size_t)(bEnd-p)); - state->memsize = (unsigned)(bEnd-p); - } - - return XXH_OK; -} - -XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* state_in, const void* input, size_t len) -{ - XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; - - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH32_update_endian(state_in, input, len, XXH_littleEndian); - else - return XXH32_update_endian(state_in, input, len, XXH_bigEndian); -} - - - -FORCE_INLINE U32 XXH32_digest_endian (const XXH32_state_t* state, XXH_endianess endian) -{ - const BYTE * p = (const BYTE*)state->mem32; - const BYTE* const bEnd = (const BYTE*)(state->mem32) + state->memsize; - U32 h32; - - if (state->large_len) { - h32 = XXH_rotl32(state->v1, 1) + XXH_rotl32(state->v2, 7) + XXH_rotl32(state->v3, 12) + XXH_rotl32(state->v4, 18); - } else { - h32 = state->v3 /* == seed */ + PRIME32_5; - } - - h32 += state->total_len_32; - - while (p+4<=bEnd) { - h32 += XXH_readLE32(p, endian) * PRIME32_3; - h32 = XXH_rotl32(h32, 17) * PRIME32_4; - p+=4; - } - - while (p> 15; - h32 *= PRIME32_2; - h32 ^= h32 >> 13; - h32 *= PRIME32_3; - h32 ^= h32 >> 16; - - return h32; -} - - -XXH_PUBLIC_API unsigned int XXH32_digest (const XXH32_state_t* state_in) -{ - XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; - - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH32_digest_endian(state_in, XXH_littleEndian); - else - return XXH32_digest_endian(state_in, XXH_bigEndian); -} - - -/*====== Canonical representation ======*/ - -/*! Default XXH result types are basic unsigned 32 and 64 bits. -* The canonical representation follows human-readable write convention, aka big-endian (large digits first). -* These functions allow transformation of hash result into and from its canonical format. -* This way, hash values can be written into a file or buffer, and remain comparable across different systems and programs. -*/ - -XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash) -{ - XXH_STATIC_ASSERT(sizeof(XXH32_canonical_t) == sizeof(XXH32_hash_t)); - if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap32(hash); - memcpy(dst, &hash, sizeof(*dst)); -} - -XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src) -{ - return XXH_readBE32(src); -} - - -#ifndef XXH_NO_LONG_LONG - -/* ******************************************************************* -* 64-bits hash functions -*********************************************************************/ - -/*====== Memory access ======*/ - -#ifndef MEM_MODULE -# define MEM_MODULE -# if !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) -# include - typedef uint64_t U64; -# else - typedef unsigned long long U64; /* if your compiler doesn't support unsigned long long, replace by another 64-bit type here. Note that xxhash.h will also need to be updated. */ -# endif -#endif - - -#if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==2)) - -/* Force direct memory access. Only works on CPU which support unaligned memory access in hardware */ -static U64 XXH_read64(const void* memPtr) { return *(const U64*) memPtr; } - -#elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==1)) - -/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */ -/* currently only defined for gcc and icc */ -typedef union { U32 u32; U64 u64; } __attribute__((packed)) unalign64; -static U64 XXH_read64(const void* ptr) { return ((const unalign64*)ptr)->u64; } - -#else - -/* portable and safe solution. Generally efficient. - * see : http://stackoverflow.com/a/32095106/646947 - */ - -static U64 XXH_read64(const void* memPtr) -{ - U64 val; - memcpy(&val, memPtr, sizeof(val)); - return val; -} - -#endif /* XXH_FORCE_DIRECT_MEMORY_ACCESS */ - -#if defined(_MSC_VER) /* Visual Studio */ -# define XXH_swap64 _byteswap_uint64 -#elif XXH_GCC_VERSION >= 403 -# define XXH_swap64 __builtin_bswap64 -#else -static U64 XXH_swap64 (U64 x) -{ - return ((x << 56) & 0xff00000000000000ULL) | - ((x << 40) & 0x00ff000000000000ULL) | - ((x << 24) & 0x0000ff0000000000ULL) | - ((x << 8) & 0x000000ff00000000ULL) | - ((x >> 8) & 0x00000000ff000000ULL) | - ((x >> 24) & 0x0000000000ff0000ULL) | - ((x >> 40) & 0x000000000000ff00ULL) | - ((x >> 56) & 0x00000000000000ffULL); -} -#endif - -FORCE_INLINE U64 XXH_readLE64_align(const void* ptr, XXH_endianess endian, XXH_alignment align) -{ - if (align==XXH_unaligned) - return endian==XXH_littleEndian ? XXH_read64(ptr) : XXH_swap64(XXH_read64(ptr)); - else - return endian==XXH_littleEndian ? *(const U64*)ptr : XXH_swap64(*(const U64*)ptr); -} - -FORCE_INLINE U64 XXH_readLE64(const void* ptr, XXH_endianess endian) -{ - return XXH_readLE64_align(ptr, endian, XXH_unaligned); -} - -static U64 XXH_readBE64(const void* ptr) -{ - return XXH_CPU_LITTLE_ENDIAN ? XXH_swap64(XXH_read64(ptr)) : XXH_read64(ptr); -} - - -/*====== xxh64 ======*/ - -static const U64 PRIME64_1 = 11400714785074694791ULL; -static const U64 PRIME64_2 = 14029467366897019727ULL; -static const U64 PRIME64_3 = 1609587929392839161ULL; -static const U64 PRIME64_4 = 9650029242287828579ULL; -static const U64 PRIME64_5 = 2870177450012600261ULL; - -static U64 XXH64_round(U64 acc, U64 input) -{ - acc += input * PRIME64_2; - acc = XXH_rotl64(acc, 31); - acc *= PRIME64_1; - return acc; -} - -static U64 XXH64_mergeRound(U64 acc, U64 val) -{ - val = XXH64_round(0, val); - acc ^= val; - acc = acc * PRIME64_1 + PRIME64_4; - return acc; -} - -FORCE_INLINE U64 XXH64_endian_align(const void* input, size_t len, U64 seed, XXH_endianess endian, XXH_alignment align) -{ - const BYTE* p = (const BYTE*)input; - const BYTE* const bEnd = p + len; - U64 h64; -#define XXH_get64bits(p) XXH_readLE64_align(p, endian, align) - -#ifdef XXH_ACCEPT_NULL_INPUT_POINTER - if (p==NULL) { - len=0; - bEnd=p=(const BYTE*)(size_t)32; - } -#endif - - if (len>=32) { - const BYTE* const limit = bEnd - 32; - U64 v1 = seed + PRIME64_1 + PRIME64_2; - U64 v2 = seed + PRIME64_2; - U64 v3 = seed + 0; - U64 v4 = seed - PRIME64_1; - - do { - v1 = XXH64_round(v1, XXH_get64bits(p)); p+=8; - v2 = XXH64_round(v2, XXH_get64bits(p)); p+=8; - v3 = XXH64_round(v3, XXH_get64bits(p)); p+=8; - v4 = XXH64_round(v4, XXH_get64bits(p)); p+=8; - } while (p<=limit); - - h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18); - h64 = XXH64_mergeRound(h64, v1); - h64 = XXH64_mergeRound(h64, v2); - h64 = XXH64_mergeRound(h64, v3); - h64 = XXH64_mergeRound(h64, v4); - - } else { - h64 = seed + PRIME64_5; - } - - h64 += (U64) len; - - while (p+8<=bEnd) { - U64 const k1 = XXH64_round(0, XXH_get64bits(p)); - h64 ^= k1; - h64 = XXH_rotl64(h64,27) * PRIME64_1 + PRIME64_4; - p+=8; - } - - if (p+4<=bEnd) { - h64 ^= (U64)(XXH_get32bits(p)) * PRIME64_1; - h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3; - p+=4; - } - - while (p> 33; - h64 *= PRIME64_2; - h64 ^= h64 >> 29; - h64 *= PRIME64_3; - h64 ^= h64 >> 32; - - return h64; -} - - -XXH_PUBLIC_API unsigned long long XXH64 (const void* input, size_t len, unsigned long long seed) -{ -#if 0 - /* Simple version, good for code maintenance, but unfortunately slow for small inputs */ - XXH64_state_t state; - XXH64_reset(&state, seed); - XXH64_update(&state, input, len); - return XXH64_digest(&state); -#else - XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; - - if (XXH_FORCE_ALIGN_CHECK) { - if ((((size_t)input) & 7)==0) { /* Input is aligned, let's leverage the speed advantage */ - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned); - else - return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned); - } } - - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned); - else - return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned); -#endif -} - -/*====== Hash Streaming ======*/ - -XXH_PUBLIC_API XXH64_state_t* XXH64_createState(void) -{ - return (XXH64_state_t*)XXH_malloc(sizeof(XXH64_state_t)); -} -XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr) -{ - XXH_free(statePtr); - return XXH_OK; -} - -XXH_PUBLIC_API void XXH64_copyState(XXH64_state_t* dstState, const XXH64_state_t* srcState) -{ - memcpy(dstState, srcState, sizeof(*dstState)); -} - -XXH_PUBLIC_API XXH_errorcode XXH64_reset(XXH64_state_t* statePtr, unsigned long long seed) -{ - XXH64_state_t state; /* using a local state to memcpy() in order to avoid strict-aliasing warnings */ - memset(&state, 0, sizeof(state)-8); /* do not write into reserved, for future removal */ - state.v1 = seed + PRIME64_1 + PRIME64_2; - state.v2 = seed + PRIME64_2; - state.v3 = seed + 0; - state.v4 = seed - PRIME64_1; - memcpy(statePtr, &state, sizeof(state)); - return XXH_OK; -} - -FORCE_INLINE XXH_errorcode XXH64_update_endian (XXH64_state_t* state, const void* input, size_t len, XXH_endianess endian) -{ - const BYTE* p = (const BYTE*)input; - const BYTE* const bEnd = p + len; - -#ifdef XXH_ACCEPT_NULL_INPUT_POINTER - if (input==NULL) return XXH_ERROR; -#endif - - state->total_len += len; - - if (state->memsize + len < 32) { /* fill in tmp buffer */ - XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, len); - state->memsize += (U32)len; - return XXH_OK; - } - - if (state->memsize) { /* tmp buffer is full */ - XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, 32-state->memsize); - state->v1 = XXH64_round(state->v1, XXH_readLE64(state->mem64+0, endian)); - state->v2 = XXH64_round(state->v2, XXH_readLE64(state->mem64+1, endian)); - state->v3 = XXH64_round(state->v3, XXH_readLE64(state->mem64+2, endian)); - state->v4 = XXH64_round(state->v4, XXH_readLE64(state->mem64+3, endian)); - p += 32-state->memsize; - state->memsize = 0; - } - - if (p+32 <= bEnd) { - const BYTE* const limit = bEnd - 32; - U64 v1 = state->v1; - U64 v2 = state->v2; - U64 v3 = state->v3; - U64 v4 = state->v4; - - do { - v1 = XXH64_round(v1, XXH_readLE64(p, endian)); p+=8; - v2 = XXH64_round(v2, XXH_readLE64(p, endian)); p+=8; - v3 = XXH64_round(v3, XXH_readLE64(p, endian)); p+=8; - v4 = XXH64_round(v4, XXH_readLE64(p, endian)); p+=8; - } while (p<=limit); - - state->v1 = v1; - state->v2 = v2; - state->v3 = v3; - state->v4 = v4; - } - - if (p < bEnd) { - XXH_memcpy(state->mem64, p, (size_t)(bEnd-p)); - state->memsize = (unsigned)(bEnd-p); - } - - return XXH_OK; -} - -XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH64_state_t* state_in, const void* input, size_t len) -{ - XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; - - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH64_update_endian(state_in, input, len, XXH_littleEndian); - else - return XXH64_update_endian(state_in, input, len, XXH_bigEndian); -} - -FORCE_INLINE U64 XXH64_digest_endian (const XXH64_state_t* state, XXH_endianess endian) -{ - const BYTE * p = (const BYTE*)state->mem64; - const BYTE* const bEnd = (const BYTE*)state->mem64 + state->memsize; - U64 h64; - - if (state->total_len >= 32) { - U64 const v1 = state->v1; - U64 const v2 = state->v2; - U64 const v3 = state->v3; - U64 const v4 = state->v4; - - h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18); - h64 = XXH64_mergeRound(h64, v1); - h64 = XXH64_mergeRound(h64, v2); - h64 = XXH64_mergeRound(h64, v3); - h64 = XXH64_mergeRound(h64, v4); - } else { - h64 = state->v3 + PRIME64_5; - } - - h64 += (U64) state->total_len; - - while (p+8<=bEnd) { - U64 const k1 = XXH64_round(0, XXH_readLE64(p, endian)); - h64 ^= k1; - h64 = XXH_rotl64(h64,27) * PRIME64_1 + PRIME64_4; - p+=8; - } - - if (p+4<=bEnd) { - h64 ^= (U64)(XXH_readLE32(p, endian)) * PRIME64_1; - h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3; - p+=4; - } - - while (p> 33; - h64 *= PRIME64_2; - h64 ^= h64 >> 29; - h64 *= PRIME64_3; - h64 ^= h64 >> 32; - - return h64; -} - -XXH_PUBLIC_API unsigned long long XXH64_digest (const XXH64_state_t* state_in) -{ - XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; - - if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) - return XXH64_digest_endian(state_in, XXH_littleEndian); - else - return XXH64_digest_endian(state_in, XXH_bigEndian); -} - - -/*====== Canonical representation ======*/ - -XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH64_canonical_t* dst, XXH64_hash_t hash) -{ - XXH_STATIC_ASSERT(sizeof(XXH64_canonical_t) == sizeof(XXH64_hash_t)); - if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap64(hash); - memcpy(dst, &hash, sizeof(*dst)); -} - -XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src) -{ - return XXH_readBE64(src); -} - -#endif /* XXH_NO_LONG_LONG */ diff --git a/src/lz4/lib/xxhash.h b/src/lz4/lib/xxhash.h deleted file mode 100644 index 870a6d910c..0000000000 --- a/src/lz4/lib/xxhash.h +++ /dev/null @@ -1,293 +0,0 @@ -/* - xxHash - Extremely Fast Hash algorithm - Header File - Copyright (C) 2012-2016, Yann Collet. - - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - xxHash source repository : https://github.com/Cyan4973/xxHash -*/ - -/* Notice extracted from xxHash homepage : - -xxHash is an extremely fast Hash algorithm, running at RAM speed limits. -It also successfully passes all tests from the SMHasher suite. - -Comparison (single thread, Windows Seven 32 bits, using SMHasher on a Core 2 Duo @3GHz) - -Name Speed Q.Score Author -xxHash 5.4 GB/s 10 -CrapWow 3.2 GB/s 2 Andrew -MumurHash 3a 2.7 GB/s 10 Austin Appleby -SpookyHash 2.0 GB/s 10 Bob Jenkins -SBox 1.4 GB/s 9 Bret Mulvey -Lookup3 1.2 GB/s 9 Bob Jenkins -SuperFastHash 1.2 GB/s 1 Paul Hsieh -CityHash64 1.05 GB/s 10 Pike & Alakuijala -FNV 0.55 GB/s 5 Fowler, Noll, Vo -CRC32 0.43 GB/s 9 -MD5-32 0.33 GB/s 10 Ronald L. Rivest -SHA1-32 0.28 GB/s 10 - -Q.Score is a measure of quality of the hash function. -It depends on successfully passing SMHasher test set. -10 is a perfect score. - -A 64-bits version, named XXH64, is available since r35. -It offers much better speed, but for 64-bits applications only. -Name Speed on 64 bits Speed on 32 bits -XXH64 13.8 GB/s 1.9 GB/s -XXH32 6.8 GB/s 6.0 GB/s -*/ - -#ifndef XXHASH_H_5627135585666179 -#define XXHASH_H_5627135585666179 1 - -#if defined (__cplusplus) -extern "C" { -#endif - - -/* **************************** -* Definitions -******************************/ -#include /* size_t */ -typedef enum { XXH_OK=0, XXH_ERROR } XXH_errorcode; - - -/* **************************** -* API modifier -******************************/ -/** XXH_PRIVATE_API -* This is useful to include xxhash functions in `static` mode -* in order to inline them, and remove their symbol from the public list. -* Methodology : -* #define XXH_PRIVATE_API -* #include "xxhash.h" -* `xxhash.c` is automatically included. -* It's not useful to compile and link it as a separate module. -*/ -#ifdef XXH_PRIVATE_API -# ifndef XXH_STATIC_LINKING_ONLY -# define XXH_STATIC_LINKING_ONLY -# endif -# if defined(__GNUC__) -# define XXH_PUBLIC_API static __inline __attribute__((unused)) -# elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) -# define XXH_PUBLIC_API static inline -# elif defined(_MSC_VER) -# define XXH_PUBLIC_API static __inline -# else -# define XXH_PUBLIC_API static /* this version may generate warnings for unused static functions; disable the relevant warning */ -# endif -#else -# define XXH_PUBLIC_API /* do nothing */ -#endif /* XXH_PRIVATE_API */ - -/*!XXH_NAMESPACE, aka Namespace Emulation : - -If you want to include _and expose_ xxHash functions from within your own library, -but also want to avoid symbol collisions with other libraries which may also include xxHash, - -you can use XXH_NAMESPACE, to automatically prefix any public symbol from xxhash library -with the value of XXH_NAMESPACE (therefore, avoid NULL and numeric values). - -Note that no change is required within the calling program as long as it includes `xxhash.h` : -regular symbol name will be automatically translated by this header. -*/ -#ifdef XXH_NAMESPACE -# define XXH_CAT(A,B) A##B -# define XXH_NAME2(A,B) XXH_CAT(A,B) -# define XXH_versionNumber XXH_NAME2(XXH_NAMESPACE, XXH_versionNumber) -# define XXH32 XXH_NAME2(XXH_NAMESPACE, XXH32) -# define XXH32_createState XXH_NAME2(XXH_NAMESPACE, XXH32_createState) -# define XXH32_freeState XXH_NAME2(XXH_NAMESPACE, XXH32_freeState) -# define XXH32_reset XXH_NAME2(XXH_NAMESPACE, XXH32_reset) -# define XXH32_update XXH_NAME2(XXH_NAMESPACE, XXH32_update) -# define XXH32_digest XXH_NAME2(XXH_NAMESPACE, XXH32_digest) -# define XXH32_copyState XXH_NAME2(XXH_NAMESPACE, XXH32_copyState) -# define XXH32_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH32_canonicalFromHash) -# define XXH32_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH32_hashFromCanonical) -# define XXH64 XXH_NAME2(XXH_NAMESPACE, XXH64) -# define XXH64_createState XXH_NAME2(XXH_NAMESPACE, XXH64_createState) -# define XXH64_freeState XXH_NAME2(XXH_NAMESPACE, XXH64_freeState) -# define XXH64_reset XXH_NAME2(XXH_NAMESPACE, XXH64_reset) -# define XXH64_update XXH_NAME2(XXH_NAMESPACE, XXH64_update) -# define XXH64_digest XXH_NAME2(XXH_NAMESPACE, XXH64_digest) -# define XXH64_copyState XXH_NAME2(XXH_NAMESPACE, XXH64_copyState) -# define XXH64_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH64_canonicalFromHash) -# define XXH64_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH64_hashFromCanonical) -#endif - - -/* ************************************* -* Version -***************************************/ -#define XXH_VERSION_MAJOR 0 -#define XXH_VERSION_MINOR 6 -#define XXH_VERSION_RELEASE 2 -#define XXH_VERSION_NUMBER (XXH_VERSION_MAJOR *100*100 + XXH_VERSION_MINOR *100 + XXH_VERSION_RELEASE) -XXH_PUBLIC_API unsigned XXH_versionNumber (void); - - -/*-********************************************************************** -* 32-bits hash -************************************************************************/ -typedef unsigned int XXH32_hash_t; - -/*! XXH32() : - Calculate the 32-bits hash of sequence "length" bytes stored at memory address "input". - The memory between input & input+length must be valid (allocated and read-accessible). - "seed" can be used to alter the result predictably. - Speed on Core 2 Duo @ 3 GHz (single thread, SMHasher benchmark) : 5.4 GB/s */ -XXH_PUBLIC_API XXH32_hash_t XXH32 (const void* input, size_t length, unsigned int seed); - -/*====== Streaming ======*/ -typedef struct XXH32_state_s XXH32_state_t; /* incomplete type */ -XXH_PUBLIC_API XXH32_state_t* XXH32_createState(void); -XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr); -XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* dst_state, const XXH32_state_t* src_state); - -XXH_PUBLIC_API XXH_errorcode XXH32_reset (XXH32_state_t* statePtr, unsigned int seed); -XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* statePtr, const void* input, size_t length); -XXH_PUBLIC_API XXH32_hash_t XXH32_digest (const XXH32_state_t* statePtr); - -/* -These functions generate the xxHash of an input provided in multiple segments. -Note that, for small input, they are slower than single-call functions, due to state management. -For small input, prefer `XXH32()` and `XXH64()` . - -XXH state must first be allocated, using XXH*_createState() . - -Start a new hash by initializing state with a seed, using XXH*_reset(). - -Then, feed the hash state by calling XXH*_update() as many times as necessary. -Obviously, input must be allocated and read accessible. -The function returns an error code, with 0 meaning OK, and any other value meaning there is an error. - -Finally, a hash value can be produced anytime, by using XXH*_digest(). -This function returns the nn-bits hash as an int or long long. - -It's still possible to continue inserting input into the hash state after a digest, -and generate some new hashes later on, by calling again XXH*_digest(). - -When done, free XXH state space if it was allocated dynamically. -*/ - -/*====== Canonical representation ======*/ - -typedef struct { unsigned char digest[4]; } XXH32_canonical_t; -XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash); -XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src); - -/* Default result type for XXH functions are primitive unsigned 32 and 64 bits. -* The canonical representation uses human-readable write convention, aka big-endian (large digits first). -* These functions allow transformation of hash result into and from its canonical format. -* This way, hash values can be written into a file / memory, and remain comparable on different systems and programs. -*/ - - -#ifndef XXH_NO_LONG_LONG -/*-********************************************************************** -* 64-bits hash -************************************************************************/ -typedef unsigned long long XXH64_hash_t; - -/*! XXH64() : - Calculate the 64-bits hash of sequence of length "len" stored at memory address "input". - "seed" can be used to alter the result predictably. - This function runs faster on 64-bits systems, but slower on 32-bits systems (see benchmark). -*/ -XXH_PUBLIC_API XXH64_hash_t XXH64 (const void* input, size_t length, unsigned long long seed); - -/*====== Streaming ======*/ -typedef struct XXH64_state_s XXH64_state_t; /* incomplete type */ -XXH_PUBLIC_API XXH64_state_t* XXH64_createState(void); -XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr); -XXH_PUBLIC_API void XXH64_copyState(XXH64_state_t* dst_state, const XXH64_state_t* src_state); - -XXH_PUBLIC_API XXH_errorcode XXH64_reset (XXH64_state_t* statePtr, unsigned long long seed); -XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH64_state_t* statePtr, const void* input, size_t length); -XXH_PUBLIC_API XXH64_hash_t XXH64_digest (const XXH64_state_t* statePtr); - -/*====== Canonical representation ======*/ -typedef struct { unsigned char digest[8]; } XXH64_canonical_t; -XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH64_canonical_t* dst, XXH64_hash_t hash); -XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src); -#endif /* XXH_NO_LONG_LONG */ - - -#ifdef XXH_STATIC_LINKING_ONLY - -/* ================================================================================================ - This section contains definitions which are not guaranteed to remain stable. - They may change in future versions, becoming incompatible with a different version of the library. - They shall only be used with static linking. - Never use these definitions in association with dynamic linking ! -=================================================================================================== */ - -/* These definitions are only meant to allow allocation of XXH state - statically, on stack, or in a struct for example. - Do not use members directly. */ - - struct XXH32_state_s { - unsigned total_len_32; - unsigned large_len; - unsigned v1; - unsigned v2; - unsigned v3; - unsigned v4; - unsigned mem32[4]; /* buffer defined as U32 for alignment */ - unsigned memsize; - unsigned reserved; /* never read nor write, will be removed in a future version */ - }; /* typedef'd to XXH32_state_t */ - -#ifndef XXH_NO_LONG_LONG - struct XXH64_state_s { - unsigned long long total_len; - unsigned long long v1; - unsigned long long v2; - unsigned long long v3; - unsigned long long v4; - unsigned long long mem64[4]; /* buffer defined as U64 for alignment */ - unsigned memsize; - unsigned reserved[2]; /* never read nor write, will be removed in a future version */ - }; /* typedef'd to XXH64_state_t */ -#endif - -# ifdef XXH_PRIVATE_API -# include "xxhash.c" /* include xxhash function bodies as `static`, for inlining */ -# endif - -#endif /* XXH_STATIC_LINKING_ONLY */ - - -#if defined (__cplusplus) -} -#endif - -#endif /* XXHASH_H_5627135585666179 */ diff --git a/src/lz4/programs/.gitignore b/src/lz4/programs/.gitignore deleted file mode 100644 index daa7f14840..0000000000 --- a/src/lz4/programs/.gitignore +++ /dev/null @@ -1,20 +0,0 @@ -# local binary (Makefile) -lz4 -unlz4 -lz4cat -lz4c -lz4c32 -datagen -frametest -frametest32 -fullbench -fullbench32 -fuzzer -fuzzer32 -*.exe - -# tests files -tmp* - -# artefacts -*.dSYM diff --git a/src/lz4/programs/COPYING b/src/lz4/programs/COPYING deleted file mode 100644 index d159169d10..0000000000 --- a/src/lz4/programs/COPYING +++ /dev/null @@ -1,339 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 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. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, 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 or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -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 give any other recipients of the Program a copy of this License -along with the Program. - -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 Program or any portion -of it, thus forming a work based on the Program, 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) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -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 Program, 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 Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) 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; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, 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 executable. However, as a -special exception, the source code 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. - -If distribution of executable or 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 counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program 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. - - 5. 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 Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program 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 to -this License. - - 7. 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 Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program 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 Program. - -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. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program 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. - - 9. The Free Software Foundation may publish revised and/or new versions -of the 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 Program -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 Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, 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 - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "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 PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. 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 PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), 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 Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. 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 program is free software; 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-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. diff --git a/src/lz4/programs/Makefile b/src/lz4/programs/Makefile deleted file mode 100644 index c7ef6d114c..0000000000 --- a/src/lz4/programs/Makefile +++ /dev/null @@ -1,172 +0,0 @@ -# ########################################################################## -# LZ4 programs - Makefile -# Copyright (C) Yann Collet 2011-2016 -# -# This Makefile is validated for Linux, macOS, *BSD, Hurd, Solaris, MSYS2 targets -# -# GPL v2 License -# -# This program is free software; 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-1301 USA. -# -# You can contact the author at : -# - LZ4 homepage : http://www.lz4.org -# - LZ4 source repository : https://github.com/Cyan4973/lz4 -# ########################################################################## -# lz4 : Command Line Utility, supporting gzip-like arguments -# lz4c : CLU, supporting also legacy lz4demo arguments -# lz4c32: Same as lz4c, but forced to compile in 32-bits mode -# ########################################################################## - -# Version numbers -LZ4DIR := ../lib -LIBVER_SRC := $(LZ4DIR)/lz4.h -LIBVER_MAJOR_SCRIPT:=`sed -n '/define LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)` -LIBVER_MINOR_SCRIPT:=`sed -n '/define LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)` -LIBVER_PATCH_SCRIPT:=`sed -n '/define LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)` -LIBVER_SCRIPT:= $(LIBVER_MAJOR_SCRIPT).$(LIBVER_MINOR_SCRIPT).$(LIBVER_PATCH_SCRIPT) -LIBVER_MAJOR := $(shell echo $(LIBVER_MAJOR_SCRIPT)) -LIBVER_MINOR := $(shell echo $(LIBVER_MINOR_SCRIPT)) -LIBVER_PATCH := $(shell echo $(LIBVER_PATCH_SCRIPT)) -LIBVER := $(shell echo $(LIBVER_SCRIPT)) - -SRCFILES := $(wildcard $(LZ4DIR)/*.c) $(wildcard *.c) -OBJFILES := $(patsubst %.c,%.o,$(SRCFILES)) - -CPPFLAGS += -I$(LZ4DIR) -DXXH_NAMESPACE=LZ4_ -CFLAGS ?= -O3 -DEBUGFLAGS:=-Wall -Wextra -Wundef -Wcast-qual -Wcast-align -Wshadow \ - -Wswitch-enum -Wdeclaration-after-statement -Wstrict-prototypes \ - -Wpointer-arith -Wstrict-aliasing=1 -CFLAGS += $(DEBUGFLAGS) $(MOREFLAGS) -FLAGS = $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) - -LZ4_VERSION=$(LIBVER) -MD2ROFF = ronn -MD2ROFF_FLAGS = --roff --warnings --manual="User Commands" --organization="lz4 $(LZ4_VERSION)" - - -# Define *.exe as extension for Windows systems -ifneq (,$(filter Windows%,$(OS))) -EXT :=.exe -VOID := nul -else -EXT := -VOID := /dev/null -endif - - - -default: lz4-release - -all: lz4 lz4c - -all32: CFLAGS+=-m32 -all32: all - -lz4: $(OBJFILES) - $(CC) $(FLAGS) $^ -o $@$(EXT) - -lz4-release: DEBUGFLAGS= -lz4-release: lz4 - -lz4c32: CFLAGS += -m32 -lz4c32 : $(SRCFILES) - $(CC) $(FLAGS) $^ -o $@$(EXT) - -lz4c: lz4 - ln -s lz4 lz4c - -lz4.1: lz4.1.md - cat $^ | $(MD2ROFF) $(MD2ROFF_FLAGS) | sed -n '/^\.\\\".*/!p' > $@ - -man: lz4.1 - -clean-man: - rm lz4.1 - -preview-man: clean-man man - man ./lz4.1 - -clean: - @$(MAKE) -C $(LZ4DIR) $@ > $(VOID) - @$(RM) core *.o *.test tmp* \ - lz4$(EXT) lz4c$(EXT) lz4c32$(EXT) unlz4 lz4cat - @echo Cleaning completed - - -#----------------------------------------------------------------------------- -# make install is validated only for Linux, OSX, BSD, Hurd and Solaris targets -#----------------------------------------------------------------------------- -ifneq (,$(filter $(shell uname),Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD NetBSD DragonFly SunOS)) - -unlz4: lz4 - ln -s lz4 unlz4 - -lz4cat: lz4 - ln -s lz4 lz4cat - -ifneq (,$(filter $(shell uname),SunOS)) -INSTALL ?= ginstall -else -INSTALL ?= install -endif - -DESTDIR ?= -# directory variables : GNU convention prefers lowercase -# support both lower and uppercase (BSD), use uppercase in script -prefix ?= /usr/local -PREFIX ?= $(prefix) -exec_prefix ?= $(PREFIX) -bindir ?= $(exec_prefix)/bin -BINDIR ?= $(bindir) -datarootdir ?= $(PREFIX)/share -mandir ?= $(datarootdir)/man - -ifneq (,$(filter $(shell uname),OpenBSD FreeBSD NetBSD DragonFly SunOS)) -MANDIR ?= $(PREFIX)/man/man1 -else -MANDIR ?= $(mandir) -endif - -INSTALL_PROGRAM ?= $(INSTALL) -m 755 -INSTALL_DATA ?= $(INSTALL) -m 644 - - -install: lz4$(EXT) lz4c$(EXT) - @echo Installing binaries - @$(INSTALL) -d -m 755 $(DESTDIR)$(BINDIR)/ $(DESTDIR)$(MANDIR)/ - @$(INSTALL_PROGRAM) lz4 $(DESTDIR)$(BINDIR)/lz4 - @ln -sf lz4 $(DESTDIR)$(BINDIR)/lz4cat - @ln -sf lz4 $(DESTDIR)$(BINDIR)/unlz4 - @$(INSTALL_PROGRAM) lz4c$(EXT) $(DESTDIR)$(BINDIR)/lz4c - @echo Installing man pages - @$(INSTALL_DATA) lz4.1 $(DESTDIR)$(MANDIR)/lz4.1 - @ln -sf lz4.1 $(DESTDIR)$(MANDIR)/lz4c.1 - @ln -sf lz4.1 $(DESTDIR)$(MANDIR)/lz4cat.1 - @ln -sf lz4.1 $(DESTDIR)$(MANDIR)/unlz4.1 - @echo lz4 installation completed - -uninstall: - @$(RM) $(DESTDIR)$(BINDIR)/lz4cat - @$(RM) $(DESTDIR)$(BINDIR)/unlz4 - @$(RM) $(DESTDIR)$(BINDIR)/lz4 - @$(RM) $(DESTDIR)$(BINDIR)/lz4c - @$(RM) $(DESTDIR)$(MANDIR)/lz4.1 - @$(RM) $(DESTDIR)$(MANDIR)/lz4c.1 - @$(RM) $(DESTDIR)$(MANDIR)/lz4cat.1 - @$(RM) $(DESTDIR)$(MANDIR)/unlz4.1 - @echo lz4 programs successfully uninstalled - -endif diff --git a/src/lz4/programs/README.md b/src/lz4/programs/README.md deleted file mode 100644 index 2ad04496b1..0000000000 --- a/src/lz4/programs/README.md +++ /dev/null @@ -1,71 +0,0 @@ -Command Line Interface for LZ4 library -============================================ - -Command Line Interface (CLI) can be created using the `make` command without any additional parameters. -There are also multiple targets that create different variations of CLI: -- `lz4` : default CLI, with a command line syntax close to gzip -- `lz4c` : Same as `lz4` with additional support legacy lz4 commands (incompatible with gzip) -- `lz4c32` : Same as `lz4c`, but forced to compile in 32-bits mode - - -#### Aggregation of parameters -CLI supports aggregation of parameters i.e. `-b1`, `-e18`, and `-i1` can be joined into `-b1e18i1`. - - - -#### Benchmark in Command Line Interface -CLI includes in-memory compression benchmark module for lz4. -The benchmark is conducted using a given filename. -The file is read into memory. -It makes benchmark more precise as it eliminates I/O overhead. - -The benchmark measures ratio, compressed size, compression and decompression speed. -One can select compression levels starting from `-b` and ending with `-e`. -The `-i` parameter selects a number of seconds used for each of tested levels. - - - -#### Usage of Command Line Interface -The full list of commands can be obtained with `-h` or `-H` parameter: -``` -Usage : - lz4 [arg] [input] [output] - -input : a filename - with no FILE, or when FILE is - or stdin, read standard input -Arguments : - -1 : Fast compression (default) - -9 : High compression - -d : decompression (default for .lz4 extension) - -z : force compression - -f : overwrite output without prompting ---rm : remove source file(s) after successful de/compression - -h/-H : display help/long help and exit - -Advanced arguments : - -V : display Version number and exit - -v : verbose mode - -q : suppress warnings; specify twice to suppress errors too - -c : force write to standard output, even if it is the console - -t : test compressed file integrity - -m : multiple input files (implies automatic output filenames) - -r : operate recursively on directories (sets also -m) - -l : compress using Legacy format (Linux kernel compression) - -B# : Block size [4-7] (default : 7) - -BD : Block dependency (improve compression ratio) ---no-frame-crc : disable stream checksum (default:enabled) ---content-size : compressed frame includes original size (default:not present) ---[no-]sparse : sparse mode (default:enabled on file, disabled on stdout) -Benchmark arguments : - -b# : benchmark file(s), using # compression level (default : 1) - -e# : test all compression levels from -bX to # (default : 1) - -i# : minimum evaluation time in seconds (default : 3s) - -B# : cut file into independent blocks of size # bytes [32+] - or predefined block size [4-7] (default: 7) -``` - -#### License - -All files in this directory are licensed under GPL-v2. -See [COPYING](COPYING) for details. -The text of the license is also included at the top of each source file. diff --git a/src/lz4/programs/bench.c b/src/lz4/programs/bench.c deleted file mode 100644 index 77a9e3f27a..0000000000 --- a/src/lz4/programs/bench.c +++ /dev/null @@ -1,521 +0,0 @@ -/* - bench.c - Demo program to benchmark open-source compression algorithms - Copyright (C) Yann Collet 2012-2016 - - GPL v2 License - - This program is free software; 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-1301 USA. - - You can contact the author at : - - LZ4 homepage : http://www.lz4.org - - LZ4 source repository : https://github.com/lz4/lz4 -*/ - - -/*-************************************ -* Compiler options -**************************************/ -#ifdef _MSC_VER /* Visual Studio */ -# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ -#endif - - -/* ************************************* -* Includes -***************************************/ -#include "platform.h" /* Compiler options */ -#include "util.h" /* UTIL_GetFileSize, UTIL_sleep */ -#include /* malloc, free */ -#include /* memset */ -#include /* fprintf, fopen, ftello */ -#include /* clock_t, clock, CLOCKS_PER_SEC */ - -#include "datagen.h" /* RDG_genBuffer */ -#include "xxhash.h" - - -#include "lz4.h" -#define COMPRESSOR0 LZ4_compress_local -static int LZ4_compress_local(const char* src, char* dst, int srcSize, int dstSize, int clevel) { (void)clevel; return LZ4_compress_default(src, dst, srcSize, dstSize); } -#include "lz4hc.h" -#define COMPRESSOR1 LZ4_compress_HC -#define DEFAULTCOMPRESSOR COMPRESSOR0 -#define LZ4_isError(errcode) (errcode==0) - - -/* ************************************* -* Constants -***************************************/ -#ifndef LZ4_GIT_COMMIT_STRING -# define LZ4_GIT_COMMIT_STRING "" -#else -# define LZ4_GIT_COMMIT_STRING LZ4_EXPAND_AND_QUOTE(LZ4_GIT_COMMIT) -#endif - -#define NBSECONDS 3 -#define TIMELOOP_MICROSEC 1*1000000ULL /* 1 second */ -#define ACTIVEPERIOD_MICROSEC 70*1000000ULL /* 70 seconds */ -#define COOLPERIOD_SEC 10 -#define DECOMP_MULT 2 /* test decompression DECOMP_MULT times longer than compression */ - -#define KB *(1 <<10) -#define MB *(1 <<20) -#define GB *(1U<<30) - -static const size_t maxMemory = (sizeof(size_t)==4) ? (2 GB - 64 MB) : (size_t)(1ULL << ((sizeof(size_t)*8)-31)); - -static U32 g_compressibilityDefault = 50; - - -/* ************************************* -* console display -***************************************/ -#define DISPLAY(...) fprintf(stderr, __VA_ARGS__) -#define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); } -static U32 g_displayLevel = 2; /* 0 : no display; 1: errors; 2 : + result + interaction + warnings; 3 : + progression; 4 : + information */ - -#define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \ - if ((clock() - g_time > refreshRate) || (g_displayLevel>=4)) \ - { g_time = clock(); DISPLAY(__VA_ARGS__); \ - if (g_displayLevel>=4) fflush(stdout); } } -static const clock_t refreshRate = CLOCKS_PER_SEC * 15 / 100; -static clock_t g_time = 0; - - -/* ************************************* -* Exceptions -***************************************/ -#ifndef DEBUG -# define DEBUG 0 -#endif -#define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__); -#define EXM_THROW(error, ...) \ -{ \ - DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \ - DISPLAYLEVEL(1, "Error %i : ", error); \ - DISPLAYLEVEL(1, __VA_ARGS__); \ - DISPLAYLEVEL(1, "\n"); \ - exit(error); \ -} - - -/* ************************************* -* Benchmark Parameters -***************************************/ -static U32 g_nbSeconds = NBSECONDS; -static size_t g_blockSize = 0; -int g_additionalParam = 0; - -void BMK_setNotificationLevel(unsigned level) { g_displayLevel=level; } - -void BMK_setAdditionalParam(int additionalParam) { g_additionalParam=additionalParam; } - -void BMK_SetNbSeconds(unsigned nbSeconds) -{ - g_nbSeconds = nbSeconds; - DISPLAYLEVEL(3, "- test >= %u seconds per compression / decompression -\n", g_nbSeconds); -} - -void BMK_SetBlockSize(size_t blockSize) -{ - g_blockSize = blockSize; -} - - -/* ******************************************************** -* Bench functions -**********************************************************/ -typedef struct { - const char* srcPtr; - size_t srcSize; - char* cPtr; - size_t cRoom; - size_t cSize; - char* resPtr; - size_t resSize; -} blockParam_t; - -struct compressionParameters -{ - int (*compressionFunction)(const char* src, char* dst, int srcSize, int dstSize, int cLevel); -}; - -#define MIN(a,b) ((a)<(b) ? (a) : (b)) -#define MAX(a,b) ((a)>(b) ? (a) : (b)) - -static int BMK_benchMem(const void* srcBuffer, size_t srcSize, - const char* displayName, int cLevel, - const size_t* fileSizes, U32 nbFiles) -{ - size_t const blockSize = (g_blockSize>=32 ? g_blockSize : srcSize) + (!srcSize) /* avoid div by 0 */ ; - U32 const maxNbBlocks = (U32) ((srcSize + (blockSize-1)) / blockSize) + nbFiles; - blockParam_t* const blockTable = (blockParam_t*) malloc(maxNbBlocks * sizeof(blockParam_t)); - size_t const maxCompressedSize = LZ4_compressBound((int)srcSize) + (maxNbBlocks * 1024); /* add some room for safety */ - void* const compressedBuffer = malloc(maxCompressedSize); - void* const resultBuffer = malloc(srcSize); - U32 nbBlocks; - UTIL_time_t ticksPerSecond; - struct compressionParameters compP; - int cfunctionId; - - /* checks */ - if (!compressedBuffer || !resultBuffer || !blockTable) - EXM_THROW(31, "allocation error : not enough memory"); - - /* init */ - if (strlen(displayName)>17) displayName += strlen(displayName)-17; /* can only display 17 characters */ - UTIL_initTimer(&ticksPerSecond); - - /* Init */ - if (cLevel < LZ4HC_CLEVEL_MIN) cfunctionId = 0; else cfunctionId = 1; - switch (cfunctionId) - { -#ifdef COMPRESSOR0 - case 0 : compP.compressionFunction = COMPRESSOR0; break; -#endif -#ifdef COMPRESSOR1 - case 1 : compP.compressionFunction = COMPRESSOR1; break; -#endif - default : compP.compressionFunction = DEFAULTCOMPRESSOR; - } - - /* Init blockTable data */ - { const char* srcPtr = (const char*)srcBuffer; - char* cPtr = (char*)compressedBuffer; - char* resPtr = (char*)resultBuffer; - U32 fileNb; - for (nbBlocks=0, fileNb=0; fileNb ACTIVEPERIOD_MICROSEC) { - DISPLAYLEVEL(2, "\rcooling down ... \r"); - UTIL_sleep(COOLPERIOD_SEC); - UTIL_getTime(&coolTime); - } - - /* Compression */ - DISPLAYLEVEL(2, "%2s-%-17.17s :%10u ->\r", marks[markNb], displayName, (U32)srcSize); - if (!cCompleted) memset(compressedBuffer, 0xE5, maxCompressedSize); /* warm up and erase result buffer */ - - UTIL_sleepMilli(1); /* give processor time to other processes */ - UTIL_waitForNextTick(ticksPerSecond); - UTIL_getTime(&clockStart); - - if (!cCompleted) { /* still some time to do compression tests */ - U32 nbLoops = 0; - do { - U32 blockNb; - for (blockNb=0; blockNbmaxTime; - } } - - cSize = 0; - { U32 blockNb; for (blockNb=0; blockNb%10u (%5.3f),%6.1f MB/s\r", - marks[markNb], displayName, (U32)srcSize, (U32)cSize, ratio, - (double)srcSize / fastestC ); - - (void)fastestD; (void)crcOrig; /* unused when decompression disabled */ -#if 1 - /* Decompression */ - if (!dCompleted) memset(resultBuffer, 0xD6, srcSize); /* warm result buffer */ - - UTIL_sleepMilli(1); /* give processor time to other processes */ - UTIL_waitForNextTick(ticksPerSecond); - UTIL_getTime(&clockStart); - - if (!dCompleted) { - U32 nbLoops = 0; - do { - U32 blockNb; - for (blockNb=0; blockNb(DECOMP_MULT*maxTime); - } } - - markNb = (markNb+1) % NB_MARKS; - DISPLAYLEVEL(2, "%2s-%-17.17s :%10u ->%10u (%5.3f),%6.1f MB/s ,%6.1f MB/s\r", - marks[markNb], displayName, (U32)srcSize, (U32)cSize, ratio, - (double)srcSize / fastestC, - (double)srcSize / fastestD ); - - /* CRC Checking */ - { U64 const crcCheck = XXH64(resultBuffer, srcSize, 0); - if (crcOrig!=crcCheck) { - size_t u; - DISPLAY("!!! WARNING !!! %14s : Invalid Checksum : %x != %x \n", displayName, (unsigned)crcOrig, (unsigned)crcCheck); - for (u=0; u u) break; - bacc += blockTable[segNb].srcSize; - } - pos = (U32)(u - bacc); - bNb = pos / (128 KB); - DISPLAY("(block %u, sub %u, pos %u) \n", segNb, bNb, pos); - break; - } - if (u==srcSize-1) { /* should never happen */ - DISPLAY("no difference detected\n"); - } } - break; - } } /* CRC Checking */ -#endif - } /* for (testNb = 1; testNb <= (g_nbSeconds + !g_nbSeconds); testNb++) */ - - if (g_displayLevel == 1) { - double cSpeed = (double)srcSize / fastestC; - double dSpeed = (double)srcSize / fastestD; - if (g_additionalParam) - DISPLAY("-%-3i%11i (%5.3f) %6.2f MB/s %6.1f MB/s %s (param=%d)\n", cLevel, (int)cSize, ratio, cSpeed, dSpeed, displayName, g_additionalParam); - else - DISPLAY("-%-3i%11i (%5.3f) %6.2f MB/s %6.1f MB/s %s\n", cLevel, (int)cSize, ratio, cSpeed, dSpeed, displayName); - } - DISPLAYLEVEL(2, "%2i#\n", cLevel); - } /* Bench */ - - /* clean up */ - free(blockTable); - free(compressedBuffer); - free(resultBuffer); - return 0; -} - - -static size_t BMK_findMaxMem(U64 requiredMem) -{ - size_t step = 64 MB; - BYTE* testmem=NULL; - - requiredMem = (((requiredMem >> 26) + 1) << 26); - requiredMem += 2*step; - if (requiredMem > maxMemory) requiredMem = maxMemory; - - while (!testmem) { - if (requiredMem > step) requiredMem -= step; - else requiredMem >>= 1; - testmem = (BYTE*) malloc ((size_t)requiredMem); - } - free (testmem); - - /* keep some space available */ - if (requiredMem > step) requiredMem -= step; - else requiredMem >>= 1; - - return (size_t)requiredMem; -} - - -static void BMK_benchCLevel(void* srcBuffer, size_t benchedSize, - const char* displayName, int cLevel, int cLevelLast, - const size_t* fileSizes, unsigned nbFiles) -{ - int l; - - const char* pch = strrchr(displayName, '\\'); /* Windows */ - if (!pch) pch = strrchr(displayName, '/'); /* Linux */ - if (pch) displayName = pch+1; - - SET_REALTIME_PRIORITY; - - if (g_displayLevel == 1 && !g_additionalParam) - DISPLAY("bench %s %s: input %u bytes, %u seconds, %u KB blocks\n", LZ4_VERSION_STRING, LZ4_GIT_COMMIT_STRING, (U32)benchedSize, g_nbSeconds, (U32)(g_blockSize>>10)); - - if (cLevelLast < cLevel) cLevelLast = cLevel; - - for (l=cLevel; l <= cLevelLast; l++) { - BMK_benchMem(srcBuffer, benchedSize, - displayName, l, - fileSizes, nbFiles); - } -} - - -/*! BMK_loadFiles() : - Loads `buffer` with content of files listed within `fileNamesTable`. - At most, fills `buffer` entirely */ -static void BMK_loadFiles(void* buffer, size_t bufferSize, - size_t* fileSizes, - const char** fileNamesTable, unsigned nbFiles) -{ - size_t pos = 0, totalSize = 0; - unsigned n; - for (n=0; n bufferSize-pos) fileSize = bufferSize-pos, nbFiles=n; /* buffer too small - stop after this file */ - { size_t const readSize = fread(((char*)buffer)+pos, 1, (size_t)fileSize, f); - if (readSize != (size_t)fileSize) EXM_THROW(11, "could not read %s", fileNamesTable[n]); - pos += readSize; } - fileSizes[n] = (size_t)fileSize; - totalSize += (size_t)fileSize; - fclose(f); - } - - if (totalSize == 0) EXM_THROW(12, "no data to bench"); -} - -static void BMK_benchFileTable(const char** fileNamesTable, unsigned nbFiles, - int cLevel, int cLevelLast) -{ - void* srcBuffer; - size_t benchedSize; - size_t* fileSizes = (size_t*)malloc(nbFiles * sizeof(size_t)); - U64 const totalSizeToLoad = UTIL_getTotalFileSize(fileNamesTable, nbFiles); - char mfName[20] = {0}; - - if (!fileSizes) EXM_THROW(12, "not enough memory for fileSizes"); - - /* Memory allocation & restrictions */ - benchedSize = BMK_findMaxMem(totalSizeToLoad * 3) / 3; - if (benchedSize==0) EXM_THROW(12, "not enough memory"); - if ((U64)benchedSize > totalSizeToLoad) benchedSize = (size_t)totalSizeToLoad; - if (benchedSize > LZ4_MAX_INPUT_SIZE) { - benchedSize = LZ4_MAX_INPUT_SIZE; - DISPLAY("File(s) bigger than LZ4's max input size; testing %u MB only...\n", (U32)(benchedSize >> 20)); - } else { - if (benchedSize < totalSizeToLoad) - DISPLAY("Not enough memory; testing %u MB only...\n", (U32)(benchedSize >> 20)); - } - srcBuffer = malloc(benchedSize + !benchedSize); /* avoid alloc of zero */ - if (!srcBuffer) EXM_THROW(12, "not enough memory"); - - /* Load input buffer */ - BMK_loadFiles(srcBuffer, benchedSize, fileSizes, fileNamesTable, nbFiles); - - /* Bench */ - snprintf (mfName, sizeof(mfName), " %u files", nbFiles); - { const char* displayName = (nbFiles > 1) ? mfName : fileNamesTable[0]; - BMK_benchCLevel(srcBuffer, benchedSize, - displayName, cLevel, cLevelLast, - fileSizes, nbFiles); - } - - /* clean up */ - free(srcBuffer); - free(fileSizes); -} - - -static void BMK_syntheticTest(int cLevel, int cLevelLast, double compressibility) -{ - char name[20] = {0}; - size_t benchedSize = 10000000; - void* const srcBuffer = malloc(benchedSize); - - /* Memory allocation */ - if (!srcBuffer) EXM_THROW(21, "not enough memory"); - - /* Fill input buffer */ - RDG_genBuffer(srcBuffer, benchedSize, compressibility, 0.0, 0); - - /* Bench */ - snprintf (name, sizeof(name), "Synthetic %2u%%", (unsigned)(compressibility*100)); - BMK_benchCLevel(srcBuffer, benchedSize, name, cLevel, cLevelLast, &benchedSize, 1); - - /* clean up */ - free(srcBuffer); -} - - -int BMK_benchFiles(const char** fileNamesTable, unsigned nbFiles, - int cLevel, int cLevelLast) -{ - double const compressibility = (double)g_compressibilityDefault / 100; - - if (cLevel > LZ4HC_CLEVEL_MAX) cLevel = LZ4HC_CLEVEL_MAX; - if (cLevelLast > LZ4HC_CLEVEL_MAX) cLevelLast = LZ4HC_CLEVEL_MAX; - if (cLevelLast < cLevel) cLevelLast = cLevel; - if (cLevelLast > cLevel) DISPLAYLEVEL(2, "Benchmarking levels from %d to %d\n", cLevel, cLevelLast); - - if (nbFiles == 0) - BMK_syntheticTest(cLevel, cLevelLast, compressibility); - else - BMK_benchFileTable(fileNamesTable, nbFiles, cLevel, cLevelLast); - return 0; -} diff --git a/src/lz4/programs/bench.h b/src/lz4/programs/bench.h deleted file mode 100644 index 15def93fff..0000000000 --- a/src/lz4/programs/bench.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - bench.h - Demo program to benchmark open-source compression algorithm - Copyright (C) Yann Collet 2012-2016 - - This program is free software; 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-1301 USA. - - You can contact the author at : - - LZ4 source repository : https://github.com/lz4/lz4 - - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c -*/ -#ifndef BENCH_H_125623623633 -#define BENCH_H_125623623633 - -#include - -int BMK_benchFiles(const char** fileNamesTable, unsigned nbFiles, - int cLevel, int cLevelLast); - -/* Set Parameters */ -void BMK_SetNbSeconds(unsigned nbLoops); -void BMK_SetBlockSize(size_t blockSize); -void BMK_setAdditionalParam(int additionalParam); -void BMK_setNotificationLevel(unsigned level); - -#endif /* BENCH_H_125623623633 */ diff --git a/src/lz4/programs/datagen.c b/src/lz4/programs/datagen.c deleted file mode 100644 index a61afc0576..0000000000 --- a/src/lz4/programs/datagen.c +++ /dev/null @@ -1,189 +0,0 @@ -/* - datagen.c - compressible data generator test tool - Copyright (C) Yann Collet 2012-2016 - - GPL v2 License - - This program is free software; 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-1301 USA. - - You can contact the author at : - - LZ4 source repository : https://github.com/lz4/lz4 - - Public forum : https://groups.google.com/forum/#!forum/lz4c -*/ - -/************************************** -* Includes -**************************************/ -#include "platform.h" /* Compiler options, SET_BINARY_MODE */ -#include "util.h" /* U32 */ -#include /* malloc */ -#include /* FILE, fwrite */ -#include /* memcpy */ - - -/************************************** -* Constants -**************************************/ -#define KB *(1 <<10) - -#define PRIME1 2654435761U -#define PRIME2 2246822519U - - -/************************************** -* Local types -**************************************/ -#define LTLOG 13 -#define LTSIZE (1<> (32 - r))) -static unsigned int RDG_rand(U32* src) -{ - U32 rand32 = *src; - rand32 *= PRIME1; - rand32 ^= PRIME2; - rand32 = RDG_rotl32(rand32, 13); - *src = rand32; - return rand32; -} - - -static void RDG_fillLiteralDistrib(litDistribTable lt, double ld) -{ - BYTE const firstChar = ld <= 0.0 ? 0 : '('; - BYTE const lastChar = ld <= 0.0 ? 255 : '}'; - BYTE character = ld <= 0.0 ? 0 : '0'; - U32 u = 0; - - while (u lastChar) character = firstChar; - } -} - - -static BYTE RDG_genChar(U32* seed, const litDistribTable lt) -{ - U32 id = RDG_rand(seed) & LTMASK; - return (lt[id]); -} - - -#define RDG_DICTSIZE (32 KB) -#define RDG_RAND15BITS ((RDG_rand(seed) >> 3) & 32767) -#define RDG_RANDLENGTH ( ((RDG_rand(seed) >> 7) & 7) ? (RDG_rand(seed) & 15) : (RDG_rand(seed) & 511) + 15) -void RDG_genBlock(void* buffer, size_t buffSize, size_t prefixSize, double matchProba, litDistribTable lt, unsigned* seedPtr) -{ - BYTE* buffPtr = (BYTE*)buffer; - const U32 matchProba32 = (U32)(32768 * matchProba); - size_t pos = prefixSize; - U32* seed = seedPtr; - - /* special case */ - while (matchProba >= 1.0) - { - size_t size0 = RDG_rand(seed) & 3; - size0 = (size_t)1 << (16 + size0 * 2); - size0 += RDG_rand(seed) & (size0-1); /* because size0 is power of 2*/ - if (buffSize < pos + size0) - { - memset(buffPtr+pos, 0, buffSize-pos); - return; - } - memset(buffPtr+pos, 0, size0); - pos += size0; - buffPtr[pos-1] = RDG_genChar(seed, lt); - } - - /* init */ - if (pos==0) buffPtr[0] = RDG_genChar(seed, lt), pos=1; - - /* Generate compressible data */ - while (pos < buffSize) - { - /* Select : Literal (char) or Match (within 32K) */ - if (RDG_RAND15BITS < matchProba32) - { - /* Copy (within 32K) */ - size_t match; - size_t d; - int length = RDG_RANDLENGTH + 4; - U32 offset = RDG_RAND15BITS + 1; - if (offset > pos) offset = (U32)pos; - match = pos - offset; - d = pos + length; - if (d > buffSize) d = buffSize; - while (pos < d) buffPtr[pos++] = buffPtr[match++]; - } - else - { - /* Literal (noise) */ - size_t d; - size_t length = RDG_RANDLENGTH; - d = pos + length; - if (d > buffSize) d = buffSize; - while (pos < d) buffPtr[pos++] = RDG_genChar(seed, lt); - } - } -} - - -void RDG_genBuffer(void* buffer, size_t size, double matchProba, double litProba, unsigned seed) -{ - litDistribTable lt; - if (litProba==0.0) litProba = matchProba / 4.5; - RDG_fillLiteralDistrib(lt, litProba); - RDG_genBlock(buffer, size, 0, matchProba, lt, &seed); -} - - -#define RDG_BLOCKSIZE (128 KB) -void RDG_genOut(unsigned long long size, double matchProba, double litProba, unsigned seed) -{ - BYTE buff[RDG_DICTSIZE + RDG_BLOCKSIZE]; - U64 total = 0; - size_t genBlockSize = RDG_BLOCKSIZE; - litDistribTable lt; - - /* init */ - if (litProba==0.0) litProba = matchProba / 4.5; - RDG_fillLiteralDistrib(lt, litProba); - SET_BINARY_MODE(stdout); - - /* Generate dict */ - RDG_genBlock(buff, RDG_DICTSIZE, 0, matchProba, lt, &seed); - - /* Generate compressible data */ - while (total < size) - { - RDG_genBlock(buff, RDG_DICTSIZE+RDG_BLOCKSIZE, RDG_DICTSIZE, matchProba, lt, &seed); - if (size-total < RDG_BLOCKSIZE) genBlockSize = (size_t)(size-total); - total += genBlockSize; - fwrite(buff, 1, genBlockSize, stdout); - /* update dict */ - memcpy(buff, buff + RDG_BLOCKSIZE, RDG_DICTSIZE); - } -} diff --git a/src/lz4/programs/datagen.h b/src/lz4/programs/datagen.h deleted file mode 100644 index 91c5b02e52..0000000000 --- a/src/lz4/programs/datagen.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - datagen.h - compressible data generator header - Copyright (C) Yann Collet 2012-2016 - - GPL v2 License - - This program is free software; 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-1301 USA. - - You can contact the author at : - - LZ4 source repository : https://github.com/lz4/lz4 - - Public forum : https://groups.google.com/forum/#!forum/lz4c -*/ - - -#include /* size_t */ - -void RDG_genOut(unsigned long long size, double matchProba, double litProba, unsigned seed); -void RDG_genBuffer(void* buffer, size_t size, double matchProba, double litProba, unsigned seed); -/* RDG_genOut - Generate 'size' bytes of compressible data into stdout. - Compressibility can be controlled using 'matchProba'. - 'LitProba' is optional, and affect variability of bytes. If litProba==0.0, default value is used. - Generated data can be selected using 'seed'. - If (matchProba, litProba and seed) are equal, the function always generate the same content. - - RDG_genBuffer - Same as RDG_genOut, but generate data into provided buffer -*/ diff --git a/src/lz4/programs/lz4.1 b/src/lz4/programs/lz4.1 deleted file mode 100644 index 39d78cdbca..0000000000 --- a/src/lz4/programs/lz4.1 +++ /dev/null @@ -1,220 +0,0 @@ -. -.TH "LZ4" "1" "July 2017" "lz4 1.8.0" "User Commands" -. -.SH "NAME" -\fBlz4\fR \- lz4, unlz4, lz4cat \- Compress or decompress \.lz4 files -. -.SH "SYNOPSIS" -\fBlz4\fR [\fIOPTIONS\fR] [\-|INPUT\-FILE] \fIOUTPUT\-FILE\fR -. -.P -\fBunlz4\fR is equivalent to \fBlz4 \-d\fR -. -.P -\fBlz4cat\fR is equivalent to \fBlz4 \-dcfm\fR -. -.P -When writing scripts that need to decompress files, it is recommended to always use the name \fBlz4\fR with appropriate arguments (\fBlz4 \-d\fR or \fBlz4 \-dc\fR) instead of the names \fBunlz4\fR and \fBlz4cat\fR\. -. -.SH "DESCRIPTION" -\fBlz4\fR is an extremely fast lossless compression algorithm, based on \fBbyte\-aligned LZ77\fR family of compression scheme\. \fBlz4\fR offers compression speeds of 400 MB/s per core, linearly scalable with multi\-core CPUs\. It features an extremely fast decoder, with speed in multiple GB/s per core, typically reaching RAM speed limit on multi\-core systems\. The native file format is the \fB\.lz4\fR format\. -. -.SS "Difference between lz4 and gzip" -\fBlz4\fR supports a command line syntax similar \fIbut not identical\fR to \fBgzip(1)\fR\. Differences are : -. -.IP "\(bu" 4 -\fBlz4\fR preserves original files -. -.IP "\(bu" 4 -\fBlz4\fR compresses a single file by default (see \fB\-m\fR for multiple files) -. -.IP "\(bu" 4 -\fBlz4 file1 file2\fR means : compress file1 \fIinto\fR file2 -. -.IP "\(bu" 4 -\fBlz4 file\.lz4\fR will default to decompression (use \fB\-z\fR to force compression) -. -.IP "\(bu" 4 -\fBlz4\fR shows real\-time notification statistics during compression or decompression of a single file (use \fB\-q\fR to silent them) -. -.IP "\(bu" 4 -If no destination name is provided, result is sent to \fBstdout\fR \fIexcept if stdout is the console\fR\. -. -.IP "\(bu" 4 -If no destination name is provided, \fBand\fR if \fBstdout\fR is the console, \fBfile\fR is compressed into \fBfile\.lz4\fR\. -. -.IP "\(bu" 4 -As a consequence of previous rules, note the following example : \fBlz4 file | consumer\fR sends compressed data to \fBconsumer\fR through \fBstdout\fR, hence it does \fInot\fR create \fBfile\.lz4\fR\. -. -.IP "" 0 -. -.P -Default behaviors can be modified by opt\-in commands, detailed below\. -. -.IP "\(bu" 4 -\fBlz4 \-m\fR makes it possible to provide multiple input filenames, which will be compressed into files using suffix \fB\.lz4\fR\. Progress notifications are also disabled by default (use \fB\-v\fR to enable them)\. This mode has a behavior which more closely mimics \fBgzip\fR command line, with the main remaining difference being that source files are preserved by default\. -. -.IP "\(bu" 4 -Similarly, \fBlz4 \-m \-d\fR can decompress multiple \fB*\.lz4\fR files\. -. -.IP "\(bu" 4 -It\'s possible to opt\-in to erase source files on successful compression or decompression, using \fB\-\-rm\fR command\. -. -.IP "\(bu" 4 -Consequently, \fBlz4 \-m \-\-rm\fR behaves the same as \fBgzip\fR\. -. -.IP "" 0 -. -.SS "Concatenation of \.lz4 files" -It is possible to concatenate \fB\.lz4\fR files as is\. \fBlz4\fR will decompress such files as if they were a single \fB\.lz4\fR file\. For example: -. -.IP "" 4 -. -.nf - -lz4 file1 > foo\.lz4 -lz4 file2 >> foo\.lz4 -. -.fi -. -.IP "" 0 -. -.P -Then \fBlz4cat foo\.lz4\fR is equivalent to \fBcat file1 file2\fR\. -. -.SH "OPTIONS" -. -.SS "Short commands concatenation" -In some cases, some options can be expressed using short command \fB\-x\fR or long command \fB\-\-long\-word\fR\. Short commands can be concatenated together\. For example, \fB\-d \-c\fR is equivalent to \fB\-dc\fR\. Long commands cannot be concatenated\. They must be clearly separated by a space\. -. -.SS "Multiple commands" -When multiple contradictory commands are issued on a same command line, only the latest one will be applied\. -. -.SS "Operation mode" -. -.TP -\fB\-z\fR \fB\-\-compress\fR -Compress\. This is the default operation mode when no operation mode option is specified, no other operation mode is implied from the command name (for example, \fBunlz4\fR implies \fB\-\-decompress\fR), nor from the input file name (for example, a file extension \fB\.lz4\fR implies \fB\-\-decompress\fR by default)\. \fB\-z\fR can also be used to force compression of an already compressed \fB\.lz4\fR file\. -. -.TP -\fB\-d\fR \fB\-\-decompress\fR \fB\-\-uncompress\fR -Decompress\. \fB\-\-decompress\fR is also the default operation when the input filename has an \fB\.lz4\fR extension\. -. -.TP -\fB\-t\fR \fB\-\-test\fR -Test the integrity of compressed \fB\.lz4\fR files\. The decompressed data is discarded\. No files are created nor removed\. -. -.TP -\fB\-b#\fR -Benchmark mode, using \fB#\fR compression level\. -. -.SS "Operation modifiers" -. -.TP -\fB\-#\fR -Compression level, with # being any value from 1 to 16\. Higher values trade compression speed for compression ratio\. Values above 16 are considered the same as 16\. Recommended values are 1 for fast compression (default), and 9 for high compression\. Speed/compression trade\-off will vary depending on data to compress\. Decompression speed remains fast at all settings\. -. -.TP -\fB\-f\fR \fB\-\-[no\-]force\fR -This option has several effects: -. -.IP -If the target file already exists, overwrite it without prompting\. -. -.IP -When used with \fB\-\-decompress\fR and \fBlz4\fR cannot recognize the type of the source file, copy the source file as is to standard output\. This allows \fBlz4cat \-\-force\fR to be used like \fBcat (1)\fR for files that have not been compressed with \fBlz4\fR\. -. -.TP -\fB\-c\fR \fB\-\-stdout\fR \fB\-\-to\-stdout\fR -Force write to standard output, even if it is the console\. -. -.TP -\fB\-m\fR \fB\-\-multiple\fR -Multiple input files\. Compressed file names will be appended a \fB\.lz4\fR suffix\. This mode also reduces notification level\. \fBlz4 \-m\fR has a behavior equivalent to \fBgzip \-k\fR (it preserves source files by default)\. -. -.TP -\fB\-r\fR -operate recursively on directories\. This mode also sets \fB\-m\fR (multiple input files)\. -. -.TP -\fB\-B#\fR -Block size [4\-7](default : 7) -. -.br -\fB\-B4\fR= 64KB ; \fB\-B5\fR= 256KB ; \fB\-B6\fR= 1MB ; \fB\-B7\fR= 4MB -. -.TP -\fB\-BD\fR -Block Dependency (improves compression ratio on small blocks) -. -.TP -\fB\-\-[no\-]frame\-crc\fR -Select frame checksum (default:enabled) -. -.TP -\fB\-\-[no\-]content\-size\fR -Header includes original size (default:not present) -. -.br -Note : this option can only be activated when the original size can be determined, hence for a file\. It won\'t work with unknown source size, such as stdin or pipe\. -. -.TP -\fB\-\-[no\-]sparse\fR -Sparse mode support (default:enabled on file, disabled on stdout) -. -.TP -\fB\-l\fR -Use Legacy format (typically for Linux Kernel compression) -. -.br -Note : \fB\-l\fR is not compatible with \fB\-m\fR (\fB\-\-multiple\fR) nor \fB\-r\fR -. -.SS "Other options" -. -.TP -\fB\-v\fR \fB\-\-verbose\fR -Verbose mode -. -.TP -\fB\-q\fR \fB\-\-quiet\fR -Suppress warnings and real\-time statistics; specify twice to suppress errors too -. -.TP -\fB\-h\fR \fB\-H\fR \fB\-\-help\fR -Display help/long help and exit -. -.TP -\fB\-V\fR \fB\-\-version\fR -Display Version number and exit -. -.TP -\fB\-k\fR \fB\-\-keep\fR -Preserve source files (default behavior) -. -.TP -\fB\-\-rm\fR -Delete source files on successful compression or decompression -. -.TP -\fB\-\-\fR -Treat all subsequent arguments as files -. -.SS "Benchmark mode" -. -.TP -\fB\-b#\fR -Benchmark file(s), using # compression level -. -.TP -\fB\-e#\fR -Benchmark multiple compression levels, from b# to e# (included) -. -.TP -\fB\-i#\fR -Minimum evaluation in seconds [1\-9] (default : 3) -. -.SH "BUGS" -Report bugs at: https://github\.com/lz4/lz4/issues -. -.SH "AUTHOR" -Yann Collet diff --git a/src/lz4/programs/lz4.1.md b/src/lz4/programs/lz4.1.md deleted file mode 100644 index c6b99bcda0..0000000000 --- a/src/lz4/programs/lz4.1.md +++ /dev/null @@ -1,218 +0,0 @@ -lz4(1) -- lz4, unlz4, lz4cat - Compress or decompress .lz4 files -================================================================ - -SYNOPSIS --------- - -`lz4` [*OPTIONS*] [-|INPUT-FILE] - -`unlz4` is equivalent to `lz4 -d` - -`lz4cat` is equivalent to `lz4 -dcfm` - -When writing scripts that need to decompress files, -it is recommended to always use the name `lz4` with appropriate arguments -(`lz4 -d` or `lz4 -dc`) instead of the names `unlz4` and `lz4cat`. - - -DESCRIPTION ------------ - -`lz4` is an extremely fast lossless compression algorithm, -based on **byte-aligned LZ77** family of compression scheme. -`lz4` offers compression speeds of 400 MB/s per core, linearly scalable with -multi-core CPUs. -It features an extremely fast decoder, with speed in multiple GB/s per core, -typically reaching RAM speed limit on multi-core systems. -The native file format is the `.lz4` format. - -### Difference between lz4 and gzip - -`lz4` supports a command line syntax similar _but not identical_ to `gzip(1)`. -Differences are : - - * `lz4` preserves original files - * `lz4` compresses a single file by default (see `-m` for multiple files) - * `lz4 file1 file2` means : compress file1 _into_ file2 - * `lz4 file.lz4` will default to decompression (use `-z` to force compression) - * `lz4` shows real-time notification statistics - during compression or decompression of a single file - (use `-q` to silent them) - * If no destination name is provided, result is sent to `stdout` - _except if stdout is the console_. - * If no destination name is provided, __and__ if `stdout` is the console, - `file` is compressed into `file.lz4`. - * As a consequence of previous rules, note the following example : - `lz4 file | consumer` sends compressed data to `consumer` through `stdout`, - hence it does _not_ create `file.lz4`. - -Default behaviors can be modified by opt-in commands, detailed below. - - * `lz4 -m` makes it possible to provide multiple input filenames, - which will be compressed into files using suffix `.lz4`. - Progress notifications are also disabled by default (use `-v` to enable them). - This mode has a behavior which more closely mimics `gzip` command line, - with the main remaining difference being that source files are preserved by default. - * Similarly, `lz4 -m -d` can decompress multiple `*.lz4` files. - * It's possible to opt-in to erase source files - on successful compression or decompression, using `--rm` command. - * Consequently, `lz4 -m --rm` behaves the same as `gzip`. - -### Concatenation of .lz4 files - -It is possible to concatenate `.lz4` files as is. -`lz4` will decompress such files as if they were a single `.lz4` file. -For example: - - lz4 file1 > foo.lz4 - lz4 file2 >> foo.lz4 - -Then `lz4cat foo.lz4` is equivalent to `cat file1 file2`. - -OPTIONS -------- - -### Short commands concatenation - -In some cases, some options can be expressed using short command `-x` -or long command `--long-word`. -Short commands can be concatenated together. -For example, `-d -c` is equivalent to `-dc`. -Long commands cannot be concatenated. -They must be clearly separated by a space. - -### Multiple commands - -When multiple contradictory commands are issued on a same command line, -only the latest one will be applied. - -### Operation mode - -* `-z` `--compress`: - Compress. - This is the default operation mode when no operation mode option is - specified, no other operation mode is implied from the command name - (for example, `unlz4` implies `--decompress`), - nor from the input file name - (for example, a file extension `.lz4` implies `--decompress` by default). - `-z` can also be used to force compression of an already compressed - `.lz4` file. - -* `-d` `--decompress` `--uncompress`: - Decompress. - `--decompress` is also the default operation when the input filename has an - `.lz4` extension. - -* `-t` `--test`: - Test the integrity of compressed `.lz4` files. - The decompressed data is discarded. - No files are created nor removed. - -* `-b#`: - Benchmark mode, using `#` compression level. - -### Operation modifiers - -* `-#`: - Compression level, with # being any value from 1 to 16. - Higher values trade compression speed for compression ratio. - Values above 16 are considered the same as 16. - Recommended values are 1 for fast compression (default), - and 9 for high compression. - Speed/compression trade-off will vary depending on data to compress. - Decompression speed remains fast at all settings. - -* `-f` `--[no-]force`: - This option has several effects: - - If the target file already exists, overwrite it without prompting. - - When used with `--decompress` and `lz4` cannot recognize the type of - the source file, copy the source file as is to standard output. - This allows `lz4cat --force` to be used like `cat (1)` for files - that have not been compressed with `lz4`. - -* `-c` `--stdout` `--to-stdout`: - Force write to standard output, even if it is the console. - -* `-m` `--multiple`: - Multiple input files. - Compressed file names will be appended a `.lz4` suffix. - This mode also reduces notification level. - `lz4 -m` has a behavior equivalent to `gzip -k` - (it preserves source files by default). - -* `-r` : - operate recursively on directories. - This mode also sets `-m` (multiple input files). - -* `-B#`: - Block size \[4-7\](default : 7)
- `-B4`= 64KB ; `-B5`= 256KB ; `-B6`= 1MB ; `-B7`= 4MB - -* `-BD`: - Block Dependency (improves compression ratio on small blocks) - -* `--[no-]frame-crc`: - Select frame checksum (default:enabled) - -* `--[no-]content-size`: - Header includes original size (default:not present)
- Note : this option can only be activated when the original size can be - determined, hence for a file. It won't work with unknown source size, - such as stdin or pipe. - -* `--[no-]sparse`: - Sparse mode support (default:enabled on file, disabled on stdout) - -* `-l`: - Use Legacy format (typically for Linux Kernel compression)
- Note : `-l` is not compatible with `-m` (`--multiple`) nor `-r` - -### Other options - -* `-v` `--verbose`: - Verbose mode - -* `-q` `--quiet`: - Suppress warnings and real-time statistics; - specify twice to suppress errors too - -* `-h` `-H` `--help`: - Display help/long help and exit - -* `-V` `--version`: - Display Version number and exit - -* `-k` `--keep`: - Preserve source files (default behavior) - -* `--rm` : - Delete source files on successful compression or decompression - -* `--` : - Treat all subsequent arguments as files - - -### Benchmark mode - -* `-b#`: - Benchmark file(s), using # compression level - -* `-e#`: - Benchmark multiple compression levels, from b# to e# (included) - -* `-i#`: - Minimum evaluation in seconds \[1-9\] (default : 3) - - -BUGS ----- - -Report bugs at: https://github.com/lz4/lz4/issues - - -AUTHOR ------- - -Yann Collet diff --git a/src/lz4/programs/lz4cli.c b/src/lz4/programs/lz4cli.c deleted file mode 100644 index b4a3c14a0f..0000000000 --- a/src/lz4/programs/lz4cli.c +++ /dev/null @@ -1,647 +0,0 @@ -/* - LZ4cli - LZ4 Command Line Interface - Copyright (C) Yann Collet 2011-2016 - - GPL v2 License - - This program is free software; 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-1301 USA. - - You can contact the author at : - - LZ4 source repository : https://github.com/lz4/lz4 - - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c -*/ -/* - Note : this is stand-alone program. - It is not part of LZ4 compression library, it is a user program of the LZ4 library. - The license of LZ4 library is BSD. - The license of xxHash library is BSD. - The license of this compression CLI program is GPLv2. -*/ - - -/**************************** -* Includes -*****************************/ -#include "platform.h" /* Compiler options, IS_CONSOLE */ -#include "util.h" /* UTIL_HAS_CREATEFILELIST, UTIL_createFileList */ -#include /* fprintf, getchar */ -#include /* exit, calloc, free */ -#include /* strcmp, strlen */ -#include "bench.h" /* BMK_benchFile, BMK_SetNbIterations, BMK_SetBlocksize, BMK_SetPause */ -#include "lz4io.h" /* LZ4IO_compressFilename, LZ4IO_decompressFilename, LZ4IO_compressMultipleFilenames */ -#include "lz4hc.h" /* LZ4HC_CLEVEL_MAX */ -#include "lz4.h" /* LZ4_VERSION_STRING */ - - -/***************************** -* Constants -******************************/ -#define COMPRESSOR_NAME "LZ4 command line interface" -#define AUTHOR "Yann Collet" -#define WELCOME_MESSAGE "*** %s %i-bits v%s, by %s ***\n", COMPRESSOR_NAME, (int)(sizeof(void*)*8), LZ4_versionString(), AUTHOR -#define LZ4_EXTENSION ".lz4" -#define LZ4CAT "lz4cat" -#define UNLZ4 "unlz4" -#define LZ4_LEGACY "lz4c" -static int g_lz4c_legacy_commands = 0; - -#define KB *(1U<<10) -#define MB *(1U<<20) -#define GB *(1U<<30) - -#define LZ4_BLOCKSIZEID_DEFAULT 7 - - -/*-************************************ -* Macros -***************************************/ -#define DISPLAY(...) fprintf(stderr, __VA_ARGS__) -#define DISPLAYLEVEL(l, ...) if (displayLevel>=l) { DISPLAY(__VA_ARGS__); } -static unsigned displayLevel = 2; /* 0 : no display ; 1: errors only ; 2 : downgradable normal ; 3 : non-downgradable normal; 4 : + information */ - - -/*-************************************ -* Exceptions -***************************************/ -#define DEBUG 0 -#define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__); -#define EXM_THROW(error, ...) \ -{ \ - DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \ - DISPLAYLEVEL(1, "Error %i : ", error); \ - DISPLAYLEVEL(1, __VA_ARGS__); \ - DISPLAYLEVEL(1, "\n"); \ - exit(error); \ -} - - -/*-************************************ -* Version modifiers -***************************************/ -#define EXTENDED_ARGUMENTS -#define EXTENDED_HELP -#define EXTENDED_FORMAT -#define DEFAULT_COMPRESSOR LZ4IO_compressFilename -#define DEFAULT_DECOMPRESSOR LZ4IO_decompressFilename -int LZ4IO_compressFilename_Legacy(const char* input_filename, const char* output_filename, int compressionlevel); /* hidden function */ - - -/*-*************************** -* Functions -*****************************/ -static int usage(const char* exeName) -{ - DISPLAY( "Usage : \n"); - DISPLAY( " %s [arg] [input] [output] \n", exeName); - DISPLAY( "\n"); - DISPLAY( "input : a filename \n"); - DISPLAY( " with no FILE, or when FILE is - or %s, read standard input\n", stdinmark); - DISPLAY( "Arguments : \n"); - DISPLAY( " -1 : Fast compression (default) \n"); - DISPLAY( " -9 : High compression \n"); - DISPLAY( " -d : decompression (default for %s extension)\n", LZ4_EXTENSION); - DISPLAY( " -z : force compression \n"); - DISPLAY( " -f : overwrite output without prompting \n"); - DISPLAY( " -k : preserve source files(s) (default) \n"); - DISPLAY( "--rm : remove source file(s) after successful de/compression \n"); - DISPLAY( " -h/-H : display help/long help and exit \n"); - return 0; -} - -static int usage_advanced(const char* exeName) -{ - DISPLAY(WELCOME_MESSAGE); - usage(exeName); - DISPLAY( "\n"); - DISPLAY( "Advanced arguments :\n"); - DISPLAY( " -V : display Version number and exit \n"); - DISPLAY( " -v : verbose mode \n"); - DISPLAY( " -q : suppress warnings; specify twice to suppress errors too\n"); - DISPLAY( " -c : force write to standard output, even if it is the console\n"); - DISPLAY( " -t : test compressed file integrity\n"); - DISPLAY( " -m : multiple input files (implies automatic output filenames)\n"); -#ifdef UTIL_HAS_CREATEFILELIST - DISPLAY( " -r : operate recursively on directories (sets also -m) \n"); -#endif - DISPLAY( " -l : compress using Legacy format (Linux kernel compression)\n"); - DISPLAY( " -B# : Block size [4-7] (default : 7) \n"); - DISPLAY( " -BD : Block dependency (improve compression ratio) \n"); - DISPLAY( " -BX : enable block checksum (default:disabled) \n"); - DISPLAY( "--no-frame-crc : disable stream checksum (default:enabled) \n"); - DISPLAY( "--content-size : compressed frame includes original size (default:not present)\n"); - DISPLAY( "--[no-]sparse : sparse mode (default:enabled on file, disabled on stdout)\n"); - DISPLAY( "Benchmark arguments : \n"); - DISPLAY( " -b# : benchmark file(s), using # compression level (default : 1) \n"); - DISPLAY( " -e# : test all compression levels from -bX to # (default : 1)\n"); - DISPLAY( " -i# : minimum evaluation time in seconds (default : 3s) \n"); - DISPLAY( " -B# : cut file into independent blocks of size # bytes [32+] \n"); - DISPLAY( " or predefined block size [4-7] (default: 7) \n"); - if (g_lz4c_legacy_commands) { - DISPLAY( "Legacy arguments : \n"); - DISPLAY( " -c0 : fast compression \n"); - DISPLAY( " -c1 : high compression \n"); - DISPLAY( " -hc : high compression \n"); - DISPLAY( " -y : overwrite output without prompting \n"); - } - EXTENDED_HELP; - return 0; -} - -static int usage_longhelp(const char* exeName) -{ - usage_advanced(exeName); - DISPLAY( "\n"); - DISPLAY( "****************************\n"); - DISPLAY( "***** Advanced comment *****\n"); - DISPLAY( "****************************\n"); - DISPLAY( "\n"); - DISPLAY( "Which values can [output] have ? \n"); - DISPLAY( "---------------------------------\n"); - DISPLAY( "[output] : a filename \n"); - DISPLAY( " '%s', or '-' for standard output (pipe mode)\n", stdoutmark); - DISPLAY( " '%s' to discard output (test mode) \n", NULL_OUTPUT); - DISPLAY( "[output] can be left empty. In this case, it receives the following value :\n"); - DISPLAY( " - if stdout is not the console, then [output] = stdout \n"); - DISPLAY( " - if stdout is console : \n"); - DISPLAY( " + for compression, output to filename%s \n", LZ4_EXTENSION); - DISPLAY( " + for decompression, output to filename without '%s'\n", LZ4_EXTENSION); - DISPLAY( " > if input filename has no '%s' extension : error \n", LZ4_EXTENSION); - DISPLAY( "\n"); - DISPLAY( "Compression levels : \n"); - DISPLAY( "---------------------\n"); - DISPLAY( "-0 ... -2 => Fast compression, all identicals\n"); - DISPLAY( "-3 ... -%d => High compression; higher number == more compression but slower\n", LZ4HC_CLEVEL_MAX); - DISPLAY( "\n"); - DISPLAY( "stdin, stdout and the console : \n"); - DISPLAY( "--------------------------------\n"); - DISPLAY( "To protect the console from binary flooding (bad argument mistake)\n"); - DISPLAY( "%s will refuse to read from console, or write to console \n", exeName); - DISPLAY( "except if '-c' command is specified, to force output to console \n"); - DISPLAY( "\n"); - DISPLAY( "Simple example :\n"); - DISPLAY( "----------------\n"); - DISPLAY( "1 : compress 'filename' fast, using default output name 'filename.lz4'\n"); - DISPLAY( " %s filename\n", exeName); - DISPLAY( "\n"); - DISPLAY( "Short arguments can be aggregated. For example :\n"); - DISPLAY( "----------------------------------\n"); - DISPLAY( "2 : compress 'filename' in high compression mode, overwrite output if exists\n"); - DISPLAY( " %s -9 -f filename \n", exeName); - DISPLAY( " is equivalent to :\n"); - DISPLAY( " %s -9f filename \n", exeName); - DISPLAY( "\n"); - DISPLAY( "%s can be used in 'pure pipe mode'. For example :\n", exeName); - DISPLAY( "-------------------------------------\n"); - DISPLAY( "3 : compress data stream from 'generator', send result to 'consumer'\n"); - DISPLAY( " generator | %s | consumer \n", exeName); - if (g_lz4c_legacy_commands) { - DISPLAY( "\n"); - DISPLAY( "***** Warning *****\n"); - DISPLAY( "Legacy arguments take precedence. Therefore : \n"); - DISPLAY( "---------------------------------\n"); - DISPLAY( " %s -hc filename\n", exeName); - DISPLAY( "means 'compress filename in high compression mode'\n"); - DISPLAY( "It is not equivalent to :\n"); - DISPLAY( " %s -h -c filename\n", exeName); - DISPLAY( "which would display help text and exit\n"); - } - return 0; -} - -static int badusage(const char* exeName) -{ - DISPLAYLEVEL(1, "Incorrect parameters\n"); - if (displayLevel >= 1) usage(exeName); - exit(1); -} - - -static void waitEnter(void) -{ - DISPLAY("Press enter to continue...\n"); - (void)getchar(); -} - -static const char* lastNameFromPath(const char* path) -{ - const char* name = path; - if (strrchr(name, '/')) name = strrchr(name, '/') + 1; - if (strrchr(name, '\\')) name = strrchr(name, '\\') + 1; /* windows */ - return name; -} - -/*! exeNameMatch() : - @return : a non-zero value if exeName matches test, excluding the extension - */ -static int exeNameMatch(const char* exeName, const char* test) -{ - return !strncmp(exeName, test, strlen(test)) && - (exeName[strlen(test)] == '\0' || exeName[strlen(test)] == '.'); -} - -/*! readU32FromChar() : - @return : unsigned integer value read from input in `char` format - allows and interprets K, KB, KiB, M, MB and MiB suffix. - Will also modify `*stringPtr`, advancing it to position where it stopped reading. - Note : function result can overflow if digit string > MAX_UINT */ -static unsigned readU32FromChar(const char** stringPtr) -{ - unsigned result = 0; - while ((**stringPtr >='0') && (**stringPtr <='9')) - result *= 10, result += **stringPtr - '0', (*stringPtr)++ ; - if ((**stringPtr=='K') || (**stringPtr=='M')) { - result <<= 10; - if (**stringPtr=='M') result <<= 10; - (*stringPtr)++ ; - if (**stringPtr=='i') (*stringPtr)++; - if (**stringPtr=='B') (*stringPtr)++; - } - return result; -} - -typedef enum { om_auto, om_compress, om_decompress, om_test, om_bench } operationMode_e; - -int main(int argc, const char** argv) -{ - int i, - cLevel=1, - cLevelLast=1, - legacy_format=0, - forceStdout=0, - main_pause=0, - multiple_inputs=0, - all_arguments_are_files=0, - operationResult=0; - operationMode_e mode = om_auto; - const char* input_filename = NULL; - const char* output_filename= NULL; - char* dynNameSpace = NULL; - const char** inFileNames = (const char**) calloc(argc, sizeof(char*)); - unsigned ifnIdx=0; - const char nullOutput[] = NULL_OUTPUT; - const char extension[] = LZ4_EXTENSION; - size_t blockSize = LZ4IO_setBlockSizeID(LZ4_BLOCKSIZEID_DEFAULT); - const char* const exeName = lastNameFromPath(argv[0]); -#ifdef UTIL_HAS_CREATEFILELIST - const char** extendedFileList = NULL; - char* fileNamesBuf = NULL; - unsigned fileNamesNb, recursive=0; -#endif - - /* Init */ - if (inFileNames==NULL) { - DISPLAY("Allocation error : not enough memory \n"); - return 1; - } - inFileNames[0] = stdinmark; - LZ4IO_setOverwrite(0); - - /* predefined behaviors, based on binary/link name */ - if (exeNameMatch(exeName, LZ4CAT)) { - mode = om_decompress; - LZ4IO_setOverwrite(1); - LZ4IO_setRemoveSrcFile(0); - forceStdout=1; - output_filename=stdoutmark; - displayLevel=1; - multiple_inputs=1; - } - if (exeNameMatch(exeName, UNLZ4)) { mode = om_decompress; } - if (exeNameMatch(exeName, LZ4_LEGACY)) { g_lz4c_legacy_commands=1; } - - /* command switches */ - for(i=1; i='0') && (*argument<='9')) { - cLevel = readU32FromChar(&argument); - argument--; - continue; - } - - - switch(argument[0]) - { - /* Display help */ - case 'V': DISPLAY(WELCOME_MESSAGE); goto _cleanup; /* Version */ - case 'h': usage_advanced(exeName); goto _cleanup; - case 'H': usage_longhelp(exeName); goto _cleanup; - - case 'e': - argument++; - cLevelLast = readU32FromChar(&argument); - argument--; - break; - - /* Compression (default) */ - case 'z': mode = om_compress; break; - - /* Use Legacy format (ex : Linux kernel compression) */ - case 'l': legacy_format = 1; blockSize = 8 MB; break; - - /* Decoding */ - case 'd': mode = om_decompress; break; - - /* Force stdout, even if stdout==console */ - case 'c': forceStdout=1; output_filename=stdoutmark; break; - - /* Test integrity */ - case 't': mode = om_test; break; - - /* Overwrite */ - case 'f': LZ4IO_setOverwrite(1); break; - - /* Verbose mode */ - case 'v': displayLevel++; break; - - /* Quiet mode */ - case 'q': if (displayLevel) displayLevel--; break; - - /* keep source file (default anyway, so useless) (for xz/lzma compatibility) */ - case 'k': LZ4IO_setRemoveSrcFile(0); break; - - /* Modify Block Properties */ - case 'B': - while (argument[1]!=0) { - int exitBlockProperties=0; - switch(argument[1]) - { - case 'D': LZ4IO_setBlockMode(LZ4IO_blockLinked); argument++; break; - case 'X': LZ4IO_setBlockChecksumMode(1); argument ++; break; /* disabled by default */ - default : - if (argument[1] < '0' || argument[1] > '9') { - exitBlockProperties=1; - break; - } else { - unsigned B; - argument++; - B = readU32FromChar(&argument); - argument--; - if (B < 4) badusage(exeName); - if (B <= 7) { - blockSize = LZ4IO_setBlockSizeID(B); - BMK_SetBlockSize(blockSize); - DISPLAYLEVEL(2, "using blocks of size %u KB \n", (U32)(blockSize>>10)); - } else { - if (B < 32) badusage(exeName); - BMK_SetBlockSize(B); - if (B >= 1024) { - DISPLAYLEVEL(2, "bench: using blocks of size %u KB \n", (U32)(B>>10)); - } else { - DISPLAYLEVEL(2, "bench: using blocks of size %u bytes \n", (U32)(B)); - } - } - break; - } - } - if (exitBlockProperties) break; - } - break; - - /* Benchmark */ - case 'b': mode = om_bench; multiple_inputs=1; - break; - -#ifdef UTIL_HAS_CREATEFILELIST - /* recursive */ - case 'r': recursive=1; -#endif - /* fall-through */ - /* Treat non-option args as input files. See https://code.google.com/p/lz4/issues/detail?id=151 */ - case 'm': multiple_inputs=1; - break; - - /* Modify Nb Seconds (benchmark only) */ - case 'i': - { unsigned iters; - argument++; - iters = readU32FromChar(&argument); - argument--; - BMK_setNotificationLevel(displayLevel); - BMK_SetNbSeconds(iters); /* notification if displayLevel >= 3 */ - } - break; - - /* Pause at the end (hidden option) */ - case 'p': main_pause=1; break; - - /* Specific commands for customized versions */ - EXTENDED_ARGUMENTS; - - /* Unrecognised command */ - default : badusage(exeName); - } - } - continue; - } - - /* Store in *inFileNames[] if -m is used. */ - if (multiple_inputs) { inFileNames[ifnIdx++]=argument; continue; } - - /* Store first non-option arg in input_filename to preserve original cli logic. */ - if (!input_filename) { input_filename=argument; continue; } - - /* Second non-option arg in output_filename to preserve original cli logic. */ - if (!output_filename) { - output_filename=argument; - if (!strcmp (output_filename, nullOutput)) output_filename = nulmark; - continue; - } - - /* 3rd non-option arg should not exist */ - DISPLAYLEVEL(1, "Warning : %s won't be used ! Do you want multiple input files (-m) ? \n", argument); - } - - DISPLAYLEVEL(3, WELCOME_MESSAGE); -#ifdef _POSIX_C_SOURCE - DISPLAYLEVEL(4, "_POSIX_C_SOURCE defined: %ldL\n", (long) _POSIX_C_SOURCE); -#endif -#ifdef _POSIX_VERSION - DISPLAYLEVEL(4, "_POSIX_VERSION defined: %ldL\n", (long) _POSIX_VERSION); -#endif -#ifdef PLATFORM_POSIX_VERSION - DISPLAYLEVEL(4, "PLATFORM_POSIX_VERSION defined: %ldL\n", (long) PLATFORM_POSIX_VERSION); -#endif -#ifdef _FILE_OFFSET_BITS - DISPLAYLEVEL(4, "_FILE_OFFSET_BITS defined: %ldL\n", (long) _FILE_OFFSET_BITS); -#endif - if ((mode == om_compress) || (mode == om_bench)) - DISPLAYLEVEL(4, "Blocks size : %u KB\n", (U32)(blockSize>>10)); - - if (multiple_inputs) { - input_filename = inFileNames[0]; -#ifdef UTIL_HAS_CREATEFILELIST - if (recursive) { /* at this stage, filenameTable is a list of paths, which can contain both files and directories */ - extendedFileList = UTIL_createFileList(inFileNames, ifnIdx, &fileNamesBuf, &fileNamesNb); - if (extendedFileList) { - unsigned u; - for (u=0; u try to select one automatically (when possible) */ - while ((!output_filename) && (multiple_inputs==0)) { - if (!IS_CONSOLE(stdout)) { output_filename=stdoutmark; break; } /* Default to stdout whenever possible (i.e. not a console) */ - if (mode == om_auto) { /* auto-determine compression or decompression, based on file extension */ - size_t const inSize = strlen(input_filename); - size_t const extSize = strlen(LZ4_EXTENSION); - size_t const extStart= (inSize > extSize) ? inSize-extSize : 0; - if (!strcmp(input_filename+extStart, LZ4_EXTENSION)) mode = om_decompress; - else mode = om_compress; - } - if (mode == om_compress) { /* compression to file */ - size_t const l = strlen(input_filename); - dynNameSpace = (char*)calloc(1,l+5); - if (dynNameSpace==NULL) { perror(exeName); exit(1); } - strcpy(dynNameSpace, input_filename); - strcat(dynNameSpace, LZ4_EXTENSION); - output_filename = dynNameSpace; - DISPLAYLEVEL(2, "Compressed filename will be : %s \n", output_filename); - break; - } - if (mode == om_decompress) {/* decompression to file (automatic name will work only if input filename has correct format extension) */ - size_t outl; - size_t const inl = strlen(input_filename); - dynNameSpace = (char*)calloc(1,inl+1); - if (dynNameSpace==NULL) { perror(exeName); exit(1); } - strcpy(dynNameSpace, input_filename); - outl = inl; - if (inl>4) - while ((outl >= inl-4) && (input_filename[outl] == extension[outl-inl+4])) dynNameSpace[outl--]=0; - if (outl != inl-5) { DISPLAYLEVEL(1, "Cannot determine an output filename\n"); badusage(exeName); } - output_filename = dynNameSpace; - DISPLAYLEVEL(2, "Decoding file %s \n", output_filename); - } - break; - } - - /* Check if output is defined as console; trigger an error in this case */ - if (!output_filename) output_filename = "*\\dummy^!//"; - if (!strcmp(output_filename,stdoutmark) && IS_CONSOLE(stdout) && !forceStdout) { - DISPLAYLEVEL(1, "refusing to write to console without -c\n"); - exit(1); - } - /* Downgrade notification level in stdout and multiple file mode */ - if (!strcmp(output_filename,stdoutmark) && (displayLevel==2)) displayLevel=1; - if ((multiple_inputs) && (displayLevel==2)) displayLevel=1; - - /* IO Stream/File */ - LZ4IO_setNotificationLevel(displayLevel); - if (ifnIdx == 0) multiple_inputs = 0; - if (mode == om_decompress) { - if (multiple_inputs) - operationResult = LZ4IO_decompressMultipleFilenames(inFileNames, ifnIdx, !strcmp(output_filename,stdoutmark) ? stdoutmark : LZ4_EXTENSION); - else - operationResult = DEFAULT_DECOMPRESSOR(input_filename, output_filename); - } else { /* compression is default action */ - if (legacy_format) { - DISPLAYLEVEL(3, "! Generating compressed LZ4 using Legacy format (deprecated) ! \n"); - LZ4IO_compressFilename_Legacy(input_filename, output_filename, cLevel); - } else { - if (multiple_inputs) - operationResult = LZ4IO_compressMultipleFilenames(inFileNames, ifnIdx, LZ4_EXTENSION, cLevel); - else - operationResult = DEFAULT_COMPRESSOR(input_filename, output_filename, cLevel); - } - } - -_cleanup: - if (main_pause) waitEnter(); - if (dynNameSpace) free(dynNameSpace); -#ifdef UTIL_HAS_CREATEFILELIST - if (extendedFileList) - UTIL_freeFileList(extendedFileList, fileNamesBuf); - else -#endif - free((void*)inFileNames); - return operationResult; -} diff --git a/src/lz4/programs/lz4io.c b/src/lz4/programs/lz4io.c deleted file mode 100644 index 06741b49c7..0000000000 --- a/src/lz4/programs/lz4io.c +++ /dev/null @@ -1,1045 +0,0 @@ -/* - LZ4io.c - LZ4 File/Stream Interface - Copyright (C) Yann Collet 2011-2017 - - GPL v2 License - - This program is free software; 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-1301 USA. - - You can contact the author at : - - LZ4 source repository : https://github.com/lz4/lz4 - - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c -*/ -/* - Note : this is stand-alone program. - It is not part of LZ4 compression library, it is a user code of the LZ4 library. - - The license of LZ4 library is BSD. - - The license of xxHash library is BSD. - - The license of this source file is GPLv2. -*/ - - -/*-************************************ -* Compiler options -**************************************/ -#ifdef _MSC_VER /* Visual Studio */ -# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ -#endif -#if defined(__MINGW32__) && !defined(_POSIX_SOURCE) -# define _POSIX_SOURCE 1 /* disable %llu warnings with MinGW on Windows */ -#endif - - -/***************************** -* Includes -*****************************/ -#include "platform.h" /* Large File Support, SET_BINARY_MODE, SET_SPARSE_FILE_MODE, PLATFORM_POSIX_VERSION, __64BIT__ */ -#include "util.h" /* UTIL_getFileStat, UTIL_setFileStat */ -#include /* fprintf, fopen, fread, stdin, stdout, fflush, getchar */ -#include /* malloc, free */ -#include /* strerror, strcmp, strlen */ -#include /* clock */ -#include /* stat64 */ -#include /* stat64 */ -#include "lz4io.h" -#include "lz4.h" /* still required for legacy format */ -#include "lz4hc.h" /* still required for legacy format */ -#include "lz4frame.h" - - -/***************************** -* Constants -*****************************/ -#define KB *(1 <<10) -#define MB *(1 <<20) -#define GB *(1U<<30) - -#define _1BIT 0x01 -#define _2BITS 0x03 -#define _3BITS 0x07 -#define _4BITS 0x0F -#define _8BITS 0xFF - -#define MAGICNUMBER_SIZE 4 -#define LZ4IO_MAGICNUMBER 0x184D2204 -#define LZ4IO_SKIPPABLE0 0x184D2A50 -#define LZ4IO_SKIPPABLEMASK 0xFFFFFFF0 -#define LEGACY_MAGICNUMBER 0x184C2102 - -#define CACHELINE 64 -#define LEGACY_BLOCKSIZE (8 MB) -#define MIN_STREAM_BUFSIZE (192 KB) -#define LZ4IO_BLOCKSIZEID_DEFAULT 7 - - -/************************************** -* Macros -**************************************/ -#define DISPLAY(...) fprintf(stderr, __VA_ARGS__) -#define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); } -static int g_displayLevel = 0; /* 0 : no display ; 1: errors ; 2 : + result + interaction + warnings ; 3 : + progression; 4 : + information */ - -#define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \ - if (((clock_t)(g_time - clock()) > refreshRate) || (g_displayLevel>=4)) \ - { g_time = clock(); DISPLAY(__VA_ARGS__); \ - if (g_displayLevel>=4) fflush(stderr); } } -static const clock_t refreshRate = CLOCKS_PER_SEC / 6; -static clock_t g_time = 0; - - -/************************************** -* Local Parameters -**************************************/ -static int g_overwrite = 1; -static int g_testMode = 0; -static int g_blockSizeId = LZ4IO_BLOCKSIZEID_DEFAULT; -static int g_blockChecksum = 0; -static int g_streamChecksum = 1; -static int g_blockIndependence = 1; -static int g_sparseFileSupport = 1; -static int g_contentSizeFlag = 0; - - -/************************************** -* Exceptions -***************************************/ -#ifndef DEBUG -# define DEBUG 0 -#endif -#define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__); -#define EXM_THROW(error, ...) \ -{ \ - DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \ - DISPLAYLEVEL(1, "Error %i : ", error); \ - DISPLAYLEVEL(1, __VA_ARGS__); \ - DISPLAYLEVEL(1, " \n"); \ - exit(error); \ -} - - -/************************************** -* Version modifiers -**************************************/ -#define EXTENDED_ARGUMENTS -#define EXTENDED_HELP -#define EXTENDED_FORMAT -#define DEFAULT_DECOMPRESSOR LZ4IO_decompressLZ4F - - -/* ************************************************** */ -/* ****************** Parameters ******************** */ -/* ************************************************** */ - -/* Default setting : overwrite = 1; return : overwrite mode (0/1) */ -int LZ4IO_setOverwrite(int yes) -{ - g_overwrite = (yes!=0); - return g_overwrite; -} - -/* Default setting : testMode = 0; return : testMode (0/1) */ -int LZ4IO_setTestMode(int yes) -{ - g_testMode = (yes!=0); - return g_testMode; -} - -/* blockSizeID : valid values : 4-5-6-7 */ -size_t LZ4IO_setBlockSizeID(unsigned bsid) -{ - static const size_t blockSizeTable[] = { 64 KB, 256 KB, 1 MB, 4 MB }; - static const unsigned minBlockSizeID = 4; - static const unsigned maxBlockSizeID = 7; - if ((bsid < minBlockSizeID) || (bsid > maxBlockSizeID)) return 0; - g_blockSizeId = bsid; - return blockSizeTable[g_blockSizeId-minBlockSizeID]; -} - -int LZ4IO_setBlockMode(LZ4IO_blockMode_t blockMode) -{ - g_blockIndependence = (blockMode == LZ4IO_blockIndependent); - return g_blockIndependence; -} - -/* Default setting : no block checksum */ -int LZ4IO_setBlockChecksumMode(int enable) -{ - g_blockChecksum = (enable != 0); - return g_blockChecksum; -} - -/* Default setting : checksum enabled */ -int LZ4IO_setStreamChecksumMode(int enable) -{ - g_streamChecksum = (enable != 0); - return g_streamChecksum; -} - -/* Default setting : 0 (no notification) */ -int LZ4IO_setNotificationLevel(int level) -{ - g_displayLevel = level; - return g_displayLevel; -} - -/* Default setting : 0 (disabled) */ -int LZ4IO_setSparseFile(int enable) -{ - g_sparseFileSupport = (enable!=0); - return g_sparseFileSupport; -} - -/* Default setting : 0 (disabled) */ -int LZ4IO_setContentSize(int enable) -{ - g_contentSizeFlag = (enable!=0); - return g_contentSizeFlag; -} - -static U32 g_removeSrcFile = 0; -void LZ4IO_setRemoveSrcFile(unsigned flag) { g_removeSrcFile = (flag>0); } - - - -/* ************************************************************************ ** -** ********************** LZ4 File / Pipe compression ********************* ** -** ************************************************************************ */ - -static int LZ4IO_GetBlockSize_FromBlockId (int id) { return (1 << (8 + (2 * id))); } -static int LZ4IO_isSkippableMagicNumber(unsigned int magic) { - return (magic & LZ4IO_SKIPPABLEMASK) == LZ4IO_SKIPPABLE0; -} - - -/** LZ4IO_openSrcFile() : - * condition : `srcFileName` must be non-NULL. - * @result : FILE* to `dstFileName`, or NULL if it fails */ -static FILE* LZ4IO_openSrcFile(const char* srcFileName) -{ - FILE* f; - - if (!strcmp (srcFileName, stdinmark)) { - DISPLAYLEVEL(4,"Using stdin for input\n"); - f = stdin; - SET_BINARY_MODE(stdin); - } else { - f = fopen(srcFileName, "rb"); - if ( f==NULL ) DISPLAYLEVEL(1, "%s: %s \n", srcFileName, strerror(errno)); - } - - return f; -} - -/** FIO_openDstFile() : - * condition : `dstFileName` must be non-NULL. - * @result : FILE* to `dstFileName`, or NULL if it fails */ -static FILE* LZ4IO_openDstFile(const char* dstFileName) -{ - FILE* f; - - if (!strcmp (dstFileName, stdoutmark)) { - DISPLAYLEVEL(4,"Using stdout for output\n"); - f = stdout; - SET_BINARY_MODE(stdout); - if (g_sparseFileSupport==1) { - g_sparseFileSupport = 0; - DISPLAYLEVEL(4, "Sparse File Support is automatically disabled on stdout ; try --sparse \n"); - } - } else { - if (!g_overwrite && strcmp (dstFileName, nulmark)) { /* Check if destination file already exists */ - f = fopen( dstFileName, "rb" ); - if (f != NULL) { /* dest exists, prompt for overwrite authorization */ - fclose(f); - if (g_displayLevel <= 1) { /* No interaction possible */ - DISPLAY("%s already exists; not overwritten \n", dstFileName); - return NULL; - } - DISPLAY("%s already exists; do you wish to overwrite (y/N) ? ", dstFileName); - { int ch = getchar(); - if ((ch!='Y') && (ch!='y')) { - DISPLAY(" not overwritten \n"); - return NULL; - } - while ((ch!=EOF) && (ch!='\n')) ch = getchar(); /* flush rest of input line */ - } } } - f = fopen( dstFileName, "wb" ); - if (f==NULL) DISPLAYLEVEL(1, "%s: %s\n", dstFileName, strerror(errno)); - } - - /* sparse file */ - if (f && g_sparseFileSupport) { SET_SPARSE_FILE_MODE(f); } - - return f; -} - - - -/*************************************** -* Legacy Compression -***************************************/ - -/* unoptimized version; solves endianess & alignment issues */ -static void LZ4IO_writeLE32 (void* p, unsigned value32) -{ - unsigned char* const dstPtr = (unsigned char*)p; - dstPtr[0] = (unsigned char)value32; - dstPtr[1] = (unsigned char)(value32 >> 8); - dstPtr[2] = (unsigned char)(value32 >> 16); - dstPtr[3] = (unsigned char)(value32 >> 24); -} - -static int LZ4IO_LZ4_compress(const char* src, char* dst, int srcSize, int dstSize, int cLevel) -{ - (void)cLevel; - return LZ4_compress_fast(src, dst, srcSize, dstSize, 1); -} - -/* LZ4IO_compressFilename_Legacy : - * This function is intentionally "hidden" (not published in .h) - * It generates compressed streams using the old 'legacy' format */ -int LZ4IO_compressFilename_Legacy(const char* input_filename, const char* output_filename, int compressionlevel) -{ - int (*compressionFunction)(const char* src, char* dst, int srcSize, int dstSize, int cLevel); - unsigned long long filesize = 0; - unsigned long long compressedfilesize = MAGICNUMBER_SIZE; - char* in_buff; - char* out_buff; - const int outBuffSize = LZ4_compressBound(LEGACY_BLOCKSIZE); - FILE* finput; - FILE* foutput; - clock_t clockEnd; - - /* Init */ - clock_t const clockStart = clock(); - compressionFunction = (compressionlevel < 3) ? LZ4IO_LZ4_compress : LZ4_compress_HC; - - finput = LZ4IO_openSrcFile(input_filename); - if (finput == NULL) EXM_THROW(20, "%s : open file error ", input_filename); - foutput = LZ4IO_openDstFile(output_filename); - if (foutput == NULL) { fclose(finput); EXM_THROW(20, "%s : open file error ", input_filename); } - - /* Allocate Memory */ - in_buff = (char*)malloc(LEGACY_BLOCKSIZE); - out_buff = (char*)malloc(outBuffSize); - if (!in_buff || !out_buff) EXM_THROW(21, "Allocation error : not enough memory"); - - /* Write Archive Header */ - LZ4IO_writeLE32(out_buff, LEGACY_MAGICNUMBER); - { size_t const sizeCheck = fwrite(out_buff, 1, MAGICNUMBER_SIZE, foutput); - if (sizeCheck != MAGICNUMBER_SIZE) EXM_THROW(22, "Write error : cannot write header"); } - - /* Main Loop */ - while (1) { - unsigned int outSize; - /* Read Block */ - size_t const inSize = (int) fread(in_buff, (size_t)1, (size_t)LEGACY_BLOCKSIZE, finput); - if (inSize == 0) break; - if (inSize > LEGACY_BLOCKSIZE) EXM_THROW(23, "Read error : wrong fread() size report "); /* should be impossible */ - filesize += inSize; - - /* Compress Block */ - outSize = compressionFunction(in_buff, out_buff+4, (int)inSize, outBuffSize, compressionlevel); - compressedfilesize += outSize+4; - DISPLAYUPDATE(2, "\rRead : %i MB ==> %.2f%% ", - (int)(filesize>>20), (double)compressedfilesize/filesize*100); - - /* Write Block */ - LZ4IO_writeLE32(out_buff, outSize); - { size_t const sizeCheck = fwrite(out_buff, 1, outSize+4, foutput); - if (sizeCheck!=(size_t)(outSize+4)) - EXM_THROW(24, "Write error : cannot write compressed block"); - } } - if (ferror(finput)) EXM_THROW(25, "Error while reading %s ", input_filename); - - /* Status */ - clockEnd = clock(); - if (clockEnd==clockStart) clockEnd+=1; /* avoid division by zero (speed) */ - filesize += !filesize; /* avoid division by zero (ratio) */ - DISPLAYLEVEL(2, "\r%79s\r", ""); /* blank line */ - DISPLAYLEVEL(2,"Compressed %llu bytes into %llu bytes ==> %.2f%%\n", - filesize, compressedfilesize, (double)compressedfilesize / filesize * 100); - { double const seconds = (double)(clockEnd - clockStart) / CLOCKS_PER_SEC; - DISPLAYLEVEL(4,"Done in %.2f s ==> %.2f MB/s\n", seconds, - (double)filesize / seconds / 1024 / 1024); - } - - /* Close & Free */ - free(in_buff); - free(out_buff); - fclose(finput); - fclose(foutput); - - return 0; -} - - -/********************************************* -* Compression using Frame format -*********************************************/ - -typedef struct { - void* srcBuffer; - size_t srcBufferSize; - void* dstBuffer; - size_t dstBufferSize; - LZ4F_compressionContext_t ctx; -} cRess_t; - -static cRess_t LZ4IO_createCResources(void) -{ - const size_t blockSize = (size_t)LZ4IO_GetBlockSize_FromBlockId (g_blockSizeId); - cRess_t ress; - - LZ4F_errorCode_t const errorCode = LZ4F_createCompressionContext(&(ress.ctx), LZ4F_VERSION); - if (LZ4F_isError(errorCode)) EXM_THROW(30, "Allocation error : can't create LZ4F context : %s", LZ4F_getErrorName(errorCode)); - - /* Allocate Memory */ - ress.srcBuffer = malloc(blockSize); - ress.srcBufferSize = blockSize; - ress.dstBufferSize = LZ4F_compressFrameBound(blockSize, NULL); /* cover worst case */ - ress.dstBuffer = malloc(ress.dstBufferSize); - if (!ress.srcBuffer || !ress.dstBuffer) EXM_THROW(31, "Allocation error : not enough memory"); - - return ress; -} - -static void LZ4IO_freeCResources(cRess_t ress) -{ - free(ress.srcBuffer); - free(ress.dstBuffer); - { LZ4F_errorCode_t const errorCode = LZ4F_freeCompressionContext(ress.ctx); - if (LZ4F_isError(errorCode)) EXM_THROW(38, "Error : can't free LZ4F context resource : %s", LZ4F_getErrorName(errorCode)); } -} - -/* - * LZ4IO_compressFilename_extRess() - * result : 0 : compression completed correctly - * 1 : missing or pb opening srcFileName - */ -static int LZ4IO_compressFilename_extRess(cRess_t ress, const char* srcFileName, const char* dstFileName, int compressionLevel) -{ - unsigned long long filesize = 0; - unsigned long long compressedfilesize = 0; - FILE* srcFile; - FILE* dstFile; - void* const srcBuffer = ress.srcBuffer; - void* const dstBuffer = ress.dstBuffer; - const size_t dstBufferSize = ress.dstBufferSize; - const size_t blockSize = (size_t)LZ4IO_GetBlockSize_FromBlockId (g_blockSizeId); - size_t readSize; - LZ4F_compressionContext_t ctx = ress.ctx; /* just a pointer */ - LZ4F_preferences_t prefs; - - /* Init */ - srcFile = LZ4IO_openSrcFile(srcFileName); - if (srcFile == NULL) return 1; - dstFile = LZ4IO_openDstFile(dstFileName); - if (dstFile == NULL) { fclose(srcFile); return 1; } - memset(&prefs, 0, sizeof(prefs)); - - - /* Set compression parameters */ - prefs.autoFlush = 1; - prefs.compressionLevel = compressionLevel; - prefs.frameInfo.blockMode = (LZ4F_blockMode_t)g_blockIndependence; - prefs.frameInfo.blockSizeID = (LZ4F_blockSizeID_t)g_blockSizeId; - prefs.frameInfo.blockChecksumFlag = (LZ4F_blockChecksum_t)g_blockChecksum; - prefs.frameInfo.contentChecksumFlag = (LZ4F_contentChecksum_t)g_streamChecksum; - if (g_contentSizeFlag) { - U64 const fileSize = UTIL_getFileSize(srcFileName); - prefs.frameInfo.contentSize = fileSize; /* == 0 if input == stdin */ - if (fileSize==0) - DISPLAYLEVEL(3, "Warning : cannot determine input content size \n"); - } - - /* read first block */ - readSize = fread(srcBuffer, (size_t)1, blockSize, srcFile); - if (ferror(srcFile)) EXM_THROW(30, "Error reading %s ", srcFileName); - filesize += readSize; - - /* single-block file */ - if (readSize < blockSize) { - /* Compress in single pass */ - size_t const cSize = LZ4F_compressFrame(dstBuffer, dstBufferSize, srcBuffer, readSize, &prefs); - if (LZ4F_isError(cSize)) EXM_THROW(31, "Compression failed : %s", LZ4F_getErrorName(cSize)); - compressedfilesize = cSize; - DISPLAYUPDATE(2, "\rRead : %u MB ==> %.2f%% ", - (unsigned)(filesize>>20), (double)compressedfilesize/(filesize+!filesize)*100); /* avoid division by zero */ - - /* Write Block */ - { size_t const sizeCheck = fwrite(dstBuffer, 1, cSize, dstFile); - if (sizeCheck!=cSize) EXM_THROW(32, "Write error : cannot write compressed block"); - } } - - else - - /* multiple-blocks file */ - { - /* Write Archive Header */ - size_t headerSize = LZ4F_compressBegin(ctx, dstBuffer, dstBufferSize, &prefs); - if (LZ4F_isError(headerSize)) EXM_THROW(33, "File header generation failed : %s", LZ4F_getErrorName(headerSize)); - { size_t const sizeCheck = fwrite(dstBuffer, 1, headerSize, dstFile); - if (sizeCheck!=headerSize) EXM_THROW(34, "Write error : cannot write header"); } - compressedfilesize += headerSize; - - /* Main Loop */ - while (readSize>0) { - size_t outSize; - - /* Compress Block */ - outSize = LZ4F_compressUpdate(ctx, dstBuffer, dstBufferSize, srcBuffer, readSize, NULL); - if (LZ4F_isError(outSize)) EXM_THROW(35, "Compression failed : %s", LZ4F_getErrorName(outSize)); - compressedfilesize += outSize; - DISPLAYUPDATE(2, "\rRead : %u MB ==> %.2f%% ", (unsigned)(filesize>>20), (double)compressedfilesize/filesize*100); - - /* Write Block */ - { size_t const sizeCheck = fwrite(dstBuffer, 1, outSize, dstFile); - if (sizeCheck!=outSize) EXM_THROW(36, "Write error : cannot write compressed block"); } - - /* Read next block */ - readSize = fread(srcBuffer, (size_t)1, (size_t)blockSize, srcFile); - filesize += readSize; - } - if (ferror(srcFile)) EXM_THROW(37, "Error reading %s ", srcFileName); - - /* End of Stream mark */ - headerSize = LZ4F_compressEnd(ctx, dstBuffer, dstBufferSize, NULL); - if (LZ4F_isError(headerSize)) EXM_THROW(38, "End of file generation failed : %s", LZ4F_getErrorName(headerSize)); - - { size_t const sizeCheck = fwrite(dstBuffer, 1, headerSize, dstFile); - if (sizeCheck!=headerSize) EXM_THROW(39, "Write error : cannot write end of stream"); } - compressedfilesize += headerSize; - } - - /* Release files */ - fclose (srcFile); - fclose (dstFile); - - /* Copy owner, file permissions and modification time */ - { stat_t statbuf; - if (strcmp (srcFileName, stdinmark) && strcmp (dstFileName, stdoutmark) && UTIL_getFileStat(srcFileName, &statbuf)) - UTIL_setFileStat(dstFileName, &statbuf); - } - - if (g_removeSrcFile) { if (remove(srcFileName)) EXM_THROW(40, "Remove error : %s: %s", srcFileName, strerror(errno)); } /* remove source file : --rm */ - - /* Final Status */ - DISPLAYLEVEL(2, "\r%79s\r", ""); - DISPLAYLEVEL(2, "Compressed %llu bytes into %llu bytes ==> %.2f%%\n", - filesize, compressedfilesize, (double)compressedfilesize/(filesize + !filesize)*100); /* avoid division by zero */ - - return 0; -} - - -int LZ4IO_compressFilename(const char* srcFileName, const char* dstFileName, int compressionLevel) -{ - clock_t const start = clock(); - cRess_t const ress = LZ4IO_createCResources(); - - int const issueWithSrcFile = LZ4IO_compressFilename_extRess(ress, srcFileName, dstFileName, compressionLevel); - - /* Free resources */ - LZ4IO_freeCResources(ress); - - /* Final Status */ - { clock_t const end = clock(); - double const seconds = (double)(end - start) / CLOCKS_PER_SEC; - DISPLAYLEVEL(4, "Completed in %.2f sec \n", seconds); - } - - return issueWithSrcFile; -} - - -#define FNSPACE 30 -int LZ4IO_compressMultipleFilenames(const char** inFileNamesTable, int ifntSize, const char* suffix, int compressionLevel) -{ - int i; - int missed_files = 0; - char* dstFileName = (char*)malloc(FNSPACE); - size_t ofnSize = FNSPACE; - const size_t suffixSize = strlen(suffix); - cRess_t ress; - - if (dstFileName == NULL) return ifntSize; /* not enough memory */ - ress = LZ4IO_createCResources(); - - /* loop on each file */ - for (i=0; i 1 GB) { - int const seekResult = UTIL_fseek(file, 1 GB, SEEK_CUR); - if (seekResult != 0) EXM_THROW(71, "1 GB skip error (sparse file support)"); - storedSkips -= 1 GB; - } - - while (ptrT < bufferTEnd) { - size_t seg0SizeT = segmentSizeT; - size_t nb0T; - - /* count leading zeros */ - if (seg0SizeT > bufferSizeT) seg0SizeT = bufferSizeT; - bufferSizeT -= seg0SizeT; - for (nb0T=0; (nb0T < seg0SizeT) && (ptrT[nb0T] == 0); nb0T++) ; - storedSkips += (unsigned)(nb0T * sizeT); - - if (nb0T != seg0SizeT) { /* not all 0s */ - errno = 0; - { int const seekResult = UTIL_fseek(file, storedSkips, SEEK_CUR); - if (seekResult) EXM_THROW(72, "Sparse skip error(%d): %s ; try --no-sparse", (int)errno, strerror(errno)); - } - storedSkips = 0; - seg0SizeT -= nb0T; - ptrT += nb0T; - { size_t const sizeCheck = fwrite(ptrT, sizeT, seg0SizeT, file); - if (sizeCheck != seg0SizeT) EXM_THROW(73, "Write error : cannot write decoded block"); - } } - ptrT += seg0SizeT; - } - - if (bufferSize & maskT) { /* size not multiple of sizeT : implies end of block */ - const char* const restStart = (const char*)bufferTEnd; - const char* restPtr = restStart; - size_t const restSize = bufferSize & maskT; - const char* const restEnd = restStart + restSize; - for (; (restPtr < restEnd) && (*restPtr == 0); restPtr++) ; - storedSkips += (unsigned) (restPtr - restStart); - if (restPtr != restEnd) { - int const seekResult = UTIL_fseek(file, storedSkips, SEEK_CUR); - if (seekResult) EXM_THROW(74, "Sparse skip error ; try --no-sparse"); - storedSkips = 0; - { size_t const sizeCheck = fwrite(restPtr, 1, restEnd - restPtr, file); - if (sizeCheck != (size_t)(restEnd - restPtr)) EXM_THROW(75, "Write error : cannot write decoded end of block"); - } } - } - - return storedSkips; -} - -static void LZ4IO_fwriteSparseEnd(FILE* file, unsigned storedSkips) -{ - if (storedSkips>0) { /* implies g_sparseFileSupport>0 */ - int const seekResult = UTIL_fseek(file, storedSkips-1, SEEK_CUR); - if (seekResult != 0) EXM_THROW(69, "Final skip error (sparse file)\n"); - { const char lastZeroByte[1] = { 0 }; - size_t const sizeCheck = fwrite(lastZeroByte, 1, 1, file); - if (sizeCheck != 1) EXM_THROW(69, "Write error : cannot write last zero\n"); - } } -} - - -static unsigned g_magicRead = 0; /* out-parameter of LZ4IO_decodeLegacyStream() */ -static unsigned long long LZ4IO_decodeLegacyStream(FILE* finput, FILE* foutput) -{ - unsigned long long streamSize = 0; - unsigned storedSkips = 0; - - /* Allocate Memory */ - char* const in_buff = (char*)malloc(LZ4_compressBound(LEGACY_BLOCKSIZE)); - char* const out_buff = (char*)malloc(LEGACY_BLOCKSIZE); - if (!in_buff || !out_buff) EXM_THROW(51, "Allocation error : not enough memory"); - - /* Main Loop */ - while (1) { - unsigned int blockSize; - - /* Block Size */ - { size_t const sizeCheck = fread(in_buff, 1, 4, finput); - if (sizeCheck == 0) break; /* Nothing to read : file read is completed */ - if (sizeCheck != 4) EXM_THROW(52, "Read error : cannot access block size "); } - blockSize = LZ4IO_readLE32(in_buff); /* Convert to Little Endian */ - if (blockSize > LZ4_COMPRESSBOUND(LEGACY_BLOCKSIZE)) { - /* Cannot read next block : maybe new stream ? */ - g_magicRead = blockSize; - break; - } - - /* Read Block */ - { size_t const sizeCheck = fread(in_buff, 1, blockSize, finput); - if (sizeCheck!=blockSize) EXM_THROW(52, "Read error : cannot access compressed block !"); } - - /* Decode Block */ - { int const decodeSize = LZ4_decompress_safe(in_buff, out_buff, blockSize, LEGACY_BLOCKSIZE); - if (decodeSize < 0) EXM_THROW(53, "Decoding Failed ! Corrupted input detected !"); - streamSize += decodeSize; - /* Write Block */ - storedSkips = LZ4IO_fwriteSparse(foutput, out_buff, decodeSize, storedSkips); /* success or die */ - } } - if (ferror(finput)) EXM_THROW(54, "Read error : ferror"); - - LZ4IO_fwriteSparseEnd(foutput, storedSkips); - - /* Free */ - free(in_buff); - free(out_buff); - - return streamSize; -} - - - -typedef struct { - void* srcBuffer; - size_t srcBufferSize; - void* dstBuffer; - size_t dstBufferSize; - FILE* dstFile; - LZ4F_decompressionContext_t dCtx; -} dRess_t; - -static const size_t LZ4IO_dBufferSize = 64 KB; -static dRess_t LZ4IO_createDResources(void) -{ - dRess_t ress; - - /* init */ - LZ4F_errorCode_t const errorCode = LZ4F_createDecompressionContext(&ress.dCtx, LZ4F_VERSION); - if (LZ4F_isError(errorCode)) EXM_THROW(60, "Can't create LZ4F context : %s", LZ4F_getErrorName(errorCode)); - - /* Allocate Memory */ - ress.srcBufferSize = LZ4IO_dBufferSize; - ress.srcBuffer = malloc(ress.srcBufferSize); - ress.dstBufferSize = LZ4IO_dBufferSize; - ress.dstBuffer = malloc(ress.dstBufferSize); - if (!ress.srcBuffer || !ress.dstBuffer) EXM_THROW(61, "Allocation error : not enough memory"); - - ress.dstFile = NULL; - return ress; -} - -static void LZ4IO_freeDResources(dRess_t ress) -{ - LZ4F_errorCode_t errorCode = LZ4F_freeDecompressionContext(ress.dCtx); - if (LZ4F_isError(errorCode)) EXM_THROW(69, "Error : can't free LZ4F context resource : %s", LZ4F_getErrorName(errorCode)); - free(ress.srcBuffer); - free(ress.dstBuffer); -} - - -static unsigned long long LZ4IO_decompressLZ4F(dRess_t ress, FILE* srcFile, FILE* dstFile) -{ - unsigned long long filesize = 0; - LZ4F_errorCode_t nextToLoad; - unsigned storedSkips = 0; - - /* Init feed with magic number (already consumed from FILE* sFile) */ - { size_t inSize = MAGICNUMBER_SIZE; - size_t outSize= 0; - LZ4IO_writeLE32(ress.srcBuffer, LZ4IO_MAGICNUMBER); - nextToLoad = LZ4F_decompress(ress.dCtx, ress.dstBuffer, &outSize, ress.srcBuffer, &inSize, NULL); - if (LZ4F_isError(nextToLoad)) EXM_THROW(62, "Header error : %s", LZ4F_getErrorName(nextToLoad)); - } - - /* Main Loop */ - for (;nextToLoad;) { - size_t readSize; - size_t pos = 0; - size_t decodedBytes = ress.dstBufferSize; - - /* Read input */ - if (nextToLoad > ress.srcBufferSize) nextToLoad = ress.srcBufferSize; - readSize = fread(ress.srcBuffer, 1, nextToLoad, srcFile); - if (!readSize) break; /* reached end of file or stream */ - - while ((pos < readSize) || (decodedBytes == ress.dstBufferSize)) { /* still to read, or still to flush */ - /* Decode Input (at least partially) */ - size_t remaining = readSize - pos; - decodedBytes = ress.dstBufferSize; - nextToLoad = LZ4F_decompress(ress.dCtx, ress.dstBuffer, &decodedBytes, (char*)(ress.srcBuffer)+pos, &remaining, NULL); - if (LZ4F_isError(nextToLoad)) EXM_THROW(66, "Decompression error : %s", LZ4F_getErrorName(nextToLoad)); - pos += remaining; - - /* Write Block */ - if (decodedBytes) { - if (!g_testMode) - storedSkips = LZ4IO_fwriteSparse(dstFile, ress.dstBuffer, decodedBytes, storedSkips); - filesize += decodedBytes; - DISPLAYUPDATE(2, "\rDecompressed : %u MB ", (unsigned)(filesize>>20)); - } - - if (!nextToLoad) break; - } - } - /* can be out because readSize == 0, which could be an fread() error */ - if (ferror(srcFile)) EXM_THROW(67, "Read error"); - - if (!g_testMode) LZ4IO_fwriteSparseEnd(dstFile, storedSkips); - if (nextToLoad!=0) EXM_THROW(68, "Unfinished stream"); - - return filesize; -} - - -#define PTSIZE (64 KB) -#define PTSIZET (PTSIZE / sizeof(size_t)) -static unsigned long long LZ4IO_passThrough(FILE* finput, FILE* foutput, unsigned char MNstore[MAGICNUMBER_SIZE]) -{ - size_t buffer[PTSIZET]; - size_t readBytes = 1; - unsigned long long total = MAGICNUMBER_SIZE; - unsigned storedSkips = 0; - - size_t const sizeCheck = fwrite(MNstore, 1, MAGICNUMBER_SIZE, foutput); - if (sizeCheck != MAGICNUMBER_SIZE) EXM_THROW(50, "Pass-through write error"); - - while (readBytes) { - readBytes = fread(buffer, 1, PTSIZE, finput); - total += readBytes; - storedSkips = LZ4IO_fwriteSparse(foutput, buffer, readBytes, storedSkips); - } - if (ferror(finput)) EXM_THROW(51, "Read Error") - - LZ4IO_fwriteSparseEnd(foutput, storedSkips); - return total; -} - - -/** Safely handle cases when (unsigned)offset > LONG_MAX */ -static int fseek_u32(FILE *fp, unsigned offset, int where) -{ - const unsigned stepMax = 1U << 30; - int errorNb = 0; - - if (where != SEEK_CUR) return -1; /* Only allows SEEK_CUR */ - while (offset > 0) { - unsigned s = offset; - if (s > stepMax) s = stepMax; - errorNb = UTIL_fseek(fp, (long) s, SEEK_CUR); - if (errorNb != 0) break; - offset -= s; - } - return errorNb; -} - -#define ENDOFSTREAM ((unsigned long long)-1) -static unsigned long long selectDecoder(dRess_t ress, FILE* finput, FILE* foutput) -{ - unsigned char MNstore[MAGICNUMBER_SIZE]; - unsigned magicNumber; - static unsigned nbFrames = 0; - - /* init */ - nbFrames++; - - /* Check Archive Header */ - if (g_magicRead) { /* magic number already read from finput (see legacy frame)*/ - magicNumber = g_magicRead; - g_magicRead = 0; - } else { - size_t const nbReadBytes = fread(MNstore, 1, MAGICNUMBER_SIZE, finput); - if (nbReadBytes==0) { nbFrames = 0; return ENDOFSTREAM; } /* EOF */ - if (nbReadBytes != MAGICNUMBER_SIZE) - EXM_THROW(40, "Unrecognized header : Magic Number unreadable"); - magicNumber = LZ4IO_readLE32(MNstore); /* Little Endian format */ - } - if (LZ4IO_isSkippableMagicNumber(magicNumber)) - magicNumber = LZ4IO_SKIPPABLE0; /* fold skippable magic numbers */ - - switch(magicNumber) - { - case LZ4IO_MAGICNUMBER: - return LZ4IO_decompressLZ4F(ress, finput, foutput); - case LEGACY_MAGICNUMBER: - DISPLAYLEVEL(4, "Detected : Legacy format \n"); - return LZ4IO_decodeLegacyStream(finput, foutput); - case LZ4IO_SKIPPABLE0: - DISPLAYLEVEL(4, "Skipping detected skippable area \n"); - { size_t const nbReadBytes = fread(MNstore, 1, 4, finput); - if (nbReadBytes != 4) - EXM_THROW(42, "Stream error : skippable size unreadable"); - } - { unsigned const size = LZ4IO_readLE32(MNstore); - int const errorNb = fseek_u32(finput, size, SEEK_CUR); - if (errorNb != 0) - EXM_THROW(43, "Stream error : cannot skip skippable area"); - } - return 0; - EXTENDED_FORMAT; /* macro extension for custom formats */ - default: - if (nbFrames == 1) { /* just started */ - /* Wrong magic number at the beginning of 1st stream */ - if (!g_testMode && g_overwrite) { - nbFrames = 0; - return LZ4IO_passThrough(finput, foutput, MNstore); - } - EXM_THROW(44,"Unrecognized header : file cannot be decoded"); - } - { long int const position = ftell(finput); /* only works for files < 2 GB */ - DISPLAYLEVEL(2, "Stream followed by undecodable data "); - if (position != -1L) - DISPLAYLEVEL(2, "at position %i ", (int)position); - DISPLAYLEVEL(2, "\n"); - } - return ENDOFSTREAM; - } -} - - -static int LZ4IO_decompressSrcFile(dRess_t ress, const char* input_filename, const char* output_filename) -{ - FILE* const foutput = ress.dstFile; - unsigned long long filesize = 0; - - /* Init */ - FILE* const finput = LZ4IO_openSrcFile(input_filename); - if (finput==NULL) return 1; - - /* Loop over multiple streams */ - for ( ; ; ) { /* endless loop, see break condition */ - unsigned long long const decodedSize = - selectDecoder(ress, finput, foutput); - if (decodedSize == ENDOFSTREAM) break; - filesize += decodedSize; - } - - /* Close input */ - fclose(finput); - if (g_removeSrcFile) { /* --rm */ - if (remove(input_filename)) - EXM_THROW(45, "Remove error : %s: %s", input_filename, strerror(errno)); - } - - /* Final Status */ - DISPLAYLEVEL(2, "\r%79s\r", ""); - DISPLAYLEVEL(2, "%-20.20s : decoded %llu bytes \n", input_filename, filesize); - (void)output_filename; - - return 0; -} - - -static int LZ4IO_decompressDstFile(dRess_t ress, const char* input_filename, const char* output_filename) -{ - FILE* const foutput = LZ4IO_openDstFile(output_filename); - if (foutput==NULL) return 1; /* failure */ - - ress.dstFile = foutput; - LZ4IO_decompressSrcFile(ress, input_filename, output_filename); - - fclose(foutput); - - /* Copy owner, file permissions and modification time */ - { stat_t statbuf; - if ( strcmp (input_filename, stdinmark) - && strcmp (output_filename, stdoutmark) - && strcmp (output_filename, nulmark) - && UTIL_getFileStat(input_filename, &statbuf) ) { - UTIL_setFileStat(output_filename, &statbuf); - /* should return value be read ? or is silent fail good enough ? */ - } } - - return 0; -} - - -int LZ4IO_decompressFilename(const char* input_filename, const char* output_filename) -{ - dRess_t const ress = LZ4IO_createDResources(); - clock_t const start = clock(); - - int const missingFiles = LZ4IO_decompressDstFile(ress, input_filename, output_filename); - - clock_t const end = clock(); - double const seconds = (double)(end - start) / CLOCKS_PER_SEC; - DISPLAYLEVEL(4, "Done in %.2f sec \n", seconds); - - LZ4IO_freeDResources(ress); - return missingFiles; -} - - -int LZ4IO_decompressMultipleFilenames(const char** inFileNamesTable, int ifntSize, const char* suffix) -{ - int i; - int skippedFiles = 0; - int missingFiles = 0; - char* outFileName = (char*)malloc(FNSPACE); - size_t ofnSize = FNSPACE; - size_t const suffixSize = strlen(suffix); - dRess_t ress = LZ4IO_createDResources(); - - if (outFileName==NULL) return ifntSize; /* not enough memory */ - ress.dstFile = LZ4IO_openDstFile(stdoutmark); - - for (i=0; i /* size_t */ - - -/* ************************************************** */ -/* Special input/output values */ -/* ************************************************** */ -#define NULL_OUTPUT "null" -static const char stdinmark[] = "stdin"; -static const char stdoutmark[] = "stdout"; -#ifdef _WIN32 -static const char nulmark[] = "nul"; -#else -static const char nulmark[] = "/dev/null"; -#endif - - -/* ************************************************** */ -/* ****************** Functions ********************* */ -/* ************************************************** */ - -int LZ4IO_compressFilename (const char* input_filename, const char* output_filename, int compressionlevel); -int LZ4IO_decompressFilename(const char* input_filename, const char* output_filename); - -int LZ4IO_compressMultipleFilenames(const char** inFileNamesTable, int ifntSize, const char* suffix, int compressionlevel); -int LZ4IO_decompressMultipleFilenames(const char** inFileNamesTable, int ifntSize, const char* suffix); - - -/* ************************************************** */ -/* ****************** Parameters ******************** */ -/* ************************************************** */ - -/* Default setting : overwrite = 1; - return : overwrite mode (0/1) */ -int LZ4IO_setOverwrite(int yes); - -/* Default setting : testMode = 0; - return : testMode (0/1) */ -int LZ4IO_setTestMode(int yes); - -/* blockSizeID : valid values : 4-5-6-7 - return : 0 if error, blockSize if OK */ -size_t LZ4IO_setBlockSizeID(unsigned blockSizeID); - -/* Default setting : independent blocks */ -typedef enum { LZ4IO_blockLinked=0, LZ4IO_blockIndependent} LZ4IO_blockMode_t; -int LZ4IO_setBlockMode(LZ4IO_blockMode_t blockMode); - -/* Default setting : no block checksum */ -int LZ4IO_setBlockChecksumMode(int xxhash); - -/* Default setting : stream checksum enabled */ -int LZ4IO_setStreamChecksumMode(int xxhash); - -/* Default setting : 0 (no notification) */ -int LZ4IO_setNotificationLevel(int level); - -/* Default setting : 0 (disabled) */ -int LZ4IO_setSparseFile(int enable); - -/* Default setting : 0 (disabled) */ -int LZ4IO_setContentSize(int enable); - -void LZ4IO_setRemoveSrcFile(unsigned flag); - - -#endif /* LZ4IO_H_237902873 */ diff --git a/src/lz4/programs/platform.h b/src/lz4/programs/platform.h deleted file mode 100644 index 66491b6802..0000000000 --- a/src/lz4/programs/platform.h +++ /dev/null @@ -1,154 +0,0 @@ -/* - platform.h - compiler and OS detection - Copyright (C) 2016-present, Przemyslaw Skibinski, Yann Collet - - This program is free software; 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-1301 USA. -*/ - -#ifndef PLATFORM_H_MODULE -#define PLATFORM_H_MODULE - -#if defined (__cplusplus) -extern "C" { -#endif - - - -/* ************************************** -* Compiler Options -****************************************/ -#if defined(_MSC_VER) -# define _CRT_SECURE_NO_WARNINGS /* Disable Visual Studio warning messages for fopen, strncpy, strerror */ -# define _CRT_SECURE_NO_DEPRECATE /* VS2005 - must be declared before and */ -# if (_MSC_VER <= 1800) /* (1800 = Visual Studio 2013) */ -# define snprintf sprintf_s /* snprintf unsupported by Visual <= 2013 */ -# endif -#endif - - -/* ************************************** -* Detect 64-bit OS -* http://nadeausoftware.com/articles/2012/02/c_c_tip_how_detect_processor_type_using_compiler_predefined_macros -****************************************/ -#if defined __ia64 || defined _M_IA64 /* Intel Itanium */ \ - || defined __powerpc64__ || defined __ppc64__ || defined __PPC64__ /* POWER 64-bit */ \ - || (defined __sparc && (defined __sparcv9 || defined __sparc_v9__ || defined __arch64__)) || defined __sparc64__ /* SPARC 64-bit */ \ - || defined __x86_64__s || defined _M_X64 /* x86 64-bit */ \ - || defined __arm64__ || defined __aarch64__ || defined __ARM64_ARCH_8__ /* ARM 64-bit */ \ - || (defined __mips && (__mips == 64 || __mips == 4 || __mips == 3)) /* MIPS 64-bit */ \ - || defined _LP64 || defined __LP64__ /* NetBSD, OpenBSD */ || defined __64BIT__ /* AIX */ || defined _ADDR64 /* Cray */ \ - || (defined __SIZEOF_POINTER__ && __SIZEOF_POINTER__ == 8) /* gcc */ -# if !defined(__64BIT__) -# define __64BIT__ 1 -# endif -#endif - - -/* ********************************************************* -* Turn on Large Files support (>4GB) for 32-bit Linux/Unix -***********************************************************/ -#if !defined(__64BIT__) || defined(__MINGW32__) /* No point defining Large file for 64 bit but MinGW-w64 requires it */ -# if !defined(_FILE_OFFSET_BITS) -# define _FILE_OFFSET_BITS 64 /* turn off_t into a 64-bit type for ftello, fseeko */ -# endif -# if !defined(_LARGEFILE_SOURCE) /* obsolete macro, replaced with _FILE_OFFSET_BITS */ -# define _LARGEFILE_SOURCE 1 /* Large File Support extension (LFS) - fseeko, ftello */ -# endif -# if defined(_AIX) || defined(__hpux) -# define _LARGE_FILES /* Large file support on 32-bits AIX and HP-UX */ -# endif -#endif - - -/* ************************************************************ -* Detect POSIX version -* PLATFORM_POSIX_VERSION = -1 for non-Unix e.g. Windows -* PLATFORM_POSIX_VERSION = 0 for Unix-like non-POSIX -* PLATFORM_POSIX_VERSION >= 1 is equal to found _POSIX_VERSION -***************************************************************/ -#if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__)) /* UNIX-like OS */ \ - || defined(__midipix__) || defined(__VMS)) -# if (defined(__APPLE__) && defined(__MACH__)) || defined(__SVR4) || defined(_AIX) || defined(__hpux) /* POSIX.1–2001 (SUSv3) conformant */ \ - || defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) /* BSD distros */ -# define PLATFORM_POSIX_VERSION 200112L -# else -# if defined(__linux__) || defined(__linux) -# ifndef _POSIX_C_SOURCE -# define _POSIX_C_SOURCE 200112L /* use feature test macro */ -# endif -# endif -# include /* declares _POSIX_VERSION */ -# if defined(_POSIX_VERSION) /* POSIX compliant */ -# define PLATFORM_POSIX_VERSION _POSIX_VERSION -# else -# define PLATFORM_POSIX_VERSION 0 -# endif -# endif -#endif -#if !defined(PLATFORM_POSIX_VERSION) -# define PLATFORM_POSIX_VERSION -1 -#endif - - -/*-********************************************* -* Detect if isatty() and fileno() are available -************************************************/ -#if (defined(__linux__) && (PLATFORM_POSIX_VERSION >= 1)) || (PLATFORM_POSIX_VERSION >= 200112L) || defined(__DJGPP__) -# include /* isatty */ -# define IS_CONSOLE(stdStream) isatty(fileno(stdStream)) -#elif defined(MSDOS) || defined(OS2) || defined(__CYGWIN__) -# include /* _isatty */ -# define IS_CONSOLE(stdStream) _isatty(_fileno(stdStream)) -#elif defined(WIN32) || defined(_WIN32) -# include /* _isatty */ -# include /* DeviceIoControl, HANDLE, FSCTL_SET_SPARSE */ -# include /* FILE */ -static __inline int IS_CONSOLE(FILE* stdStream) -{ - DWORD dummy; - return _isatty(_fileno(stdStream)) && GetConsoleMode((HANDLE)_get_osfhandle(_fileno(stdStream)), &dummy); -} -#else -# define IS_CONSOLE(stdStream) 0 -#endif - - -/****************************** -* OS-specific Includes -******************************/ -#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(_WIN32) -# include /* _O_BINARY */ -# include /* _setmode, _fileno, _get_osfhandle */ -# if !defined(__DJGPP__) -# include /* DeviceIoControl, HANDLE, FSCTL_SET_SPARSE */ -# include /* FSCTL_SET_SPARSE */ -# define SET_BINARY_MODE(file) { int unused=_setmode(_fileno(file), _O_BINARY); (void)unused; } -# define SET_SPARSE_FILE_MODE(file) { DWORD dw; DeviceIoControl((HANDLE) _get_osfhandle(_fileno(file)), FSCTL_SET_SPARSE, 0, 0, 0, 0, &dw, 0); } -# else -# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) -# define SET_SPARSE_FILE_MODE(file) -# endif -#else -# define SET_BINARY_MODE(file) -# define SET_SPARSE_FILE_MODE(file) -#endif - - - -#if defined (__cplusplus) -} -#endif - -#endif /* PLATFORM_H_MODULE */ diff --git a/src/lz4/programs/util.h b/src/lz4/programs/util.h deleted file mode 100644 index 5a69c55c0a..0000000000 --- a/src/lz4/programs/util.h +++ /dev/null @@ -1,494 +0,0 @@ -/* - util.h - utility functions - Copyright (C) 2016-present, Przemyslaw Skibinski, Yann Collet - - This program is free software; 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-1301 USA. -*/ - -#ifndef UTIL_H_MODULE -#define UTIL_H_MODULE - -#if defined (__cplusplus) -extern "C" { -#endif - - - -/*-**************************************** -* Dependencies -******************************************/ -#include "platform.h" /* PLATFORM_POSIX_VERSION */ -#include /* malloc */ -#include /* size_t, ptrdiff_t */ -#include /* fprintf */ -#include /* stat, utime */ -#include /* stat */ -#if defined(_MSC_VER) -# include /* utime */ -# include /* _chmod */ -#else -# include /* chown, stat */ -# include /* utime */ -#endif -#include /* time */ -#include - - - -/*-************************************************************** -* Basic Types -*****************************************************************/ -#if !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) -# include - typedef uint8_t BYTE; - typedef uint16_t U16; - typedef int16_t S16; - typedef uint32_t U32; - typedef int32_t S32; - typedef uint64_t U64; - typedef int64_t S64; -#else - typedef unsigned char BYTE; - typedef unsigned short U16; - typedef signed short S16; - typedef unsigned int U32; - typedef signed int S32; - typedef unsigned long long U64; - typedef signed long long S64; -#endif - - -/* ************************************************************ -* Avoid fseek()'s 2GiB barrier with MSVC, MacOS, *BSD, MinGW -***************************************************************/ -#if defined(_MSC_VER) && (_MSC_VER >= 1400) -# define UTIL_fseek _fseeki64 -#elif !defined(__64BIT__) && (PLATFORM_POSIX_VERSION >= 200112L) /* No point defining Large file for 64 bit */ -# define UTIL_fseek fseeko -#elif defined(__MINGW32__) && defined(__MSVCRT__) && !defined(__STRICT_ANSI__) && !defined(__NO_MINGW_LFS) -# define UTIL_fseek fseeko64 -#else -# define UTIL_fseek fseek -#endif - - -/*-**************************************** -* Sleep functions: Windows - Posix - others -******************************************/ -#if defined(_WIN32) -# include -# define SET_REALTIME_PRIORITY SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS) -# define UTIL_sleep(s) Sleep(1000*s) -# define UTIL_sleepMilli(milli) Sleep(milli) -#elif PLATFORM_POSIX_VERSION >= 0 /* Unix-like operating system */ -# include -# include /* setpriority */ -# include /* clock_t, nanosleep, clock, CLOCKS_PER_SEC */ -# if defined(PRIO_PROCESS) -# define SET_REALTIME_PRIORITY setpriority(PRIO_PROCESS, 0, -20) -# else -# define SET_REALTIME_PRIORITY /* disabled */ -# endif -# define UTIL_sleep(s) sleep(s) -# if (defined(__linux__) && (PLATFORM_POSIX_VERSION >= 199309L)) || (PLATFORM_POSIX_VERSION >= 200112L) /* nanosleep requires POSIX.1-2001 */ -# define UTIL_sleepMilli(milli) { struct timespec t; t.tv_sec=0; t.tv_nsec=milli*1000000ULL; nanosleep(&t, NULL); } -# else -# define UTIL_sleepMilli(milli) /* disabled */ -# endif -#else -# define SET_REALTIME_PRIORITY /* disabled */ -# define UTIL_sleep(s) /* disabled */ -# define UTIL_sleepMilli(milli) /* disabled */ -#endif - - -/* ************************************* -* Constants -***************************************/ -#define LIST_SIZE_INCREASE (8*1024) - - -/*-**************************************** -* Compiler specifics -******************************************/ -#if defined(__INTEL_COMPILER) -# pragma warning(disable : 177) /* disable: message #177: function was declared but never referenced, useful with UTIL_STATIC */ -#endif -#if defined(__GNUC__) -# define UTIL_STATIC static __attribute__((unused)) -#elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) -# define UTIL_STATIC static inline -#elif defined(_MSC_VER) -# define UTIL_STATIC static __inline -#else -# define UTIL_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */ -#endif - - -/*-**************************************** -* Time functions -******************************************/ -#if (PLATFORM_POSIX_VERSION >= 1) -#include -#include /* times */ - typedef U64 UTIL_time_t; - UTIL_STATIC void UTIL_initTimer(UTIL_time_t* ticksPerSecond) { *ticksPerSecond=sysconf(_SC_CLK_TCK); } - UTIL_STATIC void UTIL_getTime(UTIL_time_t* x) { struct tms junk; clock_t newTicks = (clock_t) times(&junk); (void)junk; *x = (UTIL_time_t)newTicks; } - UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t ticksPerSecond, UTIL_time_t clockStart, UTIL_time_t clockEnd) { return 1000000ULL * (clockEnd - clockStart) / ticksPerSecond; } - UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t ticksPerSecond, UTIL_time_t clockStart, UTIL_time_t clockEnd) { return 1000000000ULL * (clockEnd - clockStart) / ticksPerSecond; } -#elif defined(_WIN32) /* Windows */ - typedef LARGE_INTEGER UTIL_time_t; - UTIL_STATIC void UTIL_initTimer(UTIL_time_t* ticksPerSecond) { if (!QueryPerformanceFrequency(ticksPerSecond)) fprintf(stderr, "ERROR: QueryPerformance not present\n"); } - UTIL_STATIC void UTIL_getTime(UTIL_time_t* x) { QueryPerformanceCounter(x); } - UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t ticksPerSecond, UTIL_time_t clockStart, UTIL_time_t clockEnd) { return 1000000ULL*(clockEnd.QuadPart - clockStart.QuadPart)/ticksPerSecond.QuadPart; } - UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t ticksPerSecond, UTIL_time_t clockStart, UTIL_time_t clockEnd) { return 1000000000ULL*(clockEnd.QuadPart - clockStart.QuadPart)/ticksPerSecond.QuadPart; } -#else /* relies on standard C (note : clock_t measurements can be wrong when using multi-threading) */ - typedef clock_t UTIL_time_t; - UTIL_STATIC void UTIL_initTimer(UTIL_time_t* ticksPerSecond) { *ticksPerSecond=0; } - UTIL_STATIC void UTIL_getTime(UTIL_time_t* x) { *x = clock(); } - UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t ticksPerSecond, UTIL_time_t clockStart, UTIL_time_t clockEnd) { (void)ticksPerSecond; return 1000000ULL * (clockEnd - clockStart) / CLOCKS_PER_SEC; } - UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t ticksPerSecond, UTIL_time_t clockStart, UTIL_time_t clockEnd) { (void)ticksPerSecond; return 1000000000ULL * (clockEnd - clockStart) / CLOCKS_PER_SEC; } -#endif - - -/* returns time span in microseconds */ -UTIL_STATIC U64 UTIL_clockSpanMicro( UTIL_time_t clockStart, UTIL_time_t ticksPerSecond ) -{ - UTIL_time_t clockEnd; - UTIL_getTime(&clockEnd); - return UTIL_getSpanTimeMicro(ticksPerSecond, clockStart, clockEnd); -} - - -UTIL_STATIC void UTIL_waitForNextTick(UTIL_time_t ticksPerSecond) -{ - UTIL_time_t clockStart, clockEnd; - UTIL_getTime(&clockStart); - do { - UTIL_getTime(&clockEnd); - } while (UTIL_getSpanTimeNano(ticksPerSecond, clockStart, clockEnd) == 0); -} - - - -/*-**************************************** -* File functions -******************************************/ -#if defined(_MSC_VER) - #define chmod _chmod - typedef struct __stat64 stat_t; -#else - typedef struct stat stat_t; -#endif - - -UTIL_STATIC int UTIL_setFileStat(const char *filename, stat_t *statbuf) -{ - int res = 0; - struct utimbuf timebuf; - - timebuf.actime = time(NULL); - timebuf.modtime = statbuf->st_mtime; - res += utime(filename, &timebuf); /* set access and modification times */ - -#if !defined(_WIN32) - res += chown(filename, statbuf->st_uid, statbuf->st_gid); /* Copy ownership */ -#endif - - res += chmod(filename, statbuf->st_mode & 07777); /* Copy file permissions */ - - errno = 0; - return -res; /* number of errors is returned */ -} - - -UTIL_STATIC int UTIL_getFileStat(const char* infilename, stat_t *statbuf) -{ - int r; -#if defined(_MSC_VER) - r = _stat64(infilename, statbuf); - if (r || !(statbuf->st_mode & S_IFREG)) return 0; /* No good... */ -#else - r = stat(infilename, statbuf); - if (r || !S_ISREG(statbuf->st_mode)) return 0; /* No good... */ -#endif - return 1; -} - - -UTIL_STATIC int UTIL_isRegFile(const char* infilename) -{ - stat_t statbuf; - return UTIL_getFileStat(infilename, &statbuf); /* Only need to know whether it is a regular file */ -} - - -UTIL_STATIC U32 UTIL_isDirectory(const char* infilename) -{ - int r; - stat_t statbuf; -#if defined(_MSC_VER) - r = _stat64(infilename, &statbuf); - if (!r && (statbuf.st_mode & _S_IFDIR)) return 1; -#else - r = stat(infilename, &statbuf); - if (!r && S_ISDIR(statbuf.st_mode)) return 1; -#endif - return 0; -} - - -UTIL_STATIC U64 UTIL_getFileSize(const char* infilename) -{ - int r; -#if defined(_MSC_VER) - struct __stat64 statbuf; - r = _stat64(infilename, &statbuf); - if (r || !(statbuf.st_mode & S_IFREG)) return 0; /* No good... */ -#elif defined(__MINGW32__) && defined (__MSVCRT__) - struct _stati64 statbuf; - r = _stati64(infilename, &statbuf); - if (r || !(statbuf.st_mode & S_IFREG)) return 0; /* No good... */ -#else - struct stat statbuf; - r = stat(infilename, &statbuf); - if (r || !S_ISREG(statbuf.st_mode)) return 0; /* No good... */ -#endif - return (U64)statbuf.st_size; -} - - -UTIL_STATIC U64 UTIL_getTotalFileSize(const char** fileNamesTable, unsigned nbFiles) -{ - U64 total = 0; - unsigned n; - for (n=0; n= *bufEnd) { - ptrdiff_t newListSize = (*bufEnd - *bufStart) + LIST_SIZE_INCREASE; - *bufStart = (char*)UTIL_realloc(*bufStart, newListSize); - *bufEnd = *bufStart + newListSize; - if (*bufStart == NULL) { free(path); FindClose(hFile); return 0; } - } - if (*bufStart + *pos + pathLength < *bufEnd) { - strncpy(*bufStart + *pos, path, *bufEnd - (*bufStart + *pos)); - *pos += pathLength + 1; - nbFiles++; - } - } - free(path); - } while (FindNextFileA(hFile, &cFile)); - - FindClose(hFile); - return nbFiles; -} - -#elif defined(__linux__) || (PLATFORM_POSIX_VERSION >= 200112L) /* opendir, readdir require POSIX.1-2001 */ -# define UTIL_HAS_CREATEFILELIST -# include /* opendir, readdir */ -# include /* strerror, memcpy */ - -UTIL_STATIC int UTIL_prepareFileList(const char *dirName, char** bufStart, size_t* pos, char** bufEnd) -{ - DIR *dir; - struct dirent *entry; - char* path; - int dirLength, fnameLength, pathLength, nbFiles = 0; - - if (!(dir = opendir(dirName))) { - fprintf(stderr, "Cannot open directory '%s': %s\n", dirName, strerror(errno)); - return 0; - } - - dirLength = (int)strlen(dirName); - errno = 0; - while ((entry = readdir(dir)) != NULL) { - if (strcmp (entry->d_name, "..") == 0 || - strcmp (entry->d_name, ".") == 0) continue; - fnameLength = (int)strlen(entry->d_name); - path = (char*) malloc(dirLength + fnameLength + 2); - if (!path) { closedir(dir); return 0; } - memcpy(path, dirName, dirLength); - path[dirLength] = '/'; - memcpy(path+dirLength+1, entry->d_name, fnameLength); - pathLength = dirLength+1+fnameLength; - path[pathLength] = 0; - - if (UTIL_isDirectory(path)) { - nbFiles += UTIL_prepareFileList(path, bufStart, pos, bufEnd); /* Recursively call "UTIL_prepareFileList" with the new path. */ - if (*bufStart == NULL) { free(path); closedir(dir); return 0; } - } else { - if (*bufStart + *pos + pathLength >= *bufEnd) { - ptrdiff_t newListSize = (*bufEnd - *bufStart) + LIST_SIZE_INCREASE; - *bufStart = (char*)UTIL_realloc(*bufStart, newListSize); - *bufEnd = *bufStart + newListSize; - if (*bufStart == NULL) { free(path); closedir(dir); return 0; } - } - if (*bufStart + *pos + pathLength < *bufEnd) { - strncpy(*bufStart + *pos, path, *bufEnd - (*bufStart + *pos)); - *pos += pathLength + 1; - nbFiles++; - } - } - free(path); - errno = 0; /* clear errno after UTIL_isDirectory, UTIL_prepareFileList */ - } - - if (errno != 0) { - fprintf(stderr, "readdir(%s) error: %s\n", dirName, strerror(errno)); - free(*bufStart); - *bufStart = NULL; - } - closedir(dir); - return nbFiles; -} - -#else - -UTIL_STATIC int UTIL_prepareFileList(const char *dirName, char** bufStart, size_t* pos, char** bufEnd) -{ - (void)bufStart; (void)bufEnd; (void)pos; - fprintf(stderr, "Directory %s ignored (compiled without _WIN32 or _POSIX_C_SOURCE)\n", dirName); - return 0; -} - -#endif /* #ifdef _WIN32 */ - -/* - * UTIL_createFileList - takes a list of files and directories (params: inputNames, inputNamesNb), scans directories, - * and returns a new list of files (params: return value, allocatedBuffer, allocatedNamesNb). - * After finishing usage of the list the structures should be freed with UTIL_freeFileList(params: return value, allocatedBuffer) - * In case of error UTIL_createFileList returns NULL and UTIL_freeFileList should not be called. - */ -UTIL_STATIC const char** UTIL_createFileList(const char **inputNames, unsigned inputNamesNb, char** allocatedBuffer, unsigned* allocatedNamesNb) -{ - size_t pos; - unsigned i, nbFiles; - char* buf = (char*)malloc(LIST_SIZE_INCREASE); - char* bufend = buf + LIST_SIZE_INCREASE; - const char** fileTable; - - if (!buf) return NULL; - - for (i=0, pos=0, nbFiles=0; i= bufend) { - ptrdiff_t newListSize = (bufend - buf) + LIST_SIZE_INCREASE; - buf = (char*)UTIL_realloc(buf, newListSize); - bufend = buf + newListSize; - if (!buf) return NULL; - } - if (buf + pos + len < bufend) { - strncpy(buf + pos, inputNames[i], bufend - (buf + pos)); - pos += len + 1; - nbFiles++; - } - } else { - nbFiles += UTIL_prepareFileList(inputNames[i], &buf, &pos, &bufend); - if (buf == NULL) return NULL; - } } - - if (nbFiles == 0) { free(buf); return NULL; } - - fileTable = (const char**)malloc((nbFiles+1) * sizeof(const char*)); - if (!fileTable) { free(buf); return NULL; } - - for (i=0, pos=0; i bufend) { free(buf); free((void*)fileTable); return NULL; } - - *allocatedBuffer = buf; - *allocatedNamesNb = nbFiles; - - return fileTable; -} - - -UTIL_STATIC void UTIL_freeFileList(const char** filenameTable, char* allocatedBuffer) -{ - if (allocatedBuffer) free(allocatedBuffer); - if (filenameTable) free((void*)filenameTable); -} - - -#if defined (__cplusplus) -} -#endif - -#endif /* UTIL_H_MODULE */ diff --git a/src/lz4/tests/.gitignore b/src/lz4/tests/.gitignore deleted file mode 100644 index 4c0f311412..0000000000 --- a/src/lz4/tests/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ - -# test build artefacts -datagen -frametest -frametest32 -fullbench -fullbench32 -fuzzer -fuzzer32 -fasttest - -# test artefacts -tmp* -versionsTest diff --git a/src/lz4/tests/COPYING b/src/lz4/tests/COPYING deleted file mode 100644 index d159169d10..0000000000 --- a/src/lz4/tests/COPYING +++ /dev/null @@ -1,339 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 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. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, 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 or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -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 give any other recipients of the Program a copy of this License -along with the Program. - -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 Program or any portion -of it, thus forming a work based on the Program, 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) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -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 Program, 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 Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) 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; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, 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 executable. However, as a -special exception, the source code 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. - -If distribution of executable or 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 counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program 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. - - 5. 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 Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program 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 to -this License. - - 7. 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 Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program 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 Program. - -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. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program 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. - - 9. The Free Software Foundation may publish revised and/or new versions -of the 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 Program -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 Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, 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 - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "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 PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. 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 PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), 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 Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. 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 program is free software; 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-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. diff --git a/src/lz4/tests/Makefile b/src/lz4/tests/Makefile deleted file mode 100644 index f00778fae6..0000000000 --- a/src/lz4/tests/Makefile +++ /dev/null @@ -1,387 +0,0 @@ -# ########################################################################## -# LZ4 programs - Makefile -# Copyright (C) Yann Collet 2011-2016 -# -# This Makefile is validated for Linux, macOS, *BSD, Hurd, Solaris, MSYS2 targets -# -# GPL v2 License -# -# This program is free software; 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-1301 USA. -# -# You can contact the author at : -# - LZ4 homepage : http://www.lz4.org -# - LZ4 source repository : https://github.com/lz4/lz4 -# ########################################################################## -# fuzzer : Test tool, to check lz4 integrity on target platform -# frametest : Test tool, to check lz4frame integrity on target platform -# fullbench : Precisely measure speed for each LZ4 function variant -# datagen : generates synthetic data samples for tests & benchmarks -# ########################################################################## - -DESTDIR ?= -PREFIX ?= /usr/local -BINDIR := $(PREFIX)/bin -MANDIR := $(PREFIX)/share/man/man1 -LZ4DIR := ../lib -PRGDIR := ../programs -VOID := /dev/null -TESTDIR := versionsTest -PYTHON ?= python3 - -CFLAGS ?= -O3 # can select custom optimization flags. For example : CFLAGS=-O2 make -CFLAGS += -g -Wall -Wextra -Wundef -Wcast-qual -Wcast-align -Wshadow -Wswitch-enum \ - -Wdeclaration-after-statement -Wstrict-prototypes \ - -Wpointer-arith -Wstrict-aliasing=1 -CFLAGS += $(MOREFLAGS) -CPPFLAGS:= -I$(LZ4DIR) -I$(PRGDIR) -DXXH_NAMESPACE=LZ4_ -FLAGS = $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) - - -# Define *.exe as extension for Windows systems -ifneq (,$(filter Windows%,$(OS))) -EXT =.exe -else -EXT = -endif -LZ4 := $(PRGDIR)/lz4$(EXT) - - -# Default test parameters -TEST_FILES := COPYING -FUZZER_TIME := -T3mn -NB_LOOPS ?= -i1 - - -default: all - -all: fullbench fuzzer frametest datagen fasttest - -all32: CFLAGS+=-m32 -all32: all - -lz4: - $(MAKE) -C $(PRGDIR) clean $@ CFLAGS="$(CFLAGS)" - -lz4c: - $(MAKE) -C $(PRGDIR) clean $@ CFLAGS="$(CFLAGS)" - -lz4c32: # create a 32-bits version for 32/64 interop tests - $(MAKE) -C $(PRGDIR) clean $@ CFLAGS="-m32 $(CFLAGS)" - cp $(LZ4) $(LZ4)c32 - -fullbench : $(LZ4DIR)/lz4.o $(LZ4DIR)/lz4hc.o $(LZ4DIR)/lz4frame.o $(LZ4DIR)/xxhash.o fullbench.c - $(CC) $(FLAGS) $^ -o $@$(EXT) - -fullbench-lib: fullbench.c $(LZ4DIR)/xxhash.c - $(MAKE) -C $(LZ4DIR) liblz4.a - $(CC) $(FLAGS) $^ -o $@$(EXT) $(LZ4DIR)/liblz4.a - -fullbench-dll: fullbench.c $(LZ4DIR)/xxhash.c - $(MAKE) -C $(LZ4DIR) liblz4 - $(CC) $(FLAGS) $^ -o $@$(EXT) -DLZ4_DLL_IMPORT=1 $(LZ4DIR)/dll/liblz4.dll - -fuzzer : $(LZ4DIR)/lz4.o $(LZ4DIR)/lz4hc.o $(LZ4DIR)/xxhash.o fuzzer.c - $(CC) $(FLAGS) $^ -o $@$(EXT) - -frametest: $(LZ4DIR)/lz4frame.o $(LZ4DIR)/lz4.o $(LZ4DIR)/lz4hc.o $(LZ4DIR)/xxhash.o frametest.c - $(CC) $(FLAGS) $^ -o $@$(EXT) - -fasttest: $(LZ4DIR)/lz4.o fasttest.c - $(CC) $(FLAGS) $^ -o $@$(EXT) - -datagen : $(PRGDIR)/datagen.c datagencli.c - $(CC) $(FLAGS) -I$(PRGDIR) $^ -o $@$(EXT) - -clean: - @$(MAKE) -C $(LZ4DIR) $@ > $(VOID) - @$(MAKE) -C $(PRGDIR) $@ > $(VOID) - @$(RM) core *.o *.test tmp* \ - fullbench-dll$(EXT) fullbench-lib$(EXT) \ - fullbench$(EXT) fullbench32$(EXT) \ - fuzzer$(EXT) fuzzer32$(EXT) \ - frametest$(EXT) frametest32$(EXT) \ - fasttest$(EXT) datagen$(EXT) - @rm -fR $(TESTDIR) - @echo Cleaning completed - -.PHONY: versionsTest -versionsTest: - $(PYTHON) test-lz4-versions.py - - -#----------------------------------------------------------------------------- -# make install is validated only for Linux, OSX, BSD, Hurd and Solaris targets -#----------------------------------------------------------------------------- -ifneq (,$(filter $(shell uname),Linux Darwin GNU/kFreeBSD GNU OpenBSD FreeBSD NetBSD DragonFly SunOS)) - -MD5:=md5sum -ifneq (,$(filter $(shell uname), Darwin )) -MD5:=md5 -r -endif - -DIFF:=diff -ifneq (,$(filter $(shell uname),SunOS)) -DIFF:=gdiff -endif - - -test: test-lz4 test-lz4c test-fasttest test-frametest test-fullbench test-fuzzer - -test32: CFLAGS+=-m32 -test32: test - -test-lz4-sparse: lz4 datagen - @echo "\n ---- test sparse file support ----" - ./datagen -g5M -P100 > tmpSrc - $(LZ4) -B4D tmpSrc | $(LZ4) -dv --sparse > tmpB4 - $(DIFF) -s tmpSrc tmpB4 - $(LZ4) -B5D tmpSrc | $(LZ4) -dv --sparse > tmpB5 - $(DIFF) -s tmpSrc tmpB5 - $(LZ4) -B6D tmpSrc | $(LZ4) -dv --sparse > tmpB6 - $(DIFF) -s tmpSrc tmpB6 - $(LZ4) -B7D tmpSrc | $(LZ4) -dv --sparse > tmpB7 - $(DIFF) -s tmpSrc tmpB7 - $(LZ4) tmpSrc | $(LZ4) -dv --no-sparse > tmpNoSparse - $(DIFF) -s tmpSrc tmpNoSparse - ls -ls tmp* - ./datagen -s1 -g1200007 -P100 | $(LZ4) | $(LZ4) -dv --sparse > tmpOdd # Odd size file (to generate non-full last block) - ./datagen -s1 -g1200007 -P100 | $(DIFF) -s - tmpOdd - ls -ls tmpOdd - @$(RM) tmp* - @echo "\n Compatibility with Console :" - echo "Hello World 1 !" | $(LZ4) | $(LZ4) -d -c - echo "Hello World 2 !" | $(LZ4) | $(LZ4) -d | cat - echo "Hello World 3 !" | $(LZ4) --no-frame-crc | $(LZ4) -d -c - @echo "\n Compatibility with Append :" - ./datagen -P100 -g1M > tmp1M - cat tmp1M tmp1M > tmp2M - $(LZ4) -B5 -v tmp1M tmpC - $(LZ4) -d -v tmpC tmpR - $(LZ4) -d -v tmpC >> tmpR - ls -ls tmp* - $(DIFF) tmp2M tmpR - @$(RM) tmp* - -test-lz4-contentSize: lz4 datagen - @echo "\n ---- test original size support ----" - ./datagen -g15M > tmp - $(LZ4) -v tmp | $(LZ4) -t - $(LZ4) -v --content-size tmp | $(LZ4) -d > tmp2 - $(DIFF) -s tmp tmp2 - # test large size [2-4] GB - @./datagen -g3G -P100 | $(LZ4) -vv | $(LZ4) --decompress --force --sparse - tmp - @ls -ls tmp - @./datagen -g3G -P100 | $(LZ4) --quiet --content-size | $(LZ4) --verbose --decompress --force --sparse - tmp2 - @ls -ls tmp2 - $(DIFF) -s tmp tmp2 - @$(RM) tmp* - -test-lz4-frame-concatenation: lz4 datagen - @echo "\n ---- test frame concatenation ----" - @echo -n > empty.test - @echo hi > nonempty.test - cat nonempty.test empty.test nonempty.test > orig.test - @$(LZ4) -zq empty.test > empty.lz4.test - @$(LZ4) -zq nonempty.test > nonempty.lz4.test - cat nonempty.lz4.test empty.lz4.test nonempty.lz4.test > concat.lz4.test - $(LZ4) -d concat.lz4.test > result.test - sdiff orig.test result.test - @$(RM) *.test - @echo frame concatenation test completed - -test-lz4-multiple: lz4 datagen - @echo "\n ---- test multiple files ----" - @./datagen -s1 > tmp1 2> $(VOID) - @./datagen -s2 -g100K > tmp2 2> $(VOID) - @./datagen -s3 -g1M > tmp3 2> $(VOID) - $(LZ4) -f -m tmp* - ls -ls tmp* - @$(RM) tmp1 tmp2 tmp3 - $(LZ4) -df -m *.lz4 - ls -ls tmp* - $(LZ4) -f -m tmp1 notHere tmp2; echo $$? - @$(RM) tmp* - -unlz4: - @$(MAKE) -C $(PRGDIR) $@ CFLAGS="$(CFLAGS)" - -lz4cat: - @$(MAKE) -C $(PRGDIR) $@ CFLAGS="$(CFLAGS)" - -test-lz4-basic: lz4 datagen unlz4 lz4cat - @echo "\n ---- test lz4 basic compression/decompression ----" - ./datagen -g0 | $(LZ4) -v | $(LZ4) -t - ./datagen -g16KB | $(LZ4) -9 | $(LZ4) -t - ./datagen -g20KB > tmpSrc - $(LZ4) < tmpSrc | $(LZ4) -d > tmpRes - $(DIFF) -q tmpSrc tmpRes - $(LZ4) --no-frame-crc < tmpSrc | $(LZ4) -d > tmpRes - $(DIFF) -q tmpSrc tmpRes - ./datagen | $(LZ4) | $(LZ4) -t - ./datagen -g6M -P99 | $(LZ4) -9BD | $(LZ4) -t - ./datagen -g17M | $(LZ4) -9v | $(LZ4) -qt - ./datagen -g33M | $(LZ4) --no-frame-crc | $(LZ4) -t - ./datagen -g256MB | $(LZ4) -vqB4D | $(LZ4) -t - @echo "hello world" > tmp - $(LZ4) --rm -f tmp tmp.lz4 - test ! -f tmp # must fail (--rm) - test -f tmp.lz4 - $(PRGDIR)/lz4cat tmp.lz4 # must display hello world - test -f tmp.lz4 - $(PRGDIR)/unlz4 --rm tmp.lz4 tmp - test -f tmp - test ! -f tmp.lz4 # must fail (--rm) - test ! -f tmp.lz4.lz4 # must fail (unlz4) - $(PRGDIR)/lz4cat tmp # pass-through mode - test -f tmp - test ! -f tmp.lz4 # must fail (lz4cat) - $(LZ4) tmp tmp.lz4 # creates tmp.lz4 - $(PRGDIR)/lz4cat < tmp.lz4 > tmp3 # checks lz4cat works with stdin (#285) - $(DIFF) -q tmp tmp3 - $(PRGDIR)/lz4cat < tmp > tmp2 # checks lz4cat works with stdin (#285) - $(DIFF) -q tmp tmp2 - cp tmp ./-d - $(LZ4) --rm -- -d -d.lz4 # compresses ./d into ./-d.lz4 - test -f ./-d.lz4 - test ! -f ./-d - mv ./-d.lz4 ./-z - $(LZ4) -d --rm -- -z tmp4 # uncompresses ./-z into tmp4 - test ! -f ./-z - $(DIFF) -q tmp tmp4 - $(LZ4) -f tmp - cat tmp >> tmp.lz4 - $(LZ4) -f tmp.lz4 # uncompress valid frame followed by invalid data - $(LZ4) -BX tmp -c -q | $(LZ4) -tv # test block checksum - @$(RM) tmp* - -test-lz4-hugefile: lz4 datagen - @echo "\n ---- test huge files compression/decompression ----" - ./datagen -g6GB | $(LZ4) -vB5D | $(LZ4) -qt - ./datagen -g6GB | $(LZ4) -v5BD | $(LZ4) -qt - @$(RM) tmp* - -test-lz4-testmode: lz4 datagen - @echo "\n ---- bench mode ----" - $(LZ4) -bi1 - @echo "\n ---- test mode ----" - ! ./datagen | $(LZ4) -t - ! ./datagen | $(LZ4) -tf - @echo "\n ---- pass-through mode ----" - ! ./datagen | $(LZ4) -d > $(VOID) - ./datagen | $(LZ4) -df > $(VOID) - @echo "Hello World !" > tmp1 - $(LZ4) -dcf tmp1 - @echo "from underground..." > tmp2 - $(LZ4) -dcfm tmp1 tmp2 - @echo "\n ---- test cli ----" - ! $(LZ4) file-does-not-exist - ! $(LZ4) -f file-does-not-exist - ! $(LZ4) -fm file1-dne file2-dne - ! $(LZ4) -fm file1-dne file2-dne - -test-lz4-opt-parser: lz4 datagen - @echo "\n ---- test opt-parser ----" - ./datagen -g16KB | $(LZ4) -12 | $(LZ4) -t - ./datagen -P10 | $(LZ4) -12B4 | $(LZ4) -t - ./datagen -g256K | $(LZ4) -12B4D | $(LZ4) -t - ./datagen -g512K -P25 | $(LZ4) -12BD | $(LZ4) -t - ./datagen -g1M | $(LZ4) -12B5 | $(LZ4) -t - ./datagen -g2M -P99 | $(LZ4) -11B4D | $(LZ4) -t - ./datagen -g4M | $(LZ4) -11vq | $(LZ4) -qt - ./datagen -g8M | $(LZ4) -11B4 | $(LZ4) -t - ./datagen -g16M -P90 | $(LZ4) -11B5 | $(LZ4) -t - ./datagen -g32M -P10 | $(LZ4) -11B5D | $(LZ4) -t - -test-lz4: lz4 datagen test-lz4-opt-parser test-lz4-basic test-lz4-multiple test-lz4-sparse \ - test-lz4-frame-concatenation test-lz4-testmode test-lz4-contentSize \ - test-lz4-hugefile - -test-lz4c: lz4c datagen - @echo "\n ---- test lz4c version ----" - ./datagen -g256MB | $(LZ4)c -l -v | $(LZ4)c -t - -test-lz4c32: CFLAGS+=-m32 -test-lz4c32: test-lz4 - -test-interop-32-64: lz4 lz4c32 datagen - @echo "\n ---- test interoperability 32-bits -vs- 64 bits ----" - ./datagen -g16KB | $(LZ4)c32 -9 | $(LZ4) -t - ./datagen -P10 | $(LZ4) -9B4 | $(LZ4)c32 -t - ./datagen | $(LZ4)c32 | $(LZ4) -t - ./datagen -g1M | $(LZ4) -3B5 | $(LZ4)c32 -t - ./datagen -g256MB | $(LZ4)c32 -vqB4D | $(LZ4) -qt - ./datagen -g1G -P90 | $(LZ4) | $(LZ4)c32 -t - ./datagen -g6GB | $(LZ4)c32 -vq9BD | $(LZ4) -qt - -test-lz4c32-basic: lz4c32 datagen - @echo "\n ---- test lz4c32 32-bits version ----" - ./datagen -g16KB | $(LZ4)c32 -9 | $(LZ4)c32 -t - ./datagen | $(LZ4)c32 | $(LZ4)c32 -t - ./datagen -g256MB | $(LZ4)c32 -vqB4D | $(LZ4)c32 -qt - ./datagen -g6GB | $(LZ4)c32 -vqB5D | $(LZ4)c32 -qt - -test-platform: - @echo "\n ---- test lz4 $(QEMU_SYS) platform ----" - $(QEMU_SYS) ./datagen -g16KB | $(QEMU_SYS) $(LZ4) -9 | $(QEMU_SYS) $(LZ4) -t - $(QEMU_SYS) ./datagen | $(QEMU_SYS) $(LZ4) | $(QEMU_SYS) $(LZ4) -t - $(QEMU_SYS) ./datagen -g256MB | $(QEMU_SYS) $(LZ4) -vqB4D | $(QEMU_SYS) $(LZ4) -qt -ifneq ($(QEMU_SYS),qemu-arm-static) - $(QEMU_SYS) ./datagen -g3GB | $(QEMU_SYS) $(LZ4) -vqB5D | $(QEMU_SYS) $(LZ4) -qt -endif - -test-fullbench: fullbench - ./fullbench --no-prompt $(NB_LOOPS) $(TEST_FILES) - -test-fullbench32: CFLAGS += -m32 -test-fullbench32: test-fullbench - -test-fuzzer: fuzzer - ./fuzzer $(FUZZER_TIME) - -test-fuzzer32: CFLAGS += -m32 -test-fuzzer32: test-fuzzer - -test-frametest: frametest - ./frametest $(FUZZER_TIME) - -test-frametest32: CFLAGS += -m32 -test-frametest32: test-frametest - -test-fasttest: fasttest - ./fasttest - -test-mem: lz4 datagen fuzzer frametest fullbench - @echo "\n ---- valgrind tests : memory analyzer ----" - valgrind --leak-check=yes --error-exitcode=1 ./datagen -g50M > $(VOID) - ./datagen -g16KB > tmp - valgrind --leak-check=yes --error-exitcode=1 $(LZ4) -9 -BD -f tmp $(VOID) - ./datagen -g16KB -s2 > tmp2 - ./datagen -g16KB -s3 > tmp3 - valgrind --leak-check=yes --error-exitcode=1 $(LZ4) --force --multiple tmp tmp2 tmp3 - ./datagen -g16MB > tmp - valgrind --leak-check=yes --error-exitcode=1 $(LZ4) -9 -B5D -f tmp tmp2 - valgrind --leak-check=yes --error-exitcode=1 $(LZ4) -t tmp2 - valgrind --leak-check=yes --error-exitcode=1 $(LZ4) -bi1 tmp - valgrind --leak-check=yes --error-exitcode=1 ./fullbench -i1 tmp tmp2 - ./datagen -g256MB > tmp - valgrind --leak-check=yes --error-exitcode=1 $(LZ4) -B4D -f -vq tmp $(VOID) - $(RM) tmp* - valgrind --leak-check=yes --error-exitcode=1 ./fuzzer -i64 -t1 - valgrind --leak-check=yes --error-exitcode=1 ./frametest -i256 - -test-mem32: lz4c32 datagen -# unfortunately, valgrind doesn't seem to work with non-native binary... - -endif diff --git a/src/lz4/tests/README.md b/src/lz4/tests/README.md deleted file mode 100644 index 75b7b9f508..0000000000 --- a/src/lz4/tests/README.md +++ /dev/null @@ -1,71 +0,0 @@ -Programs and scripts for automated testing of LZ4 -======================================================= - -This directory contains the following programs and scripts: -- `datagen` : Synthetic and parametrable data generator, for tests -- `frametest` : Test tool that checks lz4frame integrity on target platform -- `fullbench` : Precisely measure speed for each lz4 inner functions -- `fuzzer` : Test tool, to check lz4 integrity on target platform -- `test-lz4-speed.py` : script for testing lz4 speed difference between commits -- `test-lz4-versions.py` : compatibility test between lz4 versions stored on Github - - -#### `test-lz4-versions.py` - script for testing lz4 interoperability between versions - -This script creates `versionsTest` directory to which lz4 repository is cloned. -Then all taged (released) versions of lz4 are compiled. -In the following step interoperability between lz4 versions is checked. - - -#### `test-lz4-speed.py` - script for testing lz4 speed difference between commits - -This script creates `speedTest` directory to which lz4 repository is cloned. -Then it compiles all branches of lz4 and performs a speed benchmark for a given list of files (the `testFileNames` parameter). -After `sleepTime` (an optional parameter, default 300 seconds) seconds the script checks repository for new commits. -If a new commit is found it is compiled and a speed benchmark for this commit is performed. -The results of the speed benchmark are compared to the previous results. -If compression or decompression speed for one of lz4 levels is lower than `lowerLimit` (an optional parameter, default 0.98) the speed benchmark is restarted. -If second results are also lower than `lowerLimit` the warning e-mail is send to recipients from the list (the `emails` parameter). - -Additional remarks: -- To be sure that speed results are accurate the script should be run on a "stable" target system with no other jobs running in parallel -- Using the script with virtual machines can lead to large variations of speed results -- The speed benchmark is not performed until computers' load average is lower than `maxLoadAvg` (an optional parameter, default 0.75) -- The script sends e-mails using `mutt`; if `mutt` is not available it sends e-mails without attachments using `mail`; if both are not available it only prints a warning - - -The example usage with two test files, one e-mail address, and with an additional message: -``` -./test-lz4-speed.py "silesia.tar calgary.tar" "email@gmail.com" --message "tested on my laptop" --sleepTime 60 -``` - -To run the script in background please use: -``` -nohup ./test-lz4-speed.py testFileNames emails & -``` - -The full list of parameters: -``` -positional arguments: - testFileNames file names list for speed benchmark - emails list of e-mail addresses to send warnings - -optional arguments: - -h, --help show this help message and exit - --message MESSAGE attach an additional message to e-mail - --lowerLimit LOWERLIMIT - send email if speed is lower than given limit - --maxLoadAvg MAXLOADAVG - maximum load average to start testing - --lastCLevel LASTCLEVEL - last compression level for testing - --sleepTime SLEEPTIME - frequency of repository checking in seconds -``` - - -#### License - -All files in this directory are licensed under GPL-v2. -See [COPYING](COPYING) for details. -The text of the license is also included at the top of each source file. diff --git a/src/lz4/tests/datagencli.c b/src/lz4/tests/datagencli.c deleted file mode 100644 index c985197fea..0000000000 --- a/src/lz4/tests/datagencli.c +++ /dev/null @@ -1,172 +0,0 @@ -/* - datagencli.c - compressible data command line generator - Copyright (C) Yann Collet 2012-2016 - - GPL v2 License - - This program is free software; 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-1301 USA. - - You can contact the author at : - - LZ4 source repository : https://github.com/lz4/lz4 - - Public forum : https://groups.google.com/forum/#!forum/lz4c -*/ - -/************************************** -* Includes -**************************************/ -#include "util.h" /* U32 */ -#include /* fprintf, stderr */ -#include "datagen.h" /* RDG_generate */ -#include "lz4.h" /* LZ4_VERSION_STRING */ - - -/************************************** -* Constants -**************************************/ -#define KB *(1 <<10) -#define MB *(1 <<20) -#define GB *(1U<<30) - -#define SIZE_DEFAULT (64 KB) -#define SEED_DEFAULT 0 -#define COMPRESSIBILITY_DEFAULT 50 - - -/************************************** -* Macros -**************************************/ -#define DISPLAY(...) fprintf(stderr, __VA_ARGS__) -#define DISPLAYLEVEL(l, ...) if (displayLevel>=l) { DISPLAY(__VA_ARGS__); } -static unsigned displayLevel = 2; - - -/********************************************************* -* Command line -*********************************************************/ -static int usage(char* programName) -{ - DISPLAY( "Compressible data generator\n"); - DISPLAY( "Usage :\n"); - DISPLAY( " %s [size] [args]\n", programName); - DISPLAY( "\n"); - DISPLAY( "Arguments :\n"); - DISPLAY( " -g# : generate # data (default:%i)\n", SIZE_DEFAULT); - DISPLAY( " -s# : Select seed (default:%i)\n", SEED_DEFAULT); - DISPLAY( " -P# : Select compressibility in %% (default:%i%%)\n", COMPRESSIBILITY_DEFAULT); - DISPLAY( " -h : display help and exit\n"); - DISPLAY( "Special values :\n"); - DISPLAY( " -P0 : generate incompressible noise\n"); - DISPLAY( " -P100 : generate sparse files\n"); - return 0; -} - - -int main(int argc, char** argv) -{ - int argNb; - double proba = (double)COMPRESSIBILITY_DEFAULT / 100; - double litProba = 0.0; - U64 size = SIZE_DEFAULT; - U32 seed = SEED_DEFAULT; - char* programName; - - /* Check command line */ - programName = argv[0]; - for(argNb=1; argNb='0') && (*argument<='9')) - { - size *= 10; - size += *argument - '0'; - argument++; - } - if (*argument=='K') { size <<= 10; argument++; } - if (*argument=='M') { size <<= 20; argument++; } - if (*argument=='G') { size <<= 30; argument++; } - if (*argument=='B') { argument++; } - break; - case 's': - argument++; - seed=0; - while ((*argument>='0') && (*argument<='9')) - { - seed *= 10; - seed += *argument - '0'; - argument++; - } - break; - case 'P': - argument++; - proba=0.0; - while ((*argument>='0') && (*argument<='9')) - { - proba *= 10; - proba += *argument - '0'; - argument++; - } - if (proba>100.) proba=100.; - proba /= 100.; - break; - case 'L': /* hidden argument : Literal distribution probability */ - argument++; - litProba=0.; - while ((*argument>='0') && (*argument<='9')) - { - litProba *= 10; - litProba += *argument - '0'; - argument++; - } - if (litProba>100.) litProba=100.; - litProba /= 100.; - break; - case 'v': - displayLevel = 4; - argument++; - break; - default: - return usage(programName); - } - } - - } - } - - DISPLAYLEVEL(4, "Data Generator %s \n", LZ4_VERSION_STRING); - DISPLAYLEVEL(3, "Seed = %u \n", seed); - if (proba!=COMPRESSIBILITY_DEFAULT) DISPLAYLEVEL(3, "Compressibility : %i%%\n", (U32)(proba*100)); - - RDG_genOut(size, proba, litProba, seed); - DISPLAYLEVEL(1, "\n"); - - return 0; -} diff --git a/src/lz4/tests/fasttest.c b/src/lz4/tests/fasttest.c deleted file mode 100644 index a165293f50..0000000000 --- a/src/lz4/tests/fasttest.c +++ /dev/null @@ -1,131 +0,0 @@ -/************************************** - * Compiler Options - **************************************/ -#ifdef _MSC_VER /* Visual Studio */ -# define _CRT_SECURE_NO_WARNINGS // for MSVC -# define snprintf sprintf_s -#endif -#ifdef __GNUC__ -# pragma GCC diagnostic ignored "-Wmissing-braces" /* GCC bug 53119 : doesn't accept { 0 } as initializer (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53119) */ -#endif - - -/************************************** - * Includes - **************************************/ -#include -#include -#include -#include -#include "lz4.h" - - -/* Returns non-zero on failure. */ -int test_compress(const char *input, int inSize, char *output, int outSize) -{ - LZ4_stream_t lz4Stream_body = { 0 }; - LZ4_stream_t* lz4Stream = &lz4Stream_body; - - int inOffset = 0; - int outOffset = 0; - - if (inSize & 3) return -1; - - while (inOffset < inSize) { - const int length = inSize >> 2; - if (inSize > 1024) return -2; - if (outSize - (outOffset + 8) < LZ4_compressBound(length)) return -3; - { - const int outBytes = LZ4_compress_fast_continue( - lz4Stream, input + inOffset, output + outOffset + 8, length, outSize-outOffset, 1); - if(outBytes <= 0) return -4; - memcpy(output + outOffset, &length, 4); /* input length */ - memcpy(output + outOffset + 4, &outBytes, 4); /* output length */ - inOffset += length; - outOffset += outBytes + 8; - } - } - if (outOffset + 8 > outSize) return -5; - memset(output + outOffset, 0, 4); - memset(output + outOffset + 4, 0, 4); - return 0; -} - -/* Returns non-zero on failure. Not a safe function. */ -int test_decompress(const char *uncompressed, const char *compressed) -{ - char outBufferA[1024]; - char spacing; /* So prefixEnd != dest */ - char outBufferB[1024]; - char *output = outBufferA; - char *lastOutput = outBufferB; - LZ4_streamDecode_t lz4StreamDecode_body = { 0 }; - LZ4_streamDecode_t* lz4StreamDecode = &lz4StreamDecode_body; - int offset = 0; - int unOffset = 0; - int lastBytes = 0; - - (void)spacing; - - for(;;) { - int32_t bytes; - int32_t unBytes; - /* Read uncompressed size and compressed size */ - memcpy(&unBytes, compressed + offset, 4); - memcpy(&bytes, compressed + offset + 4, 4); - offset += 8; - /* Check if we reached end of stream or error */ - if(bytes == 0 && unBytes == 0) return 0; - if(bytes <= 0 || unBytes <= 0 || unBytes > 1024) return 1; - - /* Put the last output in the dictionary */ - LZ4_setStreamDecode(lz4StreamDecode, lastOutput, lastBytes); - /* Decompress */ - bytes = LZ4_decompress_fast_continue( - lz4StreamDecode, compressed + offset, output, unBytes); - if(bytes <= 0) return 2; - /* Check result */ - { int const r = memcmp(uncompressed + unOffset, output, unBytes); - if (r) return 3; - } - { char* const tmp = output; output = lastOutput; lastOutput = tmp; } - offset += bytes; - unOffset += unBytes; - lastBytes = unBytes; - } -} - - -int main(int argc, char **argv) -{ - char input[] = - "Hello Hello Hello Hello Hello Hello Hello Hello!" - "Hello Hello Hello Hello Hello Hello Hello Hello!" - "Hello Hello Hello Hello Hello Hello Hello Hello!" - "Hello Hello Hello Hello Hello Hello Hello Hello!" - "Hello Hello Hello Hello Hello Hello Hello Hello!" - "Hello Hello Hello Hello Hello Hello Hello Hello!" - "Hello Hello Hello Hello Hello Hello Hello Hello!" - "Hello Hello Hello Hello Hello Hello Hello Hello!" - "Hello Hello Hello Hello Hello Hello Hello Hello!" - "Hello Hello Hello Hello Hello Hello Hello Hello!" - "Hello Hello Hello Hello Hello Hello Hello Hello!" - "Hello Hello Hello Hello Hello Hello Hello Hello!" - "Hello Hello Hello Hello Hello Hello Hello Hello!" - "Hello Hello Hello Hello Hello Hello Hello Hello!" - "Hello Hello Hello Hello Hello Hello Hello Hello!" - "Hello Hello Hello Hello Hello Hello Hello Hello"; - char output[LZ4_COMPRESSBOUND(4096)]; - int r; - - (void)argc; - (void)argv; - - if ((r = test_compress(input, sizeof(input), output, sizeof(output)))) { - return r; - } - if ((r = test_decompress(input, output))) { - return r; - } - return 0; -} diff --git a/src/lz4/tests/frametest.c b/src/lz4/tests/frametest.c deleted file mode 100644 index 88d0afd4db..0000000000 --- a/src/lz4/tests/frametest.c +++ /dev/null @@ -1,1066 +0,0 @@ -/* - frameTest - test tool for lz4frame - Copyright (C) Yann Collet 2014-2016 - - GPL v2 License - - This program is free software; 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-1301 USA. - - You can contact the author at : - - LZ4 homepage : http://www.lz4.org - - LZ4 source repository : https://github.com/lz4/lz4 -*/ - -/*-************************************ -* Compiler specific -**************************************/ -#ifdef _MSC_VER /* Visual Studio */ -# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ -# pragma warning(disable : 4146) /* disable: C4146: minus unsigned expression */ -#endif - - -/*-************************************ -* Includes -**************************************/ -#include "util.h" /* U32 */ -#include /* malloc, free */ -#include /* fprintf */ -#include /* strcmp */ -#include /* clock_t, clock(), CLOCKS_PER_SEC */ -#include -#include "lz4frame_static.h" -#include "lz4.h" /* LZ4_VERSION_STRING */ -#define XXH_STATIC_LINKING_ONLY -#include "xxhash.h" /* XXH64 */ - - -/* unoptimized version; solves endianess & alignment issues */ -static void FUZ_writeLE32 (void* dstVoidPtr, U32 value32) -{ - BYTE* dstPtr = (BYTE*)dstVoidPtr; - dstPtr[0] = (BYTE)value32; - dstPtr[1] = (BYTE)(value32 >> 8); - dstPtr[2] = (BYTE)(value32 >> 16); - dstPtr[3] = (BYTE)(value32 >> 24); -} - - -/*-************************************ -* Constants -**************************************/ -#define LZ4F_MAGIC_SKIPPABLE_START 0x184D2A50U - -#define KB *(1U<<10) -#define MB *(1U<<20) -#define GB *(1U<<30) - -static const U32 nbTestsDefault = 256 KB; -#define FUZ_COMPRESSIBILITY_DEFAULT 50 -static const U32 prime1 = 2654435761U; -static const U32 prime2 = 2246822519U; - - - -/*-************************************ -* Macros -**************************************/ -#define DISPLAY(...) fprintf(stderr, __VA_ARGS__) -#define DISPLAYLEVEL(l, ...) if (displayLevel>=l) { DISPLAY(__VA_ARGS__); } -#define DISPLAYUPDATE(l, ...) if (displayLevel>=l) { \ - if ((FUZ_GetClockSpan(g_clockTime) > refreshRate) || (displayLevel>=4)) \ - { g_clockTime = clock(); DISPLAY(__VA_ARGS__); \ - if (displayLevel>=4) fflush(stdout); } } -static const clock_t refreshRate = CLOCKS_PER_SEC / 6; -static clock_t g_clockTime = 0; - - -/*-*************************************** -* Local Parameters -*****************************************/ -static U32 no_prompt = 0; -static U32 displayLevel = 2; -static U32 use_pause = 0; - - -/*-******************************************************* -* Fuzzer functions -*********************************************************/ -#define MIN(a,b) ( (a) < (b) ? (a) : (b) ) -#define MAX(a,b) ( (a) > (b) ? (a) : (b) ) - -static clock_t FUZ_GetClockSpan(clock_t clockStart) -{ - return clock() - clockStart; /* works even if overflow; max span ~ 30 mn */ -} - - -#define FUZ_rotl32(x,r) ((x << r) | (x >> (32 - r))) -unsigned int FUZ_rand(unsigned int* src) -{ - U32 rand32 = *src; - rand32 *= prime1; - rand32 += prime2; - rand32 = FUZ_rotl32(rand32, 13); - *src = rand32; - return rand32 >> 5; -} - - -#define FUZ_RAND15BITS (FUZ_rand(seed) & 0x7FFF) -#define FUZ_RANDLENGTH ( (FUZ_rand(seed) & 3) ? (FUZ_rand(seed) % 15) : (FUZ_rand(seed) % 510) + 15) -static void FUZ_fillCompressibleNoiseBuffer(void* buffer, size_t bufferSize, double proba, U32* seed) -{ - BYTE* BBuffer = (BYTE*)buffer; - size_t pos = 0; - U32 P32 = (U32)(32768 * proba); - - /* First Byte */ - BBuffer[pos++] = (BYTE)(FUZ_rand(seed)); - - while (pos < bufferSize) { - /* Select : Literal (noise) or copy (within 64K) */ - if (FUZ_RAND15BITS < P32) { - /* Copy (within 64K) */ - size_t const lengthRand = FUZ_RANDLENGTH + 4; - size_t const length = MIN(lengthRand, bufferSize - pos); - size_t const end = pos + length; - size_t const offsetRand = FUZ_RAND15BITS + 1; - size_t const offset = MIN(offsetRand, pos); - size_t match = pos - offset; - while (pos < end) BBuffer[pos++] = BBuffer[match++]; - } else { - /* Literal (noise) */ - size_t const lengthRand = FUZ_RANDLENGTH + 4; - size_t const length = MIN(lengthRand, bufferSize - pos); - size_t const end = pos + length; - while (pos < end) BBuffer[pos++] = (BYTE)(FUZ_rand(seed) >> 5); - } - } -} - - -static unsigned FUZ_highbit(U32 v32) -{ - unsigned nbBits = 0; - if (v32==0) return 0; - while (v32) v32 >>= 1, nbBits ++; - return nbBits; -} - - -/*-******************************************************* -* Tests -*********************************************************/ -#define CHECK_V(v,f) v = f; if (LZ4F_isError(v)) goto _output_error -#define CHECK(f) { LZ4F_errorCode_t const CHECK_V(err_ , f); } - -int basicTests(U32 seed, double compressibility) -{ -#define COMPRESSIBLE_NOISE_LENGTH (2 MB) - void* const CNBuffer = malloc(COMPRESSIBLE_NOISE_LENGTH); - size_t const cBuffSize = LZ4F_compressFrameBound(COMPRESSIBLE_NOISE_LENGTH, NULL); - void* const compressedBuffer = malloc(cBuffSize); - void* const decodedBuffer = malloc(COMPRESSIBLE_NOISE_LENGTH); - U32 randState = seed; - size_t cSize, testSize; - LZ4F_decompressionContext_t dCtx = NULL; - LZ4F_compressionContext_t cctx = NULL; - U64 crcOrig; - int basicTests_error = 0; - LZ4F_preferences_t prefs; - memset(&prefs, 0, sizeof(prefs)); - - if (!CNBuffer || !compressedBuffer || !decodedBuffer) { - DISPLAY("allocation error, not enough memory to start fuzzer tests \n"); - goto _output_error; - } - FUZ_fillCompressibleNoiseBuffer(CNBuffer, COMPRESSIBLE_NOISE_LENGTH, compressibility, &randState); - crcOrig = XXH64(CNBuffer, COMPRESSIBLE_NOISE_LENGTH, 1); - - /* LZ4F_compressBound() : special case : srcSize == 0 */ - DISPLAYLEVEL(3, "LZ4F_compressBound(0) = "); - { size_t const cBound = LZ4F_compressBound(0, NULL); - if (cBound < 64 KB) goto _output_error; - DISPLAYLEVEL(3, " %u \n", (U32)cBound); - } - - /* Special case : null-content frame */ - testSize = 0; - DISPLAYLEVEL(3, "LZ4F_compressFrame, compress null content : "); - CHECK_V(cSize, LZ4F_compressFrame(compressedBuffer, LZ4F_compressFrameBound(testSize, NULL), CNBuffer, testSize, NULL)); - DISPLAYLEVEL(3, "null content encoded into a %u bytes frame \n", (unsigned)cSize); - - DISPLAYLEVEL(3, "LZ4F_createDecompressionContext \n"); - CHECK ( LZ4F_createDecompressionContext(&dCtx, LZ4F_VERSION) ); - - DISPLAYLEVEL(3, "LZ4F_getFrameInfo on null-content frame (#157) \n"); - { size_t avail_in = cSize; - LZ4F_frameInfo_t frame_info; - CHECK( LZ4F_getFrameInfo(dCtx, &frame_info, compressedBuffer, &avail_in) ); - } - - DISPLAYLEVEL(3, "LZ4F_freeDecompressionContext \n"); - CHECK( LZ4F_freeDecompressionContext(dCtx) ); - dCtx = NULL; - - /* test one-pass frame compression */ - testSize = COMPRESSIBLE_NOISE_LENGTH; - - DISPLAYLEVEL(3, "LZ4F_compressFrame, using fast level -3 : "); - { LZ4F_preferences_t fastCompressPrefs; - memset(&fastCompressPrefs, 0, sizeof(fastCompressPrefs)); - fastCompressPrefs.compressionLevel = -3; - CHECK_V(cSize, LZ4F_compressFrame(compressedBuffer, LZ4F_compressFrameBound(testSize, NULL), CNBuffer, testSize, &fastCompressPrefs)); - DISPLAYLEVEL(3, "Compressed %u bytes into a %u bytes frame \n", (U32)testSize, (U32)cSize); - } - - DISPLAYLEVEL(3, "LZ4F_compressFrame, using default preferences : "); - CHECK_V(cSize, LZ4F_compressFrame(compressedBuffer, LZ4F_compressFrameBound(testSize, NULL), CNBuffer, testSize, NULL)); - DISPLAYLEVEL(3, "Compressed %u bytes into a %u bytes frame \n", (U32)testSize, (U32)cSize); - - DISPLAYLEVEL(3, "Decompression test : \n"); - { size_t decodedBufferSize = COMPRESSIBLE_NOISE_LENGTH; - size_t compressedBufferSize = cSize; - - CHECK( LZ4F_createDecompressionContext(&dCtx, LZ4F_VERSION) ); - - DISPLAYLEVEL(3, "Single Pass decompression : "); - CHECK( LZ4F_decompress(dCtx, decodedBuffer, &decodedBufferSize, compressedBuffer, &compressedBufferSize, NULL) ); - { U64 const crcDest = XXH64(decodedBuffer, decodedBufferSize, 1); - if (crcDest != crcOrig) goto _output_error; } - DISPLAYLEVEL(3, "Regenerated %u bytes \n", (U32)decodedBufferSize); - - DISPLAYLEVEL(3, "Reusing decompression context \n"); - { size_t const missingBytes = 4; - size_t iSize = compressedBufferSize - missingBytes; - const BYTE* cBuff = (const BYTE*) compressedBuffer; - BYTE* const ostart = (BYTE*)decodedBuffer; - BYTE* op = ostart; - BYTE* const oend = (BYTE*)decodedBuffer + COMPRESSIBLE_NOISE_LENGTH; - size_t decResult, oSize = COMPRESSIBLE_NOISE_LENGTH; - DISPLAYLEVEL(3, "Missing last %u bytes : ", (U32)missingBytes); - CHECK_V(decResult, LZ4F_decompress(dCtx, op, &oSize, cBuff, &iSize, NULL)); - if (decResult != missingBytes) { - DISPLAY("%u bytes missing != %u bytes requested \n", (U32)missingBytes, (U32)decResult); - goto _output_error; - } - DISPLAYLEVEL(3, "indeed, requests %u bytes \n", (unsigned)decResult); - cBuff += iSize; - iSize = decResult; - op += oSize; - oSize = (size_t)(oend-op); - decResult = LZ4F_decompress(dCtx, op, &oSize, cBuff, &iSize, NULL); - if (decResult != 0) goto _output_error; /* should finish now */ - op += oSize; - if (op>oend) { DISPLAY("decompression write overflow \n"); goto _output_error; } - { U64 const crcDest = XXH64(decodedBuffer, op-ostart, 1); - if (crcDest != crcOrig) goto _output_error; - } } - - { size_t oSize = 0; - size_t iSize = 0; - LZ4F_frameInfo_t fi; - const BYTE* ip = (BYTE*)compressedBuffer; - - DISPLAYLEVEL(3, "Start by feeding 0 bytes, to get next input size : "); - CHECK( LZ4F_decompress(dCtx, NULL, &oSize, ip, &iSize, NULL) ); - //DISPLAYLEVEL(3, " %u \n", (unsigned)errorCode); - DISPLAYLEVEL(3, " OK \n"); - - DISPLAYLEVEL(3, "LZ4F_getFrameInfo on zero-size input : "); - { size_t nullSize = 0; - size_t const fiError = LZ4F_getFrameInfo(dCtx, &fi, ip, &nullSize); - if (LZ4F_getErrorCode(fiError) != LZ4F_ERROR_frameHeader_incomplete) { - DISPLAYLEVEL(3, "incorrect error : %s != ERROR_frameHeader_incomplete \n", - LZ4F_getErrorName(fiError)); - goto _output_error; - } - DISPLAYLEVEL(3, " correctly failed : %s \n", LZ4F_getErrorName(fiError)); - } - - DISPLAYLEVEL(3, "LZ4F_getFrameInfo on not enough input : "); - { size_t inputSize = 6; - size_t const fiError = LZ4F_getFrameInfo(dCtx, &fi, ip, &inputSize); - if (LZ4F_getErrorCode(fiError) != LZ4F_ERROR_frameHeader_incomplete) { - DISPLAYLEVEL(3, "incorrect error : %s != ERROR_frameHeader_incomplete \n", LZ4F_getErrorName(fiError)); - goto _output_error; - } - DISPLAYLEVEL(3, " correctly failed : %s \n", LZ4F_getErrorName(fiError)); - } - - DISPLAYLEVEL(3, "LZ4F_getFrameInfo on enough input : "); - iSize = 15 - iSize; - CHECK( LZ4F_getFrameInfo(dCtx, &fi, ip, &iSize) ); - DISPLAYLEVEL(3, " correctly decoded \n"); - ip += iSize; - } - - DISPLAYLEVEL(3, "Decode a buggy input : "); - assert(COMPRESSIBLE_NOISE_LENGTH > 64); - assert(cSize > 48); - memcpy(decodedBuffer, (char*)compressedBuffer+16, 32); /* save correct data */ - memcpy((char*)compressedBuffer+16, (const char*)decodedBuffer+32, 32); /* insert noise */ - { size_t dbSize = COMPRESSIBLE_NOISE_LENGTH; - size_t cbSize = cSize; - size_t const decompressError = LZ4F_decompress(dCtx, decodedBuffer, &dbSize, - compressedBuffer, &cbSize, - NULL); - if (!LZ4F_isError(decompressError)) goto _output_error; - DISPLAYLEVEL(3, "error detected : %s \n", LZ4F_getErrorName(decompressError)); - } - memcpy((char*)compressedBuffer+16, decodedBuffer, 32); /* restore correct data */ - - DISPLAYLEVEL(3, "Reset decompression context, since it's left in error state \n"); - LZ4F_resetDecompressionContext(dCtx); /* always successful */ - - DISPLAYLEVEL(3, "Byte after byte : "); - { BYTE* const ostart = (BYTE*)decodedBuffer; - BYTE* op = ostart; - BYTE* const oend = (BYTE*)decodedBuffer + COMPRESSIBLE_NOISE_LENGTH; - const BYTE* ip = (const BYTE*) compressedBuffer; - const BYTE* const iend = ip + cSize; - while (ip < iend) { - size_t oSize = oend-op; - size_t iSize = 1; - CHECK( LZ4F_decompress(dCtx, op, &oSize, ip, &iSize, NULL) ); - op += oSize; - ip += iSize; - } - { U64 const crcDest = XXH64(decodedBuffer, COMPRESSIBLE_NOISE_LENGTH, 1); - if (crcDest != crcOrig) goto _output_error; } - DISPLAYLEVEL(3, "Regenerated %u/%u bytes \n", (unsigned)(op-ostart), COMPRESSIBLE_NOISE_LENGTH); - } - } - - DISPLAYLEVEL(3, "Using 64 KB block : "); - prefs.frameInfo.blockSizeID = LZ4F_max64KB; - prefs.frameInfo.contentChecksumFlag = LZ4F_contentChecksumEnabled; - CHECK_V(cSize, LZ4F_compressFrame(compressedBuffer, LZ4F_compressFrameBound(testSize, &prefs), CNBuffer, testSize, &prefs)); - DISPLAYLEVEL(3, "Compressed %i bytes into a %i bytes frame \n", (int)testSize, (int)cSize); - - DISPLAYLEVEL(3, "without checksum : "); - prefs.frameInfo.contentChecksumFlag = LZ4F_noContentChecksum; - CHECK_V(cSize, LZ4F_compressFrame(compressedBuffer, LZ4F_compressFrameBound(testSize, &prefs), CNBuffer, testSize, &prefs)); - DISPLAYLEVEL(3, "Compressed %i bytes into a %i bytes frame \n", (int)testSize, (int)cSize); - - DISPLAYLEVEL(3, "Using 256 KB block : "); - prefs.frameInfo.blockSizeID = LZ4F_max256KB; - prefs.frameInfo.contentChecksumFlag = LZ4F_contentChecksumEnabled; - CHECK_V(cSize, LZ4F_compressFrame(compressedBuffer, LZ4F_compressFrameBound(testSize, &prefs), CNBuffer, testSize, &prefs)); - DISPLAYLEVEL(3, "Compressed %i bytes into a %i bytes frame \n", (int)testSize, (int)cSize); - - DISPLAYLEVEL(3, "Decompression test : \n"); - { size_t const decodedBufferSize = COMPRESSIBLE_NOISE_LENGTH; - unsigned const maxBits = FUZ_highbit((U32)decodedBufferSize); - BYTE* const ostart = (BYTE*)decodedBuffer; - BYTE* op = ostart; - BYTE* const oend = ostart + COMPRESSIBLE_NOISE_LENGTH; - const BYTE* ip = (const BYTE*)compressedBuffer; - const BYTE* const iend = (const BYTE*)compressedBuffer + cSize; - - DISPLAYLEVEL(3, "random segment sizes : "); - while (ip < iend) { - unsigned const nbBits = FUZ_rand(&randState) % maxBits; - size_t iSize = (FUZ_rand(&randState) & ((1< (size_t)(iend-ip)) iSize = iend-ip; - CHECK( LZ4F_decompress(dCtx, op, &oSize, ip, &iSize, NULL) ); - op += oSize; - ip += iSize; - } - { size_t const decodedSize = (size_t)(op - ostart); - U64 const crcDest = XXH64(decodedBuffer, decodedSize, 1); - if (crcDest != crcOrig) goto _output_error; - DISPLAYLEVEL(3, "Regenerated %u bytes \n", (U32)decodedSize); - } - - CHECK( LZ4F_freeDecompressionContext(dCtx) ); - dCtx = NULL; - } - - DISPLAYLEVEL(3, "without checksum : "); - prefs.frameInfo.contentChecksumFlag = LZ4F_noContentChecksum; - CHECK_V(cSize, LZ4F_compressFrame(compressedBuffer, LZ4F_compressFrameBound(testSize, &prefs), CNBuffer, testSize, &prefs) ); - DISPLAYLEVEL(3, "Compressed %i bytes into a %i bytes frame \n", (int)testSize, (int)cSize); - - DISPLAYLEVEL(3, "Using 1 MB block : "); - prefs.frameInfo.blockSizeID = LZ4F_max1MB; - prefs.frameInfo.contentChecksumFlag = LZ4F_contentChecksumEnabled; - CHECK_V(cSize, LZ4F_compressFrame(compressedBuffer, LZ4F_compressFrameBound(testSize, &prefs), CNBuffer, testSize, &prefs) ); - DISPLAYLEVEL(3, "Compressed %i bytes into a %i bytes frame \n", (int)testSize, (int)cSize); - - DISPLAYLEVEL(3, "without frame checksum : "); - prefs.frameInfo.contentChecksumFlag = LZ4F_noContentChecksum; - CHECK_V(cSize, LZ4F_compressFrame(compressedBuffer, LZ4F_compressFrameBound(testSize, &prefs), CNBuffer, testSize, &prefs) ); - DISPLAYLEVEL(3, "Compressed %i bytes into a %i bytes frame \n", (int)testSize, (int)cSize); - - DISPLAYLEVEL(3, "Using 4 MB block : "); - prefs.frameInfo.blockSizeID = LZ4F_max4MB; - prefs.frameInfo.contentChecksumFlag = LZ4F_contentChecksumEnabled; - { size_t const dstCapacity = LZ4F_compressFrameBound(testSize, &prefs); - DISPLAYLEVEL(4, "dstCapacity = %u ; ", (U32)dstCapacity) - CHECK_V(cSize, LZ4F_compressFrame(compressedBuffer, dstCapacity, CNBuffer, testSize, &prefs) ); - DISPLAYLEVEL(3, "Compressed %u bytes into a %u bytes frame \n", (U32)testSize, (U32)cSize); - } - - DISPLAYLEVEL(3, "without frame checksum : "); - prefs.frameInfo.contentChecksumFlag = LZ4F_noContentChecksum; - { size_t const dstCapacity = LZ4F_compressFrameBound(testSize, &prefs); - DISPLAYLEVEL(4, "dstCapacity = %u ; ", (U32)dstCapacity) - CHECK_V(cSize, LZ4F_compressFrame(compressedBuffer, dstCapacity, CNBuffer, testSize, &prefs) ); - DISPLAYLEVEL(3, "Compressed %u bytes into a %u bytes frame \n", (U32)testSize, (U32)cSize); - } - - DISPLAYLEVEL(3, "LZ4F_compressFrame with block checksum : "); - memset(&prefs, 0, sizeof(prefs)); - prefs.frameInfo.blockChecksumFlag = LZ4F_blockChecksumEnabled; - CHECK_V(cSize, LZ4F_compressFrame(compressedBuffer, LZ4F_compressFrameBound(testSize, &prefs), CNBuffer, testSize, &prefs) ); - DISPLAYLEVEL(3, "Compressed %i bytes into a %i bytes frame \n", (int)testSize, (int)cSize); - - DISPLAYLEVEL(3, "Decompress with block checksum : "); - { size_t iSize = cSize; - size_t decodedSize = COMPRESSIBLE_NOISE_LENGTH; - LZ4F_decompressionContext_t dctx; - CHECK( LZ4F_createDecompressionContext(&dctx, LZ4F_VERSION) ); - CHECK( LZ4F_decompress(dctx, decodedBuffer, &decodedSize, compressedBuffer, &iSize, NULL) ); - if (decodedSize != testSize) goto _output_error; - if (iSize != cSize) goto _output_error; - { U64 const crcDest = XXH64(decodedBuffer, decodedSize, 1); - U64 const crcSrc = XXH64(CNBuffer, testSize, 1); - if (crcDest != crcSrc) goto _output_error; - } - DISPLAYLEVEL(3, "Regenerated %u bytes \n", (U32)decodedSize); - - CHECK( LZ4F_freeDecompressionContext(dctx) ); - } - - /* frame content size tests */ - { size_t cErr; - BYTE* const ostart = (BYTE*)compressedBuffer; - BYTE* op = ostart; - CHECK( LZ4F_createCompressionContext(&cctx, LZ4F_VERSION) ); - - DISPLAYLEVEL(3, "compress without frameSize : "); - memset(&(prefs.frameInfo), 0, sizeof(prefs.frameInfo)); - CHECK_V(cErr, LZ4F_compressBegin(cctx, compressedBuffer, testSize, &prefs)); - op += cErr; - CHECK_V(cErr, LZ4F_compressUpdate(cctx, op, LZ4F_compressBound(testSize, &prefs), CNBuffer, testSize, NULL)); - op += cErr; - CHECK( LZ4F_compressEnd(cctx, compressedBuffer, testSize, NULL) ); - DISPLAYLEVEL(3, "Compressed %i bytes into a %i bytes frame \n", (int)testSize, (int)(op-ostart)); - - DISPLAYLEVEL(3, "compress with frameSize : "); - prefs.frameInfo.contentSize = testSize; - op = ostart; - CHECK_V(cErr, LZ4F_compressBegin(cctx, compressedBuffer, testSize, &prefs)); - op += cErr; - CHECK_V(cErr, LZ4F_compressUpdate(cctx, op, LZ4F_compressBound(testSize, &prefs), CNBuffer, testSize, NULL)); - op += cErr; - CHECK( LZ4F_compressEnd(cctx, compressedBuffer, testSize, NULL) ); - DISPLAYLEVEL(3, "Compressed %i bytes into a %i bytes frame \n", (int)testSize, (int)(op-ostart)); - - DISPLAYLEVEL(3, "compress with wrong frameSize : "); - prefs.frameInfo.contentSize = testSize+1; - op = ostart; - CHECK_V(cErr, LZ4F_compressBegin(cctx, compressedBuffer, testSize, &prefs)); - op += cErr; - CHECK_V(cErr, LZ4F_compressUpdate(cctx, op, LZ4F_compressBound(testSize, &prefs), CNBuffer, testSize, NULL)); - op += cErr; - cErr = LZ4F_compressEnd(cctx, op, testSize, NULL); - if (!LZ4F_isError(cErr)) goto _output_error; - DISPLAYLEVEL(3, "Error correctly detected : %s \n", LZ4F_getErrorName(cErr)); - - CHECK( LZ4F_freeCompressionContext(cctx) ); - cctx = NULL; - } - - /* dictID tests */ - { size_t cErr; - U32 const dictID = 0x99; - CHECK( LZ4F_createCompressionContext(&cctx, LZ4F_VERSION) ); - - DISPLAYLEVEL(3, "insert a dictID : "); - memset(&prefs.frameInfo, 0, sizeof(prefs.frameInfo)); - prefs.frameInfo.dictID = dictID; - CHECK_V(cErr, LZ4F_compressBegin(cctx, compressedBuffer, testSize, &prefs)); - DISPLAYLEVEL(3, "created frame header of size %i bytes \n", (int)cErr); - - DISPLAYLEVEL(3, "read a dictID : "); - CHECK( LZ4F_createDecompressionContext(&dCtx, LZ4F_VERSION) ); - memset(&prefs.frameInfo, 0, sizeof(prefs.frameInfo)); - CHECK( LZ4F_getFrameInfo(dCtx, &prefs.frameInfo, compressedBuffer, &cErr) ); - if (prefs.frameInfo.dictID != dictID) goto _output_error; - DISPLAYLEVEL(3, "%u \n", (U32)prefs.frameInfo.dictID); - - CHECK( LZ4F_freeDecompressionContext(dCtx) ); dCtx = NULL; - CHECK( LZ4F_freeCompressionContext(cctx) ); cctx = NULL; - } - - - /* Dictionary compression test */ - { size_t const dictSize = 63 KB; - size_t const dstCapacity = LZ4F_compressFrameBound(dictSize, NULL); - size_t cSizeNoDict, cSizeWithDict; - LZ4F_CDict* const cdict = LZ4F_createCDict(CNBuffer, dictSize); - if (cdict == NULL) goto _output_error; - DISPLAYLEVEL(3, "LZ4F_compressFrame_usingCDict, with NULL dict : "); - CHECK_V(cSizeNoDict, - LZ4F_compressFrame_usingCDict(compressedBuffer, dstCapacity, - CNBuffer, dictSize, - NULL, NULL) ); - DISPLAYLEVEL(3, "%u bytes \n", (unsigned)cSizeNoDict); - - DISPLAYLEVEL(3, "LZ4F_compressFrame_usingCDict, with dict : "); - CHECK_V(cSizeWithDict, - LZ4F_compressFrame_usingCDict(compressedBuffer, dstCapacity, - CNBuffer, dictSize, - cdict, NULL) ); - DISPLAYLEVEL(3, "compressed %u bytes into %u bytes \n", - (unsigned)dictSize, (unsigned)cSizeWithDict); - if (cSizeWithDict >= cSizeNoDict) goto _output_error; /* must be more efficient */ - crcOrig = XXH64(CNBuffer, dictSize, 0); - - DISPLAYLEVEL(3, "LZ4F_decompress_usingDict : "); - { LZ4F_dctx* dctx; - size_t decodedSize = COMPRESSIBLE_NOISE_LENGTH; - size_t compressedSize = cSizeWithDict; - CHECK( LZ4F_createDecompressionContext(&dctx, LZ4F_VERSION) ); - CHECK( LZ4F_decompress_usingDict(dctx, - decodedBuffer, &decodedSize, - compressedBuffer, &compressedSize, - CNBuffer, dictSize, - NULL) ); - if (compressedSize != cSizeWithDict) goto _output_error; - if (decodedSize != dictSize) goto _output_error; - { U64 const crcDest = XXH64(decodedBuffer, decodedSize, 0); - if (crcDest != crcOrig) goto _output_error; } - DISPLAYLEVEL(3, "Regenerated %u bytes \n", (U32)decodedSize); - CHECK( LZ4F_freeDecompressionContext(dctx) ); - } - - DISPLAYLEVEL(3, "LZ4F_compressFrame_usingCDict, with dict, negative level : "); - { size_t cSizeLevelMax; - LZ4F_preferences_t cParams; - memset(&cParams, 0, sizeof(cParams)); - cParams.compressionLevel = -3; - CHECK_V(cSizeLevelMax, - LZ4F_compressFrame_usingCDict(compressedBuffer, dstCapacity, - CNBuffer, dictSize, - cdict, &cParams) ); - DISPLAYLEVEL(3, "%u bytes \n", (unsigned)cSizeLevelMax); - } - - DISPLAYLEVEL(3, "LZ4F_compressFrame_usingCDict, with dict, level max : "); - { size_t cSizeLevelMax; - LZ4F_preferences_t cParams; - memset(&cParams, 0, sizeof(cParams)); - cParams.compressionLevel = LZ4F_compressionLevel_max(); - CHECK_V(cSizeLevelMax, - LZ4F_compressFrame_usingCDict(compressedBuffer, dstCapacity, - CNBuffer, dictSize, - cdict, &cParams) ); - DISPLAYLEVEL(3, "%u bytes \n", (unsigned)cSizeLevelMax); - } - - DISPLAYLEVEL(3, "LZ4F_compressFrame_usingCDict, multiple linked blocks : "); - { size_t cSizeContiguous; - size_t const inSize = dictSize * 3; - size_t const outCapacity = LZ4F_compressFrameBound(inSize, NULL); - LZ4F_preferences_t cParams; - memset(&cParams, 0, sizeof(cParams)); - cParams.frameInfo.blockMode = LZ4F_blockLinked; - cParams.frameInfo.blockSizeID = LZ4F_max64KB; - CHECK_V(cSizeContiguous, - LZ4F_compressFrame_usingCDict(compressedBuffer, outCapacity, - CNBuffer, inSize, - cdict, &cParams) ); - DISPLAYLEVEL(3, "compressed %u bytes into %u bytes \n", - (unsigned)inSize, (unsigned)cSizeContiguous); - - DISPLAYLEVEL(3, "LZ4F_decompress_usingDict on multiple linked blocks : "); - { LZ4F_dctx* dctx; - size_t decodedSize = COMPRESSIBLE_NOISE_LENGTH; - size_t compressedSize = cSizeContiguous; - CHECK( LZ4F_createDecompressionContext(&dctx, LZ4F_VERSION) ); - CHECK( LZ4F_decompress_usingDict(dctx, - decodedBuffer, &decodedSize, - compressedBuffer, &compressedSize, - CNBuffer, dictSize, - NULL) ); - if (compressedSize != cSizeContiguous) goto _output_error; - if (decodedSize != inSize) goto _output_error; - crcOrig = XXH64(CNBuffer, inSize, 0); - { U64 const crcDest = XXH64(decodedBuffer, decodedSize, 0); - if (crcDest != crcOrig) goto _output_error; } - DISPLAYLEVEL(3, "Regenerated %u bytes \n", (U32)decodedSize); - CHECK( LZ4F_freeDecompressionContext(dctx) ); - } - } - - - DISPLAYLEVEL(3, "LZ4F_compressFrame_usingCDict, multiple independent blocks : "); - { size_t cSizeIndep; - size_t const inSize = dictSize * 3; - size_t const outCapacity = LZ4F_compressFrameBound(inSize, NULL); - LZ4F_preferences_t cParams; - memset(&cParams, 0, sizeof(cParams)); - cParams.frameInfo.blockMode = LZ4F_blockIndependent; - cParams.frameInfo.blockSizeID = LZ4F_max64KB; - CHECK_V(cSizeIndep, - LZ4F_compressFrame_usingCDict(compressedBuffer, outCapacity, - CNBuffer, inSize, - cdict, &cParams) ); - DISPLAYLEVEL(3, "compressed %u bytes into %u bytes \n", - (unsigned)inSize, (unsigned)cSizeIndep); - - DISPLAYLEVEL(3, "LZ4F_decompress_usingDict on multiple independent blocks : "); - { LZ4F_dctx* dctx; - size_t decodedSize = COMPRESSIBLE_NOISE_LENGTH; - size_t compressedSize = cSizeIndep; - CHECK( LZ4F_createDecompressionContext(&dctx, LZ4F_VERSION) ); - CHECK( LZ4F_decompress_usingDict(dctx, - decodedBuffer, &decodedSize, - compressedBuffer, &compressedSize, - CNBuffer, dictSize, - NULL) ); - if (compressedSize != cSizeIndep) goto _output_error; - if (decodedSize != inSize) goto _output_error; - crcOrig = XXH64(CNBuffer, inSize, 0); - { U64 const crcDest = XXH64(decodedBuffer, decodedSize, 0); - if (crcDest != crcOrig) goto _output_error; } - DISPLAYLEVEL(3, "Regenerated %u bytes \n", (U32)decodedSize); - CHECK( LZ4F_freeDecompressionContext(dctx) ); - } - } - - LZ4F_freeCDict(cdict); - } - - - DISPLAYLEVEL(3, "Skippable frame test : \n"); - { size_t decodedBufferSize = COMPRESSIBLE_NOISE_LENGTH; - unsigned maxBits = FUZ_highbit((U32)decodedBufferSize); - BYTE* op = (BYTE*)decodedBuffer; - BYTE* const oend = (BYTE*)decodedBuffer + COMPRESSIBLE_NOISE_LENGTH; - BYTE* ip = (BYTE*)compressedBuffer; - BYTE* iend = (BYTE*)compressedBuffer + cSize + 8; - - CHECK( LZ4F_createDecompressionContext(&dCtx, LZ4F_VERSION) ); - - /* generate skippable frame */ - FUZ_writeLE32(ip, LZ4F_MAGIC_SKIPPABLE_START); - FUZ_writeLE32(ip+4, (U32)cSize); - - DISPLAYLEVEL(3, "random segment sizes : \n"); - while (ip < iend) { - unsigned nbBits = FUZ_rand(&randState) % maxBits; - size_t iSize = (FUZ_rand(&randState) & ((1< (size_t)(iend-ip)) iSize = iend-ip; - CHECK( LZ4F_decompress(dCtx, op, &oSize, ip, &iSize, NULL) ); - op += oSize; - ip += iSize; - } - DISPLAYLEVEL(3, "Skipped %i bytes \n", (int)decodedBufferSize); - - /* generate zero-size skippable frame */ - DISPLAYLEVEL(3, "zero-size skippable frame\n"); - ip = (BYTE*)compressedBuffer; - op = (BYTE*)decodedBuffer; - FUZ_writeLE32(ip, LZ4F_MAGIC_SKIPPABLE_START+1); - FUZ_writeLE32(ip+4, 0); - iend = ip+8; - - while (ip < iend) { - unsigned const nbBits = FUZ_rand(&randState) % maxBits; - size_t iSize = (FUZ_rand(&randState) & ((1< (size_t)(iend-ip)) iSize = iend-ip; - CHECK( LZ4F_decompress(dCtx, op, &oSize, ip, &iSize, NULL) ); - op += oSize; - ip += iSize; - } - DISPLAYLEVEL(3, "Skipped %i bytes \n", (int)(ip - (BYTE*)compressedBuffer - 8)); - - DISPLAYLEVEL(3, "Skippable frame header complete in first call \n"); - ip = (BYTE*)compressedBuffer; - op = (BYTE*)decodedBuffer; - FUZ_writeLE32(ip, LZ4F_MAGIC_SKIPPABLE_START+2); - FUZ_writeLE32(ip+4, 10); - iend = ip+18; - while (ip < iend) { - size_t iSize = 10; - size_t oSize = 10; - if (iSize > (size_t)(iend-ip)) iSize = iend-ip; - CHECK( LZ4F_decompress(dCtx, op, &oSize, ip, &iSize, NULL) ); - op += oSize; - ip += iSize; - } - DISPLAYLEVEL(3, "Skipped %i bytes \n", (int)(ip - (BYTE*)compressedBuffer - 8)); - } - - DISPLAY("Basic tests completed \n"); -_end: - free(CNBuffer); - free(compressedBuffer); - free(decodedBuffer); - LZ4F_freeDecompressionContext(dCtx); dCtx = NULL; - LZ4F_freeCompressionContext(cctx); cctx = NULL; - return basicTests_error; - -_output_error: - basicTests_error = 1; - DISPLAY("Error detected ! \n"); - goto _end; -} - - -static void locateBuffDiff(const void* buff1, const void* buff2, size_t size, unsigned nonContiguous) -{ - int p=0; - const BYTE* b1=(const BYTE*)buff1; - const BYTE* b2=(const BYTE*)buff2; - if (nonContiguous) { - DISPLAY("Non-contiguous output test (%i bytes)\n", (int)size); - return; - } - while (b1[p]==b2[p]) p++; - DISPLAY("Error at pos %i/%i : %02X != %02X \n", p, (int)size, b1[p], b2[p]); -} - - -int fuzzerTests(U32 seed, unsigned nbTests, unsigned startTest, double compressibility, U32 duration_s) -{ - unsigned testResult = 0; - unsigned testNb = 0; - size_t const srcDataLength = 9 MB; /* needs to be > 2x4MB to test large blocks */ - void* srcBuffer = NULL; - size_t const compressedBufferSize = LZ4F_compressFrameBound(srcDataLength, NULL); - void* compressedBuffer = NULL; - void* decodedBuffer = NULL; - U32 coreRand = seed; - LZ4F_decompressionContext_t dCtx = NULL; - LZ4F_compressionContext_t cCtx = NULL; - size_t result; - clock_t const startClock = clock(); - clock_t const clockDuration = duration_s * CLOCKS_PER_SEC; -# undef CHECK -# define CHECK(cond, ...) if (cond) { DISPLAY("Error => "); DISPLAY(__VA_ARGS__); \ - DISPLAY(" (seed %u, test nb %u) \n", seed, testNb); goto _output_error; } - - /* Create buffers */ - result = LZ4F_createDecompressionContext(&dCtx, LZ4F_VERSION); - CHECK(LZ4F_isError(result), "Allocation failed (error %i)", (int)result); - result = LZ4F_createCompressionContext(&cCtx, LZ4F_VERSION); - CHECK(LZ4F_isError(result), "Allocation failed (error %i)", (int)result); - srcBuffer = malloc(srcDataLength); - CHECK(srcBuffer==NULL, "srcBuffer Allocation failed"); - compressedBuffer = malloc(compressedBufferSize); - CHECK(compressedBuffer==NULL, "compressedBuffer Allocation failed"); - decodedBuffer = calloc(1, srcDataLength); /* calloc avoids decodedBuffer being considered "garbage" by scan-build */ - CHECK(decodedBuffer==NULL, "decodedBuffer Allocation failed"); - FUZ_fillCompressibleNoiseBuffer(srcBuffer, srcDataLength, compressibility, &coreRand); - - /* jump to requested testNb */ - for (testNb =0; (testNb < startTest); testNb++) (void)FUZ_rand(&coreRand); /* sync randomizer */ - - /* main fuzzer test loop */ - for ( ; (testNb < nbTests) || (clockDuration > FUZ_GetClockSpan(startClock)) ; testNb++) { - U32 randState = coreRand ^ prime1; - unsigned const srcBits = (FUZ_rand(&randState) % (FUZ_highbit((U32)(srcDataLength-1)) - 1)) + 1; - size_t const srcSize = (FUZ_rand(&randState) & ((1<=oend, "LZ4F_compressFrameBound overflow"); - result = LZ4F_compressEnd(cCtx, op, oend-op, &cOptions); - CHECK(LZ4F_isError(result), "Compression completion failed (error %i : %s)", (int)result, LZ4F_getErrorName(result)); - op += result; - cSize = op-(BYTE*)compressedBuffer; - DISPLAYLEVEL(5, "\nCompressed %u bytes into %u \n", (U32)srcSize, (U32)cSize); - } - - /* multi-segments decompression */ - { const BYTE* ip = (const BYTE*)compressedBuffer; - const BYTE* const iend = ip + cSize; - BYTE* op = (BYTE*)decodedBuffer; - BYTE* const oend = op + srcDataLength; - unsigned const suggestedBits = FUZ_highbit((U32)cSize); - unsigned const maxBits = MAX(3, suggestedBits); - unsigned const nonContiguousDst = FUZ_rand(&randState) % 3; /* 0 : contiguous; 1 : non-contiguous; 2 : dst overwritten */ - size_t totalOut = 0; - XXH64_state_t xxh64; - XXH64_reset(&xxh64, 1); - while (ip < iend) { - unsigned const nbBitsI = (FUZ_rand(&randState) % (maxBits-1)) + 1; - unsigned const nbBitsO = (FUZ_rand(&randState) % (maxBits)) + 1; - size_t const iSizeMax = (FUZ_rand(&randState) & ((1<='0') && (*argument<='9')) { - nbTests *= 10; - nbTests += *argument - '0'; - argument++; - } - break; - - case 'T': - argument++; - nbTests = 0; duration = 0; - for (;;) { - switch(*argument) - { - case 'm': duration *= 60; argument++; continue; - case 's': - case 'n': argument++; continue; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': duration *= 10; duration += *argument++ - '0'; continue; - } - break; - } - break; - - case 's': - argument++; - seed=0; - seedset=1; - while ((*argument>='0') && (*argument<='9')) { - seed *= 10; - seed += *argument - '0'; - argument++; - } - break; - case 't': - argument++; - testNb=0; - while ((*argument>='0') && (*argument<='9')) { - testNb *= 10; - testNb += *argument - '0'; - argument++; - } - break; - case 'P': /* compressibility % */ - argument++; - proba=0; - while ((*argument>='0') && (*argument<='9')) { - proba *= 10; - proba += *argument - '0'; - argument++; - } - if (proba<0) proba=0; - if (proba>100) proba=100; - break; - default: - ; - return FUZ_usage(programName); - } - } - } - } - - /* Get Seed */ - DISPLAY("Starting lz4frame tester (%i-bits, %s)\n", (int)(sizeof(size_t)*8), LZ4_VERSION_STRING); - - if (!seedset) { - time_t const t = time(NULL); - U32 const h = XXH32(&t, sizeof(t), 1); - seed = h % 10000; - } - DISPLAY("Seed = %u\n", seed); - if (proba!=FUZ_COMPRESSIBILITY_DEFAULT) DISPLAY("Compressibility : %i%%\n", proba); - - if (nbTests<=0) nbTests=1; - - if (testNb==0) result = basicTests(seed, ((double)proba) / 100); - if (result) return 1; - return fuzzerTests(seed, nbTests, testNb, ((double)proba) / 100, duration); -} diff --git a/src/lz4/tests/fullbench.c b/src/lz4/tests/fullbench.c deleted file mode 100644 index f489392d1f..0000000000 --- a/src/lz4/tests/fullbench.c +++ /dev/null @@ -1,723 +0,0 @@ -/* - bench.c - Demo program to benchmark open-source compression algorithm - Copyright (C) Yann Collet 2012-2016 - - GPL v2 License - - This program is free software; 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-1301 USA. - - You can contact the author at : - - LZ4 source repository : https://github.com/lz4/lz4 - - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c -*/ - - -// S_ISREG & gettimeofday() are not supported by MSVC -#if defined(_MSC_VER) || defined(_WIN32) -# define BMK_LEGACY_TIMER 1 -#endif - - -/************************************** -* Includes -**************************************/ -#include "platform.h" /* _CRT_SECURE_NO_WARNINGS, Large Files support */ -#include "util.h" /* U32, UTIL_getFileSize */ -#include /* malloc, free */ -#include /* fprintf, fopen, ftello */ -#include /* stat64 */ -#include /* stat64 */ -#include /* strcmp */ -#include /* clock_t, clock(), CLOCKS_PER_SEC */ - -#include "lz4.h" -#include "lz4hc.h" -#include "lz4frame.h" - -#include "xxhash.h" - - -/************************************** -* Constants -**************************************/ -#define PROGRAM_DESCRIPTION "LZ4 speed analyzer" -#define AUTHOR "Yann Collet" -#define WELCOME_MESSAGE "*** %s v%s %i-bits, by %s ***\n", PROGRAM_DESCRIPTION, LZ4_VERSION_STRING, (int)(sizeof(void*)*8), AUTHOR - -#define NBLOOPS 6 -#define TIMELOOP (CLOCKS_PER_SEC * 25 / 10) - -#define KB *(1 <<10) -#define MB *(1 <<20) -#define GB *(1U<<30) - -#define KNUTH 2654435761U -#define MAX_MEM (1920 MB) -#define DEFAULT_CHUNKSIZE (4 MB) - -#define ALL_COMPRESSORS 0 -#define ALL_DECOMPRESSORS 0 - - -/************************************** -* Local structures -**************************************/ -struct chunkParameters -{ - U32 id; - char* origBuffer; - char* compressedBuffer; - int origSize; - int compressedSize; -}; - - -/************************************** -* Macros -**************************************/ -#define DISPLAY(...) fprintf(stderr, __VA_ARGS__) -#define PROGRESS(...) g_noPrompt ? 0 : DISPLAY(__VA_ARGS__) - - -/************************************** -* Benchmark Parameters -**************************************/ -static int g_chunkSize = DEFAULT_CHUNKSIZE; -static int g_nbIterations = NBLOOPS; -static int g_pause = 0; -static int g_compressionTest = 1; -static int g_compressionAlgo = ALL_COMPRESSORS; -static int g_decompressionTest = 1; -static int g_decompressionAlgo = ALL_DECOMPRESSORS; -static int g_noPrompt = 0; - -static void BMK_setBlocksize(int bsize) -{ - g_chunkSize = bsize; - DISPLAY("-Using Block Size of %i KB-\n", g_chunkSize>>10); -} - -static void BMK_setNbIterations(int nbLoops) -{ - g_nbIterations = nbLoops; - DISPLAY("- %i iterations -\n", g_nbIterations); -} - -static void BMK_setPause(void) -{ - g_pause = 1; -} - - -/********************************************************* -* Private functions -*********************************************************/ -static clock_t BMK_GetClockSpan( clock_t clockStart ) -{ - return clock() - clockStart; /* works even if overflow; max span ~30 mn */ -} - - -static size_t BMK_findMaxMem(U64 requiredMem) -{ - size_t step = 64 MB; - BYTE* testmem=NULL; - - requiredMem = (((requiredMem >> 26) + 1) << 26); - requiredMem += 2*step; - if (requiredMem > MAX_MEM) requiredMem = MAX_MEM; - - while (!testmem) { - if (requiredMem > step) requiredMem -= step; - else requiredMem >>= 1; - testmem = (BYTE*) malloc ((size_t)requiredMem); - } - free (testmem); - - /* keep some space available */ - if (requiredMem > step) requiredMem -= step; - else requiredMem >>= 1; - - return (size_t)requiredMem; -} - - -/********************************************************* -* Benchmark function -*********************************************************/ -static LZ4_stream_t LZ4_stream; -static void local_LZ4_resetDictT(void) -{ - LZ4_resetStream(&LZ4_stream); -} - -static void local_LZ4_createStream(void) -{ - LZ4_resetStream(&LZ4_stream); -} - -static int local_LZ4_saveDict(const char* in, char* out, int inSize) -{ - (void)in; - return LZ4_saveDict(&LZ4_stream, out, inSize); -} - -static int local_LZ4_compress_default_large(const char* in, char* out, int inSize) -{ - return LZ4_compress_default(in, out, inSize, LZ4_compressBound(inSize)); -} - -static int local_LZ4_compress_default_small(const char* in, char* out, int inSize) -{ - return LZ4_compress_default(in, out, inSize, LZ4_compressBound(inSize)-1); -} - -static int local_LZ4_compress_fast0(const char* in, char* out, int inSize) -{ - return LZ4_compress_fast(in, out, inSize, LZ4_compressBound(inSize), 0); -} - -static int local_LZ4_compress_fast1(const char* in, char* out, int inSize) -{ - return LZ4_compress_fast(in, out, inSize, LZ4_compressBound(inSize), 1); -} - -static int local_LZ4_compress_fast2(const char* in, char* out, int inSize) -{ - return LZ4_compress_fast(in, out, inSize, LZ4_compressBound(inSize), 2); -} - -static int local_LZ4_compress_fast17(const char* in, char* out, int inSize) -{ - return LZ4_compress_fast(in, out, inSize, LZ4_compressBound(inSize), 17); -} - -static int local_LZ4_compress_fast_extState0(const char* in, char* out, int inSize) -{ - return LZ4_compress_fast_extState(&LZ4_stream, in, out, inSize, LZ4_compressBound(inSize), 0); -} - -static int local_LZ4_compress_fast_continue0(const char* in, char* out, int inSize) -{ - return LZ4_compress_fast_continue(&LZ4_stream, in, out, inSize, LZ4_compressBound(inSize), 0); -} - -#ifndef LZ4_DLL_IMPORT -/* declare hidden function */ -int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize); - -static int local_LZ4_compress_forceDict(const char* in, char* out, int inSize) -{ - return LZ4_compress_forceExtDict(&LZ4_stream, in, out, inSize); -} -#endif - - -/* HC compression functions */ -LZ4_streamHC_t LZ4_streamHC; -static void local_LZ4_resetStreamHC(void) -{ - LZ4_resetStreamHC(&LZ4_streamHC, 0); -} - -static int local_LZ4_saveDictHC(const char* in, char* out, int inSize) -{ - (void)in; - return LZ4_saveDictHC(&LZ4_streamHC, out, inSize); -} - -static int local_LZ4_compress_HC(const char* in, char* out, int inSize) -{ - return LZ4_compress_HC(in, out, inSize, LZ4_compressBound(inSize), 9); -} - -static int local_LZ4_compress_HC_extStateHC(const char* in, char* out, int inSize) -{ - return LZ4_compress_HC_extStateHC(&LZ4_streamHC, in, out, inSize, LZ4_compressBound(inSize), 9); -} - -static int local_LZ4_compress_HC_continue(const char* in, char* out, int inSize) -{ - return LZ4_compress_HC_continue(&LZ4_streamHC, in, out, inSize, LZ4_compressBound(inSize)); -} - - -/* decompression functions */ -static int local_LZ4_decompress_fast(const char* in, char* out, int inSize, int outSize) -{ - (void)inSize; - LZ4_decompress_fast(in, out, outSize); - return outSize; -} - -static int local_LZ4_decompress_fast_usingDict(const char* in, char* out, int inSize, int outSize) -{ - (void)inSize; - LZ4_decompress_fast_usingDict(in, out, outSize, out - 65536, 65536); - return outSize; -} - -static int local_LZ4_decompress_safe_usingDict(const char* in, char* out, int inSize, int outSize) -{ - (void)inSize; - LZ4_decompress_safe_usingDict(in, out, inSize, outSize, out - 65536, 65536); - return outSize; -} - -#ifndef LZ4_DLL_IMPORT -extern int LZ4_decompress_safe_forceExtDict(const char* in, char* out, int inSize, int outSize, const char* dict, int dictSize); - -static int local_LZ4_decompress_safe_forceExtDict(const char* in, char* out, int inSize, int outSize) -{ - (void)inSize; - LZ4_decompress_safe_forceExtDict(in, out, inSize, outSize, out - 65536, 65536); - return outSize; -} -#endif - -static int local_LZ4_decompress_safe_partial(const char* in, char* out, int inSize, int outSize) -{ - return LZ4_decompress_safe_partial(in, out, inSize, outSize - 5, outSize); -} - - -/* frame functions */ -static int local_LZ4F_compressFrame(const char* in, char* out, int inSize) -{ - return (int)LZ4F_compressFrame(out, LZ4F_compressFrameBound(inSize, NULL), in, inSize, NULL); -} - -static LZ4F_decompressionContext_t g_dCtx; - -static int local_LZ4F_decompress(const char* in, char* out, int inSize, int outSize) -{ - size_t srcSize = inSize; - size_t dstSize = outSize; - size_t result; - result = LZ4F_decompress(g_dCtx, out, &dstSize, in, &srcSize, NULL); - if (result!=0) { DISPLAY("Error decompressing frame : unfinished frame\n"); exit(8); } - if (srcSize != (size_t)inSize) { DISPLAY("Error decompressing frame : read size incorrect\n"); exit(9); } - return (int)dstSize; -} - - -#define NB_COMPRESSION_ALGORITHMS 100 -#define NB_DECOMPRESSION_ALGORITHMS 100 -int fullSpeedBench(const char** fileNamesTable, int nbFiles) -{ - int fileIdx=0; - - /* Init */ - { size_t const errorCode = LZ4F_createDecompressionContext(&g_dCtx, LZ4F_VERSION); - if (LZ4F_isError(errorCode)) { DISPLAY("dctx allocation issue \n"); return 10; } } - - /* Loop for each fileName */ - while (fileIdx inFileSize) benchedSize = (size_t)inFileSize; - if (benchedSize < inFileSize) - DISPLAY("Not enough memory for '%s' full size; testing %i MB only...\n", inFileName, (int)(benchedSize>>20)); - - /* Allocation */ - chunkP = (struct chunkParameters*) malloc(((benchedSize / (size_t)g_chunkSize)+1) * sizeof(struct chunkParameters)); - orig_buff = (char*) malloc(benchedSize); - nbChunks = (int) ((benchedSize + (g_chunkSize-1)) / g_chunkSize); - maxCompressedChunkSize = LZ4_compressBound(g_chunkSize); - compressedBuffSize = nbChunks * maxCompressedChunkSize; - compressed_buff = (char*)malloc((size_t)compressedBuffSize); - if(!chunkP || !orig_buff || !compressed_buff) { - DISPLAY("\nError: not enough memory!\n"); - fclose(inFile); - free(orig_buff); - free(compressed_buff); - free(chunkP); - return(12); - } - - /* Fill in src buffer */ - DISPLAY("Loading %s... \r", inFileName); - readSize = fread(orig_buff, 1, benchedSize, inFile); - fclose(inFile); - - if (readSize != benchedSize) { - DISPLAY("\nError: problem reading file '%s' !! \n", inFileName); - free(orig_buff); - free(compressed_buff); - free(chunkP); - return 13; - } - - /* Calculating input Checksum */ - crcOriginal = XXH32(orig_buff, benchedSize,0); - - - /* Bench */ - { int loopNb, nb_loops, chunkNb, cAlgNb, dAlgNb; - size_t cSize=0; - double ratio=0.; - - DISPLAY("\r%79s\r", ""); - DISPLAY(" %s : \n", inFileName); - - /* Bench Compression Algorithms */ - for (cAlgNb=0; (cAlgNb <= NB_COMPRESSION_ALGORITHMS) && (g_compressionTest); cAlgNb++) { - const char* compressorName; - int (*compressionFunction)(const char*, char*, int); - void (*initFunction)(void) = NULL; - double bestTime = 100000000.; - - /* filter compressionAlgo only */ - if ((g_compressionAlgo != ALL_COMPRESSORS) && (g_compressionAlgo != cAlgNb)) continue; - - /* Init data chunks */ - { int i; - size_t remaining = benchedSize; - char* in = orig_buff; - char* out = compressed_buff; - nbChunks = (int) (((int)benchedSize + (g_chunkSize-1))/ g_chunkSize); - for (i=0; i g_chunkSize) { chunkP[i].origSize = g_chunkSize; remaining -= g_chunkSize; } else { chunkP[i].origSize = (int)remaining; remaining = 0; } - chunkP[i].compressedBuffer = out; out += maxCompressedChunkSize; - chunkP[i].compressedSize = 0; - } - } - - switch(cAlgNb) - { - case 0 : DISPLAY("Compression functions : \n"); continue; - case 1 : compressionFunction = local_LZ4_compress_default_large; compressorName = "LZ4_compress_default"; break; - case 2 : compressionFunction = local_LZ4_compress_default_small; compressorName = "LZ4_compress_default(small dst)"; break; - case 3 : compressionFunction = local_LZ4_compress_fast0; compressorName = "LZ4_compress_fast(0)"; break; - case 4 : compressionFunction = local_LZ4_compress_fast1; compressorName = "LZ4_compress_fast(1)"; break; - case 5 : compressionFunction = local_LZ4_compress_fast2; compressorName = "LZ4_compress_fast(2)"; break; - case 6 : compressionFunction = local_LZ4_compress_fast17; compressorName = "LZ4_compress_fast(17)"; break; - case 7 : compressionFunction = local_LZ4_compress_fast_extState0; compressorName = "LZ4_compress_fast_extState(0)"; break; - case 8 : compressionFunction = local_LZ4_compress_fast_continue0; initFunction = local_LZ4_createStream; compressorName = "LZ4_compress_fast_continue(0)"; break; - - case 10: compressionFunction = local_LZ4_compress_HC; compressorName = "LZ4_compress_HC"; break; - case 12: compressionFunction = local_LZ4_compress_HC_extStateHC; compressorName = "LZ4_compress_HC_extStateHC"; break; - case 14: compressionFunction = local_LZ4_compress_HC_continue; initFunction = local_LZ4_resetStreamHC; compressorName = "LZ4_compress_HC_continue"; break; -#ifndef LZ4_DLL_IMPORT - case 20: compressionFunction = local_LZ4_compress_forceDict; initFunction = local_LZ4_resetDictT; compressorName = "LZ4_compress_forceDict"; break; -#endif - case 30: compressionFunction = local_LZ4F_compressFrame; compressorName = "LZ4F_compressFrame"; - chunkP[0].origSize = (int)benchedSize; nbChunks=1; - break; - case 40: compressionFunction = local_LZ4_saveDict; compressorName = "LZ4_saveDict"; - if (chunkP[0].origSize < 8) { DISPLAY(" cannot bench %s with less then 8 bytes \n", compressorName); continue; } - LZ4_loadDict(&LZ4_stream, chunkP[0].origBuffer, chunkP[0].origSize); - break; - case 41: compressionFunction = local_LZ4_saveDictHC; compressorName = "LZ4_saveDictHC"; - if (chunkP[0].origSize < 8) { DISPLAY(" cannot bench %s with less then 8 bytes \n", compressorName); continue; } - LZ4_loadDictHC(&LZ4_streamHC, chunkP[0].origBuffer, chunkP[0].origSize); - break; - default : - continue; /* unknown ID : just skip */ - } - - for (loopNb = 1; loopNb <= g_nbIterations; loopNb++) { - double averageTime; - clock_t clockTime; - - PROGRESS("%1i- %-28.28s :%9i ->\r", loopNb, compressorName, (int)benchedSize); - { size_t i; for (i=0; i%9i (%5.2f%%),%7.1f MB/s\r", loopNb, compressorName, (int)benchedSize, (int)cSize, ratio, (double)benchedSize / bestTime / 1000000); - } - - if (ratio<100.) - DISPLAY("%2i-%-28.28s :%9i ->%9i (%5.2f%%),%7.1f MB/s\n", cAlgNb, compressorName, (int)benchedSize, (int)cSize, ratio, (double)benchedSize / bestTime / 1000000); - else - DISPLAY("%2i-%-28.28s :%9i ->%9i (%5.1f%%),%7.1f MB/s\n", cAlgNb, compressorName, (int)benchedSize, (int)cSize, ratio, (double)benchedSize / bestTime / 100000); - } - - /* Prepare layout for decompression */ - /* Init data chunks */ - { int i; - size_t remaining = benchedSize; - char* in = orig_buff; - char* out = compressed_buff; - - nbChunks = (int) (((int)benchedSize + (g_chunkSize-1))/ g_chunkSize); - for (i=0; i g_chunkSize) { chunkP[i].origSize = g_chunkSize; remaining -= g_chunkSize; } else { chunkP[i].origSize = (int)remaining; remaining = 0; } - chunkP[i].compressedBuffer = out; out += maxCompressedChunkSize; - chunkP[i].compressedSize = 0; - } - } - for (chunkNb=0; chunkNb\r", loopNb, dName, (int)benchedSize); - - nb_loops = 0; - clockTime = clock(); - while(clock() == clockTime); - clockTime = clock(); - while(BMK_GetClockSpan(clockTime) < TIMELOOP) { - for (chunkNb=0; chunkNb %7.1f MB/s\r", loopNb, dName, (int)benchedSize, (double)benchedSize / bestTime / 1000000); - - /* CRC Checking */ - crcDecoded = XXH32(orig_buff, (int)benchedSize, 0); - if (crcOriginal!=crcDecoded) { DISPLAY("\n!!! WARNING !!! %14s : Invalid Checksum : %x != %x\n", inFileName, (unsigned)crcOriginal, (unsigned)crcDecoded); exit(1); } - } - - DISPLAY("%2i-%-29.29s :%10i -> %7.1f MB/s\n", dAlgNb, dName, (int)benchedSize, (double)benchedSize / bestTime / 1000000); - } - } - free(orig_buff); - free(compressed_buff); - free(chunkP); - } - - LZ4F_freeDecompressionContext(g_dCtx); - if (g_pause) { printf("press enter...\n"); (void)getchar(); } - - return 0; -} - - -static int usage(const char* exename) -{ - DISPLAY( "Usage :\n"); - DISPLAY( " %s [arg] file1 file2 ... fileX\n", exename); - DISPLAY( "Arguments :\n"); - DISPLAY( " -c : compression tests only\n"); - DISPLAY( " -d : decompression tests only\n"); - DISPLAY( " -H/-h : Help (this text + advanced options)\n"); - return 0; -} - -static int usage_advanced(void) -{ - DISPLAY( "\nAdvanced options :\n"); - DISPLAY( " -c# : test only compression function # [1-%i]\n", NB_COMPRESSION_ALGORITHMS); - DISPLAY( " -d# : test only decompression function # [1-%i]\n", NB_DECOMPRESSION_ALGORITHMS); - DISPLAY( " -i# : iteration loops [1-9](default : %i)\n", NBLOOPS); - DISPLAY( " -B# : Block size [4-7](default : 7)\n"); - return 0; -} - -static int badusage(const char* exename) -{ - DISPLAY("Wrong parameters\n"); - usage(exename); - return 0; -} - -int main(int argc, const char** argv) -{ - int i, - filenamesStart=2; - const char* exename = argv[0]; - const char* input_filename=0; - - // Welcome message - DISPLAY(WELCOME_MESSAGE); - - if (argc<2) { badusage(exename); return 1; } - - for(i=1; i= '0') && (argument[1]<= '9')) { - g_compressionAlgo *= 10; - g_compressionAlgo += argument[1] - '0'; - argument++; - } - break; - - // Select decompression algorithm only - case 'd': - g_compressionTest = 0; - while ((argument[1]>= '0') && (argument[1]<= '9')) { - g_decompressionAlgo *= 10; - g_decompressionAlgo += argument[1] - '0'; - argument++; - } - break; - - // Display help on usage - case 'h' : - case 'H': usage(exename); usage_advanced(); return 0; - - // Modify Block Properties - case 'B': - while (argument[1]!=0) - switch(argument[1]) - { - case '4': - case '5': - case '6': - case '7': - { int B = argument[1] - '0'; - int S = 1 << (8 + 2*B); - BMK_setBlocksize(S); - argument++; - break; - } - case 'D': argument++; break; - default : goto _exit_blockProperties; - } -_exit_blockProperties: - break; - - // Modify Nb Iterations - case 'i': - if ((argument[1] >='0') && (argument[1] <='9')) { - int iters = argument[1] - '0'; - BMK_setNbIterations(iters); - argument++; - } - break; - - // Pause at the end (hidden option) - case 'p': BMK_setPause(); break; - - // Unknown command - default : badusage(exename); return 1; - } - } - continue; - } - - // first provided filename is input - if (!input_filename) { input_filename=argument; filenamesStart=i; continue; } - - } - - // No input filename ==> Error - if(!input_filename) { badusage(exename); return 1; } - - return fullSpeedBench(argv+filenamesStart, argc-filenamesStart); - -} diff --git a/src/lz4/tests/fuzzer.c b/src/lz4/tests/fuzzer.c deleted file mode 100644 index 2e22912def..0000000000 --- a/src/lz4/tests/fuzzer.c +++ /dev/null @@ -1,1180 +0,0 @@ -/* - fuzzer.c - Fuzzer test tool for LZ4 - Copyright (C) Yann Collet 2012-2017 - - GPL v2 License - - This program is free software; 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-1301 USA. - - You can contact the author at : - - LZ4 homepage : http://www.lz4.org - - LZ4 source repo : https://github.com/lz4/lz4 -*/ - -/*-************************************ -* Compiler options -**************************************/ -#ifdef _MSC_VER /* Visual Studio */ -# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ -# pragma warning(disable : 4146) /* disable: C4146: minus unsigned expression */ -# pragma warning(disable : 4310) /* disable: C4310: constant char value > 127 */ -#endif - -#define LZ4_DISABLE_DEPRECATE_WARNINGS - -/*-************************************ -* Dependencies -**************************************/ -#include "platform.h" /* _CRT_SECURE_NO_WARNINGS */ -#include "util.h" /* U32 */ -#include -#include /* fgets, sscanf */ -#include /* strcmp */ -#include /* clock_t, clock, CLOCKS_PER_SEC */ -#define LZ4_HC_STATIC_LINKING_ONLY -#include "lz4hc.h" -#define XXH_STATIC_LINKING_ONLY -#include "xxhash.h" - - -/*-************************************ -* Basic Types -**************************************/ -#if !defined(__cplusplus) && !(defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) -typedef size_t uintptr_t; /* true on most systems, except OpenVMS-64 (which doesn't need address overflow test) */ -#endif - - -/*-************************************ -* Constants -**************************************/ -#define NB_ATTEMPTS (1<<16) -#define COMPRESSIBLE_NOISE_LENGTH (1 << 21) -#define FUZ_MAX_BLOCK_SIZE (1 << 17) -#define FUZ_MAX_DICT_SIZE (1 << 15) -#define FUZ_COMPRESSIBILITY_DEFAULT 60 -#define PRIME1 2654435761U -#define PRIME2 2246822519U -#define PRIME3 3266489917U - -#define KB *(1U<<10) -#define MB *(1U<<20) -#define GB *(1U<<30) - - -/*-*************************************** -* Macros -*****************************************/ -#define DISPLAY(...) fprintf(stdout, __VA_ARGS__) -#define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); } -static int g_displayLevel = 2; - -#define MIN(a,b) ( (a) < (b) ? (a) : (b) ) - - -/*-******************************************************* -* Fuzzer functions -*********************************************************/ -static clock_t FUZ_GetClockSpan(clock_t clockStart) -{ - return clock() - clockStart; /* works even if overflow; max span ~ 30mn */ -} - -static void FUZ_displayUpdate(unsigned testNb) -{ - static clock_t g_time = 0; - static const clock_t g_refreshRate = CLOCKS_PER_SEC / 5; - if ((FUZ_GetClockSpan(g_time) > g_refreshRate) || (g_displayLevel>=4)) { - g_time = clock(); - DISPLAY("\r%5u ", testNb); - fflush(stdout); - } -} - -static U32 FUZ_rotl32(U32 u32, U32 nbBits) -{ - return ((u32 << nbBits) | (u32 >> (32 - nbBits))); -} - -static U32 FUZ_rand(U32* src) -{ - U32 rand32 = *src; - rand32 *= PRIME1; - rand32 ^= PRIME2; - rand32 = FUZ_rotl32(rand32, 13); - *src = rand32; - return rand32; -} - - -#define FUZ_RAND15BITS ((FUZ_rand(seed) >> 3) & 32767) -#define FUZ_RANDLENGTH ( ((FUZ_rand(seed) >> 7) & 3) ? (FUZ_rand(seed) % 15) : (FUZ_rand(seed) % 510) + 15) -static void FUZ_fillCompressibleNoiseBuffer(void* buffer, size_t bufferSize, double proba, U32* seed) -{ - BYTE* const BBuffer = (BYTE*)buffer; - size_t pos = 0; - U32 const P32 = (U32)(32768 * proba); - - /* First Bytes */ - while (pos < 20) - BBuffer[pos++] = (BYTE)(FUZ_rand(seed)); - - while (pos < bufferSize) { - /* Select : Literal (noise) or copy (within 64K) */ - if (FUZ_RAND15BITS < P32) { - /* Copy (within 64K) */ - size_t const length = FUZ_RANDLENGTH + 4; - size_t const d = MIN(pos+length, bufferSize); - size_t match; - size_t offset = FUZ_RAND15BITS + 1; - while (offset > pos) offset >>= 1; - match = pos - offset; - while (pos < d) BBuffer[pos++] = BBuffer[match++]; - } else { - /* Literal (noise) */ - size_t const length = FUZ_RANDLENGTH; - size_t const d = MIN(pos+length, bufferSize); - while (pos < d) BBuffer[pos++] = (BYTE)(FUZ_rand(seed) >> 5); - } - } -} - - -#define MAX_NB_BUFF_I134 150 -#define BLOCKSIZE_I134 (32 MB) -/*! FUZ_AddressOverflow() : -* Aggressively pushes memory allocation limits, -* and generates patterns which create address space overflow. -* only possible in 32-bits mode */ -static int FUZ_AddressOverflow(void) -{ - char* buffers[MAX_NB_BUFF_I134+1]; - int nbBuff=0; - int highAddress = 0; - - DISPLAY("Overflow tests : "); - - /* Only possible in 32-bits */ - if (sizeof(void*)==8) { - DISPLAY("64 bits mode : no overflow \n"); - fflush(stdout); - return 0; - } - - buffers[0] = (char*)malloc(BLOCKSIZE_I134); - buffers[1] = (char*)malloc(BLOCKSIZE_I134); - if ((!buffers[0]) || (!buffers[1])) { - free(buffers[0]); free(buffers[1]); - DISPLAY("not enough memory for tests \n"); - return 0; - } - - for (nbBuff=2; nbBuff < MAX_NB_BUFF_I134; nbBuff++) { - DISPLAY("%3i \b\b\b\b", nbBuff); fflush(stdout); - buffers[nbBuff] = (char*)malloc(BLOCKSIZE_I134); - if (buffers[nbBuff]==NULL) goto _endOfTests; - - if (((uintptr_t)buffers[nbBuff] > (uintptr_t)0x80000000) && (!highAddress)) { - DISPLAY("high address detected : "); - fflush(stdout); - highAddress=1; - } - - { size_t const sizeToGenerateOverflow = (size_t)(- ((uintptr_t)buffers[nbBuff-1]) + 512); - unsigned const nbOf255 = (unsigned)((sizeToGenerateOverflow / 255) + 1); - char* const input = buffers[nbBuff-1]; - char* output = buffers[nbBuff]; - int r; - input[0] = (char)0xF0; /* Literal length overflow */ - input[1] = (char)0xFF; - input[2] = (char)0xFF; - input[3] = (char)0xFF; - { unsigned u; for(u = 4; u <= nbOf255+4; u++) input[u] = (char)0xff; } - r = LZ4_decompress_safe(input, output, nbOf255+64, BLOCKSIZE_I134); - if (r>0) { DISPLAY("LZ4_decompress_safe = %i \n", r); goto _overflowError; } - input[0] = (char)0x1F; /* Match length overflow */ - input[1] = (char)0x01; - input[2] = (char)0x01; - input[3] = (char)0x00; - r = LZ4_decompress_safe(input, output, nbOf255+64, BLOCKSIZE_I134); - if (r>0) { DISPLAY("LZ4_decompress_safe = %i \n", r); goto _overflowError; } - - output = buffers[nbBuff-2]; /* Reverse in/out pointer order */ - input[0] = (char)0xF0; /* Literal length overflow */ - input[1] = (char)0xFF; - input[2] = (char)0xFF; - input[3] = (char)0xFF; - r = LZ4_decompress_safe(input, output, nbOf255+64, BLOCKSIZE_I134); - if (r>0) goto _overflowError; - input[0] = (char)0x1F; /* Match length overflow */ - input[1] = (char)0x01; - input[2] = (char)0x01; - input[3] = (char)0x00; - r = LZ4_decompress_safe(input, output, nbOf255+64, BLOCKSIZE_I134); - if (r>0) goto _overflowError; - } - } - - nbBuff++; -_endOfTests: - { int i; for (i=0 ; i=4 ? printf("%2u\b\b", testNb), fflush(stdout) : 0; } - - - /* init */ - if(!CNBuffer || !compressedBuffer || !decodedBuffer) { - DISPLAY("Not enough memory to start fuzzer tests"); - goto _output_error; - } - memset(&LZ4dict, 0, sizeof(LZ4dict)); - { U32 randState = coreRandState ^ PRIME3; - FUZ_fillCompressibleNoiseBuffer(CNBuffer, COMPRESSIBLE_NOISE_LENGTH, compressibility, &randState); - } - - /* move to startCycle */ - for (cycleNb = 0; cycleNb < startCycle; cycleNb++) - (void) FUZ_rand(&coreRandState); /* sync coreRandState */ - - /* Main test loop */ - for (cycleNb = startCycle; - (cycleNb < nbCycles) || (FUZ_GetClockSpan(clockStart) < clockDuration); - cycleNb++) { - U32 testNb = 0; - U32 randState = FUZ_rand(&coreRandState) ^ PRIME3; - int const blockSize = (FUZ_rand(&randState) % (FUZ_MAX_BLOCK_SIZE-1)) + 1; - int const blockStart = FUZ_rand(&randState) % (COMPRESSIBLE_NOISE_LENGTH - blockSize); - int const dictSizeRand = FUZ_rand(&randState) % FUZ_MAX_DICT_SIZE; - int const dictSize = MIN(dictSizeRand, blockStart); - int const compressionLevel = FUZ_rand(&randState) % (LZ4HC_CLEVEL_MAX+1); - char* const block = ((char*)CNBuffer) + blockStart; - const char* dict = block - dictSize; - int compressedSize, HCcompressedSize; - int blockContinueCompressedSize; - U32 const crcOrig = XXH32(block, blockSize, 0); - U32 crcCheck; - int ret; - - FUZ_displayUpdate(cycleNb); - - /* Compression tests */ - - /* Test compression destSize */ - FUZ_DISPLAYTEST; - { int srcSize = blockSize; - int const targetSize = srcSize * ((FUZ_rand(&randState) & 127)+1) >> 7; - char endCheck = FUZ_rand(&randState) & 255; - compressedBuffer[targetSize] = endCheck; - ret = LZ4_compress_destSize(block, compressedBuffer, &srcSize, targetSize); - FUZ_CHECKTEST(ret > targetSize, "LZ4_compress_destSize() result larger than dst buffer !"); - FUZ_CHECKTEST(compressedBuffer[targetSize] != endCheck, "LZ4_compress_destSize() overwrite dst buffer !"); - FUZ_CHECKTEST(srcSize > blockSize, "LZ4_compress_destSize() fed more than src buffer !"); - DISPLAYLEVEL(5, "destSize : %7i/%7i; content%7i/%7i ", ret, targetSize, srcSize, blockSize); - if (targetSize>0) { - /* check correctness */ - U32 const crcBase = XXH32(block, srcSize, 0); - char const canary = FUZ_rand(&randState) & 255; - FUZ_CHECKTEST((ret==0), "LZ4_compress_destSize() compression failed"); - FUZ_DISPLAYTEST; - compressedSize = ret; - decodedBuffer[srcSize] = canary; - ret = LZ4_decompress_safe(compressedBuffer, decodedBuffer, compressedSize, srcSize); - FUZ_CHECKTEST(ret<0, "LZ4_decompress_safe() failed on data compressed by LZ4_compress_destSize"); - FUZ_CHECKTEST(ret!=srcSize, "LZ4_decompress_safe() failed : did not fully decompressed data"); - FUZ_CHECKTEST(decodedBuffer[srcSize] != canary, "LZ4_decompress_safe() overwrite dst buffer !"); - { U32 const crcDec = XXH32(decodedBuffer, srcSize, 0); - FUZ_CHECKTEST(crcDec!=crcBase, "LZ4_decompress_safe() corrupted decoded data"); } - - DISPLAYLEVEL(5, " OK \n"); - } - else - DISPLAYLEVEL(5, " \n"); - } - - /* Test compression HC destSize */ - FUZ_DISPLAYTEST; - { int srcSize = blockSize; - int const targetSize = srcSize * ((FUZ_rand(&randState) & 127)+1) >> 7; - char const endCheck = FUZ_rand(&randState) & 255; - void* ctx = LZ4_createHC(block); - FUZ_CHECKTEST(ctx==NULL, "LZ4_createHC() allocation failed"); - compressedBuffer[targetSize] = endCheck; - ret = LZ4_compress_HC_destSize(ctx, block, compressedBuffer, &srcSize, targetSize, compressionLevel); - LZ4_freeHC(ctx); - FUZ_CHECKTEST(ret > targetSize, "LZ4_compress_HC_destSize() result larger than dst buffer !"); - FUZ_CHECKTEST(compressedBuffer[targetSize] != endCheck, "LZ4_compress_HC_destSize() overwrite dst buffer !"); - FUZ_CHECKTEST(srcSize > blockSize, "LZ4_compress_HC_destSize() fed more than src buffer !"); - DISPLAYLEVEL(5, "destSize : %7i/%7i; content%7i/%7i ", ret, targetSize, srcSize, blockSize); - if (targetSize>0) { - /* check correctness */ - U32 const crcBase = XXH32(block, srcSize, 0); - char const canary = FUZ_rand(&randState) & 255; - FUZ_CHECKTEST((ret==0), "LZ4_compress_HC_destSize() compression failed"); - FUZ_DISPLAYTEST; - compressedSize = ret; - decodedBuffer[srcSize] = canary; - ret = LZ4_decompress_safe(compressedBuffer, decodedBuffer, compressedSize, srcSize); - FUZ_CHECKTEST(ret<0, "LZ4_decompress_safe() failed on data compressed by LZ4_compressHC_destSize"); - FUZ_CHECKTEST(ret!=srcSize, "LZ4_decompress_safe() failed : did not fully decompressed data"); - FUZ_CHECKTEST(decodedBuffer[srcSize] != canary, "LZ4_decompress_safe() overwrite dst buffer !"); - { U32 const crcDec = XXH32(decodedBuffer, srcSize, 0); - FUZ_CHECKTEST(crcDec!=crcBase, "LZ4_decompress_safe() corrupted decoded data"); } - - DISPLAYLEVEL(5, " OK \n"); - } - else - DISPLAYLEVEL(5, " \n"); - } - - /* Test compression HC */ - FUZ_DISPLAYTEST; - ret = LZ4_compress_HC(block, compressedBuffer, blockSize, (int)compressedBufferSize, compressionLevel); - FUZ_CHECKTEST(ret==0, "LZ4_compress_HC() failed"); - HCcompressedSize = ret; - - /* Test compression HC using external state */ - FUZ_DISPLAYTEST; - ret = LZ4_compress_HC_extStateHC(stateLZ4HC, block, compressedBuffer, blockSize, (int)compressedBufferSize, compressionLevel); - FUZ_CHECKTEST(ret==0, "LZ4_compress_HC_extStateHC() failed"); - - /* Test compression using external state */ - FUZ_DISPLAYTEST; - ret = LZ4_compress_fast_extState(stateLZ4, block, compressedBuffer, blockSize, (int)compressedBufferSize, 8); - FUZ_CHECKTEST(ret==0, "LZ4_compress_fast_extState() failed"); - - /* Test compression */ - FUZ_DISPLAYTEST; - ret = LZ4_compress_default(block, compressedBuffer, blockSize, (int)compressedBufferSize); - FUZ_CHECKTEST(ret==0, "LZ4_compress_default() failed"); - compressedSize = ret; - - /* Decompression tests */ - - /* Test decoding with output size being exactly what's necessary => must work */ - FUZ_DISPLAYTEST; - ret = LZ4_decompress_fast(compressedBuffer, decodedBuffer, blockSize); - FUZ_CHECKTEST(ret<0, "LZ4_decompress_fast failed despite correct space"); - FUZ_CHECKTEST(ret!=compressedSize, "LZ4_decompress_fast failed : did not fully read compressed data"); - crcCheck = XXH32(decodedBuffer, blockSize, 0); - FUZ_CHECKTEST(crcCheck!=crcOrig, "LZ4_decompress_fast corrupted decoded data"); - - /* Test decoding with one byte missing => must fail */ - FUZ_DISPLAYTEST; - decodedBuffer[blockSize-1] = 0; - ret = LZ4_decompress_fast(compressedBuffer, decodedBuffer, blockSize-1); - FUZ_CHECKTEST(ret>=0, "LZ4_decompress_fast should have failed, due to Output Size being too small"); - FUZ_CHECKTEST(decodedBuffer[blockSize-1], "LZ4_decompress_fast overrun specified output buffer"); - - /* Test decoding with one byte too much => must fail */ - FUZ_DISPLAYTEST; - ret = LZ4_decompress_fast(compressedBuffer, decodedBuffer, blockSize+1); - FUZ_CHECKTEST(ret>=0, "LZ4_decompress_fast should have failed, due to Output Size being too large"); - - /* Test decoding with output size exactly what's necessary => must work */ - FUZ_DISPLAYTEST; - decodedBuffer[blockSize] = 0; - ret = LZ4_decompress_safe(compressedBuffer, decodedBuffer, compressedSize, blockSize); - FUZ_CHECKTEST(ret<0, "LZ4_decompress_safe failed despite sufficient space"); - FUZ_CHECKTEST(ret!=blockSize, "LZ4_decompress_safe did not regenerate original data"); - FUZ_CHECKTEST(decodedBuffer[blockSize], "LZ4_decompress_safe overrun specified output buffer size"); - crcCheck = XXH32(decodedBuffer, blockSize, 0); - FUZ_CHECKTEST(crcCheck!=crcOrig, "LZ4_decompress_safe corrupted decoded data"); - - // Test decoding with more than enough output size => must work - FUZ_DISPLAYTEST; - decodedBuffer[blockSize] = 0; - decodedBuffer[blockSize+1] = 0; - ret = LZ4_decompress_safe(compressedBuffer, decodedBuffer, compressedSize, blockSize+1); - FUZ_CHECKTEST(ret<0, "LZ4_decompress_safe failed despite amply sufficient space"); - FUZ_CHECKTEST(ret!=blockSize, "LZ4_decompress_safe did not regenerate original data"); - //FUZ_CHECKTEST(decodedBuffer[blockSize], "LZ4_decompress_safe wrote more than (unknown) target size"); // well, is that an issue ? - FUZ_CHECKTEST(decodedBuffer[blockSize+1], "LZ4_decompress_safe overrun specified output buffer size"); - crcCheck = XXH32(decodedBuffer, blockSize, 0); - FUZ_CHECKTEST(crcCheck!=crcOrig, "LZ4_decompress_safe corrupted decoded data"); - - // Test decoding with output size being one byte too short => must fail - FUZ_DISPLAYTEST; - decodedBuffer[blockSize-1] = 0; - ret = LZ4_decompress_safe(compressedBuffer, decodedBuffer, compressedSize, blockSize-1); - FUZ_CHECKTEST(ret>=0, "LZ4_decompress_safe should have failed, due to Output Size being one byte too short"); - FUZ_CHECKTEST(decodedBuffer[blockSize-1], "LZ4_decompress_safe overrun specified output buffer size"); - - // Test decoding with output size being 10 bytes too short => must fail - FUZ_DISPLAYTEST; - if (blockSize>10) - { - decodedBuffer[blockSize-10] = 0; - ret = LZ4_decompress_safe(compressedBuffer, decodedBuffer, compressedSize, blockSize-10); - FUZ_CHECKTEST(ret>=0, "LZ4_decompress_safe should have failed, due to Output Size being 10 bytes too short"); - FUZ_CHECKTEST(decodedBuffer[blockSize-10], "LZ4_decompress_safe overrun specified output buffer size"); - } - - // Test decoding with input size being one byte too short => must fail - FUZ_DISPLAYTEST; - ret = LZ4_decompress_safe(compressedBuffer, decodedBuffer, compressedSize-1, blockSize); - FUZ_CHECKTEST(ret>=0, "LZ4_decompress_safe should have failed, due to input size being one byte too short (blockSize=%i, ret=%i, compressedSize=%i)", blockSize, ret, compressedSize); - - // Test decoding with input size being one byte too large => must fail - FUZ_DISPLAYTEST; - decodedBuffer[blockSize] = 0; - ret = LZ4_decompress_safe(compressedBuffer, decodedBuffer, compressedSize+1, blockSize); - FUZ_CHECKTEST(ret>=0, "LZ4_decompress_safe should have failed, due to input size being too large"); - FUZ_CHECKTEST(decodedBuffer[blockSize], "LZ4_decompress_safe overrun specified output buffer size"); - - // Test partial decoding with target output size being max/2 => must work - FUZ_DISPLAYTEST; - ret = LZ4_decompress_safe_partial(compressedBuffer, decodedBuffer, compressedSize, blockSize/2, blockSize); - FUZ_CHECKTEST(ret<0, "LZ4_decompress_safe_partial failed despite sufficient space"); - - // Test partial decoding with target output size being just below max => must work - FUZ_DISPLAYTEST; - ret = LZ4_decompress_safe_partial(compressedBuffer, decodedBuffer, compressedSize, blockSize-3, blockSize); - FUZ_CHECKTEST(ret<0, "LZ4_decompress_safe_partial failed despite sufficient space"); - - /* Test Compression with limited output size */ - - /* Test compression with output size being exactly what's necessary (should work) */ - FUZ_DISPLAYTEST; - ret = LZ4_compress_default(block, compressedBuffer, blockSize, compressedSize); - FUZ_CHECKTEST(ret==0, "LZ4_compress_default() failed despite sufficient space"); - - /* Test compression with output size being exactly what's necessary and external state (should work) */ - FUZ_DISPLAYTEST; - ret = LZ4_compress_fast_extState(stateLZ4, block, compressedBuffer, blockSize, compressedSize, 1); - FUZ_CHECKTEST(ret==0, "LZ4_compress_fast_extState() failed despite sufficient space"); - - /* Test HC compression with output size being exactly what's necessary (should work) */ - FUZ_DISPLAYTEST; - ret = LZ4_compress_HC(block, compressedBuffer, blockSize, HCcompressedSize, compressionLevel); - FUZ_CHECKTEST(ret==0, "LZ4_compress_HC() failed despite sufficient space"); - - /* Test HC compression with output size being exactly what's necessary (should work) */ - FUZ_DISPLAYTEST; - ret = LZ4_compress_HC_extStateHC(stateLZ4HC, block, compressedBuffer, blockSize, HCcompressedSize, compressionLevel); - FUZ_CHECKTEST(ret==0, "LZ4_compress_HC_extStateHC() failed despite sufficient space"); - - /* Test compression with missing bytes into output buffer => must fail */ - FUZ_DISPLAYTEST; - { int missingBytes = (FUZ_rand(&randState) % 0x3F) + 1; - if (missingBytes >= compressedSize) missingBytes = compressedSize-1; - missingBytes += !missingBytes; /* avoid special case missingBytes==0 */ - compressedBuffer[compressedSize-missingBytes] = 0; - ret = LZ4_compress_default(block, compressedBuffer, blockSize, compressedSize-missingBytes); - FUZ_CHECKTEST(ret, "LZ4_compress_default should have failed (output buffer too small by %i byte)", missingBytes); - FUZ_CHECKTEST(compressedBuffer[compressedSize-missingBytes], "LZ4_compress_default overran output buffer ! (%i missingBytes)", missingBytes) - } - - /* Test HC compression with missing bytes into output buffer => must fail */ - FUZ_DISPLAYTEST; - { int missingBytes = (FUZ_rand(&randState) % 0x3F) + 1; - if (missingBytes >= HCcompressedSize) missingBytes = HCcompressedSize-1; - missingBytes += !missingBytes; /* avoid special case missingBytes==0 */ - compressedBuffer[HCcompressedSize-missingBytes] = 0; - ret = LZ4_compress_HC(block, compressedBuffer, blockSize, HCcompressedSize-missingBytes, compressionLevel); - FUZ_CHECKTEST(ret, "LZ4_compress_HC should have failed (output buffer too small by %i byte)", missingBytes); - FUZ_CHECKTEST(compressedBuffer[HCcompressedSize-missingBytes], "LZ4_compress_HC overran output buffer ! (%i missingBytes)", missingBytes) - } - - - /*-******************/ - /* Dictionary tests */ - /*-******************/ - - /* Compress using dictionary */ - FUZ_DISPLAYTEST; - { LZ4_stream_t LZ4_stream; - LZ4_resetStream(&LZ4_stream); - LZ4_compress_fast_continue (&LZ4_stream, dict, compressedBuffer, dictSize, (int)compressedBufferSize, 1); /* Just to fill hash tables */ - blockContinueCompressedSize = LZ4_compress_fast_continue (&LZ4_stream, block, compressedBuffer, blockSize, (int)compressedBufferSize, 1); - FUZ_CHECKTEST(blockContinueCompressedSize==0, "LZ4_compress_fast_continue failed"); - } - - /* Decompress with dictionary as prefix */ - FUZ_DISPLAYTEST; - memcpy(decodedBuffer, dict, dictSize); - ret = LZ4_decompress_fast_usingDict(compressedBuffer, decodedBuffer+dictSize, blockSize, decodedBuffer, dictSize); - FUZ_CHECKTEST(ret!=blockContinueCompressedSize, "LZ4_decompress_fast_usingDict did not read all compressed block input"); - crcCheck = XXH32(decodedBuffer+dictSize, blockSize, 0); - if (crcCheck!=crcOrig) { - int i=0; - while (block[i]==decodedBuffer[i]) i++; - printf("Wrong Byte at position %i/%i\n", i, blockSize); - - } - FUZ_CHECKTEST(crcCheck!=crcOrig, "LZ4_decompress_fast_usingDict corrupted decoded data (dict %i)", dictSize); - - FUZ_DISPLAYTEST; - ret = LZ4_decompress_safe_usingDict(compressedBuffer, decodedBuffer+dictSize, blockContinueCompressedSize, blockSize, decodedBuffer, dictSize); - FUZ_CHECKTEST(ret!=blockSize, "LZ4_decompress_safe_usingDict did not regenerate original data"); - crcCheck = XXH32(decodedBuffer+dictSize, blockSize, 0); - FUZ_CHECKTEST(crcCheck!=crcOrig, "LZ4_decompress_safe_usingDict corrupted decoded data"); - - /* Compress using External dictionary */ - FUZ_DISPLAYTEST; - dict -= (FUZ_rand(&randState) & 0xF) + 1; /* Separation, so it is an ExtDict */ - if (dict < (char*)CNBuffer) dict = (char*)CNBuffer; - LZ4_loadDict(&LZ4dict, dict, dictSize); - blockContinueCompressedSize = LZ4_compress_fast_continue(&LZ4dict, block, compressedBuffer, blockSize, (int)compressedBufferSize, 1); - FUZ_CHECKTEST(blockContinueCompressedSize==0, "LZ4_compress_fast_continue failed"); - - FUZ_DISPLAYTEST; - LZ4_loadDict(&LZ4dict, dict, dictSize); - ret = LZ4_compress_fast_continue(&LZ4dict, block, compressedBuffer, blockSize, blockContinueCompressedSize-1, 1); - FUZ_CHECKTEST(ret>0, "LZ4_compress_fast_continue using ExtDict should fail : one missing byte for output buffer : %i written, %i buffer", ret, blockContinueCompressedSize); - - FUZ_DISPLAYTEST; - LZ4_loadDict(&LZ4dict, dict, dictSize); - ret = LZ4_compress_fast_continue(&LZ4dict, block, compressedBuffer, blockSize, blockContinueCompressedSize, 1); - FUZ_CHECKTEST(ret!=blockContinueCompressedSize, "LZ4_compress_limitedOutput_compressed size is different (%i != %i)", ret, blockContinueCompressedSize); - FUZ_CHECKTEST(ret<=0, "LZ4_compress_fast_continue should work : enough size available within output buffer"); - - /* Decompress with dictionary as external */ - FUZ_DISPLAYTEST; - decodedBuffer[blockSize] = 0; - ret = LZ4_decompress_fast_usingDict(compressedBuffer, decodedBuffer, blockSize, dict, dictSize); - FUZ_CHECKTEST(ret!=blockContinueCompressedSize, "LZ4_decompress_fast_usingDict did not read all compressed block input"); - FUZ_CHECKTEST(decodedBuffer[blockSize], "LZ4_decompress_fast_usingDict overrun specified output buffer size"); - crcCheck = XXH32(decodedBuffer, blockSize, 0); - if (crcCheck!=crcOrig) FUZ_findDiff(block, decodedBuffer); - FUZ_CHECKTEST(crcCheck!=crcOrig, "LZ4_decompress_fast_usingDict corrupted decoded data (dict %i)", dictSize); - - FUZ_DISPLAYTEST; - decodedBuffer[blockSize] = 0; - ret = LZ4_decompress_safe_usingDict(compressedBuffer, decodedBuffer, blockContinueCompressedSize, blockSize, dict, dictSize); - FUZ_CHECKTEST(ret!=blockSize, "LZ4_decompress_safe_usingDict did not regenerate original data"); - FUZ_CHECKTEST(decodedBuffer[blockSize], "LZ4_decompress_safe_usingDict overrun specified output buffer size"); - crcCheck = XXH32(decodedBuffer, blockSize, 0); - FUZ_CHECKTEST(crcCheck!=crcOrig, "LZ4_decompress_safe_usingDict corrupted decoded data"); - - FUZ_DISPLAYTEST; - decodedBuffer[blockSize-1] = 0; - ret = LZ4_decompress_fast_usingDict(compressedBuffer, decodedBuffer, blockSize-1, dict, dictSize); - FUZ_CHECKTEST(ret>=0, "LZ4_decompress_fast_usingDict should have failed : wrong original size (-1 byte)"); - FUZ_CHECKTEST(decodedBuffer[blockSize-1], "LZ4_decompress_fast_usingDict overrun specified output buffer size"); - - FUZ_DISPLAYTEST; - decodedBuffer[blockSize-1] = 0; - ret = LZ4_decompress_safe_usingDict(compressedBuffer, decodedBuffer, blockContinueCompressedSize, blockSize-1, dict, dictSize); - FUZ_CHECKTEST(ret>=0, "LZ4_decompress_safe_usingDict should have failed : not enough output size (-1 byte)"); - FUZ_CHECKTEST(decodedBuffer[blockSize-1], "LZ4_decompress_safe_usingDict overrun specified output buffer size"); - - FUZ_DISPLAYTEST; - { U32 const missingBytes = (FUZ_rand(&randState) & 0xF) + 2; - if ((U32)blockSize > missingBytes) { - decodedBuffer[blockSize-missingBytes] = 0; - ret = LZ4_decompress_safe_usingDict(compressedBuffer, decodedBuffer, blockContinueCompressedSize, blockSize-missingBytes, dict, dictSize); - FUZ_CHECKTEST(ret>=0, "LZ4_decompress_safe_usingDict should have failed : output buffer too small (-%u byte)", missingBytes); - FUZ_CHECKTEST(decodedBuffer[blockSize-missingBytes], "LZ4_decompress_safe_usingDict overrun specified output buffer size (-%u byte) (blockSize=%i)", missingBytes, blockSize); - } } - - /* Compress HC using External dictionary */ - FUZ_DISPLAYTEST; - dict -= (FUZ_rand(&randState) & 7); /* even bigger separation */ - if (dict < (char*)CNBuffer) dict = (char*)CNBuffer; - LZ4_resetStreamHC (&LZ4dictHC, compressionLevel); - LZ4_loadDictHC(&LZ4dictHC, dict, dictSize); - blockContinueCompressedSize = LZ4_compress_HC_continue(&LZ4dictHC, block, compressedBuffer, blockSize, (int)compressedBufferSize); - FUZ_CHECKTEST(blockContinueCompressedSize==0, "LZ4_compress_HC_continue failed"); - - FUZ_DISPLAYTEST; - LZ4_loadDictHC(&LZ4dictHC, dict, dictSize); - ret = LZ4_compress_HC_continue(&LZ4dictHC, block, compressedBuffer, blockSize, blockContinueCompressedSize-1); - FUZ_CHECKTEST(ret>0, "LZ4_compress_HC_continue using ExtDict should fail : one missing byte for output buffer (%i != %i)", ret, blockContinueCompressedSize); - - FUZ_DISPLAYTEST; - LZ4_loadDictHC(&LZ4dictHC, dict, dictSize); - ret = LZ4_compress_HC_continue(&LZ4dictHC, block, compressedBuffer, blockSize, blockContinueCompressedSize); - FUZ_CHECKTEST(ret!=blockContinueCompressedSize, "LZ4_compress_HC_continue size is different (%i != %i)", ret, blockContinueCompressedSize); - FUZ_CHECKTEST(ret<=0, "LZ4_compress_HC_continue should work : enough size available within output buffer"); - - FUZ_DISPLAYTEST; - decodedBuffer[blockSize] = 0; - ret = LZ4_decompress_safe_usingDict(compressedBuffer, decodedBuffer, blockContinueCompressedSize, blockSize, dict, dictSize); - FUZ_CHECKTEST(ret!=blockSize, "LZ4_decompress_safe_usingDict did not regenerate original data"); - FUZ_CHECKTEST(decodedBuffer[blockSize], "LZ4_decompress_safe_usingDict overrun specified output buffer size"); - crcCheck = XXH32(decodedBuffer, blockSize, 0); - if (crcCheck!=crcOrig) - FUZ_findDiff(block, decodedBuffer); - FUZ_CHECKTEST(crcCheck!=crcOrig, "LZ4_decompress_safe_usingDict corrupted decoded data"); - - /* Compress HC continue destSize */ - FUZ_DISPLAYTEST; - { int const availableSpace = (FUZ_rand(&randState) % blockSize) + 5; - int consumedSize = blockSize; - FUZ_DISPLAYTEST; - LZ4_resetStreamHC (&LZ4dictHC, compressionLevel); - LZ4_loadDictHC(&LZ4dictHC, dict, dictSize); - blockContinueCompressedSize = LZ4_compress_HC_continue_destSize(&LZ4dictHC, block, compressedBuffer, &consumedSize, availableSpace); - DISPLAYLEVEL(5, " LZ4_compress_HC_continue_destSize : compressed %6i/%6i into %6i/%6i at cLevel=%i\n", consumedSize, blockSize, blockContinueCompressedSize, availableSpace, compressionLevel); - FUZ_CHECKTEST(blockContinueCompressedSize==0, "LZ4_compress_HC_continue_destSize failed"); - FUZ_CHECKTEST(blockContinueCompressedSize > availableSpace, "LZ4_compress_HC_continue_destSize write overflow"); - FUZ_CHECKTEST(consumedSize > blockSize, "LZ4_compress_HC_continue_destSize read overflow"); - - FUZ_DISPLAYTEST; - decodedBuffer[consumedSize] = 0; - ret = LZ4_decompress_safe_usingDict(compressedBuffer, decodedBuffer, blockContinueCompressedSize, consumedSize, dict, dictSize); - FUZ_CHECKTEST(ret!=consumedSize, "LZ4_decompress_safe_usingDict did not regenerate original data"); - FUZ_CHECKTEST(decodedBuffer[consumedSize], "LZ4_decompress_safe_usingDict overrun specified output buffer size") - { U32 const crcSrc = XXH32(block, consumedSize, 0); - U32 const crcDst = XXH32(decodedBuffer, consumedSize, 0); - if (crcSrc!=crcDst) - FUZ_findDiff(block, decodedBuffer); - FUZ_CHECKTEST(crcSrc!=crcDst, "LZ4_decompress_safe_usingDict corrupted decoded data"); - } - } - - /* ***** End of tests *** */ - /* Fill stats */ - bytes += blockSize; - cbytes += compressedSize; - hcbytes += HCcompressedSize; - ccbytes += blockContinueCompressedSize; - } - - if (nbCycles<=1) nbCycles = cycleNb; /* end by time */ - bytes += !bytes; /* avoid division by 0 */ - printf("\r%7u /%7u - ", cycleNb, nbCycles); - printf("all tests completed successfully \n"); - printf("compression ratio: %0.3f%%\n", (double)cbytes/bytes*100); - printf("HC compression ratio: %0.3f%%\n", (double)hcbytes/bytes*100); - printf("ratio with dict: %0.3f%%\n", (double)ccbytes/bytes*100); - - /* release memory */ - { -_exit: - free(CNBuffer); - free(compressedBuffer); - free(decodedBuffer); - free(stateLZ4); - free(stateLZ4HC); - return result; - -_output_error: - result = 1; - goto _exit; - } -} - - -#define testInputSize (192 KB) -#define testCompressedSize (128 KB) -#define ringBufferSize (8 KB) - -static void FUZ_unitTests(int compressionLevel) -{ - const unsigned testNb = 0; - const unsigned seed = 0; - const unsigned cycleNb= 0; - char testInput[testInputSize]; - char testCompressed[testCompressedSize]; - char testVerify[testInputSize]; - char ringBuffer[ringBufferSize]; - U32 randState = 1; - - /* Init */ - FUZ_fillCompressibleNoiseBuffer(testInput, testInputSize, 0.50, &randState); - - /* 32-bits address space overflow test */ - FUZ_AddressOverflow(); - - /* LZ4 streaming tests */ - { LZ4_stream_t* statePtr; - LZ4_stream_t streamingState; - U64 crcOrig; - int result; - - /* Allocation test */ - statePtr = LZ4_createStream(); - FUZ_CHECKTEST(statePtr==NULL, "LZ4_createStream() allocation failed"); - LZ4_freeStream(statePtr); - - /* simple compression test */ - crcOrig = XXH64(testInput, testCompressedSize, 0); - LZ4_resetStream(&streamingState); - result = LZ4_compress_fast_continue(&streamingState, testInput, testCompressed, testCompressedSize, testCompressedSize-1, 1); - FUZ_CHECKTEST(result==0, "LZ4_compress_fast_continue() compression failed!"); - - result = LZ4_decompress_safe(testCompressed, testVerify, result, testCompressedSize); - FUZ_CHECKTEST(result!=(int)testCompressedSize, "LZ4_decompress_safe() decompression failed"); - { U64 const crcNew = XXH64(testVerify, testCompressedSize, 0); - FUZ_CHECKTEST(crcOrig!=crcNew, "LZ4_decompress_safe() decompression corruption"); } - - /* ring buffer test */ - { XXH64_state_t xxhOrig; - XXH64_state_t xxhNew; - LZ4_streamDecode_t decodeState; - const U32 maxMessageSizeLog = 10; - const U32 maxMessageSizeMask = (1< ringBufferSize) rNext = 0; - if (dNext + messageSize > dBufferSize) dNext = 0; - } - } - } - - /* LZ4 HC streaming tests */ - { LZ4_streamHC_t* sp; - LZ4_streamHC_t sHC; - U64 crcOrig; - int result; - - /* Allocation test */ - sp = LZ4_createStreamHC(); - FUZ_CHECKTEST(sp==NULL, "LZ4_createStreamHC() allocation failed"); - LZ4_freeStreamHC(sp); - - /* simple HC compression test */ - crcOrig = XXH64(testInput, testCompressedSize, 0); - LZ4_resetStreamHC(&sHC, compressionLevel); - result = LZ4_compress_HC_continue(&sHC, testInput, testCompressed, testCompressedSize, testCompressedSize-1); - FUZ_CHECKTEST(result==0, "LZ4_compressHC_limitedOutput_continue() compression failed"); - - result = LZ4_decompress_safe(testCompressed, testVerify, result, testCompressedSize); - FUZ_CHECKTEST(result!=(int)testCompressedSize, "LZ4_decompress_safe() decompression failed"); - { U64 const crcNew = XXH64(testVerify, testCompressedSize, 0); - FUZ_CHECKTEST(crcOrig!=crcNew, "LZ4_decompress_safe() decompression corruption"); } - - /* simple dictionary HC compression test */ - crcOrig = XXH64(testInput + 64 KB, testCompressedSize, 0); - LZ4_resetStreamHC(&sHC, compressionLevel); - LZ4_loadDictHC(&sHC, testInput, 64 KB); - result = LZ4_compress_HC_continue(&sHC, testInput + 64 KB, testCompressed, testCompressedSize, testCompressedSize-1); - FUZ_CHECKTEST(result==0, "LZ4_compressHC_limitedOutput_continue() dictionary compression failed : result = %i", result); - - result = LZ4_decompress_safe_usingDict(testCompressed, testVerify, result, testCompressedSize, testInput, 64 KB); - FUZ_CHECKTEST(result!=(int)testCompressedSize, "LZ4_decompress_safe() simple dictionary decompression test failed"); - { U64 const crcNew = XXH64(testVerify, testCompressedSize, 0); - FUZ_CHECKTEST(crcOrig!=crcNew, "LZ4_decompress_safe() simple dictionary decompression test : corruption"); } - - /* multiple HC compression test with dictionary */ - { int result1, result2; - int segSize = testCompressedSize / 2; - crcOrig = XXH64(testInput + segSize, testCompressedSize, 0); - LZ4_resetStreamHC(&sHC, compressionLevel); - LZ4_loadDictHC(&sHC, testInput, segSize); - result1 = LZ4_compress_HC_continue(&sHC, testInput + segSize, testCompressed, segSize, segSize -1); - FUZ_CHECKTEST(result1==0, "LZ4_compressHC_limitedOutput_continue() dictionary compression failed : result = %i", result1); - result2 = LZ4_compress_HC_continue(&sHC, testInput + 2*segSize, testCompressed+result1, segSize, segSize-1); - FUZ_CHECKTEST(result2==0, "LZ4_compressHC_limitedOutput_continue() dictionary compression failed : result = %i", result2); - - result = LZ4_decompress_safe_usingDict(testCompressed, testVerify, result1, segSize, testInput, segSize); - FUZ_CHECKTEST(result!=segSize, "LZ4_decompress_safe() dictionary decompression part 1 failed"); - result = LZ4_decompress_safe_usingDict(testCompressed+result1, testVerify+segSize, result2, segSize, testInput, 2*segSize); - FUZ_CHECKTEST(result!=segSize, "LZ4_decompress_safe() dictionary decompression part 2 failed"); - { U64 const crcNew = XXH64(testVerify, testCompressedSize, 0); - FUZ_CHECKTEST(crcOrig!=crcNew, "LZ4_decompress_safe() dictionary decompression corruption"); } - } - - /* remote dictionary HC compression test */ - crcOrig = XXH64(testInput + 64 KB, testCompressedSize, 0); - LZ4_resetStreamHC(&sHC, compressionLevel); - LZ4_loadDictHC(&sHC, testInput, 32 KB); - result = LZ4_compress_HC_continue(&sHC, testInput + 64 KB, testCompressed, testCompressedSize, testCompressedSize-1); - FUZ_CHECKTEST(result==0, "LZ4_compressHC_limitedOutput_continue() remote dictionary failed : result = %i", result); - - result = LZ4_decompress_safe_usingDict(testCompressed, testVerify, result, testCompressedSize, testInput, 32 KB); - FUZ_CHECKTEST(result!=(int)testCompressedSize, "LZ4_decompress_safe_usingDict() decompression failed following remote dictionary HC compression test"); - { U64 const crcNew = XXH64(testVerify, testCompressedSize, 0); - FUZ_CHECKTEST(crcOrig!=crcNew, "LZ4_decompress_safe_usingDict() decompression corruption"); } - - /* multiple HC compression with ext. dictionary */ - { XXH64_state_t crcOrigState; - XXH64_state_t crcNewState; - const char* dict = testInput + 3; - int dictSize = (FUZ_rand(&randState) & 8191); - char* dst = testVerify; - - size_t segStart = dictSize + 7; - int segSize = (FUZ_rand(&randState) & 8191); - int segNb = 1; - - LZ4_resetStreamHC(&sHC, compressionLevel); - LZ4_loadDictHC(&sHC, dict, dictSize); - - XXH64_reset(&crcOrigState, 0); - XXH64_reset(&crcNewState, 0); - - while (segStart + segSize < testInputSize) { - XXH64_update(&crcOrigState, testInput + segStart, segSize); - crcOrig = XXH64_digest(&crcOrigState); - result = LZ4_compress_HC_continue(&sHC, testInput + segStart, testCompressed, segSize, LZ4_compressBound(segSize)); - FUZ_CHECKTEST(result==0, "LZ4_compressHC_limitedOutput_continue() dictionary compression failed : result = %i", result); - - result = LZ4_decompress_safe_usingDict(testCompressed, dst, result, segSize, dict, dictSize); - FUZ_CHECKTEST(result!=segSize, "LZ4_decompress_safe_usingDict() dictionary decompression part %i failed", segNb); - XXH64_update(&crcNewState, dst, segSize); - { U64 const crcNew = XXH64_digest(&crcNewState); - if (crcOrig != crcNew) FUZ_findDiff(dst, testInput+segStart); - FUZ_CHECKTEST(crcOrig!=crcNew, "LZ4_decompress_safe_usingDict() part %i corruption", segNb); - } - - dict = dst; - //dict = testInput + segStart; - dictSize = segSize; - - dst += segSize + 1; - segNb ++; - - segStart += segSize + (FUZ_rand(&randState) & 0xF) + 1; - segSize = (FUZ_rand(&randState) & 8191); - } - } - - /* ring buffer test */ - { XXH64_state_t xxhOrig; - XXH64_state_t xxhNew; - LZ4_streamDecode_t decodeState; - const U32 maxMessageSizeLog = 10; - const U32 maxMessageSizeMask = (1< ringBufferSize) rNext = 0; - if (dNext + messageSize > dBufferSize) dNext = 0; - } - } - - /* small decoder-side ring buffer test */ - { XXH64_state_t xxhOrig; - XXH64_state_t xxhNew; - LZ4_streamDecode_t decodeState; - const U32 maxMessageSizeLog = 12; - const U32 maxMessageSizeMask = (1< dBufferSize) dNext = 0; - - while (totalMessageSize < 9 MB) { - XXH64_update(&xxhOrig, testInput + iNext, messageSize); - crcOrig = XXH64_digest(&xxhOrig); - - result = LZ4_compress_HC_continue(&sHC, testInput + iNext, testCompressed, messageSize, testCompressedSize-ringBufferSize); - FUZ_CHECKTEST(result==0, "LZ4_compressHC_limitedOutput_continue() compression failed"); - - result = LZ4_decompress_safe_continue(&decodeState, testCompressed, testVerify + dNext, result, messageSize); - FUZ_CHECKTEST(result!=(int)messageSize, "64K D.ringBuffer : LZ4_decompress_safe() test failed"); - - XXH64_update(&xxhNew, testVerify + dNext, messageSize); - { U64 const crcNew = XXH64_digest(&xxhNew); - if (crcOrig != crcNew) FUZ_findDiff(testInput + iNext, testVerify + dNext); - FUZ_CHECKTEST(crcOrig!=crcNew, "LZ4_decompress_safe() decompression corruption during small decoder-side ring buffer test"); - } - /* prepare next message */ - dNext += messageSize; - totalMessageSize += messageSize; - messageSize = (FUZ_rand(&randState) & maxMessageSizeMask) + 1; - iNext = (FUZ_rand(&randState) & 65535); - if (dNext > dBufferSize) dNext = 0; - } - } - } - - printf("All unit tests completed successfully compressionLevel=%d \n", compressionLevel); - return; -_output_error: - exit(1); -} - - -static int FUZ_usage(const char* programName) -{ - DISPLAY( "Usage :\n"); - DISPLAY( " %s [args]\n", programName); - DISPLAY( "\n"); - DISPLAY( "Arguments :\n"); - DISPLAY( " -i# : Nb of tests (default:%i) \n", NB_ATTEMPTS); - DISPLAY( " -T# : Duration of tests, in seconds (default: use Nb of tests) \n"); - DISPLAY( " -s# : Select seed (default:prompt user)\n"); - DISPLAY( " -t# : Select starting test number (default:0)\n"); - DISPLAY( " -P# : Select compressibility in %% (default:%i%%)\n", FUZ_COMPRESSIBILITY_DEFAULT); - DISPLAY( " -v : verbose\n"); - DISPLAY( " -p : pause at the end\n"); - DISPLAY( " -h : display help and exit\n"); - return 0; -} - - -int main(int argc, const char** argv) -{ - U32 seed = 0; - int seedset = 0; - int argNb; - int nbTests = NB_ATTEMPTS; - int testNb = 0; - int proba = FUZ_COMPRESSIBILITY_DEFAULT; - int use_pause = 0; - const char* programName = argv[0]; - U32 duration = 0; - - /* Check command line */ - for(argNb=1; argNb='0') && (*argument<='9')) { - nbTests *= 10; - nbTests += *argument - '0'; - argument++; - } - break; - - case 'T': - argument++; - nbTests = 0; duration = 0; - for (;;) { - switch(*argument) - { - case 'm': duration *= 60; argument++; continue; - case 's': - case 'n': argument++; continue; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': duration *= 10; duration += *argument++ - '0'; continue; - } - break; - } - break; - - case 's': - argument++; - seed=0; seedset=1; - while ((*argument>='0') && (*argument<='9')) { - seed *= 10; - seed += *argument - '0'; - argument++; - } - break; - - case 't': /* select starting test nb */ - argument++; - testNb=0; - while ((*argument>='0') && (*argument<='9')) { - testNb *= 10; - testNb += *argument - '0'; - argument++; - } - break; - - case 'P': /* change probability */ - argument++; - proba=0; - while ((*argument>='0') && (*argument<='9')) { - proba *= 10; - proba += *argument - '0'; - argument++; - } - if (proba<0) proba=0; - if (proba>100) proba=100; - break; - default: ; - } - } - } - } - - printf("Starting LZ4 fuzzer (%i-bits, v%s)\n", (int)(sizeof(size_t)*8), LZ4_versionString()); - - if (!seedset) { - time_t const t = time(NULL); - U32 const h = XXH32(&t, sizeof(t), 1); - seed = h % 10000; - } - printf("Seed = %u\n", seed); - - if (proba!=FUZ_COMPRESSIBILITY_DEFAULT) printf("Compressibility : %i%%\n", proba); - - if ((seedset==0) && (testNb==0)) { FUZ_unitTests(LZ4HC_CLEVEL_DEFAULT); FUZ_unitTests(LZ4HC_CLEVEL_OPT_MIN); } - - if (nbTests<=0) nbTests=1; - - { int const result = FUZ_test(seed, nbTests, testNb, ((double)proba) / 100, duration); - if (use_pause) { - DISPLAY("press enter ... \n"); - (void)getchar(); - } - return result; - } -} diff --git a/src/lz4/tests/test-lz4-speed.py b/src/lz4/tests/test-lz4-speed.py deleted file mode 100644 index ca8f0101e1..0000000000 --- a/src/lz4/tests/test-lz4-speed.py +++ /dev/null @@ -1,351 +0,0 @@ -#! /usr/bin/env python3 - -# -# Copyright (c) 2016-present, Przemyslaw Skibinski, Yann Collet, Facebook, Inc. -# All rights reserved. -# -# This source code is licensed under the BSD-style license found in the -# LICENSE file in the root directory of this source tree. An additional grant -# of patent rights can be found in the PATENTS file in the same directory. -# - -# Limitations: -# - doesn't support filenames with spaces -# - dir1/lz4 and dir2/lz4 will be merged in a single results file - -import argparse -import os -import string -import subprocess -import time -import traceback -import hashlib - -script_version = 'v1.7.2 (2016-11-08)' -default_repo_url = 'https://github.com/lz4/lz4.git' -working_dir_name = 'speedTest' -working_path = os.getcwd() + '/' + working_dir_name # /path/to/lz4/tests/speedTest -clone_path = working_path + '/' + 'lz4' # /path/to/lz4/tests/speedTest/lz4 -email_header = 'lz4_speedTest' -pid = str(os.getpid()) -verbose = False -clang_version = "unknown" -gcc_version = "unknown" -args = None - - -def hashfile(hasher, fname, blocksize=65536): - with open(fname, "rb") as f: - for chunk in iter(lambda: f.read(blocksize), b""): - hasher.update(chunk) - return hasher.hexdigest() - - -def log(text): - print(time.strftime("%Y/%m/%d %H:%M:%S") + ' - ' + text) - - -def execute(command, print_command=True, print_output=False, print_error=True, param_shell=True): - if print_command: - log("> " + command) - popen = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=param_shell, cwd=execute.cwd) - stdout_lines, stderr_lines = popen.communicate(timeout=args.timeout) - stderr_lines = stderr_lines.decode("utf-8") - stdout_lines = stdout_lines.decode("utf-8") - if print_output: - if stdout_lines: - print(stdout_lines) - if stderr_lines: - print(stderr_lines) - if popen.returncode is not None and popen.returncode != 0: - if stderr_lines and not print_output and print_error: - print(stderr_lines) - raise RuntimeError(stdout_lines + stderr_lines) - return (stdout_lines + stderr_lines).splitlines() -execute.cwd = None - - -def does_command_exist(command): - try: - execute(command, verbose, False, False) - except Exception: - return False - return True - - -def send_email(emails, topic, text, have_mutt, have_mail): - logFileName = working_path + '/' + 'tmpEmailContent' - with open(logFileName, "w") as myfile: - myfile.writelines(text) - myfile.close() - if have_mutt: - execute('mutt -s "' + topic + '" ' + emails + ' < ' + logFileName, verbose) - elif have_mail: - execute('mail -s "' + topic + '" ' + emails + ' < ' + logFileName, verbose) - else: - log("e-mail cannot be sent (mail or mutt not found)") - - -def send_email_with_attachments(branch, commit, last_commit, args, text, results_files, - logFileName, have_mutt, have_mail): - with open(logFileName, "w") as myfile: - myfile.writelines(text) - myfile.close() - email_topic = '[%s:%s] Warning for %s:%s last_commit=%s speed<%s ratio<%s' \ - % (email_header, pid, branch, commit, last_commit, - args.lowerLimit, args.ratioLimit) - if have_mutt: - execute('mutt -s "' + email_topic + '" ' + args.emails + ' -a ' + results_files - + ' < ' + logFileName) - elif have_mail: - execute('mail -s "' + email_topic + '" ' + args.emails + ' < ' + logFileName) - else: - log("e-mail cannot be sent (mail or mutt not found)") - - -def git_get_branches(): - execute('git fetch -p', verbose) - branches = execute('git branch -rl', verbose) - output = [] - for line in branches: - if ("HEAD" not in line) and ("coverity_scan" not in line) and ("gh-pages" not in line): - output.append(line.strip()) - return output - - -def git_get_changes(branch, commit, last_commit): - fmt = '--format="%h: (%an) %s, %ar"' - if last_commit is None: - commits = execute('git log -n 10 %s %s' % (fmt, commit)) - else: - commits = execute('git --no-pager log %s %s..%s' % (fmt, last_commit, commit)) - return str('Changes in %s since %s:\n' % (branch, last_commit)) + '\n'.join(commits) - - -def get_last_results(resultsFileName): - if not os.path.isfile(resultsFileName): - return None, None, None, None - commit = None - csize = [] - cspeed = [] - dspeed = [] - with open(resultsFileName, 'r') as f: - for line in f: - words = line.split() - if len(words) <= 4: # branch + commit + compilerVer + md5 - commit = words[1] - csize = [] - cspeed = [] - dspeed = [] - if (len(words) == 8) or (len(words) == 9): # results: "filename" or "XX files" - csize.append(int(words[1])) - cspeed.append(float(words[3])) - dspeed.append(float(words[5])) - return commit, csize, cspeed, dspeed - - -def benchmark_and_compare(branch, commit, last_commit, args, executableName, md5sum, compilerVersion, resultsFileName, - testFilePath, fileName, last_csize, last_cspeed, last_dspeed): - sleepTime = 30 - while os.getloadavg()[0] > args.maxLoadAvg: - log("WARNING: bench loadavg=%.2f is higher than %s, sleeping for %s seconds" - % (os.getloadavg()[0], args.maxLoadAvg, sleepTime)) - time.sleep(sleepTime) - start_load = str(os.getloadavg()) - result = execute('programs/%s -rqi5b1e%s %s' % (executableName, args.lastCLevel, testFilePath), print_output=True) - end_load = str(os.getloadavg()) - linesExpected = args.lastCLevel + 1 - if len(result) != linesExpected: - raise RuntimeError("ERROR: number of result lines=%d is different that expected %d\n%s" % (len(result), linesExpected, '\n'.join(result))) - with open(resultsFileName, "a") as myfile: - myfile.write('%s %s %s md5=%s\n' % (branch, commit, compilerVersion, md5sum)) - myfile.write('\n'.join(result) + '\n') - myfile.close() - if (last_cspeed == None): - log("WARNING: No data for comparison for branch=%s file=%s " % (branch, fileName)) - return "" - commit, csize, cspeed, dspeed = get_last_results(resultsFileName) - text = "" - for i in range(0, min(len(cspeed), len(last_cspeed))): - print("%s:%s -%d cSpeed=%6.2f cLast=%6.2f cDiff=%1.4f dSpeed=%6.2f dLast=%6.2f dDiff=%1.4f ratioDiff=%1.4f %s" % (branch, commit, i+1, cspeed[i], last_cspeed[i], cspeed[i]/last_cspeed[i], dspeed[i], last_dspeed[i], dspeed[i]/last_dspeed[i], float(last_csize[i])/csize[i], fileName)) - if (cspeed[i]/last_cspeed[i] < args.lowerLimit): - text += "WARNING: %s -%d cSpeed=%.2f cLast=%.2f cDiff=%.4f %s\n" % (executableName, i+1, cspeed[i], last_cspeed[i], cspeed[i]/last_cspeed[i], fileName) - if (dspeed[i]/last_dspeed[i] < args.lowerLimit): - text += "WARNING: %s -%d dSpeed=%.2f dLast=%.2f dDiff=%.4f %s\n" % (executableName, i+1, dspeed[i], last_dspeed[i], dspeed[i]/last_dspeed[i], fileName) - if (float(last_csize[i])/csize[i] < args.ratioLimit): - text += "WARNING: %s -%d cSize=%d last_cSize=%d diff=%.4f %s\n" % (executableName, i+1, csize[i], last_csize[i], float(last_csize[i])/csize[i], fileName) - if text: - text = args.message + ("\nmaxLoadAvg=%s load average at start=%s end=%s\n%s last_commit=%s md5=%s\n" % (args.maxLoadAvg, start_load, end_load, compilerVersion, last_commit, md5sum)) + text - return text - - -def update_config_file(branch, commit): - last_commit = None - commitFileName = working_path + "/commit_" + branch.replace("/", "_") + ".txt" - if os.path.isfile(commitFileName): - with open(commitFileName, 'r') as infile: - last_commit = infile.read() - with open(commitFileName, 'w') as outfile: - outfile.write(commit) - return last_commit - - -def double_check(branch, commit, args, executableName, md5sum, compilerVersion, resultsFileName, filePath, fileName): - last_commit, csize, cspeed, dspeed = get_last_results(resultsFileName) - if not args.dry_run: - text = benchmark_and_compare(branch, commit, last_commit, args, executableName, md5sum, compilerVersion, resultsFileName, filePath, fileName, csize, cspeed, dspeed) - if text: - log("WARNING: redoing tests for branch %s: commit %s" % (branch, commit)) - text = benchmark_and_compare(branch, commit, last_commit, args, executableName, md5sum, compilerVersion, resultsFileName, filePath, fileName, csize, cspeed, dspeed) - return text - - -def test_commit(branch, commit, last_commit, args, testFilePaths, have_mutt, have_mail): - local_branch = branch.split('/')[1] - version = local_branch.rpartition('-')[2] + '_' + commit - if not args.dry_run: - execute('make -C programs clean lz4 CC=clang MOREFLAGS="-Werror -Wconversion -Wno-sign-conversion -DLZ4_GIT_COMMIT=%s" && ' % version + - 'mv programs/lz4 programs/lz4_clang && ' + - 'make -C programs clean lz4 lz4c32 MOREFLAGS="-DLZ4_GIT_COMMIT=%s"' % version) - md5_lz4 = hashfile(hashlib.md5(), clone_path + '/programs/lz4') - md5_lz4c32 = hashfile(hashlib.md5(), clone_path + '/programs/lz4c32') - md5_lz4_clang = hashfile(hashlib.md5(), clone_path + '/programs/lz4_clang') - print("md5(lz4)=%s\nmd5(lz4c32)=%s\nmd5(lz4_clang)=%s" % (md5_lz4, md5_lz4c32, md5_lz4_clang)) - print("gcc_version=%s clang_version=%s" % (gcc_version, clang_version)) - - logFileName = working_path + "/log_" + branch.replace("/", "_") + ".txt" - text_to_send = [] - results_files = "" - - for filePath in testFilePaths: - fileName = filePath.rpartition('/')[2] - resultsFileName = working_path + "/results_" + branch.replace("/", "_") + "_" + fileName.replace(".", "_") + ".txt" - text = double_check(branch, commit, args, 'lz4', md5_lz4, 'gcc_version='+gcc_version, resultsFileName, filePath, fileName) - if text: - text_to_send.append(text) - results_files += resultsFileName + " " - resultsFileName = working_path + "/results32_" + branch.replace("/", "_") + "_" + fileName.replace(".", "_") + ".txt" - text = double_check(branch, commit, args, 'lz4c32', md5_lz4c32, 'gcc_version='+gcc_version, resultsFileName, filePath, fileName) - if text: - text_to_send.append(text) - results_files += resultsFileName + " " - resultsFileName = working_path + "/resultsClang_" + branch.replace("/", "_") + "_" + fileName.replace(".", "_") + ".txt" - text = double_check(branch, commit, args, 'lz4_clang', md5_lz4_clang, 'clang_version='+clang_version, resultsFileName, filePath, fileName) - if text: - text_to_send.append(text) - results_files += resultsFileName + " " - if text_to_send: - send_email_with_attachments(branch, commit, last_commit, args, text_to_send, results_files, logFileName, have_mutt, have_mail) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser() - parser.add_argument('testFileNames', help='file or directory names list for speed benchmark') - parser.add_argument('emails', help='list of e-mail addresses to send warnings') - parser.add_argument('--message', '-m', help='attach an additional message to e-mail', default="") - parser.add_argument('--repoURL', help='changes default repository URL', default=default_repo_url) - parser.add_argument('--lowerLimit', '-l', type=float, help='send email if speed is lower than given limit', default=0.98) - parser.add_argument('--ratioLimit', '-r', type=float, help='send email if ratio is lower than given limit', default=0.999) - parser.add_argument('--maxLoadAvg', type=float, help='maximum load average to start testing', default=0.75) - parser.add_argument('--lastCLevel', type=int, help='last compression level for testing', default=5) - parser.add_argument('--sleepTime', '-s', type=int, help='frequency of repository checking in seconds', default=300) - parser.add_argument('--timeout', '-t', type=int, help='timeout for executing shell commands', default=1800) - parser.add_argument('--dry-run', dest='dry_run', action='store_true', help='not build', default=False) - parser.add_argument('--verbose', '-v', action='store_true', help='more verbose logs', default=False) - args = parser.parse_args() - verbose = args.verbose - - # check if test files are accessible - testFileNames = args.testFileNames.split() - testFilePaths = [] - for fileName in testFileNames: - fileName = os.path.expanduser(fileName) - if os.path.isfile(fileName) or os.path.isdir(fileName): - testFilePaths.append(os.path.abspath(fileName)) - else: - log("ERROR: File/directory not found: " + fileName) - exit(1) - - # check availability of e-mail senders - have_mutt = does_command_exist("mutt -h") - have_mail = does_command_exist("mail -V") - if not have_mutt and not have_mail: - log("ERROR: e-mail senders 'mail' or 'mutt' not found") - exit(1) - - clang_version = execute("clang -v 2>&1 | grep 'clang version' | sed -e 's:.*version \\([0-9.]*\\).*:\\1:' -e 's:\\.\\([0-9][0-9]\\):\\1:g'", verbose)[0]; - gcc_version = execute("gcc -dumpversion", verbose)[0]; - - if verbose: - print("PARAMETERS:\nrepoURL=%s" % args.repoURL) - print("working_path=%s" % working_path) - print("clone_path=%s" % clone_path) - print("testFilePath(%s)=%s" % (len(testFilePaths), testFilePaths)) - print("message=%s" % args.message) - print("emails=%s" % args.emails) - print("maxLoadAvg=%s" % args.maxLoadAvg) - print("lowerLimit=%s" % args.lowerLimit) - print("ratioLimit=%s" % args.ratioLimit) - print("lastCLevel=%s" % args.lastCLevel) - print("sleepTime=%s" % args.sleepTime) - print("timeout=%s" % args.timeout) - print("dry_run=%s" % args.dry_run) - print("verbose=%s" % args.verbose) - print("have_mutt=%s have_mail=%s" % (have_mutt, have_mail)) - - # clone lz4 repo if needed - if not os.path.isdir(working_path): - os.mkdir(working_path) - if not os.path.isdir(clone_path): - execute.cwd = working_path - execute('git clone ' + args.repoURL) - if not os.path.isdir(clone_path): - log("ERROR: lz4 clone not found: " + clone_path) - exit(1) - execute.cwd = clone_path - - # check if speedTest.pid already exists - pidfile = "./speedTest.pid" - if os.path.isfile(pidfile): - log("ERROR: %s already exists, exiting" % pidfile) - exit(1) - - send_email(args.emails, '[%s:%s] test-lz4-speed.py %s has been started' % (email_header, pid, script_version), args.message, have_mutt, have_mail) - with open(pidfile, 'w') as the_file: - the_file.write(pid) - - branch = "" - commit = "" - first_time = True - while True: - try: - if first_time: - first_time = False - else: - if verbose: - log("sleep for %s seconds" % args.sleepTime) - time.sleep(args.sleepTime) - loadavg = os.getloadavg()[0] - if (loadavg <= args.maxLoadAvg): - branches = git_get_branches() - for branch in branches: - commit = execute('git show -s --format=%h ' + branch, verbose)[0] - last_commit = update_config_file(branch, commit) - if commit == last_commit: - log("skipping branch %s: head %s already processed" % (branch, commit)) - else: - log("build branch %s: head %s is different from prev %s" % (branch, commit, last_commit)) - execute('git checkout -- . && git checkout ' + branch) - print(git_get_changes(branch, commit, last_commit)) - test_commit(branch, commit, last_commit, args, testFilePaths, have_mutt, have_mail) - else: - log("WARNING: main loadavg=%.2f is higher than %s" % (loadavg, args.maxLoadAvg)) - except Exception as e: - stack = traceback.format_exc() - email_topic = '[%s:%s] ERROR in %s:%s' % (email_header, pid, branch, commit) - send_email(args.emails, email_topic, stack, have_mutt, have_mail) - print(stack) - except KeyboardInterrupt: - os.unlink(pidfile) - send_email(args.emails, '[%s:%s] test-lz4-speed.py %s has been stopped' % (email_header, pid, script_version), args.message, have_mutt, have_mail) - exit(0) diff --git a/src/lz4/tests/test-lz4-versions.py b/src/lz4/tests/test-lz4-versions.py deleted file mode 100644 index d7fd199e64..0000000000 --- a/src/lz4/tests/test-lz4-versions.py +++ /dev/null @@ -1,156 +0,0 @@ -#!/usr/bin/env python3 -"""Test LZ4 interoperability between versions""" - -# -# Copyright (C) 2011-present, Takayuki Matsuoka -# All rights reserved. -# GPL v2 License -# - -import glob -import subprocess -import filecmp -import os -import shutil -import sys -import hashlib - -repo_url = 'https://github.com/lz4/lz4.git' -tmp_dir_name = 'tests/versionsTest' -make_cmd = 'make' -git_cmd = 'git' -test_dat_src = 'README.md' -test_dat = 'test_dat' -head = 'v999' - -def proc(cmd_args, pipe=True, dummy=False): - if dummy: - return - if pipe: - subproc = subprocess.Popen(cmd_args, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE) - else: - subproc = subprocess.Popen(cmd_args) - return subproc.communicate() - -def make(args, pipe=True): - return proc([make_cmd] + args, pipe) - -def git(args, pipe=True): - return proc([git_cmd] + args, pipe) - -def get_git_tags(): - stdout, stderr = git(['tag', '-l', 'r[0-9][0-9][0-9]']) - tags = stdout.decode('utf-8').split() - stdout, stderr = git(['tag', '-l', 'v[1-9].[0-9].[0-9]']) - tags += stdout.decode('utf-8').split() - return tags - -# https://stackoverflow.com/a/19711609/2132223 -def sha1_of_file(filepath): - with open(filepath, 'rb') as f: - return hashlib.sha1(f.read()).hexdigest() - -if __name__ == '__main__': - error_code = 0 - base_dir = os.getcwd() + '/..' # /path/to/lz4 - tmp_dir = base_dir + '/' + tmp_dir_name # /path/to/lz4/tests/versionsTest - clone_dir = tmp_dir + '/' + 'lz4' # /path/to/lz4/tests/versionsTest/lz4 - programs_dir = base_dir + '/programs' # /path/to/lz4/programs - os.makedirs(tmp_dir, exist_ok=True) - - # since Travis clones limited depth, we should clone full repository - if not os.path.isdir(clone_dir): - git(['clone', repo_url, clone_dir]) - - shutil.copy2(base_dir + '/' + test_dat_src, tmp_dir + '/' + test_dat) - - # Retrieve all release tags - print('Retrieve all release tags :') - os.chdir(clone_dir) - tags = [head] + get_git_tags() - print(tags); - - # Build all release lz4c and lz4c32 - for tag in tags: - os.chdir(base_dir) - dst_lz4c = '{}/lz4c.{}' .format(tmp_dir, tag) # /path/to/lz4/test/lz4test/lz4c. - dst_lz4c32 = '{}/lz4c32.{}'.format(tmp_dir, tag) # /path/to/lz4/test/lz4test/lz4c32. - if not os.path.isfile(dst_lz4c) or not os.path.isfile(dst_lz4c32) or tag == head: - if tag != head: - r_dir = '{}/{}'.format(tmp_dir, tag) # /path/to/lz4/test/lz4test/ - os.makedirs(r_dir, exist_ok=True) - os.chdir(clone_dir) - git(['--work-tree=' + r_dir, 'checkout', tag, '--', '.'], False) - os.chdir(r_dir + '/programs') # /path/to/lz4/lz4test//programs - else: - os.chdir(programs_dir) - make(['clean', 'lz4c'], False) - shutil.copy2('lz4c', dst_lz4c) - make(['clean', 'lz4c32'], False) - shutil.copy2('lz4c32', dst_lz4c32) - - # Compress test.dat by all released lz4c and lz4c32 - print('Compress test.dat by all released lz4c and lz4c32') - os.chdir(tmp_dir) - for lz4 in glob.glob("*.lz4"): - os.remove(lz4) - for tag in tags: - proc(['./lz4c.' + tag, '-1fz', test_dat, test_dat + '_1_64_' + tag + '.lz4']) - proc(['./lz4c.' + tag, '-9fz', test_dat, test_dat + '_9_64_' + tag + '.lz4']) - proc(['./lz4c32.' + tag, '-1fz', test_dat, test_dat + '_1_32_' + tag + '.lz4']) - proc(['./lz4c32.' + tag, '-9fz', test_dat, test_dat + '_9_32_' + tag + '.lz4']) - - print('Full list of compressed files') - lz4s = sorted(glob.glob('*.lz4')) - for lz4 in lz4s: - print(lz4 + ' : ' + repr(os.path.getsize(lz4))) - - # Remove duplicated .lz4 files - print('') - print('Duplicated files') - lz4s = sorted(glob.glob('*.lz4')) - for i, lz4 in enumerate(lz4s): - if not os.path.isfile(lz4): - continue - for j in range(i+1, len(lz4s)): - lz4t = lz4s[j] - if not os.path.isfile(lz4t): - continue - if filecmp.cmp(lz4, lz4t): - os.remove(lz4t) - print('{} == {}'.format(lz4, lz4t)) - - print('Enumerate only different compressed files') - lz4s = sorted(glob.glob('*.lz4')) - for lz4 in lz4s: - print(lz4 + ' : ' + repr(os.path.getsize(lz4)) + ', ' + sha1_of_file(lz4)) - - # Decompress remained .lz4 files by all released lz4c and lz4c32 - print('Decompression tests and verifications') - lz4s = sorted(glob.glob('*.lz4')) - for dec in glob.glob("*.dec"): - os.remove(dec) - for lz4 in lz4s: - print(lz4, end=" ") - for tag in tags: - print(tag, end=" ") - proc(['./lz4c.' + tag, '-df', lz4, lz4 + '_d64_' + tag + '.dec']) - proc(['./lz4c32.' + tag, '-df', lz4, lz4 + '_d32_' + tag + '.dec']) - print(' OK') # well, here, decompression has worked; but file is not yet verified - - # Compare all '.dec' files with test_dat - decs = glob.glob('*.dec') - for dec in decs: - if not filecmp.cmp(dec, test_dat): - print('ERR : ' + dec) - error_code = 1 - else: - print('OK : ' + dec) - os.remove(dec) - - if error_code != 0: - print('ERROR') - - sys.exit(error_code) diff --git a/src/lz4/visual/.gitignore b/src/lz4/visual/.gitignore deleted file mode 100644 index dea92fc6cf..0000000000 --- a/src/lz4/visual/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -# Visual C++ -.vs/ -*Copy -*.db -*.opensdf -*.sdf -*.suo -*.user - -VS2010/bin/ diff --git a/src/lz4/visual/README.md b/src/lz4/visual/README.md deleted file mode 100644 index 216971f322..0000000000 --- a/src/lz4/visual/README.md +++ /dev/null @@ -1,53 +0,0 @@ -Projects for various integrated development environments (IDE) -============================================================== - -#### Included projects - -The following projects are included with the lz4 distribution: -- `VS2010` - Visual Studio 2010 project (which also works well with Visual Studio 2012, 2013, 2015) - - -#### How to compile lz4 with Visual Studio - -1. Install Visual Studio e.g. VS 2015 Community Edition (it's free). -2. Download the latest version of lz4 from https://github.com/lz4/lz4/releases -3. Decompress ZIP archive. -4. Go to decompressed directory then to `visual` then `VS2010` and open `lz4.sln` -5. Visual Studio will ask about converting VS2010 project to VS2015 and you should agree. -6. Change `Debug` to `Release` and if you have 64-bit Windows change also `Win32` to `x64`. -7. Press F7 on keyboard or select `BUILD` from the menu bar and choose `Build Solution`. -8. If compilation will be fine a compiled executable will be in `visual\VS2010\bin\x64_Release\lz4.exe` - - -#### Projects available within lz4.sln - -The Visual Studio solution file `lz4.sln` contains many projects that will be compiled to the -`visual\VS2010\bin\$(Platform)_$(Configuration)` directory. For example `lz4` set to `x64` and -`Release` will be compiled to `visual\VS2010\bin\x64_Release\lz4.exe`. The solution file contains the -following projects: - -- `lz4` : Command Line Utility, supporting gzip-like arguments -- `datagen` : Synthetic and parametrable data generator, for tests -- `frametest` : Test tool that checks lz4frame integrity on target platform -- `fullbench` : Precisely measure speed for each lz4 inner functions -- `fuzzer` : Test tool, to check lz4 integrity on target platform -- `liblz4` : A static LZ4 library compiled to `liblz4_static.lib` -- `liblz4-dll` : A dynamic LZ4 library (DLL) compiled to `liblz4.dll` with the import library `liblz4.lib` -- `fullbench-dll` : The fullbench program compiled with the import library; the executable requires LZ4 DLL - - -#### Using LZ4 DLL with Microsoft Visual C++ project - -The header files `lib\lz4.h`, `lib\lz4hc.h`, `lib\lz4frame.h` and the import library -`visual\VS2010\bin\$(Platform)_$(Configuration)\liblz4.lib` are required to compile a -project using Visual C++. - -1. The path to header files should be added to `Additional Include Directories` that can - be found in Project Properties of Visual Studio IDE in the `C/C++` Property Pages on the `General` page. -2. The import library has to be added to `Additional Dependencies` that can - be found in Project Properties in the `Linker` Property Pages on the `Input` page. - If one will provide only the name `liblz4.lib` without a full path to the library - then the directory has to be added to `Linker\General\Additional Library Directories`. - -The compiled executable will require LZ4 DLL which is available at -`visual\VS2010\bin\$(Platform)_$(Configuration)\liblz4.dll`. diff --git a/src/lz4/visual/VS2010/datagen/datagen.vcxproj b/src/lz4/visual/VS2010/datagen/datagen.vcxproj deleted file mode 100644 index aaf81adf48..0000000000 --- a/src/lz4/visual/VS2010/datagen/datagen.vcxproj +++ /dev/null @@ -1,165 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {D745AE2F-596A-403A-9B91-81A8C6779243} - Win32Proj - datagen - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - true - Unicode - - - Application - false - true - Unicode - - - - - - - - - - - - - - - - - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - false - - - Console - true - - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - - - Console - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - false - - - Console - true - true - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - - - Console - true - true - true - - - - - - - - - - - - - diff --git a/src/lz4/visual/VS2010/frametest/frametest.vcxproj b/src/lz4/visual/VS2010/frametest/frametest.vcxproj deleted file mode 100644 index 76d12c98a5..0000000000 --- a/src/lz4/visual/VS2010/frametest/frametest.vcxproj +++ /dev/null @@ -1,172 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7} - Win32Proj - frametest - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - true - Unicode - - - Application - false - true - Unicode - - - - - - - - - - - - - - - - - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - false - - - Console - true - - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - - - Console - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - false - - - Console - true - true - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - - - Console - true - true - true - - - - - - - - - - - - - - - - - - - - diff --git a/src/lz4/visual/VS2010/fullbench-dll/fullbench-dll.vcxproj b/src/lz4/visual/VS2010/fullbench-dll/fullbench-dll.vcxproj deleted file mode 100644 index c10552affa..0000000000 --- a/src/lz4/visual/VS2010/fullbench-dll/fullbench-dll.vcxproj +++ /dev/null @@ -1,176 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {13992FD2-077E-4954-B065-A428198201A9} - Win32Proj - fullbench-dll - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - true - Unicode - - - Application - false - true - Unicode - - - - - - - - - - - - - - - - - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions) - true - false - - - Console - true - $(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories) - liblz4.lib;%(AdditionalDependencies) - - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - - - Console - true - $(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories) - liblz4.lib;%(AdditionalDependencies) - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions) - false - false - - - Console - true - true - true - $(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories) - liblz4.lib;%(AdditionalDependencies) - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - - - Console - true - true - true - $(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories) - liblz4.lib;%(AdditionalDependencies) - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/lz4/visual/VS2010/fullbench/fullbench.vcxproj b/src/lz4/visual/VS2010/fullbench/fullbench.vcxproj deleted file mode 100644 index e2d95c9fa1..0000000000 --- a/src/lz4/visual/VS2010/fullbench/fullbench.vcxproj +++ /dev/null @@ -1,172 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E} - Win32Proj - fullbench - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - true - Unicode - - - Application - false - true - Unicode - - - - - - - - - - - - - - - - - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - false - - - Console - true - - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - - - Console - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - false - - - Console - true - true - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - - - Console - true - true - true - - - - - - - - - - - - - - - - - - - - diff --git a/src/lz4/visual/VS2010/fuzzer/fuzzer.vcxproj b/src/lz4/visual/VS2010/fuzzer/fuzzer.vcxproj deleted file mode 100644 index 85d6c9ba42..0000000000 --- a/src/lz4/visual/VS2010/fuzzer/fuzzer.vcxproj +++ /dev/null @@ -1,169 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {18B9F1A7-9C66-4352-898B-30804DADE0FD} - Win32Proj - fuzzer - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - true - Unicode - - - Application - false - true - Unicode - - - - - - - - - - - - - - - - - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - false - - - Console - true - - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - - - Console - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - false - - - Console - true - true - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - - - Console - true - true - true - - - - - - - - - - - - - - - - - diff --git a/src/lz4/visual/VS2010/liblz4-dll/liblz4-dll.rc b/src/lz4/visual/VS2010/liblz4-dll/liblz4-dll.rc deleted file mode 100644 index b1871feae5..0000000000 --- a/src/lz4/visual/VS2010/liblz4-dll/liblz4-dll.rc +++ /dev/null @@ -1,51 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// - -#include "lz4.h" /* LZ4_VERSION_STRING */ -#define APSTUDIO_READONLY_SYMBOLS -#include "verrsrc.h" -#undef APSTUDIO_READONLY_SYMBOLS - - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -LANGUAGE 9, 1 - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION LZ4_VERSION_MAJOR,LZ4_VERSION_MINOR,LZ4_VERSION_RELEASE,0 - PRODUCTVERSION LZ4_VERSION_MAJOR,LZ4_VERSION_MINOR,LZ4_VERSION_RELEASE,0 - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK -#ifdef _DEBUG - FILEFLAGS VS_FF_DEBUG -#else - FILEFLAGS 0x0L -#endif - FILEOS VOS_NT_WINDOWS32 - FILETYPE VFT_DLL - FILESUBTYPE VFT2_UNKNOWN -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904B0" - BEGIN - VALUE "CompanyName", "Yann Collet" - VALUE "FileDescription", "Extremely fast compression" - VALUE "FileVersion", LZ4_VERSION_STRING - VALUE "InternalName", "lz4.dll" - VALUE "LegalCopyright", "Copyright (C) 2013-2016, Yann Collet" - VALUE "OriginalFilename", "lz4.dll" - VALUE "ProductName", "LZ4" - VALUE "ProductVersion", LZ4_VERSION_STRING - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 1200 - END -END - -#endif diff --git a/src/lz4/visual/VS2010/liblz4-dll/liblz4-dll.vcxproj b/src/lz4/visual/VS2010/liblz4-dll/liblz4-dll.vcxproj deleted file mode 100644 index 389f13c183..0000000000 --- a/src/lz4/visual/VS2010/liblz4-dll/liblz4-dll.vcxproj +++ /dev/null @@ -1,175 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {9800039D-4AAA-43A4-BB78-FEF6F4836927} - Win32Proj - liblz4-dll - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - liblz4-dll - - - - DynamicLibrary - true - Unicode - - - DynamicLibrary - true - Unicode - - - DynamicLibrary - false - true - Unicode - - - DynamicLibrary - false - true - Unicode - - - - - - - - - - - - - - - - - - - true - liblz4 - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - liblz4 - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - liblz4 - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - liblz4 - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - true - false - - - true - - - - - - - Level4 - Disabled - WIN32;_DEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - - - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - false - false - - - true - true - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - - - true - true - true - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/lz4/visual/VS2010/liblz4/liblz4.vcxproj b/src/lz4/visual/VS2010/liblz4/liblz4.vcxproj deleted file mode 100644 index a0b800094d..0000000000 --- a/src/lz4/visual/VS2010/liblz4/liblz4.vcxproj +++ /dev/null @@ -1,171 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476} - Win32Proj - liblz4 - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - false - true - Unicode - - - StaticLibrary - false - true - Unicode - - - - - - - - - - - - - - - - - - - true - liblz4_static - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - liblz4_static - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - liblz4_static - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - liblz4_static - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - true - false - - - true - - - - - - - Level4 - Disabled - WIN32;_DEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - - - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - false - false - - - true - true - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - - - true - true - true - - - - - - - - - - - - - - - - - - - diff --git a/src/lz4/visual/VS2010/lz4.sln b/src/lz4/visual/VS2010/lz4.sln deleted file mode 100644 index 78f223bf48..0000000000 --- a/src/lz4/visual/VS2010/lz4.sln +++ /dev/null @@ -1,98 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Express 2012 for Windows Desktop -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lz4", "lz4\lz4.vcxproj", "{E30329AC-0057-4FE0-8FDA-7F650D398C4C}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblz4-dll", "liblz4-dll\liblz4-dll.vcxproj", "{9800039D-4AAA-43A4-BB78-FEF6F4836927}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblz4", "liblz4\liblz4.vcxproj", "{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fuzzer", "fuzzer\fuzzer.vcxproj", "{18B9F1A7-9C66-4352-898B-30804DADE0FD}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fullbench", "fullbench\fullbench.vcxproj", "{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "frametest", "frametest\frametest.vcxproj", "{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "datagen", "datagen\datagen.vcxproj", "{D745AE2F-596A-403A-9B91-81A8C6779243}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fullbench-dll", "fullbench-dll\fullbench-dll.vcxproj", "{13992FD2-077E-4954-B065-A428198201A9}" - ProjectSection(ProjectDependencies) = postProject - {9800039D-4AAA-43A4-BB78-FEF6F4836927} = {9800039D-4AAA-43A4-BB78-FEF6F4836927} - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - Release|Win32 = Release|Win32 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Debug|Win32.ActiveCfg = Debug|Win32 - {E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Debug|Win32.Build.0 = Debug|Win32 - {E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Debug|x64.ActiveCfg = Debug|x64 - {E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Debug|x64.Build.0 = Debug|x64 - {E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Release|Win32.ActiveCfg = Release|Win32 - {E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Release|Win32.Build.0 = Release|Win32 - {E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Release|x64.ActiveCfg = Release|x64 - {E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Release|x64.Build.0 = Release|x64 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Debug|Win32.ActiveCfg = Debug|Win32 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Debug|Win32.Build.0 = Debug|Win32 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Debug|x64.ActiveCfg = Debug|x64 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Debug|x64.Build.0 = Debug|x64 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Release|Win32.ActiveCfg = Release|Win32 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Release|Win32.Build.0 = Release|Win32 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Release|x64.ActiveCfg = Release|x64 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Release|x64.Build.0 = Release|x64 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Debug|Win32.ActiveCfg = Debug|Win32 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Debug|Win32.Build.0 = Debug|Win32 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Debug|x64.ActiveCfg = Debug|x64 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Debug|x64.Build.0 = Debug|x64 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Release|Win32.ActiveCfg = Release|Win32 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Release|Win32.Build.0 = Release|Win32 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Release|x64.ActiveCfg = Release|x64 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Release|x64.Build.0 = Release|x64 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Debug|Win32.ActiveCfg = Debug|Win32 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Debug|Win32.Build.0 = Debug|Win32 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Debug|x64.ActiveCfg = Debug|x64 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Debug|x64.Build.0 = Debug|x64 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Release|Win32.ActiveCfg = Release|Win32 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Release|Win32.Build.0 = Release|Win32 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Release|x64.ActiveCfg = Release|x64 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Release|x64.Build.0 = Release|x64 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Debug|Win32.ActiveCfg = Debug|Win32 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Debug|Win32.Build.0 = Debug|Win32 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Debug|x64.ActiveCfg = Debug|x64 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Debug|x64.Build.0 = Debug|x64 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Release|Win32.ActiveCfg = Release|Win32 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Release|Win32.Build.0 = Release|Win32 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Release|x64.ActiveCfg = Release|x64 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Release|x64.Build.0 = Release|x64 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Debug|Win32.ActiveCfg = Debug|Win32 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Debug|Win32.Build.0 = Debug|Win32 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Debug|x64.ActiveCfg = Debug|x64 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Debug|x64.Build.0 = Debug|x64 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Release|Win32.ActiveCfg = Release|Win32 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Release|Win32.Build.0 = Release|Win32 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Release|x64.ActiveCfg = Release|x64 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Release|x64.Build.0 = Release|x64 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Debug|Win32.ActiveCfg = Debug|Win32 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Debug|Win32.Build.0 = Debug|Win32 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Debug|x64.ActiveCfg = Debug|x64 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Debug|x64.Build.0 = Debug|x64 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Release|Win32.ActiveCfg = Release|Win32 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Release|Win32.Build.0 = Release|Win32 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Release|x64.ActiveCfg = Release|x64 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Release|x64.Build.0 = Release|x64 - {13992FD2-077E-4954-B065-A428198201A9}.Debug|Win32.ActiveCfg = Debug|Win32 - {13992FD2-077E-4954-B065-A428198201A9}.Debug|Win32.Build.0 = Debug|Win32 - {13992FD2-077E-4954-B065-A428198201A9}.Debug|x64.ActiveCfg = Debug|x64 - {13992FD2-077E-4954-B065-A428198201A9}.Debug|x64.Build.0 = Debug|x64 - {13992FD2-077E-4954-B065-A428198201A9}.Release|Win32.ActiveCfg = Release|Win32 - {13992FD2-077E-4954-B065-A428198201A9}.Release|Win32.Build.0 = Release|Win32 - {13992FD2-077E-4954-B065-A428198201A9}.Release|x64.ActiveCfg = Release|x64 - {13992FD2-077E-4954-B065-A428198201A9}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/src/lz4/visual/VS2010/lz4/lz4.rc b/src/lz4/visual/VS2010/lz4/lz4.rc deleted file mode 100644 index c593edf85f..0000000000 --- a/src/lz4/visual/VS2010/lz4/lz4.rc +++ /dev/null @@ -1,51 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// - -#include "lz4.h" /* LZ4_VERSION_STRING */ -#define APSTUDIO_READONLY_SYMBOLS -#include "verrsrc.h" -#undef APSTUDIO_READONLY_SYMBOLS - - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -LANGUAGE 9, 1 - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION LZ4_VERSION_MAJOR,LZ4_VERSION_MINOR,LZ4_VERSION_RELEASE,0 - PRODUCTVERSION LZ4_VERSION_MAJOR,LZ4_VERSION_MINOR,LZ4_VERSION_RELEASE,0 - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK -#ifdef _DEBUG - FILEFLAGS VS_FF_DEBUG -#else - FILEFLAGS 0x0L -#endif - FILEOS VOS_NT_WINDOWS32 - FILETYPE VFT_DLL - FILESUBTYPE VFT2_UNKNOWN -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904B0" - BEGIN - VALUE "CompanyName", "Yann Collet" - VALUE "FileDescription", "Extremely fast compression" - VALUE "FileVersion", LZ4_VERSION_STRING - VALUE "InternalName", "lz4.exe" - VALUE "LegalCopyright", "Copyright (C) 2013-2016, Yann Collet" - VALUE "OriginalFilename", "lz4.exe" - VALUE "ProductName", "LZ4" - VALUE "ProductVersion", LZ4_VERSION_STRING - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 1200 - END -END - -#endif diff --git a/src/lz4/visual/VS2010/lz4/lz4.vcxproj b/src/lz4/visual/VS2010/lz4/lz4.vcxproj deleted file mode 100644 index 693e1217d1..0000000000 --- a/src/lz4/visual/VS2010/lz4/lz4.vcxproj +++ /dev/null @@ -1,185 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {E30329AC-0057-4FE0-8FDA-7F650D398C4C} - Win32Proj - lz4 - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - true - Unicode - - - Application - false - true - Unicode - - - - - - - - - - - - - - - - - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - false - - - Console - true - setargv.obj;%(AdditionalDependencies) - - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - - - Console - true - setargv.obj;%(AdditionalDependencies) - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - false - - - Console - true - true - true - setargv.obj;%(AdditionalDependencies) - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - - - Console - true - true - true - setargv.obj;%(AdditionalDependencies) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/nudb/.gitignore b/src/nudb/.gitignore deleted file mode 100644 index 99f984bdaa..0000000000 --- a/src/nudb/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -bin/ -bin64/ diff --git a/src/nudb/.gitmodules b/src/nudb/.gitmodules deleted file mode 100644 index 0115ab4e41..0000000000 --- a/src/nudb/.gitmodules +++ /dev/null @@ -1,9 +0,0 @@ -[submodule "extras/beast"] - path = extras/beast - url = https://github.com/vinniefalco/Beast.git -[submodule "extras/rocksdb"] - path = extras/rocksdb - url = https://github.com/facebook/rocksdb.git -[submodule "doc/docca"] - path = doc/docca - url = https://github.com/vinniefalco/docca.git diff --git a/src/nudb/.travis.yml b/src/nudb/.travis.yml deleted file mode 100644 index 1900451f96..0000000000 --- a/src/nudb/.travis.yml +++ /dev/null @@ -1,89 +0,0 @@ -language: cpp - -env: - global: - - LLVM_VERSION=3.8.0 - # Maintenance note: to move to a new version - # of boost, update both BOOST_ROOT and BOOST_URL. - # Note that for simplicity, BOOST_ROOT's final - # namepart must match the folder name internal - # to boost's .tar.gz. - - LCOV_ROOT=$HOME/lcov - - VALGRIND_ROOT=$HOME/valgrind-install - - BOOST_ROOT=$HOME/boost_1_60_0 - - BOOST_URL='http://downloads.sourceforge.net/project/boost/boost/1.60.0/boost_1_60_0.tar.gz?r=https%3A%2F%2Fsourceforge.net%2Fprojects%2Fboost%2Ffiles%2Fboost%2F1.60.0%2Fboost_1_60_0.tar.gz&ts=1460417589&use_mirror=netix' -packages: &gcc5_pkgs - - gcc-5 - - g++-5 - - python-software-properties - - libssl-dev - - libffi-dev - - libstdc++6 - - binutils-gold - # Provides a backtrace if the unittests crash - - gdb - # Needed for installing valgrind - - subversion - - automake - - autotools-dev - - libc6-dbg - # Needed to build rocksdb - - libsnappy-dev - -matrix: - include: - # GCC/Coverage/Autobahn - - compiler: gcc - env: - - GCC_VER=5 - - VARIANT=coverage - - ADDRESS_MODEL=64 - - BUILD_SYSTEM=cmake - - PATH=$PWD/cmake/bin:$PATH - addons: &ao_gcc5 - apt: - sources: ['ubuntu-toolchain-r-test'] - packages: *gcc5_pkgs - - # Clang/UndefinedBehaviourSanitizer - - compiler: clang - env: - - GCC_VER=5 - - VARIANT=usan - - CLANG_VER=3.8 - - ADDRESS_MODEL=64 - - UBSAN_OPTIONS='print_stacktrace=1' - - BUILD_SYSTEM=cmake - - PATH=$PWD/cmake/bin:$PATH - - PATH=$PWD/llvm-$LLVM_VERSION/bin:$PATH - addons: *ao_gcc5 - - # Clang/AddressSanitizer - - compiler: clang - env: - - GCC_VER=5 - - VARIANT=asan - - CLANG_VER=3.8 - - ADDRESS_MODEL=64 - - PATH=$PWD/llvm-$LLVM_VERSION/bin:$PATH - addons: *ao_gcc5 - -cache: - directories: - - $BOOST_ROOT - - $VALGRIND_ROOT - - llvm-$LLVM_VERSION - - cmake - -before_install: - - scripts/install-dependencies.sh - -script: - - scripts/build-and-test.sh - -after_script: - - cat nohup.out || echo "nohup.out already deleted" - -notifications: - email: - false diff --git a/src/nudb/CHANGELOG.md b/src/nudb/CHANGELOG.md deleted file mode 100644 index d7d65c3fe0..0000000000 --- a/src/nudb/CHANGELOG.md +++ /dev/null @@ -1,58 +0,0 @@ -1.0.0-b6 - -* Fix incorrect file deletion in create() - ---- - -1.0.0-b5 - -* fail_file also fails on reads -* Fix bug in rekey where an error code wasn't checked -* Increase coverage -* Add buffer unit test -* Add is_File concept and checks -* Update documentation -* Add example program -* Demote exceptions to asserts in gentex -* Improved commit process -* Dynamic block size in custom allocator - ---- - -1.0.0-b4 - -* Improved test coverage -* Use master branch for codecov badge -* Throw on API calls when no database open -* Benchmarks vs. RocksDB - -### API Changes: - -* `insert` sets `error::key_exists` instead of returning `false` -* `fetch` sets `error::key_not_found` instead of returning `false` - ---- - -1.0.0-b3 - -* Tune buffer sizes for performance -* Fix large POSIX and Win32 writes -* Adjust progress indicator for nudb tool -* Document link requirements -* Add visit test -* Improved coverage - ---- - -1.0.0-b2 - -* Minor documentation and tidying -* Add CHANGELOG - ---- - -1.0.0-b1 - -* Initial source tree - - diff --git a/src/nudb/CMakeLists.txt b/src/nudb/CMakeLists.txt deleted file mode 100644 index af1bfc33a3..0000000000 --- a/src/nudb/CMakeLists.txt +++ /dev/null @@ -1,87 +0,0 @@ -cmake_minimum_required (VERSION 3.2) - -project (nudb) - -set_property (GLOBAL PROPERTY USE_FOLDERS ON) - -if (WIN32) - set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP /W4 /wd4100 /D _WIN32_WINNT=0x0600 /D_SCL_SECURE_NO_WARNINGS=1 /D_CRT_SECURE_NO_WARNINGS=1") - set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /SAFESEH:NO") -else () - set (Boost_USE_STATIC_LIBS ON) - set (Boost_USE_MULTITHREADED ON) - find_package (Boost REQUIRED COMPONENTS filesystem program_options system thread) - include_directories (SYSTEM ${Boost_INCLUDE_DIRS}) - link_directories (${Boost_LIBRARY_DIR}) - - set (THREADS_PREFER_PTHREAD_FLAG ON) - find_package (Threads) - - set (CMAKE_CXX_FLAGS - "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -Wpedantic") -endif () - -if ("${VARIANT}" STREQUAL "coverage") - set (CMAKE_CXX_FLAGS - "${CMAKE_CXX_FLAGS} -fprofile-arcs -ftest-coverage") - set (CMAKE_BUILD_TYPE RELWITHDEBINFO) - set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -lgcov") -elseif ("${VARIANT}" STREQUAL "asan") - set (CMAKE_CXX_FLAGS - "${CMAKE_CXX_FLAGS} -fsanitize=address -fno-omit-frame-pointer") - set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fsanitize=address") - set (CMAKE_BUILD_TYPE RELWITHDEBINFO) -elseif ("${VARIANT}" STREQUAL "usan") - set (CMAKE_CXX_FLAGS - "${CMAKE_CXX_FLAGS} -fsanitize=undefined -fno-omit-frame-pointer") - set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fsanitize=undefined") - set (CMAKE_BUILD_TYPE RELWITHDEBINFO) -elseif ("${VARIANT}" STREQUAL "debug") - set (CMAKE_BUILD_TYPE DEBUG) -elseif ("${VARIANT}" STREQUAL "release") - set (CMAKE_BUILD_TYPE RELEASE) -endif () - -function (DoGroupSources curdir rootdir folder) - file (GLOB children RELATIVE ${PROJECT_SOURCE_DIR}/${curdir} ${PROJECT_SOURCE_DIR}/${curdir}/*) - foreach (child ${children}) - if (IS_DIRECTORY ${PROJECT_SOURCE_DIR}/${curdir}/${child}) - DoGroupSources (${curdir}/${child} ${rootdir} ${folder}) - elseif (${child} STREQUAL "CMakeLists.txt") - source_group ("" FILES ${PROJECT_SOURCE_DIR}/${curdir}/${child}) - else () - string (REGEX REPLACE ^${rootdir} ${folder} groupname ${curdir}) - #set (groupname ${curdir}) - string (REPLACE "/" "\\" groupname ${groupname}) - source_group (${groupname} FILES ${PROJECT_SOURCE_DIR}/${curdir}/${child}) - endif () - endforeach () -endfunction () - -function (GroupSources curdir folder) - DoGroupSources (${curdir} ${curdir} ${folder}) -endfunction () - -include_directories ( - include - extras - extras/beast/extras - ) - -file (GLOB_RECURSE BEAST_INCLUDES - ${PROJECT_SOURCE_DIR}/extras/beast/extras/beast/unit_test/*.hpp - ${PROJECT_SOURCE_DIR}/extras/beast/extras/beast/unit_test/*.ipp -) - -file (GLOB_RECURSE EXTRAS_INCLUDES - ${PROJECT_SOURCE_DIR}/extras/nudb/* -) - -file (GLOB_RECURSE NUDB_INCLUDES - ${PROJECT_SOURCE_DIR}/include/nudb/* -) - -add_subdirectory (bench) -add_subdirectory (examples) -add_subdirectory (test) -add_subdirectory (tools) diff --git a/src/nudb/Jamroot b/src/nudb/Jamroot deleted file mode 100644 index 7c140b811c..0000000000 --- a/src/nudb/Jamroot +++ /dev/null @@ -1,93 +0,0 @@ -# -# Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -# -# Distributed under the Boost Software License, Version 1.0. (See accompanying -# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -# - -import os ; -import feature ; -import boost ; - -boost.use-project ; - -variant coverage - : - debug - : - "-fprofile-arcs -ftest-coverage" - "-lgcov" - ; - -variant asan - : - release - : - "-fsanitize=address -fno-omit-frame-pointer" - "-fsanitize=address" - ; - -variant msan - : - debug - : - "-fsanitize=memory -fno-omit-frame-pointer -fsanitize-memory-track-origins=2 -fsanitize-memory-use-after-dtor" - "-fsanitize=memory" - ; - -variant usan - : - debug - : - "-fsanitize=undefined -fno-omit-frame-pointer" - "-fsanitize=undefined" - ; - -project nudb - : requirements - ./extras - ./extras/beast/extras - ./include - #/boost//headers - /boost/system//boost_system - /boost/thread//boost_thread - /boost/filesystem//boost_filesystem - /boost/program_options//boost_program_options - BOOST_ALL_NO_LIB=1 - BOOST_SYSTEM_NO_DEPRECATED=1 - multi - static - shared - on - gcc:-std=c++11 - gcc:-Wno-unused-variable - clang:-std=c++11 - msvc:_SCL_SECURE_NO_WARNINGS=1 - msvc:_CRT_SECURE_NO_WARNINGS=1 - msvc:-bigobj - LINUX:_XOPEN_SOURCE=600 - LINUX:_GNU_SOURCE=1 - SOLARIS:_XOPEN_SOURCE=500 - SOLARIS:__EXTENSIONS__ - SOLARIS:socket - SOLARIS:nsl - NT:_WIN32_WINNT=0x0601 - NT,cw:ws2_32 - NT,cw:mswsock - NT,gcc:ws2_32 - NT,gcc:mswsock - NT,gcc-cygwin:__USE_W32_SOCKETS - HPUX,gcc:_XOPEN_SOURCE_EXTENDED - HPUX:ipv6 - QNXNTO:socket - HAIKU:network - : usage-requirements - . - : - build-dir bin - ; - -build-project bench ; -build-project examples ; -build-project test ; -build-project tools ; diff --git a/src/nudb/LICENSE_1_0.txt b/src/nudb/LICENSE_1_0.txt deleted file mode 100644 index 36b7cd93cd..0000000000 --- a/src/nudb/LICENSE_1_0.txt +++ /dev/null @@ -1,23 +0,0 @@ -Boost Software License - Version 1.0 - August 17th, 2003 - -Permission is hereby granted, free of charge, to any person or organization -obtaining a copy of the software and accompanying documentation covered by -this license (the "Software") to use, reproduce, display, distribute, -execute, and transmit the Software, and to prepare derivative works of the -Software, and to permit third-parties to whom the Software is furnished to -do so, all subject to the following: - -The copyright notices in the Software and this entire statement, including -the above license grant, this restriction and the following disclaimer, -must be included in all copies of the Software, in whole or in part, and -all derivative works of the Software, unless such copies or derivative -works are solely in the form of machine-executable object code generated by -a source language processor. - -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, TITLE AND NON-INFRINGEMENT. IN NO EVENT -SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE -FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/src/nudb/README.md b/src/nudb/README.md deleted file mode 100644 index 4d3b0d7e8b..0000000000 --- a/src/nudb/README.md +++ /dev/null @@ -1,466 +0,0 @@ -NuDB - -[![Join the chat at https://gitter.im/vinniefalco/NuDB](https://badges.gitter.im/vinniefalco/NuDB.svg)](https://gitter.im/vinniefalco/NuDB?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status] -(https://travis-ci.org/vinniefalco/NuDB.svg?branch=master)](https://travis-ci.org/vinniefalco/NuDB) [![codecov] -(https://codecov.io/gh/vinniefalco/NuDB/branch/master/graph/badge.svg)](https://codecov.io/gh/vinniefalco/NuDB) [![coveralls] -(https://coveralls.io/repos/github/vinniefalco/NuDB/badge.svg?branch=master)](https://coveralls.io/github/vinniefalco/NuDB?branch=master) [![Documentation] -(https://img.shields.io/badge/documentation-master-brightgreen.svg)](http://vinniefalco.github.io/nudb/) [![License] -(https://img.shields.io/badge/license-boost-brightgreen.svg)](LICENSE_1_0.txt) - -# A Key/Value Store For SSDs - ---- - -## Contents - -- [Introduction](#introduction) -- [Description](#description) -- [Requirements](#requirements) -- [Example](#example) -- [Building](#building) -- [Algorithm](#algorithm) -- [Licence](#licence) -- [Contact](#contact) - ---- - -## Introduction - -NuDB is an append-only, key/value store specifically optimized for random -read performance on modern SSDs or equivalent high-IOPS devices. The most -common application for NuDB is content addressible storage where a -cryptographic digest of the data is used as the key. The read performance -and memory usage are independent of the size of the database. These are -some other features: - -* Low memory footprint -* Database size up to 281TB -* All keys are the same size -* Append-only, no update or delete -* Value sizes from 1 to 2^32 bytes (4GB) -* Performance independent of growth -* Optimized for concurrent fetch -* Key file can be rebuilt if needed -* Inserts are atomic and consistent -* Data file may be efficiently iterated -* Key and data files may be on different devices -* Hardened against algorithmic complexity attacks -* Header-only, no separate library to build - -## Description - -This software is close to final. Interfaces are stable. -For recent changes see the [CHANGELOG](CHANGELOG.md). - -NuDB has been in use for over a year on production servers -running [rippled](https://github.com/ripple/rippled), with -database sizes over 3 terabytes. - -* [Repository](https://github.com/vinniefalco/Beast) -* [Documentation](http://vinniefalco.github.io/nudb/) - -## Requirements - -* Boost 1.58 or higher -* C++11 or greater -* SSD drive, or equivalent device with high IOPS - -## Example - -This complete program creates a database, opens the database, -inserts several key/value pairs, fetches the key/value pairs, -closes the database, then erases the database files. Source -code for this program is located in the examples directory. - -```C++ -#include -#include -#include - -int main() -{ - using namespace nudb; - std::size_t constexpr N = 1000; - using key_type = std::uint32_t; - error_code ec; - auto const dat_path = "db.dat"; - auto const key_path = "db.key"; - auto const log_path = "db.log"; - create( - dat_path, key_path, log_path, - 1, - make_salt(), - sizeof(key_type), - block_size("."), - 0.5f, - ec); - store db; - db.open(dat_path, key_path, log_path, ec); - char data = 0; - // Insert - for(key_type i = 0; i < N; ++i) - db.insert(&i, &data, sizeof(data), ec); - // Fetch - for(key_type i = 0; i < N; ++i) - db.fetch(&i, - [&](void const* buffer, std::size_t size) - { - // do something with buffer, size - }, ec); - db.close(ec); - erase_file(dat_path); - erase_file(key_path); - erase_file(log_path); -} -``` - -## Building - -NuDB is header-only so there are no libraries to build. To use it in your -project, simply copy the NuDB sources to your project's source tree -(alternatively, bring NuDB into your Git repository using the -`git subtree` or `git submodule` commands). Then, edit your build scripts -to add the `include/` directory to the list of paths checked by the C++ -compiler when searching for includes. NuDB `#include` lines will look -like this: - -``` -#include -``` - -To link your program successfully, you'll need to add the Boost.Thread and -Boost.System libraries to link with. Please visit the Boost documentation -for instructions on how to do this for your particular build system. - -NuDB tests require Beast, and the benchmarks require RocksDB. These projects -are linked to the repository using git submodules. Before building the tests -or benchmarks, these commands should be issued at the root of the repository: - -``` -git submodule init -git submodule update -``` - -For the examples and tests, NuDB provides build scripts for Boost.Build (b2) -and CMake. To generate build scripts using CMake, execute these commands at -the root of the repository (project and solution files will be generated -for Visual Studio users): - -``` -cd bin -cmake .. # for 32-bit Windows build - -cd ../bin64 -cmake .. # for Linux/Mac builds, OR -cmake -G"Visual Studio 14 2015 Win64" .. # for 64-bit Windows builds -``` - -To build with Boost.Build, it is necessary to have the b2 executable -in your path. And b2 needs to know how to find the Boost sources. The -easiest way to do this is make sure that the version of b2 in your path -is the one at the root of the Boost source tree, which is built when -running `bootstrap.sh` (or `bootstrap.bat` on Windows). - -Once b2 is in your path, simply run b2 in the root of the Beast -repository to automatically build the required Boost libraries if they -are not already built, build the examples, then build and run the unit -tests. - -On OSX it may be necessary to pass "toolset=clang" on the b2 command line. -Alternatively, this may be site in site-config.jam or user-config.jam. - -The files in the repository are laid out thusly: - -``` -./ - bench/ Holds the benchmark sources and scripts - bin/ Holds executables and project files - bin64/ Holds 64-bit Windows executables and project files - examples/ Holds example program source code - extras/ Additional APIs, may change - include/ Add this to your compiler includes - nudb/ - test/ Unit tests and benchmarks - tools/ Holds the command line tool sources -``` - -## Algorithm - -Three files are used. - -* The data file holds keys and values stored sequentially and size-prefixed. -* The key file holds a series of fixed-size bucket records forming an on-disk - hash table. -* The log file stores bookkeeping information used to restore consistency when -an external failure occurs. - -In typical cases a fetch costs one I/O cycle to consult the key file, and if the -key is present, one I/O cycle to read the value. - -### Usage - -Callers must define these parameters when _creating_ a database: - -* `KeySize`: The size of a key in bytes. -* `BlockSize`: The physical size of a key file record. - -The ideal block size matches the sector size or block size of the -underlying physical media that holds the key file. Functions are -provided to return a best estimate of this value for a particular -device, but a default of 4096 should work for typical installations. -The implementation tries to fit as many entries as possible in a key -file record, to maximize the amount of useful work performed per I/O. - -* `LoadFactor`: The desired fraction of bucket occupancy - -`LoadFactor` is chosen to make bucket overflows unlikely without -sacrificing bucket occupancy. A value of 0.50 seems to work well with -a good hash function. - -Callers must also provide these parameters when a database is _opened:_ - -* `Appnum`: An application-defined integer constant which can be retrieved -later from the database [TODO]. -* `AllocSize`: A significant multiple of the average data size. - -Memory is recycled to improve performance, so NuDB needs `AllocSize` as a -hint about the average size of the data being inserted. For an average data size -of 1KB (one kilobyte), `AllocSize` of sixteen megabytes (16MB) is sufficient. If -the `AllocSize` is too low, the memory recycler will not make efficient use of -allocated blocks. - -Two operations are defined: `fetch`, and `insert`. - -#### `fetch` - -The `fetch` operation retrieves a variable length value given the -key. The caller supplies a factory used to provide a buffer for storing -the value. This interface allows custom memory allocation strategies. - -#### `insert` - -`insert` adds a key/value pair to the store. Value data must contain at least -one byte. Duplicate keys are disallowed. Insertions are serialized, which means -[TODO]. - -### Implementation - -All insertions are buffered in memory, with inserted values becoming -immediately discoverable in subsequent or concurrent calls to fetch. -Periodically, buffered data is safely committed to disk files using -a separate dedicated thread associated with the database. This commit -process takes place at least once per second, or more often during -a detected surge in insertion activity. In the commit process the -key/value pairs receive the following treatment: - -An insertion is performed by appending a value record to the data file. -The value record has some header information including the size of the -data and a copy of the key; the data file is iteratable without the key -file. The value data follows the header. The data file is append-only -and immutable: once written, bytes are never changed. - -Initially the hash table in the key file consists of a single bucket. -After the load factor is exceeded from insertions, the hash table grows -in size by one bucket by doing a "split". The split operation is the -[linear hashing algorithm](http://en.wikipedia.org/wiki/Linear_hashing) -as described by Litwin and Larson. - -When a bucket is split, each key is rehashed, and either remains in the -original bucket or gets moved to the a bucket appended to the end of -the key file. - -An insertion on a full bucket first triggers the "spill" algorithm. - -First, a spill record is appended to the data file, containing header -information followed by the entire bucket record. Then the bucket's size is set -to zero and the offset of the spill record is stored in the bucket. At this -point the insertion may proceed normally, since the bucket is empty. Spilled -buckets in the data file are always full. - -Because every bucket holds the offset of the next spill record in the -data file, the buckets form a linked list. In practice, careful -selection of capacity and load factor will keep the percentage of -buckets with one spill record to a minimum, with no bucket requiring -two spill records. - -The implementation of fetch is straightforward: first the bucket in the -key file is checked, then each spill record in the linked list of -spill records is checked, until the key is found or there are no more -records. As almost all buckets have no spill records, the average -fetch requires one I/O (not including reading the value). - -One complication in the scheme is when a split occurs on a bucket that -has one or more spill records. In this case, both the bucket being split -and the new bucket may overflow. This is handled by performing the -spill algorithm for each overflow that occurs. The new buckets may have -one or more spill records each, depending on the number of keys that -were originally present. - -Because the data file is immutable, a bucket's original spill records -are no longer referenced after the bucket is split. These blocks of data -in the data file are unrecoverable wasted space. Correctly configured -databases can have a typical waste factor of 1%, which is acceptable. -These unused bytes can be removed by visiting each value in the value -file using an off-line process and inserting it into a new database, -then delete the old database and use the new one instead. - -### Recovery - -To provide atomicity and consistency, a log file associated with the -database stores information used to roll back partial commits. - -### Iteration - -Each record in the data file is prefixed with a header identifying -whether it is a value record or a spill record, along with the size of -the record in bytes and a copy of the key if it's a value record, so values can -be iterated by incrementing a byte counter. A key file can be regenerated from -just the data file by iterating the values and performing the key -insertion algorithm. - -### Concurrency - -Locks are never held during disk reads and writes. Fetches are fully -concurrent, while inserts are serialized. Inserts fail on duplicate -keys, and are atomic: they either succeed immediately or fail. -After an insert, the key is immediately visible to subsequent fetches. - -### Formats - -All integer values are stored as big endian. The uint48_t format -consists of 6 bytes. - -#### Key File - -The Key File contains the Header followed by one or more -fixed-length Bucket Records. - -#### Header (104 bytes) - - char[8] Type The characters "nudb.key" - uint16 Version Holds the version number - uint64 UID Unique ID generated on creation - uint64 Appnum Application defined constant - uint16 KeySize Key size in bytes - - uint64 Salt A random seed - uint64 Pepper The salt hashed - uint16 BlockSize Size of a file block in bytes - - uint16 LoadFactor Target fraction in 65536ths - - uint8[56] Reserved Zeroes - uint8[] Reserved Zero-pad to block size - -`Type` identifies the file as belonging to nudb. `UID` is -generated randomly when the database is created, and this value -is stored in the data and log files as well - it's used -to determine if files belong to the same database. `Salt` is -generated when the database is created and helps prevent -complexity attacks; it is prepended to the key material -when computing a hash, or used to initialize the state of -the hash function. `Appnum` is an application defined constant -set when the database is created. It can be used for anything, -for example to distinguish between different data formats. - -`Pepper` is computed by hashing `Salt` using a hash function -seeded with the salt. This is used to fingerprint the hash -function used. If a database is opened and the fingerprint -does not match the hash calculation performed using the template -argument provided when constructing the store, an exception -is thrown. - -The header for the key file contains the File Header followed by -the information above. The Capacity is the number of keys per -bucket, and defines the size of a bucket record. The load factor -is the target fraction of bucket occupancy. - -None of the information in the key file header or the data file -header may be changed after the database is created, including -the Appnum. - -#### Bucket Record (fixed-length) - - uint16 Count Number of keys in this bucket - uint48 Spill Offset of the next spill record or 0 - BucketEntry[] Entries The bucket entries - -#### Bucket Entry - - uint48 Offset Offset in data file of the data - uint48 Size The size of the value in bytes - uint48 Hash The hash of the key - -### Data File - -The Data File contains the Header followed by zero or more -variable-length Value Records and Spill Records. - -#### Header (92 bytes) - - char[8] Type The characters "nudb.dat" - uint16 Version Holds the version number - uint64 UID Unique ID generated on creation - uint64 Appnum Application defined constant - uint16 KeySize Key size in bytes - uint8[64] (reserved) Zeroes - -UID contains the same value as the salt in the corresponding key -file. This is placed in the data file so that key and value files -belonging to the same database can be identified. - -#### Data Record (variable-length) - - uint48 Size Size of the value in bytes - uint8[KeySize] Key The key. - uint8[Size] Data The value data. - -#### Spill Record (fixed-length) - - uint48 Zero All zero, identifies a spill record - uint16 Size Bytes in spill bucket (for skipping) - Bucket SpillBucket Bucket Record - -#### Log File - -The Log file contains the Header followed by zero or more fixed size -log records. Each log record contains a snapshot of a bucket. When a -database is not closed cleanly, the recovery process applies the log -records to the key file, overwriting data that may be only partially -updated with known good information. After the log records are applied, -the data and key files are truncated to the last known good size. - -#### Header (62 bytes) - - char[8] Type The characters "nudb.log" - uint16 Version Holds the version number - uint64 UID Unique ID generated on creation - uint64 Appnum Application defined constant - uint16 KeySize Key size in bytes - - uint64 Salt A random seed. - uint64 Pepper The salt hashed - uint16 BlockSize Size of a file block in bytes - - uint64 KeyFileSize Size of key file. - uint64 DataFileSize Size of data file. - -#### Log Record - - uint64_t Index Bucket index (0-based) - Bucket Bucket Compact Bucket record - -Compact buckets include only Size entries. These are primarily -used to minimize the volume of writes to the log file. - -## License - -Distributed under the Boost Software License, Version 1.0. -(See accompanying file [LICENSE_1_0.txt](LICENSE_1_0.txt) or copy at -http://www.boost.org/LICENSE_1_0.txt) - -## Contact - -Please report issues or questions here: -https://github.com/vinniefalco/NuDB/issues diff --git a/src/nudb/TODO.txt b/src/nudb/TODO.txt deleted file mode 100644 index 432f762120..0000000000 --- a/src/nudb/TODO.txt +++ /dev/null @@ -1,2 +0,0 @@ -* Support 32/64-bit - -- xxhasher specialization for 4/8 byte size-t diff --git a/src/nudb/bench/CMakeLists.txt b/src/nudb/bench/CMakeLists.txt deleted file mode 100644 index ab96d1df1b..0000000000 --- a/src/nudb/bench/CMakeLists.txt +++ /dev/null @@ -1,363 +0,0 @@ -cmake_minimum_required (VERSION 3.2) - -GroupSources(bench /) -GroupSources(include/nudb nudb) -GroupSources(extras/nudb extras) -GroupSources(extras/beast/include/beast beast) -GroupSources(extras/beast/extras/beast beast) -GroupSources(extras/rocksdb rocksdb) - -if (WIN32) - set(CMAKE_CONFIGURATION_TYPES Release) -endif () - -project (bench) - -############################################################ - -macro(append_flags name) - foreach (arg ${ARGN}) - set(${name} "${${name}} ${arg}") - endforeach() -endmacro() - -############################################################ - -set (DEPS "${PROJECT_SOURCE_DIR}/../extras") - -set (DEFAULT_WITH_ROCKSDB true) - -set (WITH_ROCKSDB ${DEFAULT_WITH_ROCKSDB} CACHE BOOL "Runs benchmarks against rocksdb") - -if (WITH_ROCKSDB) - set(ROCKSDB ${DEPS}/rocksdb) - - set(ROCKSDB_SRC - ${ROCKSDB}/db/auto_roll_logger.cc - ${ROCKSDB}/db/builder.cc - ${ROCKSDB}/db/c.cc - ${ROCKSDB}/db/column_family.cc - ${ROCKSDB}/db/compacted_db_impl.cc - ${ROCKSDB}/db/compaction.cc - ${ROCKSDB}/db/compaction_iterator.cc - ${ROCKSDB}/db/compaction_job.cc - ${ROCKSDB}/db/compaction_picker.cc - ${ROCKSDB}/db/convenience.cc - ${ROCKSDB}/db/db_filesnapshot.cc - ${ROCKSDB}/db/dbformat.cc - ${ROCKSDB}/db/db_impl.cc - ${ROCKSDB}/db/db_impl_debug.cc - ${ROCKSDB}/db/db_impl_readonly.cc - ${ROCKSDB}/db/db_impl_experimental.cc - ${ROCKSDB}/db/db_impl_add_file.cc - ${ROCKSDB}/db/db_info_dumper.cc - ${ROCKSDB}/db/db_iter.cc - ${ROCKSDB}/db/experimental.cc - ${ROCKSDB}/db/event_helpers.cc - ${ROCKSDB}/db/file_indexer.cc - ${ROCKSDB}/db/filename.cc - ${ROCKSDB}/db/flush_job.cc - ${ROCKSDB}/db/flush_scheduler.cc - ${ROCKSDB}/db/forward_iterator.cc - ${ROCKSDB}/db/internal_stats.cc - ${ROCKSDB}/db/log_reader.cc - ${ROCKSDB}/db/log_writer.cc - ${ROCKSDB}/db/managed_iterator.cc - ${ROCKSDB}/db/memtable_allocator.cc - ${ROCKSDB}/db/memtable.cc - ${ROCKSDB}/db/memtable_list.cc - ${ROCKSDB}/db/merge_helper.cc - ${ROCKSDB}/db/merge_operator.cc - ${ROCKSDB}/db/repair.cc - ${ROCKSDB}/db/snapshot_impl.cc - ${ROCKSDB}/db/table_cache.cc - ${ROCKSDB}/db/table_properties_collector.cc - ${ROCKSDB}/db/transaction_log_impl.cc - ${ROCKSDB}/db/version_builder.cc - ${ROCKSDB}/db/version_edit.cc - ${ROCKSDB}/db/version_set.cc - ${ROCKSDB}/db/wal_manager.cc - ${ROCKSDB}/db/write_batch.cc - ${ROCKSDB}/db/write_batch_base.cc - ${ROCKSDB}/db/write_controller.cc - ${ROCKSDB}/db/write_thread.cc - ${ROCKSDB}/db/xfunc_test_points.cc - ${ROCKSDB}/memtable/hash_cuckoo_rep.cc - ${ROCKSDB}/memtable/hash_linklist_rep.cc - ${ROCKSDB}/memtable/hash_skiplist_rep.cc - ${ROCKSDB}/memtable/skiplistrep.cc - ${ROCKSDB}/memtable/vectorrep.cc - ${ROCKSDB}/port/stack_trace.cc - ${ROCKSDB}/table/adaptive_table_factory.cc - ${ROCKSDB}/table/block_based_filter_block.cc - ${ROCKSDB}/table/block_based_table_builder.cc - ${ROCKSDB}/table/block_based_table_factory.cc - ${ROCKSDB}/table/block_based_table_reader.cc - ${ROCKSDB}/table/block_builder.cc - ${ROCKSDB}/table/block.cc - ${ROCKSDB}/table/block_prefix_index.cc - ${ROCKSDB}/table/bloom_block.cc - ${ROCKSDB}/table/cuckoo_table_builder.cc - ${ROCKSDB}/table/cuckoo_table_factory.cc - ${ROCKSDB}/table/cuckoo_table_reader.cc - ${ROCKSDB}/table/flush_block_policy.cc - ${ROCKSDB}/table/format.cc - ${ROCKSDB}/table/full_filter_block.cc - ${ROCKSDB}/table/get_context.cc - ${ROCKSDB}/table/iterator.cc - ${ROCKSDB}/table/merger.cc - ${ROCKSDB}/table/meta_blocks.cc - ${ROCKSDB}/table/sst_file_writer.cc - ${ROCKSDB}/table/plain_table_builder.cc - ${ROCKSDB}/table/plain_table_factory.cc - ${ROCKSDB}/table/plain_table_index.cc - ${ROCKSDB}/table/plain_table_key_coding.cc - ${ROCKSDB}/table/plain_table_reader.cc - ${ROCKSDB}/table/persistent_cache_helper.cc - ${ROCKSDB}/table/table_properties.cc - ${ROCKSDB}/table/two_level_iterator.cc - ${ROCKSDB}/tools/dump/db_dump_tool.cc - ${ROCKSDB}/util/arena.cc - ${ROCKSDB}/util/bloom.cc - # ${ROCKSDB}/util/build_version.cc - ${ROCKSDB}/util/coding.cc - ${ROCKSDB}/util/comparator.cc - ${ROCKSDB}/util/compaction_job_stats_impl.cc - ${ROCKSDB}/util/concurrent_arena.cc - ${ROCKSDB}/util/crc32c.cc - ${ROCKSDB}/util/delete_scheduler.cc - ${ROCKSDB}/util/dynamic_bloom.cc - ${ROCKSDB}/util/env.cc - ${ROCKSDB}/util/env_chroot.cc - ${ROCKSDB}/util/env_hdfs.cc - ${ROCKSDB}/util/file_util.cc - ${ROCKSDB}/util/file_reader_writer.cc - ${ROCKSDB}/util/filter_policy.cc - ${ROCKSDB}/util/hash.cc - ${ROCKSDB}/util/histogram.cc - ${ROCKSDB}/util/histogram_windowing.cc - ${ROCKSDB}/util/instrumented_mutex.cc - ${ROCKSDB}/util/iostats_context.cc - ${ROCKSDB}/util/lru_cache.cc - ${ROCKSDB}/util/threadpool.cc - ${ROCKSDB}/util/transaction_test_util.cc - ${ROCKSDB}/util/sharded_cache.cc - ${ROCKSDB}/util/sst_file_manager_impl.cc - ${ROCKSDB}/utilities/backupable/backupable_db.cc - ${ROCKSDB}/utilities/blob_db/blob_db.cc - ${ROCKSDB}/utilities/convenience/info_log_finder.cc - ${ROCKSDB}/utilities/checkpoint/checkpoint.cc - ${ROCKSDB}/utilities/compaction_filters/remove_emptyvalue_compactionfilter.cc - ${ROCKSDB}/utilities/document/document_db.cc - ${ROCKSDB}/utilities/document/json_document_builder.cc - ${ROCKSDB}/utilities/document/json_document.cc - ${ROCKSDB}/utilities/env_mirror.cc - ${ROCKSDB}/utilities/env_registry.cc - ${ROCKSDB}/utilities/flashcache/flashcache.cc - ${ROCKSDB}/utilities/geodb/geodb_impl.cc - ${ROCKSDB}/utilities/leveldb_options/leveldb_options.cc - ${ROCKSDB}/utilities/memory/memory_util.cc - ${ROCKSDB}/utilities/merge_operators/put.cc - ${ROCKSDB}/utilities/merge_operators/max.cc - ${ROCKSDB}/utilities/merge_operators/string_append/stringappend2.cc - ${ROCKSDB}/utilities/merge_operators/string_append/stringappend.cc - ${ROCKSDB}/utilities/merge_operators/uint64add.cc - ${ROCKSDB}/utilities/option_change_migration/option_change_migration.cc - ${ROCKSDB}/utilities/options/options_util.cc - ${ROCKSDB}/utilities/persistent_cache/persistent_cache_tier.cc - ${ROCKSDB}/utilities/persistent_cache/volatile_tier_impl.cc - ${ROCKSDB}/utilities/persistent_cache/block_cache_tier_file.cc - ${ROCKSDB}/utilities/persistent_cache/block_cache_tier_metadata.cc - ${ROCKSDB}/utilities/persistent_cache/block_cache_tier.cc - ${ROCKSDB}/utilities/redis/redis_lists.cc - ${ROCKSDB}/utilities/simulator_cache/sim_cache.cc - ${ROCKSDB}/utilities/spatialdb/spatial_db.cc - ${ROCKSDB}/utilities/table_properties_collectors/compact_on_deletion_collector.cc - ${ROCKSDB}/utilities/transactions/optimistic_transaction_impl.cc - ${ROCKSDB}/utilities/transactions/optimistic_transaction_db_impl.cc - ${ROCKSDB}/utilities/transactions/transaction_base.cc - ${ROCKSDB}/utilities/transactions/transaction_db_impl.cc - ${ROCKSDB}/utilities/transactions/transaction_db_mutex_impl.cc - ${ROCKSDB}/utilities/transactions/transaction_lock_mgr.cc - ${ROCKSDB}/utilities/transactions/transaction_impl.cc - ${ROCKSDB}/utilities/transactions/transaction_util.cc - ${ROCKSDB}/utilities/ttl/db_ttl_impl.cc - ${ROCKSDB}/utilities/date_tiered/date_tiered_db_impl.cc - ${ROCKSDB}/utilities/write_batch_with_index/write_batch_with_index.cc - ${ROCKSDB}/utilities/write_batch_with_index/write_batch_with_index_internal.cc - ${ROCKSDB}/util/event_logger.cc - ${ROCKSDB}/util/log_buffer.cc - ${ROCKSDB}/util/logging.cc - ${ROCKSDB}/util/memenv.cc - ${ROCKSDB}/util/murmurhash.cc - ${ROCKSDB}/util/mutable_cf_options.cc - ${ROCKSDB}/util/options.cc - ${ROCKSDB}/util/options_helper.cc - ${ROCKSDB}/util/options_parser.cc - ${ROCKSDB}/util/options_sanity_check.cc - ${ROCKSDB}/util/perf_context.cc - ${ROCKSDB}/util/perf_level.cc - ${ROCKSDB}/util/random.cc - ${ROCKSDB}/util/rate_limiter.cc - ${ROCKSDB}/util/slice.cc - ${ROCKSDB}/util/statistics.cc - ${ROCKSDB}/util/status.cc - ${ROCKSDB}/util/status_message.cc - ${ROCKSDB}/util/string_util.cc - ${ROCKSDB}/util/sync_point.cc - ${ROCKSDB}/util/thread_local.cc - ${ROCKSDB}/util/thread_status_impl.cc - ${ROCKSDB}/util/thread_status_updater.cc - ${ROCKSDB}/util/thread_status_updater_debug.cc - ${ROCKSDB}/util/thread_status_util.cc - ${ROCKSDB}/util/thread_status_util_debug.cc - ${ROCKSDB}/util/xfunc.cc - ${ROCKSDB}/util/xxhash.cc - ) - - if (WIN32) - add_definitions( - -DOS_WIN - ) - set(ROCKSDB_SRC ${ROCKSDB_SRC} - ${ROCKSDB}/port/win/io_win.cc - ${ROCKSDB}/port/win/env_default.cc - ${ROCKSDB}/port/win/env_win.cc - ${ROCKSDB}/port/win/port_win.cc - ${ROCKSDB}/port/win/win_logger.cc - ${ROCKSDB}/port/win/xpress_win.cc - ) - else () - #if (${CMAKE_SYSTEM_NAME} MATCHES Linux) - add_definitions( - -DOS_LINUX - -DROCKSDB_PLATFORM_POSIX - -DROCKSDB_LIB_IO_POSIX - ) - set(ROCKSDB_SRC ${ROCKSDB_SRC} - ${ROCKSDB}/util/io_posix.cc - ${ROCKSDB}/util/env_posix.cc - ${ROCKSDB}/port/port_posix.cc - ) - endif () - - include_directories( - SYSTEM - ${ROCKSDB} - ${ROCKSDB}/include - ${ROCKSDB}/third-party/gtest-1.7.0/fused-src - ) - - add_definitions( - -DWITH_ROCKSDB - ) -endif(WITH_ROCKSDB) - -if (NOT WIN32) - append_flags(CMAKE_CXX_FLAGS -std=c++11) -endif () - -if(WIN32) - add_compile_options( - /bigobj # Increase object file max size - /EHa # ExceptionHandling all - /fp:precise # Floating point behavior - /Gd # __cdecl calling convention - /Gm- # Minimal rebuild: disabled - /GR # Enable RTTI - /Gy- # Function level linking: disabled - /FS - /MP # Multiprocessor compilation - /openmp- # pragma omp: disabled - /Zc:forScope # Language extension: for scope - /Zi # Generate complete debug info - /errorReport:none # No error reporting to Internet - /nologo # Suppress login banner - /W3 # Warning level 3 - /WX- # Disable warnings as errors - /wd"4018" - /wd"4244" - /wd"4267" - /wd"4800" # Disable C4800(int to bool performance) - /wd"4503" # Decorated name length exceeded, name was truncated - ) - - add_definitions( - -D_WIN32_WINNT=0x6000 - -D_ITERATOR_DEBUG_LEVEL=0 - -D_SCL_SECURE_NO_WARNINGS - -D_CRT_SECURE_NO_WARNINGS - -DWIN32_CONSOLE - -DNOMINMAX) - - append_flags(CMAKE_EXE_LINKER_FLAGS - /DEBUG - /DYNAMICBASE - /ERRORREPORT:NONE - /MACHINE:X64 - /MANIFEST - /nologo - /NXCOMPAT - /SUBSYSTEM:CONSOLE - /TLBID:1) - - # There seems to be an issue using generator experssions with multiple values, - # split the expression - # /GS Buffers security check: enable - add_compile_options($<$:/GS>) - # /MTd Language: Multi-threaded Debug CRT - add_compile_options($<$:/MTd>) - # /Od Optimization: Disabled - add_compile_options($<$:/Od>) - # /RTC1 Run-time error checks: - add_compile_options($<$:/RTC1>) - - # Generator expressions are not supported in add_definitions, use set_property instead - set_property( - DIRECTORY - APPEND - PROPERTY COMPILE_DEFINITIONS - $<$:_CRTDBG_MAP_ALLOC>) - - # /MT Language: Multi-threaded CRT - add_compile_options($<$:/MT>) - add_compile_options($<$:/Ox>) - # /Ox Optimization: Full - -endif (WIN32) - - -include_directories( - ../include - ../test - . - ${DEPS} - ) - -add_executable(bench - ${BEAST_INCLUDES} - ${EXTRAS_INCLUDES} - ${NUDB_INCLUDES} - ${ROCKSDB_SRC} - bench.cpp - ) - -target_link_libraries(bench - ${Boost_LIBRARIES} - ) - -if (WITH_ROCKSDB) - if (WIN32) - target_link_libraries(bench - Rpcrt4 - ) - else () - target_link_libraries(bench - rt - Threads::Threads - z - snappy - ) - endif () -endif () - diff --git a/src/nudb/bench/Jamfile b/src/nudb/bench/Jamfile deleted file mode 100644 index 42e863e120..0000000000 --- a/src/nudb/bench/Jamfile +++ /dev/null @@ -1,226 +0,0 @@ -# -# Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -# -# Distributed under the Boost Software License, Version 1.0. (See accompanying -# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -# - -# Properties: -# -# with-rocksdb=no|yes Select building with rocksdb support (not supported on windows) - -import feature : feature ; - -path-constant ROCKSDB : ../extras/rocksdb ; - -feature with-rocksdb : no yes : propagated optional ; - -path-constant ROCKSDB_SRC : - $(ROCKSDB)/db/auto_roll_logger.cc - $(ROCKSDB)/db/builder.cc - $(ROCKSDB)/db/c.cc - $(ROCKSDB)/db/column_family.cc - $(ROCKSDB)/db/compacted_db_impl.cc - $(ROCKSDB)/db/compaction.cc - $(ROCKSDB)/db/compaction_iterator.cc - $(ROCKSDB)/db/compaction_job.cc - $(ROCKSDB)/db/compaction_picker.cc - $(ROCKSDB)/db/convenience.cc - $(ROCKSDB)/db/db_filesnapshot.cc - $(ROCKSDB)/db/dbformat.cc - $(ROCKSDB)/db/db_impl.cc - $(ROCKSDB)/db/db_impl_debug.cc - $(ROCKSDB)/db/db_impl_readonly.cc - $(ROCKSDB)/db/db_impl_experimental.cc - $(ROCKSDB)/db/db_impl_add_file.cc - $(ROCKSDB)/db/db_info_dumper.cc - $(ROCKSDB)/db/db_iter.cc - $(ROCKSDB)/db/experimental.cc - $(ROCKSDB)/db/event_helpers.cc - $(ROCKSDB)/db/file_indexer.cc - $(ROCKSDB)/db/filename.cc - $(ROCKSDB)/db/flush_job.cc - $(ROCKSDB)/db/flush_scheduler.cc - $(ROCKSDB)/db/forward_iterator.cc - $(ROCKSDB)/db/internal_stats.cc - $(ROCKSDB)/db/log_reader.cc - $(ROCKSDB)/db/log_writer.cc - $(ROCKSDB)/db/managed_iterator.cc - $(ROCKSDB)/db/memtable_allocator.cc - $(ROCKSDB)/db/memtable.cc - $(ROCKSDB)/db/memtable_list.cc - $(ROCKSDB)/db/merge_helper.cc - $(ROCKSDB)/db/merge_operator.cc - $(ROCKSDB)/db/repair.cc - $(ROCKSDB)/db/snapshot_impl.cc - $(ROCKSDB)/db/table_cache.cc - $(ROCKSDB)/db/table_properties_collector.cc - $(ROCKSDB)/db/transaction_log_impl.cc - $(ROCKSDB)/db/version_builder.cc - $(ROCKSDB)/db/version_edit.cc - $(ROCKSDB)/db/version_set.cc - $(ROCKSDB)/db/wal_manager.cc - $(ROCKSDB)/db/write_batch.cc - $(ROCKSDB)/db/write_batch_base.cc - $(ROCKSDB)/db/write_controller.cc - $(ROCKSDB)/db/write_thread.cc - $(ROCKSDB)/db/xfunc_test_points.cc - $(ROCKSDB)/memtable/hash_cuckoo_rep.cc - $(ROCKSDB)/memtable/hash_linklist_rep.cc - $(ROCKSDB)/memtable/hash_skiplist_rep.cc - $(ROCKSDB)/memtable/skiplistrep.cc - $(ROCKSDB)/memtable/vectorrep.cc - $(ROCKSDB)/port/stack_trace.cc - $(ROCKSDB)/table/adaptive_table_factory.cc - $(ROCKSDB)/table/block_based_filter_block.cc - $(ROCKSDB)/table/block_based_table_builder.cc - $(ROCKSDB)/table/block_based_table_factory.cc - $(ROCKSDB)/table/block_based_table_reader.cc - $(ROCKSDB)/table/block_builder.cc - $(ROCKSDB)/table/block.cc - $(ROCKSDB)/table/block_prefix_index.cc - $(ROCKSDB)/table/bloom_block.cc - $(ROCKSDB)/table/cuckoo_table_builder.cc - $(ROCKSDB)/table/cuckoo_table_factory.cc - $(ROCKSDB)/table/cuckoo_table_reader.cc - $(ROCKSDB)/table/flush_block_policy.cc - $(ROCKSDB)/table/format.cc - $(ROCKSDB)/table/full_filter_block.cc - $(ROCKSDB)/table/get_context.cc - $(ROCKSDB)/table/iterator.cc - $(ROCKSDB)/table/merger.cc - $(ROCKSDB)/table/meta_blocks.cc - $(ROCKSDB)/table/sst_file_writer.cc - $(ROCKSDB)/table/plain_table_builder.cc - $(ROCKSDB)/table/plain_table_factory.cc - $(ROCKSDB)/table/plain_table_index.cc - $(ROCKSDB)/table/plain_table_key_coding.cc - $(ROCKSDB)/table/plain_table_reader.cc - $(ROCKSDB)/table/persistent_cache_helper.cc - $(ROCKSDB)/table/table_properties.cc - $(ROCKSDB)/table/two_level_iterator.cc - $(ROCKSDB)/tools/dump/db_dump_tool.cc - $(ROCKSDB)/util/arena.cc - $(ROCKSDB)/util/bloom.cc - # $(ROCKSDB)/util/build_version.cc - $(ROCKSDB)/util/coding.cc - $(ROCKSDB)/util/comparator.cc - $(ROCKSDB)/util/compaction_job_stats_impl.cc - $(ROCKSDB)/util/concurrent_arena.cc - $(ROCKSDB)/util/crc32c.cc - $(ROCKSDB)/util/delete_scheduler.cc - $(ROCKSDB)/util/dynamic_bloom.cc - $(ROCKSDB)/util/env.cc - $(ROCKSDB)/util/env_chroot.cc - $(ROCKSDB)/util/env_hdfs.cc - $(ROCKSDB)/util/file_util.cc - $(ROCKSDB)/util/file_reader_writer.cc - $(ROCKSDB)/util/filter_policy.cc - $(ROCKSDB)/util/hash.cc - $(ROCKSDB)/util/histogram.cc - $(ROCKSDB)/util/histogram_windowing.cc - $(ROCKSDB)/util/instrumented_mutex.cc - $(ROCKSDB)/util/iostats_context.cc - $(ROCKSDB)/util/lru_cache.cc - $(ROCKSDB)/util/threadpool.cc - $(ROCKSDB)/util/transaction_test_util.cc - $(ROCKSDB)/util/sharded_cache.cc - $(ROCKSDB)/util/sst_file_manager_impl.cc - $(ROCKSDB)/utilities/backupable/backupable_db.cc - $(ROCKSDB)/utilities/blob_db/blob_db.cc - $(ROCKSDB)/utilities/convenience/info_log_finder.cc - $(ROCKSDB)/utilities/checkpoint/checkpoint.cc - $(ROCKSDB)/utilities/compaction_filters/remove_emptyvalue_compactionfilter.cc - $(ROCKSDB)/utilities/document/document_db.cc - $(ROCKSDB)/utilities/document/json_document_builder.cc - $(ROCKSDB)/utilities/document/json_document.cc - $(ROCKSDB)/utilities/env_mirror.cc - $(ROCKSDB)/utilities/env_registry.cc - $(ROCKSDB)/utilities/flashcache/flashcache.cc - $(ROCKSDB)/utilities/geodb/geodb_impl.cc - $(ROCKSDB)/utilities/leveldb_options/leveldb_options.cc - $(ROCKSDB)/utilities/memory/memory_util.cc - $(ROCKSDB)/utilities/merge_operators/put.cc - $(ROCKSDB)/utilities/merge_operators/max.cc - $(ROCKSDB)/utilities/merge_operators/string_append/stringappend2.cc - $(ROCKSDB)/utilities/merge_operators/string_append/stringappend.cc - $(ROCKSDB)/utilities/merge_operators/uint64add.cc - $(ROCKSDB)/utilities/option_change_migration/option_change_migration.cc - $(ROCKSDB)/utilities/options/options_util.cc - $(ROCKSDB)/utilities/persistent_cache/persistent_cache_tier.cc - $(ROCKSDB)/utilities/persistent_cache/volatile_tier_impl.cc - $(ROCKSDB)/utilities/persistent_cache/block_cache_tier_file.cc - $(ROCKSDB)/utilities/persistent_cache/block_cache_tier_metadata.cc - $(ROCKSDB)/utilities/persistent_cache/block_cache_tier.cc - $(ROCKSDB)/utilities/redis/redis_lists.cc - $(ROCKSDB)/utilities/simulator_cache/sim_cache.cc - $(ROCKSDB)/utilities/spatialdb/spatial_db.cc - $(ROCKSDB)/utilities/table_properties_collectors/compact_on_deletion_collector.cc - $(ROCKSDB)/utilities/transactions/optimistic_transaction_impl.cc - $(ROCKSDB)/utilities/transactions/optimistic_transaction_db_impl.cc - $(ROCKSDB)/utilities/transactions/transaction_base.cc - $(ROCKSDB)/utilities/transactions/transaction_db_impl.cc - $(ROCKSDB)/utilities/transactions/transaction_db_mutex_impl.cc - $(ROCKSDB)/utilities/transactions/transaction_lock_mgr.cc - $(ROCKSDB)/utilities/transactions/transaction_impl.cc - $(ROCKSDB)/utilities/transactions/transaction_util.cc - $(ROCKSDB)/utilities/ttl/db_ttl_impl.cc - $(ROCKSDB)/utilities/date_tiered/date_tiered_db_impl.cc - $(ROCKSDB)/utilities/write_batch_with_index/write_batch_with_index.cc - $(ROCKSDB)/utilities/write_batch_with_index/write_batch_with_index_internal.cc - $(ROCKSDB)/util/event_logger.cc - $(ROCKSDB)/util/log_buffer.cc - $(ROCKSDB)/util/logging.cc - $(ROCKSDB)/util/memenv.cc - $(ROCKSDB)/util/murmurhash.cc - $(ROCKSDB)/util/mutable_cf_options.cc - $(ROCKSDB)/util/options.cc - $(ROCKSDB)/util/options_helper.cc - $(ROCKSDB)/util/options_parser.cc - $(ROCKSDB)/util/options_sanity_check.cc - $(ROCKSDB)/util/perf_context.cc - $(ROCKSDB)/util/perf_level.cc - $(ROCKSDB)/util/random.cc - $(ROCKSDB)/util/rate_limiter.cc - $(ROCKSDB)/util/slice.cc - $(ROCKSDB)/util/statistics.cc - $(ROCKSDB)/util/status.cc - $(ROCKSDB)/util/status_message.cc - $(ROCKSDB)/util/string_util.cc - $(ROCKSDB)/util/sync_point.cc - $(ROCKSDB)/util/thread_local.cc - $(ROCKSDB)/util/thread_status_impl.cc - $(ROCKSDB)/util/thread_status_updater.cc - $(ROCKSDB)/util/thread_status_updater_debug.cc - $(ROCKSDB)/util/thread_status_util.cc - $(ROCKSDB)/util/thread_status_util_debug.cc - $(ROCKSDB)/util/xfunc.cc - $(ROCKSDB)/util/xxhash.cc - ; - -path-constant ROCKSDB_POSIX_SRC : - # Posix only - $(ROCKSDB)/util/io_posix.cc - $(ROCKSDB)/util/env_posix.cc - $(ROCKSDB)/port/port_posix.cc - ; - -project bench - : requirements - yes:$(ROCKSDB_SRC) - yes:WITH_ROCKSDB - yes:$(ROCKSDB) - yes:$(ROCKSDB)/include - yes:$(ROCKSDB)/third-party/gtest-1.7.0/fused-src - # Posix only - LINUX,yes:ROCKSDB_PLATFORM_POSIX - LINUX,yes:ROCKSDB_LIB_IO_POSIX - # LINUX Only - LINUX,yes:OS_LINUX - LINUX,yes:/boost/thread//boost_thread - LINUX,yes:$(ROCKSDB_POSIX_SRC) - ; - -exe bench : - bench.cpp - ; \ No newline at end of file diff --git a/src/nudb/bench/README.md b/src/nudb/bench/README.md deleted file mode 100644 index 94d0dbe9b8..0000000000 --- a/src/nudb/bench/README.md +++ /dev/null @@ -1,102 +0,0 @@ -# Benchmarks for NuDB - -These benchmarks time two operations: - -1. The time to insert N values into a database. The inserted keys and values are - pseudo-randomly generated. The random number generator is always seeded with - the same value for each run, so the same values are always inserted. -2. The time to fetch M existing values from a database with N values. The order - that the keys are fetched are pseudo-randomly generated. The random number - generator is always seeded with the same value on each fun, so the keys are - always looked up in the same order. - -At the end of a run, the program outputs a table of operations per second. The -tables have a row for each database size, and a column for each database (in -cases where NuDB is compared against other databases). A cell in the table is -the number of operations per second for that trial. For example, in the table -below NuDB had 340397 Ops/Sec when fetching from an existing database with -10,000,000 values. This is a summary report, and only reports samples at order -of magnitudes of ten. - -A sample output: - -``` -insert (per second) - num_db_keys nudb rocksdb - 100000 406598 231937 - 1000000 374330 258519 - 10000000 NA NA - -fetch (per second) - num_db_keys nudb rocksdb - 100000 325228 697158 - 1000000 333443 34557 - 10000000 337300 20835 -``` - -In addition to the summary report, the benchmark can collect detailed samples. -The `--raw_out` command line options is used to specify a file to output the raw -samples. The python 3 script `plot_bench.py` may be used to plot the result. For -example, if bench was run as `bench --raw_out=samples.txt`, the the python -script can be run as `python plot_bench.py -i samples.txt`. The python script -requires the `pandas` and `seaborn` packages (anaconda python is a good way to -install and manage python if these packages are not already -installed: [anaconda download](https://www.continuum.io/downloads)). - -# Building - -## Building with CMake - -Note: Building with RocksDB is currently not supported on Windows. - -1. The benchmark requires boost. If building with rocksdb, it also requires zlib - and snappy. These are popular libraries and should be available through the - package manager. -1. The benchmark and test programs require some submodules that are not - installed by default. Get these submodules by running: - `git submodule update --init` -2. From the main nudb directory, create a directory for the build and change to - that directory: `mkdir bench_build;cd bench_build` -3. Generate a project file or makefile. - * If building on Linux, generate a makefile. If building with rocksdb - support, use: `cmake -DCMAKE_BUILD_TYPE=Release ../bench` If building - without rocksdb support, use: `cmake -DCMAKE_BUILD_TYPE=Release ../bench - -DWITH_ROCKSDB=false` Replace `../bench` with the path to the `bench` - directory if the build directory is not in the suggested location. - * If building on windows, generate a project file. The CMake gui program is - useful for this. Use the `bench` directory as the `source` directory and - the `bench_build` directory as the `binaries` directory. Press the `Add - Entry` button and add a `BOOST_ROOT` variable that points to the `boost` - directory. Hit `configure`. A dialog box will pop up. Select the generator - for Win64. Select `generate` to generate the visual studio project. -4. Compile the program. - * If building on Linux, run: `make` - * If building on Windows, open the project file generated above in Visual - Studio. - -## Test the build - -Try running the benchmark with a small database: `./bench --num_batches=10`. A -report similar to sample should appear after a few seconds. - -# Command Line Options - -* `batch_size arg` : Number of elements to insert or fetch per batch. If not - specified, it defaults to 20000. -* `num_batches arg` : Number of batches to run. If not specified, it defaults to - 500. -* `db_dir arg` : Directory to place the databases. If not specified, it defaults to - boost::filesystem::temp_directory_path (likely `/tmp` on Linux) -* `raw_out arg` : File to record the raw measurements. This is useful for plotting. If - not specified the raw measurements will not be output. -* `--dbs arg` : Databases to run the benchmark on. Currently, only `nudb` and - `rocksdb` are supported. Building with `rocksdb` is optional on Linux, and - only `nudb` is supported on windows. The argument may be a list. If `dbs` is - not specified, it defaults to all the database the build supports (either - `nudb` or `nudb rocksdb`). -* `--key_size arg` : nudb key size. If not specified the default is 64. -* `--block_size arg` : nudb block size. This is an advanced argument. If not - specified the default is 4096. -* `--load_factor arg` : nudb load factor. This is an advanced argument. If not - specified the default is 0.5. - diff --git a/src/nudb/bench/bench.cpp b/src/nudb/bench/bench.cpp deleted file mode 100644 index ed2c79655d..0000000000 --- a/src/nudb/bench/bench.cpp +++ /dev/null @@ -1,535 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#include -#include -#include - -#if WITH_ROCKSDB -#include "rocksdb/db.h" - -char const* rocksdb_build_git_sha="Benchmark Dummy Sha"; -char const* rocksdb_build_compile_date="Benchmark Dummy Compile Date"; -#endif - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace nudb { -namespace test { - -beast::unit_test::dstream dout{std::cout}; -beast::unit_test::dstream derr{std::cerr}; - -struct stop_watch -{ - using clock = std::chrono::steady_clock; - using time_point = clock::time_point; - time_point start_; - - stop_watch() : start_(clock::now()) - { - } - - std::chrono::duration - elapsed() const - { - return std::chrono::duration_cast>( - clock::now() - start_); - } -}; - -class bench_progress -{ - progress p_; - std::uint64_t const total_=0; - std::uint64_t batch_start_=0; - -public: - bench_progress(std::ostream& os, std::uint64_t total) - : p_(os), total_(total) - { - p_(0, total); - } - void - update(std::uint64_t batch_amount) - { - p_(batch_start_ + batch_amount, total_); - batch_start_ += batch_amount; - } -}; - -class gen_key_value -{ - test_store& ts_; - std::uint64_t cur_; - -public: - gen_key_value(test_store& ts, std::uint64_t cur) - : ts_(ts), - cur_(cur) - { - } - item_type - operator()() - { - return ts_[cur_++]; - } -}; - -class rand_existing_key -{ - xor_shift_engine rng_; - std::uniform_int_distribution dist_; - test_store& ts_; - - public: - rand_existing_key(test_store& ts, - std::uint64_t max_index, - std::uint64_t seed = 1337) - : dist_(0, max_index), - ts_(ts) - { - rng_.seed(seed); - } - item_type - operator()() - { - return ts_[dist_(rng_)]; - } -}; - - -template -std::chrono::duration -time_block(std::uint64_t n, Generator&& g, F&& f) -{ - stop_watch timer; - for (std::uint64_t i = 0; i < n; ++i) - { - f(g()); - } - return timer.elapsed(); -} - -template -void -time_fetch_insert_interleaved( - std::uint64_t batch_size, - std::uint64_t num_batches, - test_store& ts, - Inserter&& inserter, - Fetcher&& fetcher, - AddSample&& add_sample, - PreFetchHook&& pre_fetch_hook, - bench_progress& progress) -{ - std::uint64_t next_insert_index = 0; - for (auto b = 0ull; b < num_batches; ++b) - { - auto const insert_time = time_block( - batch_size, gen_key_value{ts, next_insert_index}, inserter); - add_sample( - "insert", next_insert_index, batch_size / insert_time.count()); - next_insert_index += batch_size; - progress.update(batch_size); - pre_fetch_hook(); - auto const fetch_time = time_block( - batch_size, rand_existing_key{ts, next_insert_index - 1}, fetcher); - add_sample("fetch", next_insert_index, batch_size / fetch_time.count()); - progress.update(batch_size); - } -} - -#if WITH_ROCKSDB -template -void -do_timings_rocks( - std::string const& db_dir, - std::uint64_t batch_size, - std::uint64_t num_batches, - std::uint32_t key_size, - AddSample&& add_sample, - bench_progress& progress) -{ - temp_dir td{db_dir}; - std::unique_ptr pdb = [&td] { - rocksdb::DB* db = nullptr; - rocksdb::Options options; - options.create_if_missing = true; - auto const status = rocksdb::DB::Open(options, td.path(), &db); - if (!status.ok()) - db = nullptr; - return std::unique_ptr{db}; - }(); - - if (!pdb) - { - derr << "Failed to open rocks db.\n"; - return; - } - - auto inserter = [key_size, &pdb](item_type const& v) { - auto const s = pdb->Put(rocksdb::WriteOptions(), - rocksdb::Slice(reinterpret_cast(v.key), key_size), - rocksdb::Slice(reinterpret_cast(v.data), v.size)); - if (!s.ok()) - throw std::runtime_error("Rocks Insert: " + s.ToString()); - }; - - auto fetcher = [key_size, &pdb](item_type const& v) { - std::string value; - auto const s = pdb->Get(rocksdb::ReadOptions(), - rocksdb::Slice(reinterpret_cast(v.key), key_size), - &value); - if (!s.ok()) - throw std::runtime_error("Rocks Fetch: " + s.ToString()); - }; - - test_store ts{key_size, 0, 0}; - try - { - time_fetch_insert_interleaved(batch_size, num_batches, ts, - std::move(inserter), std::move(fetcher), - std::forward(add_sample), [] {}, progress); - } - catch (std::exception const& e) - { - derr << "Error: " << e.what() << '\n'; - } -} -#endif - -template -void -do_timings(std::string const& db_dir, - std::uint64_t batch_size, - std::uint64_t num_batches, - std::uint32_t key_size, - std::size_t block_size, - float load_factor, - AddSample&& add_sample, - bench_progress& progress) -{ - boost::system::error_code ec; - - try - { - test_store ts{db_dir, key_size, block_size, load_factor}; - ts.create(ec); - if (ec) - goto fail; - ts.open(ec); - if (ec) - goto fail; - - auto inserter = [&ts, &ec](item_type const& v) { - ts.db.insert(v.key, v.data, v.size, ec); - if (ec) - throw boost::system::system_error(ec); - }; - - auto fetcher = [&ts, &ec](item_type const& v) { - ts.db.fetch(v.key, [&](void const* data, std::size_t size) {}, ec); - if (ec) - throw boost::system::system_error(ec); - }; - - auto pre_fetch_hook = [&ts, &ec]() { - // Close then open the db otherwise the - // commit thread confounds the timings - ts.close(ec); - if (ec) - throw boost::system::system_error(ec); - ts.open(ec); - if (ec) - throw boost::system::system_error(ec); - }; - - time_fetch_insert_interleaved(batch_size, num_batches, ts, - std::move(inserter), std::move(fetcher), - std::forward(add_sample), std::move(pre_fetch_hook), - progress); - } - catch (boost::system::system_error const& e) - { - ec = e.code(); - } - catch (std::exception const& e) - { - derr << "Error: " << e.what() << '\n'; - } - -fail: - if (ec) - derr << "Error: " << ec.message() << '\n'; - - return; -} - -namespace po = boost::program_options; - -void -print_help(std::string const& prog_name, const po::options_description& desc) -{ - derr << prog_name << ' ' << desc; -} - -po::variables_map -parse_args(int argc, char** argv, po::options_description& desc) -{ - -#if WITH_ROCKSDB - std::vector const default_dbs = {"nudb", "rocksdb"}; -#else - std::vector const default_dbs = {"nudb"}; -#endif - std::vector const default_ops({100000,1000000}); - - desc.add_options() - ("help,h", "Display this message.") - ("batch_size", - po::value(), - "Batch Size Default: 20000)") - ("num_batches", - po::value(), - "Num Batches Default: 500)") - ("dbs", - po::value>()->multitoken(), - "databases (Default: nudb rocksdb)") - ("block_size", po::value(), - "nudb block size (default: 4096)") - ("key_size", po::value(), - "key size (default: 64)") - ("load_factor", po::value(), - "nudb load factor (default: 0.5)") - ("db_dir", po::value(), - "Directory to place the databases" - " (default: boost::filesystem::temp_directory_path)") - ("raw_out", po::value(), - "File to record the raw measurements (useful for plotting)" - " (default: no output)") - ; - - po::variables_map vm; - po::store(po::command_line_parser(argc, argv).options(desc).run(), vm); - po::notify(vm); - - return vm; -} - -template -T -get_opt(po::variables_map const& vm, std::string const& key, T const& default_value) -{ - return vm.count(key) ? vm[key].as() : default_value; -} - -} // test -} // nudb - -int -main(int argc, char** argv) -{ - using namespace nudb::test; - - po::variables_map vm; - - { - po::options_description desc{"Benchmark Options"}; - bool parse_error = false; - try - { - vm = parse_args(argc, argv, desc); - } - catch (std::exception const& e) - { - derr << "Incorrect command line syntax.\n"; - derr << "Exception: " << e.what() << '\n'; - parse_error = true; - } - - if (vm.count("help") || parse_error) - { - auto prog_name = boost::filesystem::path(argv[0]).stem().string(); - print_help(prog_name, desc); - return 0; - } - } - - auto const batch_size = get_opt(vm, "batch_size", 20000); - auto const num_batches = get_opt(vm, "num_batches", 500); - auto const block_size = get_opt(vm, "block_size", 4096); - auto const load_factor = get_opt(vm, "load_factor", 0.5f); - auto const key_size = get_opt(vm, "key_size", 64); - auto const db_dir = [&vm]() -> std::string { - auto r = get_opt(vm, "db_dir", ""); - if (!r.empty() && r.back() != '/' && r.back() != '\\') - { - r += '/'; - } - return r; - }(); - auto const raw_out = get_opt(vm, "raw_out", ""); -#if WITH_ROCKSDB - std::vector const default_dbs({"nudb", "rocksdb"}); -#else - std::vector const default_dbs({"nudb"}); -#endif - auto to_set = [](std::vector const& v) { - return std::set(v.begin(), v.end()); - }; - auto const dbs = to_set(get_opt>(vm, "dbs", default_dbs)); - - for (auto const& db : dbs) - { - if (db == "rocksdb") - { -#if !WITH_ROCKSDB - derr << "Benchmark was not built with rocksdb support\n"; - exit(1); -#endif - continue; - } - - if (db != "nudb" && db != "rocksdb") - { - derr << "Unsupported database: " << db << '\n'; - exit(1); - } - } - - bool const with_rocksdb = dbs.count("rocksdb") != 0; - (void) with_rocksdb; - bool const with_nudb = dbs.count("nudb") != 0; - std::uint64_t const num_db = int(with_nudb) + int(with_rocksdb); - std::uint64_t const total_ops = num_db * batch_size * num_batches * 2; - bench_progress progress(derr, total_ops); - - enum - { - db_nudb, - db_rocks, - db_last - }; - enum - { - op_insert, - op_fetch, - op_last - }; - std::array db_names{{"nudb", "rocksdb"}}; - std::array op_names{{"insert", "fetch"}}; - using result_dict = boost::container::flat_multimap; - result_dict ops_per_sec[db_last][op_last]; - // Reserve up front to database that run later don't have less memory - for (int i = 0; i < db_last; ++i) - for (int j = 0; j < op_last; ++j) - ops_per_sec[i][j].reserve(num_batches); - - std::ofstream raw_out_stream; - bool const record_raw_out = !raw_out.empty(); - if (record_raw_out) - { - raw_out_stream.open(raw_out, std::ios::trunc); - raw_out_stream << "num_db_items,db,op,ops/sec\n"; - } - for (int i = 0; i < db_last; ++i) - { - auto result = [&] - (std::string const& op_name, std::uint64_t num_items, - double sample) { - auto op_idx = op_name == "insert" ? op_insert : op_fetch; - ops_per_sec[i][op_idx].emplace(num_items, sample); - if (record_raw_out) - raw_out_stream << num_items << ',' << db_names[i] << ',' - << op_name << ',' << std::fixed << sample - << std::endl; // flush - - }; - if (with_nudb && i == db_nudb) - do_timings(db_dir, batch_size, num_batches, key_size, block_size, - load_factor, result, progress); -#if WITH_ROCKSDB - if (with_rocksdb && i == db_rocks) - do_timings_rocks( - db_dir, batch_size, num_batches, key_size, result, progress); -#endif - } - - // Write summary by sampling raw data at powers of 10 - auto const col_w = 14; - auto const iter_w = 15; - - for (int op_idx = 0; op_idx < op_last; ++op_idx) - { - auto const& t = op_names[op_idx]; - dout << '\n' << t << " (per second)\n"; - dout << std::setw(iter_w) << "num_db_keys"; - if (with_nudb) - dout << std::setw(col_w) << "nudb"; -#if WITH_ROCKSDB - if (with_rocksdb) - dout << std::setw(col_w) << "rocksdb"; -#endif - dout << '\n'; - auto const max_sample = [&ops_per_sec] { - std::uint64_t r = 0; - for (auto i = 0; i < db_last; ++i) - for (auto j = 0; j < op_last; ++j) - if (!ops_per_sec[i][j].empty()) - r = std::max(r, ops_per_sec[i][j].rbegin()->first); // no `back()` - return r; - }(); - auto const min_sample = batch_size; - - auto write_val = [&]( - result_dict const& dict, std::uint64_t key) { - dout << std::setw(col_w) << std::fixed << std::setprecision(2); - // Take the average of all the values, or "NA" if none collected - auto l = dict.lower_bound(key); - auto u = dict.upper_bound(key); - if (l == u) - dout << "NA"; - else - { - auto const total = std::accumulate(l, u, 0, - [](double a, std::pair const& b) { - return a + b.second; - }); - dout << total / std::distance(l, u); - } - }; - for (std::uint64_t n = 100; n <= max_sample; n *= 10) - { - if (n=500000], hue='db', col='op') - plt.show(p) - return d # for testing - - -def parse_args(): - parser = argparse.ArgumentParser( - description=('Plot the benchmark results')) - parser.add_argument( - '--input', - '-i', - help=('input'), ) - return parser.parse_args() - - -if __name__ == '__main__': - args = parse_args() - result_filename = args.input - if not result_filename: - print('No result file specified. Exiting') - else: - run_main(result_filename) diff --git a/src/nudb/doc/.gitignore b/src/nudb/doc/.gitignore deleted file mode 100644 index fc40be018b..0000000000 --- a/src/nudb/doc/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -bin -html -temp -reference.qbk -out.txt diff --git a/src/nudb/doc/Jamfile.v2 b/src/nudb/doc/Jamfile.v2 deleted file mode 100644 index 6b3a8e0d2e..0000000000 --- a/src/nudb/doc/Jamfile.v2 +++ /dev/null @@ -1,77 +0,0 @@ -# -# Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -# -# Distributed under the Boost Software License, Version 1.0. (See accompanying -# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -# - -import os ; - -local broot = [ os.environ BOOST_ROOT ] ; - -project nudb/doc ; - -using boostbook ; -using quickbook ; -using doxygen ; - -path-constant out : . ; - -install stylesheets - : - $(broot)/doc/src/boostbook.css - : - $(out)/html - ; - -explicit stylesheets ; - -install images - : - [ glob $(broot)/doc/src/images/*.png ] - images/logo.png - : - $(out)/html/images - ; - -explicit images ; - -install callouts - : - [ glob $(broot)/doc/src/images/callouts/*.png ] - : - $(out)/html/images/callouts - ; - -explicit callout ; - -xml doc - : - main.qbk - : - temp - $(broot)/tools/boostbook/dtd - ; - -boostbook boostdoc - : - doc - : - chapter.autolabel=0 - boost.image.src=images/logo.png - boost.image.alt="NuDB Logo" - boost.image.w=1270 - boost.image.h=80 - boost.root=$(broot) - chapter.autolabel=0 - chunk.first.sections=1 # Chunk the first top-level section? - chunk.section.depth=8 # Depth to which sections should be chunked - generate.section.toc.level=1 # Control depth of TOC generation in sections - toc.max.depth=2 # How many levels should be created for each TOC? - toc.section.depth=2 # How deep should recursive sections appear in the TOC? - generate.toc="chapter nop section nop" - : - temp - stylesheets - images - ; diff --git a/src/nudb/doc/boostbook.dtd b/src/nudb/doc/boostbook.dtd deleted file mode 100644 index bd4c3f871e..0000000000 --- a/src/nudb/doc/boostbook.dtd +++ /dev/null @@ -1,439 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -%DocBook; diff --git a/src/nudb/doc/docca b/src/nudb/doc/docca deleted file mode 160000 index 335dbf9c36..0000000000 --- a/src/nudb/doc/docca +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 335dbf9c3613e997ed56d540cc8c5ff2e28cab2d diff --git a/src/nudb/doc/images/logo.png b/src/nudb/doc/images/logo.png deleted file mode 100644 index 8636189ae947810fac2623e58dbe0bff38d49637..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 153828 zcmaI7b95$A(=QrMY}=gJwrx94%!zH=HYc_{nc$h&wkJ-WSa;s7{sXJM^ zd78RdfQbT}%q&P{9Zan()GSN^-amjA0$^Z};RAfVOxbmj9BB>yj5zJK(8x|zvI|BJ=VPLTY68KtABLMra$VnNEu z#Lj5W!pcg@#l^(R!O6wN%0SA-!pg?X^6%tgWaZ%Ft9Qd+}h2}nU9&-)6tWNKZvGgPVR1kg4WX{?Boi6#r4>%qQ+*Ve01OqT%FZ|KGEy zV(sMS&tymX&ZacXzOGbo*~v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9JB&^DwufsdG0#cWDj<9KxT>DP~b*Xz9+txv>AvQO;%_-K4I52LI)ndMX|T;3(( z5h)IJ;z2q9N%)kIy@K)sOgXwIIyA@SmTbXQ@$v+&B& qf5AK4ds)ZlYR diff --git a/src/nudb/doc/images/logo.psd b/src/nudb/doc/images/logo.psd deleted file mode 100644 index 8a4669aab064709e9b6629ec4d924a1d71aba3f2..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 737507 zcmeFa2Vi7nxjue+Z_{T|C%tDTWwX11U3NEHWt*F&ib^(_O~R%znQXy=AmX)LQB+h= zsaFNP;4gD;7{d1r$WYidX)~ENA z*Z%U-{-&qjddg$-SNt||(-=EfPv?$**YPJDoEaM4m&(NVq(;Z5R@MIczi+OMkB_XX zJ!RRp_0d;GnvW^#SczSOwINmTvayygS*| zok-$;Uq@GO|FXXR?&a~^t9G@4qvO*fd;52--8UvNJG5tdF0-n(mIf-k za_gF$DGW3<+sW40IXpd?I5;$u=;}-+3O(b-<3W@DfplspGo9W&Jw35HyYii5)0yen zvFVxkz+hjz`IPagk?8}oEypJgzkFf*g`QIDhccLh#RVSQ|y9vRddMUm(*U#|@ zB61PY*^Uyu4r_nD%@`Rj?8VGndV+2F$Z#Sxk(x|RWoEG-U5oc)WVnCtbb4|qvwCP| zW@3DJh_*bje`+MRku&+7IXEC+Rg+U6FU&Kg-(?_yX;Z*;?^u%-;JCs`8b9~}x z%|%e*eJ*2TAM80hO-+1J<6-Pu*#P0@8n?PquDU}o#kp;US{ zzjIkBVf(jkXmoLFeq$%b*?!IprDs#S56z@j)$U5oPS2%>Q^hiq?TPMLm^T}1`_N=+ zHFhsPIJmxevI{2{=6cLdXy(W4gq=LRlPt4NjQ{=Cw0&;V zqa*kGZzjTkylvZ#E(m!sIt`=X*G~`65f0_L9YMD%maRyxNN(uqUeULfx?Q=Vd&T`h|3VlrD}KX7l(gwAP`;Y|jLIFm?9gR-z;!_X`zp zwuAjc!vw;she=JQMvhM`YF(Jtf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sCzNmj3eZ>W;EqN1Bw8EhhTr{4C&5&<8`!PRJ@=UL&VwFWAu)x}8uqE+*1 z=;3J32l^)Fw>B2p%dDAhj=st8fSpwBN$|kX=ySb95VY5!*DIp5HO6m z8BU0ZV>DkzTObw-Is7>)cFG`y`KBZx%>~IFE?xid|s>j<5d=~l%;RIBw!9g?@ zUezENiwxi`9G&#j?9H8XP-ZfdU=a@2efoIs;yX38s|@|Xw;)3{PVj8GQDA5xwzksA zL2ZZep?;cF2e>nk8FXV~Fc@R-Hnv2y0&seK#l!tVB%MO!z^Ft6!S*G3S%lAPn?aiD zY1zjK%xSz4W8mPb%)+mG^~0Ijuk!QQnPYSl(ktbgDCb0kYnXF_0SVF#1>m#*+>aPl zGBJaIGSiOHw3zqv(esme9_GU7Wg7Dbt}{`k;c*6|C}-u7A;@rJg7agD6y+SCbf^26 zG@1^iVc}NrVVK+YE0R-h3l>s{K+w+7ax#;2QQ9+Gg%qJQg9&i~9 z=$}Ri6QRi$#y^o+DS&Z>!bXjBivqkpArLf&xa#68OAwWg&k(m#5$Op*3VMnfpHdVsC?79rIuVjIL&%PZ(*3mnUmG4 OyY&x2?(~-zasLOM7$)5S diff --git a/src/nudb/doc/images/readme2.png b/src/nudb/doc/images/readme2.png deleted file mode 100644 index fc130b61565ef6154763bd17ce82844fe2469ca1..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 106410 zcmaI7byOU|w=RlXaCZiGcXtbJL4q^LV1o?q5L^d$*FbOy5Zr@9fWTnE39dl`y!_6+ z=ic|nJFi!-?y6qj{`Rh2d#&nS605DLjDTaF+m|QK4HNBzUcmG^8nh3 z=_)AwZ(aXtl5`Fbh?^KUw~vnxmk&P|*u$QiS5#E=KOB5~oc|D4mPx}96 zP_Xs1@c_9&KwwwEe;BQ-!Cnwax__4buO_&-{U2Ia&;RYFe-7jJwQ}R;<>L8Ill~j1 zq4EC@b#eJWXitc)?f{G`|H5l%h^e}ILabbEY*iH`>HaZrfj~epMSe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_pPeGNxgMIouH1J5}QbXk`sPr9bYpeR+Ii<~}vpq%po#!9(z zhUE%U-z@8L%`@#-MtYC;_y7A(k8gg2dFo<}Az9b$+IDJevEPXV83sQvC*~mluOlen zlttdR9iYz)B2m1UV0#%h^OB6+mvfFiq0VgrR9g%Y~Lu&8z}pN=Ps z`M3Y`?@v$9mq*JF@lD%zFxukqtPmPDuN4$M7xCPkn(QC|zSYaty$gogRqu@al_UN8jVSA6`HIvWwx(_do2ndq9V~ zWRyU4zcpB&cz!g4pnvl4N-0KUbeQ8pKfJ0&+g)>Yd9(cDi?>%-br(j*<1SO!ow65n{Zsd#!BRCVEFP^Juu{#UHdO&WEI7wJ7d$}mH z^X#+sddv=6DzFTH7M)~48cJnDM+c{yj7AhvS}I*i?k^P9%AkJq|G z-As9d8Ub}K5pIVy#J?rJ1X;W<$3$LFN#fGbfb^0M^#hU0{zhFx)=Bz5}c&f#tm%_rbIc%&BykBGXWl2eCj<9zGM}P)#pHu7(8})N=zre*V*js_|@01ZDB6oynFxG zw-TG-Jcrf4$nJumL&>INVCLfJWHc-9ZtpZ}_GdDxXZE2Q6a$80kPit{ry1HQR50+m zOkvB(sCTZdo1cxrl0=mdCgRT&OJx0;du8`-_2)P4yGU(3<&t8LeTMc)$}>r_@{{5M zMVz15+J%XcfVI&vB{eKx$i_BWj5?^22E`wJNjV-><9^?`%})D7+=pRr-4!{u z2EzU}uuu}esZ=$KBDjFi23A@WcuFP - - - - -

- Index - -
diff --git a/src/nudb/doc/main.qbk b/src/nudb/doc/main.qbk deleted file mode 100644 index 8ab0d4eb04..0000000000 --- a/src/nudb/doc/main.qbk +++ /dev/null @@ -1,342 +0,0 @@ -[/ - Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -] - -[library NuDB - [quickbook 1.6] - [copyright 2015 - 2016 Vinnie Falco] - [purpose C++ Library] - [license - Distributed under the Boost Software License, Version 1.0. - (See accompanying file LICENSE_1_0.txt or copy at - [@http://www.boost.org/LICENSE_1_0.txt]) - ] - [authors [Falco, Vinnie]] - [category template] - [category generic] -] - -[template mdash[] '''— '''] -[template indexterm1[term1] ''''''[term1]''''''] -[template indexterm2[term1 term2] ''''''[term1]''''''[term2]''''''] - -[variablelist - [[ - [link nudb.overview Overview] - ][ - An overview of features, requirements, and credits, plus - rationale and design information. - ]] - [[ - [link nudb.example Example] - ][ - An example that illustrates the use of NuDB. - ]] - [[ - [link nudb.usage Usage] - ][ - An explanation of operations on the database. - ]] - [[ - [link nudb.ref Reference] - ][ - Detailed class and function reference. - ]] - [[ - [link nudb.index Index] - ][ - Book-style text index of the documentation. - ]] -] - -[section:overview Overview] - -NuDB is an append only, key/value store specifically optimized for random -read performance on modern SSDs or equivalent high-IOPS decices. The most -common application for NuDB is content addressible storage where a -cryptographic digest of the data is used as the key. The read performance -and memory usage are independent of the size of the database. These are -some other features: - -[heading History] - -The first versions of rippled, the application behind the Ripple consensus -network, used SQLite as their back end for unstructured data. The -performance quickly became a limiting factor. - -Then rippled then went through a series of back ends including LMDB, LevelDB, and -RocksDB. Each of these databases performed well at first, but as the data -size increased, memory usage increased and performance dropped off drastically. - -The problem is caching. Each of these databases relies on some O(n) data -structure, such as a Bloom filter, to improve their performance. These work -well until the structures no longer fit in memory. In addition, many virtual -machines are memory constrained. - -To address this issue, the developers performed a thought experiment -- if -you assume the data size is so large that no O(n) caching is effective, what -is the best read performance you could expect? They reached the following -conclusions: - -1) Writes should not block reads. -2) Reads should be limited only by the SSD's IOPS limit. -3) A read for a non-present key should require one IOP. -4) A read for a present key whose data can be read in a single IOP should -only require two IOPs, one to figure out where it is and one to read it in. - -NuDB is designed to come as close to this ideal as possible. - -[heading Design] - -NuDB uses three files to hold the data and indexes. The data file is append -only and contains sufficient information to rebuild the index. The index -file is random access and contains hash buckets. When an update is in -progress, a temporary journal file is used to roll the update back if -needed. - -NuDB uses linear hashing to dynamically increase the number of buckets in -the index file as the data size grows. Bucket overflows are handled by -adding "overflow" records to the data file. Bucket overflows can be -minimized by increasing the number of buckets, leading to a size/speed -tradeoff. Typical databases keep the average bucket half full (or half -empty, depending on your point of view) resulting in spill records -accounting for less than 1% of reads. - -Inserts are buffered in memory and appended to the data file immediately. -Updates to the index file are performed as an atomic operation. Fetch -operations retrieve records in the process of being modified from memory -during the update operation so that writes do not block fetches. - -Before the index file is modified, a journal file is created to recover -consistency in the event of a crash during the update. The recovery process -will index all records written to the data file, so the aggregation of index -updates does not increase the time which a crash would result in loss of -data. - -Iteration can be performed on the data file directly. Since it is append -only, there is no risk of other operations corrupting an iteration in -progress. - -[heading Performance] - -Writes do not block reads. Read rates are typically around 90% of the SSD's -IOPS limit. An average fetch for a non-present key typically requires fewer -than 1.01 IOPs. An average fetch for a present key requires fewer than 1.01 -IOPs plus however many IOPs it takes to read the data. - -[heading Applications] - -Content addressable storage associates data with its cryptographic digest. -This type of storage is commonly used in decentralized blockchain applications. - -Often these applications require following hash chains -- where one object -contains the hash of another object that ultimately leads to the object -desired. NuDB's low latency and high speed are particularly advantageous -in these kinds of applications. - -NuDB is append only and does not support a delete operation. To support -retaining limited historical information, NuDB is often used in a dual -database configuration. One database is older and is read only, the other -is newer and is read/write. Periodically, the older database is discarded and -the newer database becomes the new read only database and a new read/write -database is created. - -[endsect] - - - -[section:example Example] - -This complete program creates a database, opens the database, inserts several -key/value pairs, fetches the key/value pairs, closes the database, then erases -the database files. Source code for this program is located in the examples -directory. - -``` -#include -#include -#include - -int main() -{ - using namespace nudb; - std::size_t constexpr N = 1000; - using key_type = std::uint32_t; - error_code ec; - auto const dat_path = "db.dat"; - auto const key_path = "db.key"; - auto const log_path = "db.log"; - create( - dat_path, key_path, log_path, - 1, - make_salt(), - sizeof(key_type), - block_size("."), - 0.5f, - ec); - store db; - db.open(dat_path, key_path, log_path, - 16 * 1024 * 1024, ec); - char data = 0; - // Insert - for(key_type i = 0; i < N; ++i) - db.insert(&i, &data, sizeof(data), ec); - // Fetch - for(key_type i = 0; i < N; ++i) - db.fetch(&i, - [&](void const* buffer, std::size_t size) - { - // do something with buffer, size - }, ec); - db.close(ec); - erase_file(dat_path); - erase_file(key_path); - erase_file(log_path); -} -``` - -[endsect] - - - -[section:usage Usage] - -[heading Files] - -A database is represented by three files: the data file, the key file, -and the log file. Each file has a distinct header in a well known format. -The data file holds all of the key/value pairs and is serially iterable. The -key file holds a hash table indexing all of the contents in the data file. -The log file holds information used to roll the database back in the event -of a failure. - -[heading Create/Open] - -The [link nudb.ref.nudb__create create] function creates a new data file and key -file for a database with the specified parameters. The caller specifies -the hash function to use as a template argument, the file paths, -and the database constants: - -[note - Sample code and identifiers mentioned in this section are written - as if the following declarations are in effect: - ``` - #include - using namespace nudb; - error_code ec; - ``` -] - -``` -create( - "nudb.dat", // Path to data file - "nudb.key", // Path to key file - "nudb.log", // Path to log file - 1, // Application-defined constant - make_salt(), // A random integer - 4, // The size of keys - block_size(".") // Block size in key file - 0.5f // The load factor - ec); -``` - -The application-defined constant is a 64-bit unsigned integer which the -caller may set to any value. This value can be retrieved from an open -database, where it will be equal to the value used at creation time. This -constant can be used for any purpose. For example, to inform the application -of what application-specific version was used to create the database. - -The salt is a 64-bit unsigned integer used to prevent algorithmic complexity -attacks. Hash functions used during database operations are constructed with -the salt, providing an opportunity to permute the hash function. This feature -is useful when inserted database keys come from untrusted sources, such as the -network. - -The key size is specified when the database is created, and cannot be changed. -All key files indexing the same data file will use the key size of the data -file. - -The block size indicates the size of buckets in the key file. The best choice -for the block size is the natural sector size of the device. For most SSDs -in production today this is 4096, or less often 8192 or 16384. The function -[link nudb.ref.nudb__block_size block_size] returns the best guess of the block -size used by the device mounted at the specified path. - -The load factor determines the target bucket occupancy fraction. There is -almost never a need to specify anything other than the recommended value of -0.5, which strikes the perfect balance of space-efficiency and fast lookup. - -An open database is represented by objects of type -[link nudb.ref.nudb__basic_store basic_store], templated on the hasher. The type -alias [link nudb.ref.nudb__store store] represents a database using -[link nudb.ref.nudb__xxhasher xxhasher], the default hash function. To open -a database, declare a database object and then call the -[link nudb.ref.nudb__basic_store.open open] member function: - -``` -store db; -db.open("nudb.dat", "nudb.key", "nudb.log", ec); -``` - -When opening a database that was previously opened by a program that was -terminated abnormally, the implementation automatically invokes the -recovery process. This process restores the integrity of the database by -replaying the log file if it is present. - -[heading Insert/Fetch] - -Once a database is open, it becomes possible to insert new key/value pairs -and look them up. Insertions are straightforward: - -``` -db.insert(key, data, bytes, ec); -``` - -If the key already exists, the error is set to -[link nudb.ref.nudb__error.key_exists error::key_exists]. All keys in a NuDB -database must be unique. Multiple threads can call insert at the same time. -Internally however, insertions are serialized to present a consistent view -of the database to callers. - -Retrieving a key/value pair if it exists is similary straightforward: - -``` -db.fetch(key, - [&](void const* buffer, std::size_t size) - { - ... - }, ec); -``` - -To give callers control over memory allocation strategies, the fetch -function takes a callback object as a parameter. The callback is invoked -with a pointer to the data and size, if the item exists in the database. -The callback can decide how to store this information, if at all. - -[endsect] - -[section Command Line Tool] - -To allow administration, NuDB comes with the "nudb" command line tool, -which may be built using b2 or CMake. Files for the tool are located in -the "tools" directory. Once the tool is built, and located in your path, -execute this command for additional instructions: - -``` -nudb help -``` - -[endsect] - -[section:ref Reference] -[xinclude quickref.xml] -[include types/File.qbk] -[include types/Hasher.qbk] -[include types/Progress.qbk] -[include reference.qbk] -[endsect] - -[xinclude index.xml] diff --git a/src/nudb/doc/makeqbk.sh b/src/nudb/doc/makeqbk.sh deleted file mode 100644 index 3da8c0790f..0000000000 --- a/src/nudb/doc/makeqbk.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/bash - -# Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -# -# Distributed under the Boost Software License, Version 1.0. (See accompanying -# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - -mkdir -p temp -doxygen source.dox -cd temp -xsltproc combine.xslt index.xml > all.xml -xsltproc ../reference.xsl all.xml > ../reference.qbk diff --git a/src/nudb/doc/quickref.xml b/src/nudb/doc/quickref.xml deleted file mode 100644 index 243e57cb94..0000000000 --- a/src/nudb/doc/quickref.xml +++ /dev/null @@ -1,82 +0,0 @@ - - - - - - - - - - - - - - NuDB - - - - - - - Classes - - basic_store - native_file - no_progress - posix_file - store - win32_file - xxhasher - - Constants - - errc - error - file_mode - - - - Functions - - block_size - create - erase_file - make_error_code - recover - rekey - verify - visit - - Type Traits - - is_File - is_Hasher - is_Progress - - - - Types - - error_category - error_code - error_condition - path_type - system_error - verify_info - - Concepts - - File - Progress - Hasher - - - - - - diff --git a/src/nudb/doc/reference.xsl b/src/nudb/doc/reference.xsl deleted file mode 100644 index ec2a22d30e..0000000000 --- a/src/nudb/doc/reference.xsl +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/src/nudb/doc/source.dox b/src/nudb/doc/source.dox deleted file mode 100644 index 73bff7b030..0000000000 --- a/src/nudb/doc/source.dox +++ /dev/null @@ -1,333 +0,0 @@ -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- -DOXYFILE_ENCODING = UTF-8 -PROJECT_NAME = "NuDB" -PROJECT_NUMBER = -PROJECT_BRIEF = C++ Library -PROJECT_LOGO = -OUTPUT_DIRECTORY = -CREATE_SUBDIRS = NO -ALLOW_UNICODE_NAMES = NO -OUTPUT_LANGUAGE = English -BRIEF_MEMBER_DESC = YES -REPEAT_BRIEF = YES -ABBREVIATE_BRIEF = -ALWAYS_DETAILED_SEC = NO -INLINE_INHERITED_MEMB = YES -FULL_PATH_NAMES = NO -STRIP_FROM_PATH = ../include/ -STRIP_FROM_INC_PATH = -SHORT_NAMES = NO -JAVADOC_AUTOBRIEF = YES -QT_AUTOBRIEF = NO -MULTILINE_CPP_IS_BRIEF = NO -INHERIT_DOCS = YES -SEPARATE_MEMBER_PAGES = NO -TAB_SIZE = 4 -ALIASES = -TCL_SUBST = -OPTIMIZE_OUTPUT_FOR_C = NO -OPTIMIZE_OUTPUT_JAVA = NO -OPTIMIZE_FOR_FORTRAN = NO -OPTIMIZE_OUTPUT_VHDL = NO -EXTENSION_MAPPING = -MARKDOWN_SUPPORT = YES -AUTOLINK_SUPPORT = YES -BUILTIN_STL_SUPPORT = NO -CPP_CLI_SUPPORT = NO -SIP_SUPPORT = NO -IDL_PROPERTY_SUPPORT = YES -DISTRIBUTE_GROUP_DOC = NO -GROUP_NESTED_COMPOUNDS = NO -SUBGROUPING = YES -INLINE_GROUPED_CLASSES = NO -INLINE_SIMPLE_STRUCTS = NO -TYPEDEF_HIDES_STRUCT = NO -LOOKUP_CACHE_SIZE = 0 - -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- -EXTRACT_ALL = YES -EXTRACT_PRIVATE = YES -EXTRACT_PACKAGE = NO -EXTRACT_STATIC = YES -EXTRACT_LOCAL_CLASSES = YES -EXTRACT_LOCAL_METHODS = YES -EXTRACT_ANON_NSPACES = NO -HIDE_UNDOC_MEMBERS = NO -HIDE_UNDOC_CLASSES = NO -HIDE_FRIEND_COMPOUNDS = NO -HIDE_IN_BODY_DOCS = NO -INTERNAL_DOCS = NO -CASE_SENSE_NAMES = YES -HIDE_SCOPE_NAMES = NO -HIDE_COMPOUND_REFERENCE= NO -SHOW_INCLUDE_FILES = NO -SHOW_GROUPED_MEMB_INC = NO -FORCE_LOCAL_INCLUDES = NO -INLINE_INFO = NO -SORT_MEMBER_DOCS = NO -SORT_BRIEF_DOCS = NO -SORT_MEMBERS_CTORS_1ST = YES -SORT_GROUP_NAMES = NO -SORT_BY_SCOPE_NAME = NO -STRICT_PROTO_MATCHING = NO -GENERATE_TODOLIST = NO -GENERATE_TESTLIST = NO -GENERATE_BUGLIST = NO -GENERATE_DEPRECATEDLIST= NO -ENABLED_SECTIONS = -MAX_INITIALIZER_LINES = 30 -SHOW_USED_FILES = NO -SHOW_FILES = NO -SHOW_NAMESPACES = NO -FILE_VERSION_FILTER = -LAYOUT_FILE = -CITE_BIB_FILES = - -#--------------------------------------------------------------------------- -# Configuration options related to warning and progress messages -#--------------------------------------------------------------------------- -QUIET = NO -WARNINGS = YES -WARN_IF_UNDOCUMENTED = YES -WARN_IF_DOC_ERROR = YES -WARN_NO_PARAMDOC = NO -WARN_AS_ERROR = NO -WARN_FORMAT = "$file:$line: $text" -WARN_LOGFILE = - -#--------------------------------------------------------------------------- -# Configuration options related to the input files -#--------------------------------------------------------------------------- -INPUT = ../include/nudb/ -INPUT_ENCODING = UTF-8 -FILE_PATTERNS = -RECURSIVE = NO -EXCLUDE = -EXCLUDE_SYMLINKS = NO -EXCLUDE_PATTERNS = -EXCLUDE_SYMBOLS = -EXAMPLE_PATH = -EXAMPLE_PATTERNS = -EXAMPLE_RECURSIVE = NO -IMAGE_PATH = -INPUT_FILTER = -FILTER_PATTERNS = -FILTER_SOURCE_FILES = NO -FILTER_SOURCE_PATTERNS = -USE_MDFILE_AS_MAINPAGE = - -#--------------------------------------------------------------------------- -# Configuration options related to source browsing -#--------------------------------------------------------------------------- -SOURCE_BROWSER = NO -INLINE_SOURCES = NO -STRIP_CODE_COMMENTS = YES -REFERENCED_BY_RELATION = NO -REFERENCES_RELATION = NO -REFERENCES_LINK_SOURCE = YES -SOURCE_TOOLTIPS = YES -USE_HTAGS = NO -VERBATIM_HEADERS = YES -CLANG_ASSISTED_PARSING = NO -CLANG_OPTIONS = - -#--------------------------------------------------------------------------- -# Configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- -ALPHABETICAL_INDEX = YES -COLS_IN_ALPHA_INDEX = 5 -IGNORE_PREFIX = - -#--------------------------------------------------------------------------- -# Configuration options related to the HTML output -#--------------------------------------------------------------------------- -GENERATE_HTML = NO -HTML_OUTPUT = dhtm -HTML_FILE_EXTENSION = .html -HTML_HEADER = -HTML_FOOTER = -HTML_STYLESHEET = -HTML_EXTRA_STYLESHEET = -HTML_EXTRA_FILES = -HTML_COLORSTYLE_HUE = 220 -HTML_COLORSTYLE_SAT = 100 -HTML_COLORSTYLE_GAMMA = 80 -HTML_TIMESTAMP = NO -HTML_DYNAMIC_SECTIONS = NO -HTML_INDEX_NUM_ENTRIES = 100 -GENERATE_DOCSET = NO -DOCSET_FEEDNAME = "Doxygen generated docs" -DOCSET_BUNDLE_ID = org.doxygen.Project -DOCSET_PUBLISHER_ID = org.doxygen.Publisher -DOCSET_PUBLISHER_NAME = Publisher -GENERATE_HTMLHELP = NO -CHM_FILE = -HHC_LOCATION = -GENERATE_CHI = NO -CHM_INDEX_ENCODING = -BINARY_TOC = NO -TOC_EXPAND = NO -GENERATE_QHP = NO -QCH_FILE = -QHP_NAMESPACE = org.doxygen.Project -QHP_VIRTUAL_FOLDER = doc -QHP_CUST_FILTER_NAME = -QHP_CUST_FILTER_ATTRS = -QHP_SECT_FILTER_ATTRS = -QHG_LOCATION = -GENERATE_ECLIPSEHELP = NO -ECLIPSE_DOC_ID = org.doxygen.Project -DISABLE_INDEX = NO -GENERATE_TREEVIEW = NO -ENUM_VALUES_PER_LINE = 4 -TREEVIEW_WIDTH = 250 -EXT_LINKS_IN_WINDOW = NO -FORMULA_FONTSIZE = 10 -FORMULA_TRANSPARENT = YES -USE_MATHJAX = NO -MATHJAX_FORMAT = HTML-CSS -MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest -MATHJAX_EXTENSIONS = -MATHJAX_CODEFILE = -SEARCHENGINE = YES -SERVER_BASED_SEARCH = NO -EXTERNAL_SEARCH = NO -SEARCHENGINE_URL = -SEARCHDATA_FILE = searchdata.xml -EXTERNAL_SEARCH_ID = -EXTRA_SEARCH_MAPPINGS = - -#--------------------------------------------------------------------------- -# Configuration options related to the LaTeX output -#--------------------------------------------------------------------------- -GENERATE_LATEX = NO -LATEX_OUTPUT = latex -LATEX_CMD_NAME = latex -MAKEINDEX_CMD_NAME = makeindex -COMPACT_LATEX = NO -PAPER_TYPE = a4 -EXTRA_PACKAGES = -LATEX_HEADER = -LATEX_FOOTER = -LATEX_EXTRA_STYLESHEET = -LATEX_EXTRA_FILES = -PDF_HYPERLINKS = YES -USE_PDFLATEX = YES -LATEX_BATCHMODE = NO -LATEX_HIDE_INDICES = NO -LATEX_SOURCE_CODE = NO -LATEX_BIB_STYLE = plain -LATEX_TIMESTAMP = NO - -#--------------------------------------------------------------------------- -# Configuration options related to the RTF output -#--------------------------------------------------------------------------- -GENERATE_RTF = NO -RTF_OUTPUT = rtf -COMPACT_RTF = NO -RTF_HYPERLINKS = NO -RTF_STYLESHEET_FILE = -RTF_EXTENSIONS_FILE = -RTF_SOURCE_CODE = NO - -#--------------------------------------------------------------------------- -# Configuration options related to the man page output -#--------------------------------------------------------------------------- -GENERATE_MAN = NO -MAN_OUTPUT = man -MAN_EXTENSION = .3 -MAN_SUBDIR = -MAN_LINKS = NO - -#--------------------------------------------------------------------------- -# Configuration options related to the XML output -#--------------------------------------------------------------------------- -GENERATE_XML = YES -XML_OUTPUT = temp/ -XML_PROGRAMLISTING = YES - -#--------------------------------------------------------------------------- -# Configuration options related to the DOCBOOK output -#--------------------------------------------------------------------------- -GENERATE_DOCBOOK = NO -DOCBOOK_OUTPUT = docbook -DOCBOOK_PROGRAMLISTING = NO - -#--------------------------------------------------------------------------- -# Configuration options for the AutoGen Definitions output -#--------------------------------------------------------------------------- -GENERATE_AUTOGEN_DEF = NO -GENERATE_PERLMOD = NO -PERLMOD_LATEX = NO -PERLMOD_PRETTY = YES -PERLMOD_MAKEVAR_PREFIX = - -#--------------------------------------------------------------------------- -# Configuration options related to the preprocessor -#--------------------------------------------------------------------------- -ENABLE_PREPROCESSING = YES -MACRO_EXPANSION = YES -EXPAND_ONLY_PREDEF = YES -SEARCH_INCLUDES = YES -INCLUDE_PATH = ../ -INCLUDE_FILE_PATTERNS = -PREDEFINED = DOXYGEN \ - GENERATING_DOCS \ - _MSC_VER \ - NUDB_POSIX_FILE=1 - -EXPAND_AS_DEFINED = -SKIP_FUNCTION_MACROS = YES - -#--------------------------------------------------------------------------- -# Configuration options related to external references -#--------------------------------------------------------------------------- -TAGFILES = -GENERATE_TAGFILE = -ALLEXTERNALS = NO -EXTERNAL_GROUPS = YES -EXTERNAL_PAGES = YES -PERL_PATH = /usr/bin/perl - -#--------------------------------------------------------------------------- -# Configuration options related to the dot tool -#--------------------------------------------------------------------------- -CLASS_DIAGRAMS = NO -MSCGEN_PATH = -DIA_PATH = -HIDE_UNDOC_RELATIONS = YES -HAVE_DOT = NO -DOT_NUM_THREADS = 0 -DOT_FONTNAME = Helvetica -DOT_FONTSIZE = 10 -DOT_FONTPATH = -CLASS_GRAPH = YES -COLLABORATION_GRAPH = YES -GROUP_GRAPHS = YES -UML_LOOK = NO -UML_LIMIT_NUM_FIELDS = 10 -TEMPLATE_RELATIONS = NO -INCLUDE_GRAPH = YES -INCLUDED_BY_GRAPH = YES -CALL_GRAPH = NO -CALLER_GRAPH = NO -GRAPHICAL_HIERARCHY = YES -DIRECTORY_GRAPH = YES -DOT_IMAGE_FORMAT = png -INTERACTIVE_SVG = NO -DOT_PATH = -DOTFILE_DIRS = -MSCFILE_DIRS = -DIAFILE_DIRS = -PLANTUML_JAR_PATH = -PLANTUML_INCLUDE_PATH = -DOT_GRAPH_MAX_NODES = 50 -MAX_DOT_GRAPH_DEPTH = 0 -DOT_TRANSPARENT = NO -DOT_MULTI_TARGETS = NO -GENERATE_LEGEND = YES -DOT_CLEANUP = YES diff --git a/src/nudb/doc/types/File.qbk b/src/nudb/doc/types/File.qbk deleted file mode 100644 index f36259cdd4..0000000000 --- a/src/nudb/doc/types/File.qbk +++ /dev/null @@ -1,159 +0,0 @@ -[/ - Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -] - -[section:File File] - -The [*File] concept abstracts access to files in the underlying file system. -Two implementations are provided, one for the Win32 API and the other for -POSIX compliant systems. The [link nudb.ref.nudb__native_file native_file] type -alias is automatically set to either [link nudb.ref.nudb__win32_file win32_file] -or [link nudb.ref.nudb__posix_file posix_file] as appropriate. - -To support interfaces other than Win32 or POSIX, callers may provide their -own [*File] type that meets these requirements. The unit test code also provides -its own [*File] type which causes simulated operating system file failures -to exercise all failure paths in the implementation. - -In the table below: - -* `X` denotes a [*File] type -* `a` and `b` denote values of type `X` -* `c` denotes a (possibly const) value of type `X` -* `m` denotes a value of type [link nudb.ref.nudb__file_mode file_mode] -* `f` denotes a value of type [link nudb.ref.nudb__path_type path_type] -* `q` denotes a value of type `void*` -* `p` denotes a value of type `void const*` -* `ec` denotes a value of type [link nudb.ref.nudb__error_code error_code] - - -* `o` denotes a value of type `std::uint64_t` -* `n` denotes a value of type `std::size_t` - -[table File requirements -[[operation] [type] [semantics, pre/post-conditions]] -[ - [`X a{std::move(b)}`] - [ ] - [ - `X` is `MoveConstructible` - ] -] -[ - [`c.is_open()`] - [`bool`] - [ - Returns `true` if `c` refers to an open file. - ] -] -[ - [`a.close()`] - [ ] - [ - If `a` refers to an open file, closes the file. Does nothing if - `a` does not refer to an open file. After this call, `a.open()` - will return `false`. - ] -] -[ - [`a.create(m,f,ec)`] - [ ] - [ - Attempts to create a file at the path specified by `f`, and - open it with the mode specified by `m`. If an error occurs, - `ec` is set to the system specific error code. If no error - occurs, a subsequent call to `a.is_open()` will return `true`. - Undefined behavior if `a` already refers to an open file. - ] -] -[ - [`a.open(m,f,ec)`] - [ ] - [ - Attempts to open the file at the path specified by `f`. If - an error occurs, `ec` is set to the system specific error - code. If no error occurs, a subsequent call to `a.is_open()` - will return `true`. Undefined behavior if `a` already refers - to an open file. - ] -] -[ - [`X::erase(f,ec)`] - [ ] - [ - Attempts to delete the file at the path specified by `f`. - If an error occurs, `ec` is set to the system specific error - code. - ] -] -[ - [`c.size(ec)`] - [ `std::uint64_t` ] - [ - Returns the size of the file in bytes. This value is also equal to - lowest byte offset for which a read will always return a - [link nudb.ref.nudb__error short_read] error. Undefined - behavior if `a` does not refer to an open file. - ] -] -[ - [`a.read(o,p,n,ec)`] - [ ] - [ - Attempts to read `n` bytes from the open file referred to by `a`, - starting at offset `o`, and storing the results in the memory - pointed to by `p`, which must be at least of size `n` bytes. - If an error occurs, `ec` is set to the system specific error - code. Undefined behavior if `a` does not refer to an open file. - ] -] -[ - [`a.write(o,q,n,ec)`] - [ ] - [ - Attempts to write `n` bytes to the open file referred to by `a` - and opened with a write mode, starting at offset `o`, and storing - the results in the memory pointed to by `p`, which must be at - least of size `n` bytes. If an error occurs, `ec` is set to the - system specific error code. Undefined behavior if `a` does not - refer to an open file. - ] -] -[ - [`a.sync(ec)`] - [ ] - [ - Attempts to synchronize the file on disk. This instructs the - operating system to ensure that any data which resides in caches - or buffers is fully written to the underlying storage device - before this call returns. If an error occurs, `ec` is set to the - system specific error code. Undefined behavior if `a` does not - refer to an open file. - - NuDB's database integrity guarantees are only valid if the - implementation of `sync` assures that all data is fully written - to the underlying file before the call returns. - ] -] -[ - [`a.trunc(o,ec)`] - [ ] - [ - Attempts to change the size of the open file referred to by `a` - and opened with a write mode, to the size in bytes specified - by `o`. If an error occurs, `ec` is set to the system specific - error code. Undefined behavior if `a` does not refer to an open - file. After a successful call, `a.size(ec)` will return `o`. - - NuDB's database integrity guarantees are only valid if the - implementation of `trunc` assures that subsequent calls to - `size` will return `o`, even if the program is terminated or the - device is taken offline before calling `size`. - ] -] -] - -[endsect] diff --git a/src/nudb/doc/types/Hasher.qbk b/src/nudb/doc/types/Hasher.qbk deleted file mode 100644 index e80955b9ee..0000000000 --- a/src/nudb/doc/types/Hasher.qbk +++ /dev/null @@ -1,56 +0,0 @@ -[/ - Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -] - -[section:Hasher Hasher] - -A [@Hasher] implements a hash algorithm. This is used to compute the small -digests NuDB needs to effectively implement a hash table. NuDB provides -the default implementation [link nudb.ref.nudb__xxhasher xxhasher], which is -suitable for most use cases. For advanced applications, a user supplied -hash function may be supplied which must meet these requirements. - -In the table below: - -* `X` denotes a hasher class -* `a` denotes a value of type `X const` -* `s` denotes a value of type `std::uint64_t` -* `p` denotes a value of type `void const*` -* `n` denotes a value of type `std::size_t` - -[table Hasher requirements -[[operation] [type] [semantics, pre/post-conditions]] -[ - [`X a{s}`] - [ ] - [ - `a` is constructed with a seed value integer. To achieve resistance - from algorithmic complexity attacks, an implementation of [*Hasher] - should ensure that values returned from the hash function will be - distinctly different for different values of `s` given the same - inputs. If algorithmic complexity attack resistance is not a - requirement, the seed may be ignored upon construction. - ] -] -[ - [`a(p,n)`] - [ `std::uint64_t` ] - [ - Returns the digest of the memory `n` bytes in size and pointed - to by `p`. `n` will never be zero. A good hash function will - return values with these qualities: - -* Values are uniformly distributed in the full range - -* Values for the same input are distinctly different for different seeds - -* Small changes in the input produce unpredictable output values - - ] -] -] - -[endsect] diff --git a/src/nudb/doc/types/Progress.qbk b/src/nudb/doc/types/Progress.qbk deleted file mode 100644 index 44a76ad51d..0000000000 --- a/src/nudb/doc/types/Progress.qbk +++ /dev/null @@ -1,40 +0,0 @@ -[/ - Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) - - Distributed under the Boost Software License, Version 1.0. (See accompanying - file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -] - -[section:Progress Progress] - -A [*Progress] object provides feedback to callers on the progress of -long running operations such as calls to [link nudb.ref.nudb__verify verify] or -[link nudb.ref.nudb__rekey rekey] which can take days or weeks for database that -measure in the terabytes. These objects are used by passing them as parameters -to the appropriate functions, where the will be called periodically with -numbers that indicate the amount of work completed, versus the total amount -of work required. - -In the table below: - -* `X` denotes a progress class -* `a` denotes a value of type `X` -* `p` and `q` denote values of type `std::uint64_t` - -[table Progress requirements -[[operation] [type] [semantics, pre/post-conditions]] -[ - [`a(p, q)`] - [ ] - [ - Indicates to the progress object that work has been performed and - intermediate results calculated. `p` represents the amount of work - completed from the beginning of the operation. `q` represents the - total amount of work required. The fraction of completed work is - therefore `p/q`, with zero representing no work complete, and one - represents all work complete. `p` and `q` are unitless. - ] -] -] - -[endsect] diff --git a/src/nudb/examples/CMakeLists.txt b/src/nudb/examples/CMakeLists.txt deleted file mode 100644 index ab7e10061a..0000000000 --- a/src/nudb/examples/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -# Part of nudb - -GroupSources (include/nudb nudb) -GroupSources (extras/nudb extras) -GroupSources (examples/ "/") - -add_executable (example - ${NUDB_INCLUDES} - ${EXTRAS_INCLUDES} - example.cpp -) - -if (WIN32) - target_link_libraries (example ${Boost_LIBRARIES}) -else () - target_link_libraries (example ${Boost_LIBRARIES} rt Threads::Threads) -endif () diff --git a/src/nudb/examples/Jamfile b/src/nudb/examples/Jamfile deleted file mode 100644 index d165cc9145..0000000000 --- a/src/nudb/examples/Jamfile +++ /dev/null @@ -1,12 +0,0 @@ -# -# Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -# -# Distributed under the Boost Software License, Version 1.0. (See accompanying -# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -# - -import os ; - -exe example : - example.cpp - ; diff --git a/src/nudb/examples/example.cpp b/src/nudb/examples/example.cpp deleted file mode 100644 index c9a96961cf..0000000000 --- a/src/nudb/examples/example.cpp +++ /dev/null @@ -1,46 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#include -#include -#include - -int main() -{ - using namespace nudb; - std::size_t constexpr N = 1000; - using key_type = std::uint32_t; - error_code ec; - auto const dat_path = "db.dat"; - auto const key_path = "db.key"; - auto const log_path = "db.log"; - create( - dat_path, key_path, log_path, - 1, - make_salt(), - sizeof(key_type), - block_size("."), - 0.5f, - ec); - store db; - db.open(dat_path, key_path, log_path, ec); - char data = 0; - // Insert - for(key_type i = 0; i < N; ++i) - db.insert(&i, &data, sizeof(data), ec); - // Fetch - for(key_type i = 0; i < N; ++i) - db.fetch(&i, - [&](void const* buffer, std::size_t size) - { - // do something with buffer, size - }, ec); - db.close(ec); - erase_file(dat_path); - erase_file(key_path); - erase_file(log_path); -} diff --git a/src/nudb/extras/README.md b/src/nudb/extras/README.md deleted file mode 100644 index eb458c1692..0000000000 --- a/src/nudb/extras/README.md +++ /dev/null @@ -1,5 +0,0 @@ -This directory contains: - -* Additional interfaces not strictly part of NuDB's public APIs - -* Git submodules of dependencies used to build the tests and benchmarks diff --git a/src/nudb/extras/beast b/src/nudb/extras/beast deleted file mode 160000 index 2f9a8440c2..0000000000 --- a/src/nudb/extras/beast +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 2f9a8440c2432d8a196571d6300404cb76314125 diff --git a/src/nudb/extras/nudb/test/fail_file.hpp b/src/nudb/extras/nudb/test/fail_file.hpp deleted file mode 100644 index 252f2feed2..0000000000 --- a/src/nudb/extras/nudb/test/fail_file.hpp +++ /dev/null @@ -1,343 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_TEST_FAIL_FILE_HPP -#define NUDB_TEST_FAIL_FILE_HPP - -#include -#include -#include -#include -#include -#include -#include - -namespace nudb { -namespace test { - -/// Test error codes. -enum class test_error -{ - /// No error - success = 0, - - /// Simulated failure - failure -}; - -/// Returns the error category used for test error codes. -inline -error_category const& -test_category() -{ - struct cat_t : public error_category - { - char const* - name() const noexcept override - { - return "nudb"; - } - - std::string - message(int ev) const override - { - switch(static_cast(ev)) - { - case test_error::failure: - return "test failure"; - - default: - return "test error"; - } - } - - error_condition - default_error_condition(int ev) const noexcept override - { - return error_condition{ev, *this}; - } - - bool - equivalent(int ev, - error_condition const& ec) const noexcept override - { - return ec.value() == ev && &ec.category() == this; - } - - bool - equivalent(error_code const& ec, int ev) const noexcept override - { - return ec.value() == ev && &ec.category() == this; - } - }; - static cat_t const cat{}; - return cat; -} - -/// Returns a test error code. -inline -error_code -make_error_code(test_error ev) -{ - return error_code{static_cast(ev), test_category()}; -} - -} // test -} // nudb - -namespace boost { -namespace system { -template<> -struct is_error_code_enum -{ - static bool const value = true; -}; -} // system -} // boost - -namespace nudb { -namespace test { - -/** Countdown to test failure mode. - - The counter is constructed with a target ordinal and decremented - by callers. When the count reaches zero, a simulated test failure - is generated. -*/ -class fail_counter -{ - std::size_t target_; - std::atomic count_; - -public: - fail_counter(fail_counter const&) = delete; - fail_counter& operator=(fail_counter const&) = delete; - - /// Construct the counter with a target ordinal. - explicit - fail_counter(std::size_t target = 0) - { - reset(target); - } - - /// Reset the counter to fail at the nth step, or 0 for no failure. - void - reset(std::size_t n = 0) - { - target_ = n; - count_.store(0); - } - - /// Returns `true` if a simulated failure should be generated. - bool - fail() - { - return target_ && (++count_ >= target_); - } -}; - -/** A file wrapper to simulate file system failures. - - This wraps an object meeting the requirements of File. On each call, - the fail counter is decremented. When the counter reaches zero, a simulated - failure is generated. -*/ -template -class fail_file -{ - static_assert(is_File::value, - "File requirements not met"); - - File f_; - fail_counter* c_ = nullptr; - -public: - fail_file() = default; - fail_file(fail_file const&) = delete; - fail_file& operator=(fail_file const&) = delete; - ~fail_file() = default; - - fail_file(fail_file&&); - - fail_file& - operator=(fail_file&& other); - - explicit - fail_file(fail_counter& c); - - bool - is_open() const - { - return f_.is_open(); - } - - path_type const& - path() const - { - return f_.path(); - } - - std::uint64_t - size(error_code& ec) const - { - return f_.size(ec); - } - - void - close() - { - f_.close(); - } - - void - create(file_mode mode, path_type const& path, error_code& ec) - { - return f_.create(mode, path, ec); - } - - void - open(file_mode mode, path_type const& path, error_code& ec) - { - return f_.open(mode, path, ec); - } - - static - void - erase(path_type const& path, error_code& ec) - { - File::erase(path, ec); - } - - void - read(std::uint64_t offset, - void* buffer, std::size_t bytes, error_code& ec); - - void - write(std::uint64_t offset, - void const* buffer, std::size_t bytes, error_code& ec); - - void - sync(error_code& ec); - - void - trunc(std::uint64_t length, error_code& ec); - -private: - bool - fail(); - - void - do_fail(error_code& ec) - { - ec = test_error::failure; - } -}; - -template -fail_file:: -fail_file(fail_file&& other) - : f_(std::move(other.f_)) - , c_(other.c_) -{ - other.c_ = nullptr; -} - -template -fail_file& -fail_file:: -operator=(fail_file&& other) -{ - f_ = std::move(other.f_); - c_ = other.c_; - other.c_ = nullptr; - return *this; -} - -template -fail_file:: -fail_file(fail_counter& c) - : c_(&c) -{ -} - -template -void -fail_file:: -read(std::uint64_t offset, - void* buffer, std::size_t bytes, error_code& ec) -{ - if(fail()) - { - do_fail(ec); - return; - } - f_.read(offset, buffer, bytes, ec); -} - -template -void -fail_file:: -write(std::uint64_t offset, - void const* buffer, std::size_t bytes, error_code& ec) -{ - if(fail()) - { - do_fail(ec); - return; - } - if(fail()) - { - // partial write - f_.write(offset, buffer,(bytes + 1) / 2, ec); - if(ec) - return; - do_fail(ec); - return; - } - f_.write(offset, buffer, bytes, ec); -} - -template -void -fail_file:: -sync(error_code& ec) -{ - if(fail()) - do_fail(ec); - // We don't need a real sync for - // testing, it just slows things down. - //f_.sync(); -} - -template -void -fail_file:: -trunc(std::uint64_t length, error_code& ec) -{ - if(fail()) - { - do_fail(ec); - return; - } - f_.trunc(length, ec); -} - -template -bool -fail_file:: -fail() -{ - if(c_) - return c_->fail(); - return false; -} - -} // test -} // nudb - -#endif - diff --git a/src/nudb/extras/nudb/test/temp_dir.hpp b/src/nudb/extras/nudb/test/temp_dir.hpp deleted file mode 100644 index 470d6603b8..0000000000 --- a/src/nudb/extras/nudb/test/temp_dir.hpp +++ /dev/null @@ -1,73 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_TEST_TEMP_DIR_HPP -#define NUDB_TEST_TEMP_DIR_HPP - -#include -#include - -namespace nudb { -namespace test { - -/** RAII temporary directory path. - - The directory and all its contents are deleted when - the instance of `temp_dir` is destroyed. -*/ -class temp_dir -{ - boost::filesystem::path path_; - -public: - temp_dir(const temp_dir&) = delete; - temp_dir& operator=(const temp_dir&) = delete; - - /// Construct a temporary directory. - explicit - temp_dir(boost::filesystem::path dir) - { - if (dir.empty()) - dir = boost::filesystem::temp_directory_path(); - - do - { - path_ = - dir / boost::filesystem::unique_path(); - } - while(boost::filesystem::exists(path_)); - boost::filesystem::create_directory(path_); - } - - /// Destroy a temporary directory. - ~temp_dir() - { - boost::filesystem::remove_all(path_); - } - - /// Get the native path for the temporary directory - std::string - path() const - { - return path_.string(); - } - - /** Get the native path for the a file. - - The file does not need to exist. - */ - std::string - file(std::string const& name) const - { - return (path_ / name).string(); - } -}; - -} // test -} // nudb - -#endif diff --git a/src/nudb/extras/nudb/test/test_store.hpp b/src/nudb/extras/nudb/test/test_store.hpp deleted file mode 100644 index a43cdda93a..0000000000 --- a/src/nudb/extras/nudb/test/test_store.hpp +++ /dev/null @@ -1,451 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_TEST_TEST_STORE_HPP -#define NUDB_TEST_TEST_STORE_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace nudb { -namespace test { - -template -class Buffer_t -{ - std::size_t size_ = 0; - std::size_t capacity_ = 0; - std::unique_ptr p_; - -public: - Buffer_t() = default; - - Buffer_t(Buffer_t&& other); - - Buffer_t(Buffer_t const& other); - - Buffer_t& operator=(Buffer_t&& other); - - Buffer_t& operator=(Buffer_t const& other); - - bool - empty() const - { - return size_ == 0; - } - - std::size_t - size() const - { - return size_; - } - - std::uint8_t* - data() - { - return p_.get(); - } - - std::uint8_t const* - data() const - { - return p_.get(); - } - - void - clear(); - - void - shrink_to_fit(); - - std::uint8_t* - resize(std::size_t size); - - std::uint8_t* - operator()(void const* data, std::size_t size); -}; - -template -Buffer_t<_>:: -Buffer_t(Buffer_t&& other) - : size_(other.size_) - , capacity_(other.capacity_) - , p_(std::move(other.p_)) -{ - other.size_ = 0; - other.capacity_ = 0; -} - -template -Buffer_t<_>:: -Buffer_t(Buffer_t const& other) -{ - if(! other.empty()) - std::memcpy(resize(other.size()), - other.data(), other.size()); -} - -template -auto -Buffer_t<_>:: -operator=(Buffer_t&& other) -> - Buffer_t& -{ - if(&other != this) - { - size_ = other.size_; - capacity_ = other.capacity_; - p_ = std::move(other.p_); - other.size_ = 0; - other.capacity_ = 0; - } - return *this; -} - -template -auto -Buffer_t<_>:: -operator=(Buffer_t const& other) -> - Buffer_t& -{ - if(&other != this) - { - if(other.empty()) - size_ = 0; - else - std::memcpy(resize(other.size()), - other.data(), other.size()); - } - return *this; -} - -template -void -Buffer_t<_>:: -clear() -{ - size_ = 0; - capacity_ = 0; - p_.reset(); -} - -template -void -Buffer_t<_>:: -shrink_to_fit() -{ - if(empty() || size_ == capacity_) - return; - std::unique_ptr p{ - new std::uint8_t[size_]}; - capacity_ = size_; - std::memcpy(p.get(), p_.get(), size_); - std::swap(p, p_); -} - -template -std::uint8_t* -Buffer_t<_>:: -resize(std::size_t size) -{ - if(capacity_ < size) - { - p_.reset(new std::uint8_t[size]); - capacity_ = size; - } - size_ = size; - return p_.get(); -} - -template -std::uint8_t* -Buffer_t<_>:: -operator()(void const* data, std::size_t size) -{ - if(data == nullptr || size == 0) - return resize(0); - return reinterpret_cast( - std::memcpy(resize(size), data, size)); -} - -using Buffer = Buffer_t<>; - -//------------------------------------------------------------------------------ - -/// Describes a test generated key/value pair -struct item_type -{ - std::uint8_t* key; - std::uint8_t* data; - std::size_t size; -}; - -/// Interface to facilitate tests -template -class basic_test_store -{ - using Hasher = xxhasher; - - temp_dir td_; - std::uniform_int_distribution sizef_; - std::function createf_; - std::function openf_; - Buffer buf_; - -public: - path_type const dp; - path_type const kp; - path_type const lp; - std::size_t const keySize; - std::size_t const blockSize; - float const loadFactor; - static std::uint64_t constexpr appnum = 1; - static std::uint64_t constexpr salt = 42; - basic_store db; - - template - basic_test_store(std::size_t keySize, - std::size_t blockSize, float loadFactor, - Args&&... args); - - template - basic_test_store( - boost::filesystem::path const& temp_dir, - std::size_t keySize, std::size_t blockSize, float loadFactor, - Args&&... args); - - ~basic_test_store(); - - item_type - operator[](std::uint64_t i); - - void - create(error_code& ec); - - void - open(error_code& ec); - - void - close(error_code& ec) - { - db.close(ec); - } - - void - erase(); - -private: - template - static - void - rngfill( - void* dest, std::size_t size, Generator& g); -}; - -template -template -basic_test_store::basic_test_store( - boost::filesystem::path const& temp_dir, - std::size_t keySize_, std::size_t blockSize_, - float loadFactor_, Args&&... args) - : td_(temp_dir) - , sizef_(250, 750) - , createf_( - [this, args...](error_code& ec) - { - nudb::create( - dp, kp, lp, appnum, salt, - keySize, blockSize, loadFactor, ec, - args...); - }) - , openf_( - [this, args...](error_code& ec) - { - db.open(dp, kp, lp, ec, args...); - }) - , dp(td_.file("nudb.dat")) - , kp(td_.file("nudb.key")) - , lp(td_.file("nudb.log")) - , keySize(keySize_) - , blockSize(blockSize_) - , loadFactor(loadFactor_) -{ -} - -template -template -basic_test_store::basic_test_store(std::size_t keySize_, - std::size_t blockSize_, float loadFactor_, - Args&&... args) - : basic_test_store(boost::filesystem::path{}, - keySize_, - blockSize_, - loadFactor_, - std::forward(args)...) -{ -} - -template -basic_test_store:: -~basic_test_store() -{ - erase(); -} - -template -auto -basic_test_store:: -operator[](std::uint64_t i) -> - item_type -{ - xor_shift_engine g{i + 1}; - item_type item; - item.size = sizef_(g); - auto const needed = keySize + item.size; - rngfill(buf_.resize(needed), needed, g); - // put key last so we can get some unaligned - // keys, this increases coverage of xxhash. - item.data = buf_.data(); - item.key = buf_.data() + item.size; - return item; -} - -template -void -basic_test_store:: -create(error_code& ec) -{ - createf_(ec); -} - -template -void -basic_test_store:: -open(error_code& ec) -{ - openf_(ec); - if(ec) - return; - if(db.key_size() != keySize) - ec = error::invalid_key_size; - else if(db.block_size() != blockSize) - ec = error::invalid_block_size; -} - -template -void -basic_test_store:: -erase() -{ - erase_file(dp); - erase_file(kp); - erase_file(lp); -} - -template -template -void -basic_test_store:: -rngfill( - void* dest, std::size_t size, Generator& g) -{ - using result_type = - typename Generator::result_type; - while(size >= sizeof(result_type)) - { - auto const v = g(); - std::memcpy(dest, &v, sizeof(v)); - dest = reinterpret_cast< - std::uint8_t*>(dest) + sizeof(v); - size -= sizeof(v); - } - if(size > 0) - { - auto const v = g(); - std::memcpy(dest, &v, size); - } -} - -using test_store = basic_test_store; - -//------------------------------------------------------------------------------ - -template -static -std::string -num (T t) -{ - std::string s = std::to_string(t); - std::reverse(s.begin(), s.end()); - std::string s2; - s2.reserve(s.size() + (s.size()+2)/3); - int n = 0; - for (auto c : s) - { - if (n == 3) - { - n = 0; - s2.insert (s2.begin(), ','); - } - ++n; - s2.insert(s2.begin(), c); - } - return s2; -} - -template -std::ostream& -operator<<(std::ostream& os, verify_info const& info) -{ - os << - "avg_fetch: " << std::fixed << std::setprecision(3) << info.avg_fetch << "\n" << - "waste: " << std::fixed << std::setprecision(3) << info.waste * 100 << "%" << "\n" << - "overhead: " << std::fixed << std::setprecision(1) << info.overhead * 100 << "%" << "\n" << - "actual_load: " << std::fixed << std::setprecision(0) << info.actual_load * 100 << "%" << "\n" << - "version: " << num(info.version) << "\n" << - "uid: " << fhex(info.uid) << "\n" << - "appnum: " << info.appnum << "\n" << - "key_size: " << num(info.key_size) << "\n" << - "salt: " << fhex(info.salt) << "\n" << - "pepper: " << fhex(info.pepper) << "\n" << - "block_size: " << num(info.block_size) << "\n" << - "bucket_size: " << num(info.bucket_size) << "\n" << - "load_factor: " << std::fixed << std::setprecision(0) << info.load_factor * 100 << "%" << "\n" << - "capacity: " << num(info.capacity) << "\n" << - "buckets: " << num(info.buckets) << "\n" << - "key_count: " << num(info.key_count) << "\n" << - "value_count: " << num(info.value_count) << "\n" << - "value_bytes: " << num(info.value_bytes) << "\n" << - "spill_count: " << num(info.spill_count) << "\n" << - "spill_count_tot: " << num(info.spill_count_tot) << "\n" << - "spill_bytes: " << num(info.spill_bytes) << "\n" << - "spill_bytes_tot: " << num(info.spill_bytes_tot) << "\n" << - "key_file_size: " << num(info.key_file_size) << "\n" << - "dat_file_size: " << num(info.dat_file_size) << std::endl; - - std::string s; - for (size_t i = 0; i < info.hist.size(); ++i) - s += (i==0) ? - std::to_string(info.hist[i]) : - (", " + std::to_string(info.hist[i])); - os << "hist: " << s << std::endl; - return os; -} - -} // test -} // nudb - -#endif - diff --git a/src/nudb/extras/nudb/test/xor_shift_engine.hpp b/src/nudb/extras/nudb/test/xor_shift_engine.hpp deleted file mode 100644 index a6529933e5..0000000000 --- a/src/nudb/extras/nudb/test/xor_shift_engine.hpp +++ /dev/null @@ -1,105 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_TEST_XOR_SHIFT_ENGINE_HPP -#define NUDB_TEST_XOR_SHIFT_ENGINE_HPP - -#include -#include -#include - -namespace nudb { -namespace test { - -/** XOR-shift Generator. - - Meets the requirements of UniformRandomNumberGenerator. - - Simple and fast RNG based on: - http://xorshift.di.unimi.it/xorshift128plus.c - does not accept seed==0 -*/ -class xor_shift_engine -{ -public: - using result_type = std::uint64_t; - - xor_shift_engine(xor_shift_engine const&) = default; - xor_shift_engine& operator=(xor_shift_engine const&) = default; - - explicit - xor_shift_engine(result_type val = 1977u) - { - seed(val); - } - - void - seed(result_type seed); - - result_type - operator()(); - - static - result_type constexpr - min() - { - return std::numeric_limits::min(); - } - - static - result_type constexpr - max() - { - return std::numeric_limits::max(); - } - -private: - result_type s_[2]; - - static - result_type - murmurhash3(result_type x); -}; - -inline -void -xor_shift_engine::seed(result_type seed) -{ - if(seed == 0) - throw std::domain_error("invalid seed"); - s_[0] = murmurhash3(seed); - s_[1] = murmurhash3(s_[0]); -} - -inline -auto -xor_shift_engine::operator()() -> - result_type -{ - result_type s1 = s_[0]; - result_type const s0 = s_[1]; - s_[0] = s0; - s1 ^= s1<< 23; - return(s_[1] =(s1 ^ s0 ^(s1 >> 17) ^(s0 >> 26))) + s0; -} - -inline -auto -xor_shift_engine::murmurhash3(result_type x) - -> result_type -{ - x ^= x >> 33; - x *= 0xff51afd7ed558ccdULL; - x ^= x >> 33; - x *= 0xc4ceb9fe1a85ec53ULL; - return x ^= x >> 33; -} - -} // test -} // nudb - -#endif diff --git a/src/nudb/extras/nudb/util.hpp b/src/nudb/extras/nudb/util.hpp deleted file mode 100644 index c34f574075..0000000000 --- a/src/nudb/extras/nudb/util.hpp +++ /dev/null @@ -1,288 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef UTIL_HPP -#define UTIL_HPP - -#include "basic_seconds_clock.hpp" - -#include -#include -#include -#include - -namespace nudb { - -template -int -log2(std::uint64_t n) -{ - int i = -(n == 0); - - auto const S = - [&](int k) - { - if(n >=(std::uint64_t{1} << k)) - { - i += k; - n >>= k; - } - }; - S(32); S(16); S(8); S(4); S(2); S(1); - return i; -} - -// Format a decimal integer with comma separators -template -std::string -fdec(T t) -{ - std::string s = std::to_string(t); - std::reverse(s.begin(), s.end()); - std::string s2; - s2.reserve(s.size() +(s.size()+2)/3); - int n = 0; - for(auto c : s) - { - if(n == 3) - { - n = 0; - s2.insert(s2.begin(), ','); - } - ++n; - s2.insert(s2.begin(), c); - } - return s2; -} - -// format 64-bit unsigned as fixed width, 0 padded hex -template -std::string -fhex(T v) -{ - std::string s{"0x0000000000000000"}; - auto it = s.end(); - for(it = s.end(); v; v >>= 4) - *--it = "0123456789abcdef"[v & 0xf]; - return s; -} - -// Format an array of integers as a comma separated list -template -static -std::string -fhist(std::array const& hist) -{ - std::size_t n; - for(n = hist.size() - 1; n > 0; --n) - if(hist[n]) - break; - std::string s = std::to_string(hist[0]); - for(std::size_t i = 1; i <= n; ++i) - s += ", " + std::to_string(hist[i]); - return s; -} - -class save_stream_state -{ - std::ostream& os_; - std::streamsize precision_; - std::ios::fmtflags flags_; - std::ios::char_type fill_; - -public: - ~save_stream_state() - { - os_.precision(precision_); - os_.flags(flags_); - os_.fill(fill_); - } - save_stream_state(save_stream_state const&) = delete; - save_stream_state& operator=(save_stream_state const&) = delete; - explicit save_stream_state(std::ostream& os) - : os_(os) - , precision_(os.precision()) - , flags_(os.flags()) - , fill_(os.fill()) - { - } -}; - -template -std::ostream& -pretty_time(std::ostream& os, std::chrono::duration d) -{ - save_stream_state _(os); - using namespace std::chrono; - if(d < microseconds{1}) - { - // use nanoseconds - if(d < nanoseconds{100}) - { - // use floating - using ns = duration; - os << std::fixed << std::setprecision(1) << ns(d).count(); - } - else - { - // use integral - os << round(d).count(); - } - os << "ns"; - } - else if(d < milliseconds{1}) - { - // use microseconds - if(d < microseconds{100}) - { - // use floating - using ms = duration; - os << std::fixed << std::setprecision(1) << ms(d).count(); - } - else - { - // use integral - os << round(d).count(); - } - os << "us"; - } - else if(d < seconds{1}) - { - // use milliseconds - if(d < milliseconds{100}) - { - // use floating - using ms = duration; - os << std::fixed << std::setprecision(1) << ms(d).count(); - } - else - { - // use integral - os << round(d).count(); - } - os << "ms"; - } - else if(d < minutes{1}) - { - // use seconds - if(d < seconds{100}) - { - // use floating - using s = duration; - os << std::fixed << std::setprecision(1) << s(d).count(); - } - else - { - // use integral - os << round(d).count(); - } - os << "s"; - } - else - { - // use minutes - if(d < minutes{100}) - { - // use floating - using m = duration>; - os << std::fixed << std::setprecision(1) << m(d).count(); - } - else - { - // use integral - os << round(d).count(); - } - os << "min"; - } - return os; -} - -template -std::string -fmtdur(std::chrono::duration const& d) -{ - std::stringstream ss; - pretty_time(ss, d); - return ss.str(); -} - -//------------------------------------------------------------------------------ - -class progress -{ - using clock_type = basic_seconds_clock; - - std::ostream& os_; - clock_type::time_point start_; - clock_type::time_point now_; - clock_type::time_point report_; - std::uint64_t prev_; - bool estimate_; - -public: - explicit - progress(std::ostream& os) - : os_(os) - { - } - - void - operator()(std::uint64_t amount, std::uint64_t total) - { - using namespace std::chrono; - auto const now = clock_type::now(); - if(amount == 0) - { - now_ = clock_type::now(); - start_ = now_; - report_ = now_; - prev_ = 0; - estimate_ = false; - return; - } - if(now == now_) - return; - now_ = now; - auto const elapsed = now - start_; - if(! estimate_) - { - // Wait a bit before showing the first estimate - if(elapsed < seconds{30}) - return; - estimate_ = true; - } - else if(now - report_ < seconds{60}) - { - // Only show estimates periodically - return; - } - auto const rate = double(amount) / elapsed.count(); - auto const remain = clock_type::duration{ - static_cast( - (total - amount) / rate)}; - os_ << - "Remaining: " << fmtdur(remain) << - " (" << fdec(amount) << " of " << fdec(total) << - " in " << fmtdur(elapsed) << - ", " << fdec(amount - prev_) << - " in " << fmtdur(now - report_) << - ")\n"; - report_ = now; - prev_ = amount; - } - - clock_type::duration - elapsed() const - { - using namespace std::chrono; - return now_ - start_; - } -}; - -} // nudb - -#endif diff --git a/src/nudb/extras/rocksdb b/src/nudb/extras/rocksdb deleted file mode 160000 index a297643f2e..0000000000 --- a/src/nudb/extras/rocksdb +++ /dev/null @@ -1 +0,0 @@ -Subproject commit a297643f2e327a8bc7061bfc838fdf11935a2cf2 diff --git a/src/nudb/include/nudb/basic_store.hpp b/src/nudb/include/nudb/basic_store.hpp deleted file mode 100644 index 0e69195fbb..0000000000 --- a/src/nudb/include/nudb/basic_store.hpp +++ /dev/null @@ -1,436 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_BASIC_STORE_HPP -#define NUDB_BASIC_STORE_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace nudb { - -/** A high performance, insert-only key/value database for SSDs. - - To create a database first call the @ref create - free function. Then construct a @ref basic_store and - call @ref open on it: - - @code - error_code ec; - create( - "db.dat", "db.key", "db.log", - 1, make_salt(), 8, 4096, 0.5f, ec); - basic_store db; - db.open("db.dat", "db.key", "db.log", ec); - @endcode - - @tparam Hasher The hash function to use. This type - must meet the requirements of @b Hasher. - - @tparam File The type of File object to use. This type - must meet the requirements of @b File. -*/ -template -class basic_store -{ -public: - using hash_type = Hasher; - using file_type = File; - -private: - using clock_type = - std::chrono::steady_clock; - - using time_point = - typename clock_type::time_point; - - struct state - { - File df; - File kf; - File lf; - path_type dp; - path_type kp; - path_type lp; - Hasher hasher; - detail::pool p0; - detail::pool p1; - detail::cache c1; - detail::key_file_header kh; - - std::size_t rate = 0; - time_point when = clock_type::now(); - - state(state const&) = delete; - state& operator=(state const&) = delete; - - state(state&&) = default; - state& operator=(state&&) = default; - - state(File&& df_, File&& kf_, File&& lf_, - path_type const& dp_, path_type const& kp_, - path_type const& lp_, - detail::key_file_header const& kh_); - }; - - bool open_ = false; - - // Use optional because some - // members cannot be default-constructed. - // - boost::optional s_; // State of an open database - - std::size_t frac_; // accumulates load - std::size_t thresh_; // split threshold - nbuck_t buckets_; // number of buckets - nbuck_t modulus_; // hash modulus - - std::mutex u_; // serializes insert() - detail::gentex g_; - boost::shared_mutex m_; - std::thread t_; - std::condition_variable_any cv_; - - error_code ec_; - std::atomic ecb_; // `true` when ec_ set - - std::size_t dataWriteSize_; - std::size_t logWriteSize_; - -public: - /** Default constructor. - - A default constructed database is initially closed. - */ - basic_store() = default; - - /// Copy constructor (disallowed) - basic_store(basic_store const&) = delete; - - /// Copy assignment (disallowed) - basic_store& operator=(basic_store const&) = delete; - - /** Destroy the database. - - Files are closed, memory is freed, and data that has not been - committed is discarded. To ensure that all inserted data is - written, it is necessary to call @ref close before destroying - the @ref basic_store. - - This function ignores errors returned by @ref close; to receive - those errors it is necessary to call @ref close before the - @ref basic_store is destroyed. - */ - ~basic_store(); - - /** Returns `true` if the database is open. - - @par Thread safety - - Safe to call concurrently with any function - except @ref open or @ref close. - */ - bool - is_open() const - { - return open_; - } - - /** Return the path to the data file. - - @par Requirements - - The database must be open. - - @par Thread safety - - Safe to call concurrently with any function - except @ref open or @ref close. - - @return The data file path. - */ - path_type const& - dat_path() const; - - /** Return the path to the key file. - - @par Requirements - - The database must be open. - - @par Thread safety - - Safe to call concurrently with any function - except @ref open or @ref close. - - @return The key file path. - */ - path_type const& - key_path() const; - - /** Return the path to the log file. - - @par Requirements - - The database must be open. - - @par Thread safety - - Safe to call concurrently with any function - except @ref open or @ref close. - - @return The log file path. - */ - path_type const& - log_path() const; - - /** Return the appnum associated with the database. - - This is an unsigned 64-bit integer associated with the - database and defined by the application. It is set - once when the database is created in a call to - @ref create. - - @par Requirements - - The database must be open. - - @par Thread safety - - Safe to call concurrently with any function - except @ref open or @ref close. - - @return The appnum. - */ - std::uint64_t - appnum() const; - - /** Return the key size associated with the database. - - The key size is defined by the application when the - database is created in a call to @ref create. The - key size cannot be changed on an existing database. - - @par Requirements - - The database must be open. - - @par Thread safety - - Safe to call concurrently with any function - except @ref open or @ref close. - - @return The size of keys in the database. - */ - std::size_t - key_size() const; - - /** Return the block size associated with the database. - - The block size is defined by the application when the - database is created in a call to @ref create or when a - key file is regenerated in a call to @ref rekey. The - block size cannot be changed on an existing key file. - Instead, a new key file may be created with a different - block size. - - @par Requirements - - The database must be open. - - @par Thread safety - - Safe to call concurrently with any function - except @ref open or @ref close. - - @return The size of blocks in the key file. - */ - std::size_t - block_size() const; - - /** Close the database. - - All data is committed before closing. - - If an error occurs, the database is still closed. - - @par Requirements - - The database must be open. - - @par Thread safety - - Not thread safe. The caller is responsible for - ensuring that no other member functions are - called concurrently. - - @param ec Set to the error, if any occurred. - */ - void - close(error_code& ec); - - /** Open a database. - - The database identified by the specified data, key, and - log file paths is opened. If a log file is present, the - recovery mechanism is invoked to restore database integrity - before the function returns. - - @par Requirements - - The database must be not be open. - - @par Thread safety - - Not thread safe. The caller is responsible for - ensuring that no other member functions are - called concurrently. - - @param dat_path The path to the data file. - - @param key_path The path to the key file. - - @param log_path The path to the log file. - - @param ec Set to the error, if any occurred. - - @param args Optional arguments passed to @b File constructors. - - */ - template - void - open( - path_type const& dat_path, - path_type const& key_path, - path_type const& log_path, - error_code& ec, - Args&&... args); - - /** Fetch a value. - - The function checks the database for the specified - key, and invokes the callback if it is found. If - the key is not found, `ec` is set to @ref error::key_not_found. - If any other errors occur, `ec` is set to the - corresponding error. - - @par Requirements - - The database must be open. - - @par Thread safety - - Safe to call concurrently with any function except - @ref close. - - @note If the implementation encounters an error while - committing data to the database, this function will - immediately return with `ec` set to the error which - occurred. All subsequent calls to @ref fetch will - return the same error until the database is closed. - - @param key A pointer to a memory buffer of at least - @ref key_size() bytes, containing the key to be searched - for. - - @param callback A function which will be called with the - value data if the fetch is successful. The equivalent - signature must be: - @code - void callback( - void const* buffer, // A buffer holding the value - std::size_t size // The size of the value in bytes - ); - @endcode - The buffer provided to the callback remains valid - until the callback returns, ownership is not transferred. - - @param ec Set to the error, if any occurred. - */ - template - void - fetch(void const* key, Callback && callback, error_code& ec); - - /** Insert a value. - - This function attempts to insert the specified key/value - pair into the database. If the key already exists, - `ec` is set to @ref error::key_exists. If an error - occurs, `ec` is set to the corresponding error. - - @par Requirements - - The database must be open. - - @par Thread safety - - Safe to call concurrently with any function except - @ref close. - - @note If the implementation encounters an error while - committing data to the database, this function will - immediately return with `ec` set to the error which - occurred. All subsequent calls to @ref insert will - return the same error until the database is closed. - - @param key A buffer holding the key to be inserted. The - size of the buffer should be at least the `key_size` - associated with the open database. - - @param data A buffer holding the value to be inserted. - - @param bytes The size of the buffer holding the value - data. This value must be greater than 0 and no more - than 0xffffffff. - - @param ec Set to the error, if any occurred. - */ - void - insert(void const* key, void const* data, - nsize_t bytes, error_code& ec); - -private: - template - void - fetch(detail::nhash_t h, void const* key, - detail::bucket b, Callback && callback, error_code& ec); - - bool - exists(detail::nhash_t h, void const* key, - detail::shared_lock_type* lock, detail::bucket b, error_code& ec); - - void - split(detail::bucket& b1, detail::bucket& b2, - detail::bucket& tmp, nbuck_t n1, nbuck_t n2, - nbuck_t buckets, nbuck_t modulus, - detail::bulk_writer& w, error_code& ec); - - detail::bucket - load(nbuck_t n, detail::cache& c1, - detail::cache& c0, void* buf, error_code& ec); - - void - commit(detail::unique_lock_type& m, - std::size_t& work, error_code& ec); - - void - run(); -}; - -} // nudb - -#include - -#endif diff --git a/src/nudb/include/nudb/concepts.hpp b/src/nudb/include/nudb/concepts.hpp deleted file mode 100644 index 3d01d36a90..0000000000 --- a/src/nudb/include/nudb/concepts.hpp +++ /dev/null @@ -1,205 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_CONCEPTS_HPP -#define NUDB_CONCEPTS_HPP - -#include -#include -#include -#include -#include - -namespace nudb { - -namespace detail { - -template -class check_is_File -{ - template().is_open()), - bool>> - static R check1(int); - template - static std::false_type check1(...); - using type1 = decltype(check1(0)); - - template().close(), - std::true_type{})> - static R check2(int); - template - static std::false_type check2(...); - using type2 = decltype(check2(0)); - - template().create( - std::declval(), - std::declval(), - std::declval()), - std::true_type{})> - static R check3(int); - template - static std::false_type check3(...); - using type3 = decltype(check3(0)); - - template().open( - std::declval(), - std::declval(), - std::declval()), - std::true_type{})> - static R check4(int); - template - static std::false_type check4(...); - using type4 = decltype(check4(0)); - - template(), - std::declval()), - std::true_type{})> - static R check5(int); - template - static std::false_type check5(...); - using type5 = decltype(check5(0)); - - template().size( - std::declval())), - std::uint64_t>> - static R check6(int); - template - static std::false_type check6(...); - using type6 = decltype(check6(0)); - - template().read( - std::declval(), - std::declval(), - std::declval(), - std::declval()), - std::true_type{})> - static R check7(int); - template - static std::false_type check7(...); - using type7 = decltype(check7(0)); - - template().write( - std::declval(), - std::declval(), - std::declval(), - std::declval()), - std::true_type{})> - static R check8(int); - template - static std::false_type check8(...); - using type8 = decltype(check8(0)); - - template().sync( - std::declval()), - std::true_type{})> - static R check9(int); - template - static std::false_type check9(...); - using type9 = decltype(check9(0)); - - template().trunc( - std::declval(), - std::declval()), - std::true_type{})> - static R check10(int); - template - static std::false_type check10(...); - using type10 = decltype(check10(0)); - -public: - using type = std::integral_constant::value && - type1::value && type2::value && type3::value && - type4::value && type5::value && type6::value && - type7::value && type8::value && type9::value && - type10::value - >; -}; - -template -class check_is_Hasher -{ - template> - static R check1(int); - template - static std::false_type check1(...); - using type1 = decltype(check1(0)); - - template().operator()( - std::declval(), - std::declval())), - std::uint64_t>> - static R check2(int); - template - static std::false_type check2(...); - using type2 = decltype(check2(0)); -public: - using type = std::integral_constant; -}; - -template -class check_is_Progress -{ - template().operator()( - std::declval(), - std::declval()), - std::true_type{})> - static R check1(int); - template - static std::false_type check1(...); -public: - using type = decltype(check1(0)); -}; - -} // detail - -/// Determine if `T` meets the requirements of @b `File` -template -#if GENERATING_DOCS -struct is_File : std::integral_constant{}; -#else -using is_File = typename detail::check_is_File::type; -#endif - - -/// Determine if `T` meets the requirements of @b `Hasher` -template -#if GENERATING_DOCS -struct is_Hasher : std::integral_constant{}; -#else -using is_Hasher = typename detail::check_is_Hasher::type; -#endif - -/// Determine if `T` meets the requirements of @b `Progress` -template -#if GENERATING_DOCS -struct is_Progress : std::integral_constant{}; -#else -using is_Progress = typename detail::check_is_Progress::type; -#endif - -} // nudb - -#endif diff --git a/src/nudb/include/nudb/create.hpp b/src/nudb/include/nudb/create.hpp deleted file mode 100644 index cb37ecbd91..0000000000 --- a/src/nudb/include/nudb/create.hpp +++ /dev/null @@ -1,117 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_CREATE_HPP -#define NUDB_CREATE_HPP - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace nudb { - -/** Return a random salt. - - This function will use the system provided random - number device to generate a uniformly distributed - 64-bit unsigned value suitable for use the salt - value in a call to @ref create. -*/ -template -std::uint64_t -make_salt(); - -/** Create a new database. - - This function creates a set of new database files with - the given parameters. The files must not already exist or - else an error is returned. - - If an error occurs while the files are being created, - the function attempts to remove the files before - returning. - - @par Example - @code - error_code ec; - create( - "db.dat", "db.key", "db.log", - 1, make_salt(), 8, 4096, 0.5f, ec); - @endcode - - @par Template Parameters - - @tparam Hasher The hash function to use. This type must - meet the requirements of @b Hasher. The same hash - function must be used every time the database is opened, - or else an error is returned. The provided @ref xxhasher - is a suitable general purpose hash function. - - @tparam File The type of file to use. Use the default of - @ref native_file unless customizing the file behavior. - - @param dat_path The path to the data file. - - @param key_path The path to the key file. - - @param log_path The path to the log file. - - @param appnum A caller-defined value stored in the file - headers. When opening the database, the same value is - preserved and returned to the caller. - - @param salt A random unsigned integer used to permute - the hash function to make it unpredictable. The return - value of @ref make_salt returns a suitable value. - - @param key_size The number of bytes in each key. - - @param blockSize The size of a key file block. Larger - blocks hold more keys but require more I/O cycles per - operation. The ideal block size the largest size that - may be read in a single I/O cycle, and device dependent. - The return value of @ref block_size returns a suitable - value for the volume of a given path. - - @param load_factor A number between zero and one - representing the average bucket occupancy (number of - items). A value of 0.5 is perfect. Lower numbers - waste space, and higher numbers produce negligible - savings at the cost of increased I/O cycles. - - @param ec Set to the error, if any occurred. - - @param args Optional arguments passed to @b File constructors. -*/ -template< - class Hasher, - class File = native_file, - class... Args -> -void -create( - path_type const& dat_path, - path_type const& key_path, - path_type const& log_path, - std::uint64_t appnum, - std::uint64_t salt, - nsize_t key_size, - nsize_t blockSize, - float load_factor, - error_code& ec, - Args&&... args); - -} // nudb - -#include - -#endif diff --git a/src/nudb/include/nudb/detail/arena.hpp b/src/nudb/include/nudb/detail/arena.hpp deleted file mode 100644 index e033140e7c..0000000000 --- a/src/nudb/include/nudb/detail/arena.hpp +++ /dev/null @@ -1,296 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_DETAIL_ARENA_HPP -#define NUDB_DETAIL_ARENA_HPP - -#include -#include -#include -#include -#include -#include -#include - -#if NUDB_DEBUG_ARENA -#include -#include -#endif - -namespace nudb { -namespace detail { - -/* Custom memory manager that allocates in large blocks. - - The implementation measures the rate of allocations in - bytes per second and tunes the large block size to fit - one second's worth of allocations. -*/ -template -class arena_t -{ - using clock_type = - std::chrono::steady_clock; - - using time_point = - typename clock_type::time_point; - - class element; - - char const* label_; // diagnostic - std::size_t alloc_ = 0; // block size - std::size_t used_ = 0; // bytes allocated - element* list_ = nullptr; // list of blocks - time_point when_ = clock_type::now(); - -public: - arena_t(arena_t const&) = delete; - arena_t& operator=(arena_t&&) = delete; - arena_t& operator=(arena_t const&) = delete; - - ~arena_t(); - - explicit - arena_t(char const* label = ""); - - arena_t(arena_t&& other); - - // Set the allocation size - void - hint(std::size_t alloc) - { - alloc_ = alloc; - } - - // Free all memory - void - clear(); - - void - periodic_activity(); - - std::uint8_t* - alloc(std::size_t n); - - template - friend - void - swap(arena_t& lhs, arena_t& rhs); -}; - -//------------------------------------------------------------------------------ - -template -class arena_t<_>::element -{ - std::size_t const capacity_; - std::size_t used_ = 0; - element* next_; - -public: - element(std::size_t capacity, element* next) - : capacity_(capacity) - , next_(next) - { - } - - element* - next() const - { - return next_; - } - - void - clear() - { - used_ = 0; - } - - std::size_t - remain() const - { - return capacity_ - used_; - } - - std::size_t - capacity() const - { - return capacity_; - } - - std::uint8_t* - alloc(std::size_t n); -}; - -template -std::uint8_t* -arena_t<_>::element:: -alloc(std::size_t n) -{ - if(n > capacity_ - used_) - return nullptr; - auto const p = const_cast( - reinterpret_cast(this + 1) - ) + used_; - used_ += n; - return p; -} - -//------------------------------------------------------------------------------ - -template -arena_t<_>:: -arena_t(char const* label) - : label_(label) -{ -} - -template -arena_t<_>:: -~arena_t() -{ - clear(); -} - -template -arena_t<_>:: -arena_t(arena_t&& other) - : label_(other.label_) - , alloc_(other.alloc_) - , used_(other.used_) - , list_(other.list_) - , when_(other.when_) -{ - other.used_ = 0; - other.list_ = nullptr; - other.when_ = clock_type::now(); - other.alloc_ = 0; -} - -template -void -arena_t<_>:: -clear() -{ - used_ = 0; - while(list_) - { - auto const e = list_; - list_ = list_->next(); - e->~element(); - delete[] reinterpret_cast(e); - } -} - -template -void -arena_t<_>:: -periodic_activity() -{ - using namespace std::chrono; - auto const now = clock_type::now(); - auto const elapsed = now - when_; - if(elapsed < milliseconds{500}) - return; - when_ = now; - auto const rate = static_cast(std::ceil( - used_ / duration_cast>(elapsed).count())); -#if NUDB_DEBUG_ARENA - beast::unit_test::dstream dout{std::cout}; - auto const size = - [](element* e) - { - std::size_t n = 0; - while(e) - { - ++n; - e = e->next(); - } - return n; - }; -#endif - if(rate >= alloc_ * 2) - { - // adjust up - alloc_ = std::max(rate, alloc_ * 2); - #if NUDB_DEBUG_ARENA - dout << label_ << ": " - "rate=" << rate << - ", alloc=" << alloc_ << " UP" - ", nused=" << used_ << - ", used=" << size(list_) << - "\n"; - #endif - } - else if(rate <= alloc_ / 2) - { - // adjust down - alloc_ /= 2; - #if NUDB_DEBUG_ARENA - dout << label_ << ": " - "rate=" << rate << - ", alloc=" << alloc_ << " DOWN" - ", nused=" << used_ << - ", used=" << size(list_) << - "\n"; - #endif - } - else - { - #if NUDB_DEBUG_ARENA - dout << label_ << ": " - "rate=" << rate << - ", alloc=" << alloc_ << - ", nused=" << used_ << - ", used=" << size(list_) << - "\n"; - #endif - } -} - -template -std::uint8_t* -arena_t<_>:: -alloc(std::size_t n) -{ - // Undefined behavior: Zero byte allocations - BOOST_ASSERT(n != 0); - n = 8 *((n + 7) / 8); - std::uint8_t* p; - if(list_) - { - p = list_->alloc(n); - if(p) - { - used_ += n; - return p; - } - } - auto const size = std::max(alloc_, n); - auto const e = reinterpret_cast( - new std::uint8_t[sizeof(element) + size]); - list_ = ::new(e) element{size, list_}; - used_ += n; - return list_->alloc(n); -} - -template -void -swap(arena_t<_>& lhs, arena_t<_>& rhs) -{ - using std::swap; - swap(lhs.used_, rhs.used_); - swap(lhs.list_, rhs.list_); - // don't swap alloc_ or when_ -} - -using arena = arena_t<>; - -} // detail -} // nudb - -#endif diff --git a/src/nudb/include/nudb/detail/bucket.hpp b/src/nudb/include/nudb/detail/bucket.hpp deleted file mode 100644 index 8a8efbf610..0000000000 --- a/src/nudb/include/nudb/detail/bucket.hpp +++ /dev/null @@ -1,473 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_DETAIL_BUCKET_HPP -#define NUDB_DETAIL_BUCKET_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace nudb { -namespace detail { - -// Returns bucket index given hash, buckets, and modulus -// -inline -nbuck_t -bucket_index(nhash_t h, nbuck_t buckets, std::uint64_t modulus) -{ - BOOST_ASSERT(modulus <= 0x100000000ULL); - auto n = h % modulus; - if(n >= buckets) - n -= modulus / 2; - return static_cast(n); -} - -//------------------------------------------------------------------------------ - -// Tag for constructing empty buckets -struct empty_t -{ - constexpr empty_t() = default; -}; - -static empty_t constexpr empty{}; - -// Allows inspection and manipulation of bucket blobs in memory -template -class bucket_t -{ - nsize_t block_size_; // Size of a key file block - nkey_t size_; // Current key count - noff_t spill_; // Offset of next spill record or 0 - std::uint8_t* p_; // Pointer to the bucket blob - -public: - struct value_type - { - noff_t offset; - nhash_t hash; - nsize_t size; - }; - - bucket_t() = default; - bucket_t(bucket_t const&) = default; - bucket_t& operator=(bucket_t const&) = default; - - bucket_t(nsize_t block_size, void* p); - - bucket_t(nsize_t block_size, void* p, empty_t); - - nsize_t - block_size() const - { - return block_size_; - } - - // Serialized bucket size. - // Excludes empty - nsize_t - actual_size() const - { - return bucket_size(size_); - } - - bool - empty() const - { - return size_ == 0; - } - - bool - full() const - { - return size_ >= - detail::bucket_capacity(block_size_); - } - - nkey_t - size() const - { - return size_; - } - - // Returns offset of next spill record or 0 - // - noff_t - spill() const - { - return spill_; - } - - // Set offset of next spill record - // - void - spill(noff_t offset); - - // Clear contents of the bucket - // - void - clear(); - - // Returns the record for a key - // entry without bounds checking. - // - value_type const - at(nkey_t i) const; - - value_type const - operator[](nkey_t i) const - { - return at(i); - } - - // Returns index of entry with prefix - // equal to or greater than the given prefix. - // - nkey_t - lower_bound(nhash_t h) const; - - void - insert(noff_t offset, nsize_t size, nhash_t h); - - // Erase an element by index - // - void - erase(nkey_t i); - - // Read a full bucket from the - // file at the specified offset. - // - template - void - read(File& f, noff_t, error_code& ec); - - // Read a compact bucket - // - template - void - read(bulk_reader& r, error_code& ec); - - // Write a compact bucket to the stream. - // This only writes entries that are not empty. - // - void - write(ostream& os) const; - - // Write a bucket to the file at the specified offset. - // The full block_size() bytes are written. - // - template - void - write(File& f,noff_t offset, error_code& ec) const; - -private: - // Update size and spill in the blob - void - update(); -}; - -//------------------------------------------------------------------------------ - -template -bucket_t<_>:: -bucket_t(nsize_t block_size, void* p) - : block_size_(block_size) - , p_(reinterpret_cast(p)) -{ - // Bucket Record - istream is(p_, block_size); - detail::read(is, size_); // Count - detail::read(is, spill_); // Spill -} - -template -bucket_t<_>:: -bucket_t(nsize_t block_size, void* p, empty_t) - : block_size_(block_size) - , size_(0) - , spill_(0) - , p_(reinterpret_cast(p)) -{ - clear(); -} - -template -void -bucket_t<_>:: -spill(noff_t offset) -{ - spill_ = offset; - update(); -} - -template -void -bucket_t<_>::clear() -{ - size_ = 0; - spill_ = 0; - std::memset(p_, 0, block_size_); -} - -template -auto -bucket_t<_>:: -at(nkey_t i) const -> - value_type const -{ - value_type result; - // Bucket Entry - auto const w = - field::size + // Offset - field::size + // Size - field::size; // Prefix - // Bucket Record - detail::istream is{p_ + - field::size + // Count - field::size + // Spill - i * w, w}; - // Bucket Entry - detail::read( - is, result.offset); // Offset - detail::read_size48( - is, result.size); // Size - detail::read( - is, result.hash); // Hash - return result; -} - -template -nkey_t -bucket_t<_>:: -lower_bound(nhash_t h) const -{ - // Bucket Entry - auto const w = - field::size + // Offset - field::size + // Size - field::size; // Hash - // Bucket Record - auto const p = p_ + - field::size + // Count - field::size + // Spill - // Bucket Entry - field::size + // Offset - field::size; // Size - nkey_t step; - nkey_t first = 0; - nkey_t count = size_; - while(count > 0) - { - step = count / 2; - nkey_t i = first + step; - nhash_t h1; - readp(p + i * w, h1); - if(h1 < h) - { - first = i + 1; - count -= step + 1; - } - else - { - count = step; - } - } - return first; -} - -template -void -bucket_t<_>:: -insert( - noff_t offset, nsize_t size, nhash_t h) -{ - auto const i = lower_bound(h); - // Bucket Record - auto const p = p_ + - field< - std::uint16_t>::size + // Count - field::size; // Spill - // Bucket Entry - auto const w = - field::size + // Offset - field::size + // Size - field::size; // Hash - std::memmove( - p +(i + 1) * w, - p + i * w, - (size_ - i) * w); - ++size_; - update(); - // Bucket Entry - ostream os{p + i * w, w}; - detail::write( - os, offset); // Offset - detail::write( - os, size); // Size - detail::write( - os, h); // Prefix -} - -template -void -bucket_t<_>:: -erase(nkey_t i) -{ - // Bucket Record - auto const p = p_ + - field::size + // Count - field::size; // Spill - auto const w = - field::size + // Offset - field::size + // Size - field::size; // Hash - --size_; - if(i < size_) - std::memmove( - p + i * w, - p +(i + 1) * w, - (size_ - i) * w); - std::memset(p + size_ * w, 0, w); - update(); -} - -template -template -void -bucket_t<_>:: -read(File& f, noff_t offset, error_code& ec) -{ - auto const cap = bucket_capacity(block_size_); - // Excludes padding to block size - f.read(offset, p_, bucket_size(cap), ec); - if(ec) - return; - istream is{p_, block_size_}; - detail::read(is, size_); // Count - detail::read(is, spill_); // Spill - if(size_ > cap) - { - ec = error::invalid_bucket_size; - return; - } -} - -template -template -void -bucket_t<_>:: -read(bulk_reader& r, error_code& ec) -{ - // Bucket Record(compact) - auto is = r.prepare( - detail::field::size + - detail::field::size, ec); - if(ec) - return; - detail::read(is, size_); // Count - detail::read(is, spill_); // Spill - update(); - // Excludes empty bucket entries - auto const w = size_ * ( - field::size + // Offset - field::size + // Size - field::size); // Hash - is = r.prepare(w, ec); - if(ec) - return; - std::memcpy(p_ + - field::size + // Count - field::size, // Spill - is.data(w), w); // Entries -} - -template -void -bucket_t<_>:: -write(ostream& os) const -{ - // Does not pad up to the block size. This - // is called to write to the data file. - auto const size = actual_size(); - // Bucket Record - std::memcpy(os.data(size), p_, size); -} - -template -template -void -bucket_t<_>:: -write(File& f, noff_t offset, error_code& ec) const -{ - // Includes zero pad up to the block - // size, to make the key file size always - // a multiple of the block size. - auto const size = actual_size(); - std::memset(p_ + size, 0, block_size_ - size); - // Bucket Record - f.write(offset, p_, block_size_, ec); - if(ec) - return; -} - -template -void -bucket_t<_>:: -update() -{ - // Bucket Record - ostream os{p_, block_size_}; - detail::write(os, size_); // Count - detail::write(os, spill_); // Spill -} - -using bucket = bucket_t<>; - -//------------------------------------------------------------------------------ - -// Spill bucket if full. -// The bucket is cleared after it spills. -// -template -void -maybe_spill( - bucket& b, bulk_writer& w, error_code& ec) -{ - if(b.full()) - { - // Spill Record - auto const offset = w.offset(); - auto os = w.prepare( - field::size + // Zero - field::size + // Size - b.actual_size(), ec); - if(ec) - return; - write(os, 0ULL); // Zero - write( - os, b.actual_size()); // Size - auto const spill = - offset + os.size(); - b.write(os); // Bucket - // Update bucket - b.clear(); - b.spill(spill); - } -} - -} // detail -} // nudb - -#endif diff --git a/src/nudb/include/nudb/detail/buffer.hpp b/src/nudb/include/nudb/detail/buffer.hpp deleted file mode 100644 index fc9f187ff7..0000000000 --- a/src/nudb/include/nudb/detail/buffer.hpp +++ /dev/null @@ -1,86 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_DETAIL_BUFFER_HPP -#define NUDB_DETAIL_BUFFER_HPP - -#include -#include -#include - -namespace nudb { -namespace detail { - -// Simple growable memory buffer -class buffer -{ -private: - std::size_t size_ = 0; - std::unique_ptr buf_; - -public: - ~buffer() = default; - buffer() = default; - buffer(buffer const&) = delete; - buffer& operator=(buffer const&) = delete; - - explicit - buffer(std::size_t n) - : size_(n) - , buf_(new std::uint8_t[n]) - { - } - - buffer(buffer&& other) - : size_(other.size_) - , buf_(std::move(other.buf_)) - { - other.size_ = 0; - } - - buffer& - operator=(buffer&& other) - { - size_ = other.size_; - buf_ = std::move(other.buf_); - other.size_ = 0; - return *this; - } - - std::size_t - size() const - { - return size_; - } - - std::uint8_t* - get() const - { - return buf_.get(); - } - - void - reserve(std::size_t n) - { - if(size_ < n) - buf_.reset(new std::uint8_t[n]); - size_ = n; - } - - // BufferFactory - void* - operator()(std::size_t n) - { - reserve(n); - return buf_.get(); - } -}; - -} // detail -} // nudb - -#endif diff --git a/src/nudb/include/nudb/detail/bulkio.hpp b/src/nudb/include/nudb/detail/bulkio.hpp deleted file mode 100644 index 22e72073a3..0000000000 --- a/src/nudb/include/nudb/detail/bulkio.hpp +++ /dev/null @@ -1,196 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_DETAIL_BULKIO_HPP -#define NUDB_DETAIL_BULKIO_HPP - -#include -#include -#include -#include -#include -#include - -namespace nudb { -namespace detail { - -// Scans a file in sequential large reads -template -class bulk_reader -{ - File& f_; - buffer buf_; - noff_t last_; // size of file - noff_t offset_; // current position - std::size_t avail_; // bytes left to read in buf - std::size_t used_; // bytes consumed in buf - -public: - bulk_reader(File& f, noff_t offset, - noff_t last, std::size_t buffer_size); - - noff_t - offset() const - { - return offset_ - avail_; - } - - bool - eof() const - { - return offset() >= last_; - } - - istream - prepare(std::size_t needed, error_code& ec); -}; - -template -bulk_reader:: -bulk_reader(File& f, noff_t offset, - noff_t last, std::size_t buffer_size) - : f_(f) - , last_(last) - , offset_(offset) - , avail_(0) - , used_(0) -{ - buf_.reserve(buffer_size); -} - -template -istream -bulk_reader:: -prepare(std::size_t needed, error_code& ec) -{ - if(needed > avail_) - { - if(offset_ + needed - avail_ > last_) - { - ec = error::short_read; - return {}; - } - if(needed > buf_.size()) - { - buffer buf; - buf.reserve(needed); - std::memcpy(buf.get(), - buf_.get() + used_, avail_); - buf_ = std::move(buf); - } - else - { - std::memmove(buf_.get(), - buf_.get() + used_, avail_); - } - - auto const n = std::min(buf_.size() - avail_, - static_cast(last_ - offset_)); - f_.read(offset_, buf_.get() + avail_, n, ec); - if(ec) - return {}; - offset_ += n; - avail_ += n; - used_ = 0; - } - istream is{buf_.get() + used_, needed}; - used_ += needed; - avail_ -= needed; - return is; -} - -//------------------------------------------------------------------------------ - -// Buffers file writes -// Caller must call flush manually at the end -template -class bulk_writer -{ - File& f_; - buffer buf_; - noff_t offset_; // current position - std::size_t used_; // bytes written to buf - -public: - bulk_writer(File& f, noff_t offset, - std::size_t buffer_size); - - ostream - prepare(std::size_t needed, error_code& ec); - - // Returns the number of bytes buffered - std::size_t - size() - { - return used_; - } - - // Return current offset in file. This - // is advanced with each call to prepare. - noff_t - offset() const - { - return offset_ + used_; - } - - // Caller must invoke flush manually in - // order to handle any error conditions. - void - flush(error_code& ec); -}; - -template -bulk_writer:: -bulk_writer(File& f, - noff_t offset, std::size_t buffer_size) - : f_(f) - , offset_(offset) - , used_(0) - -{ - buf_.reserve(buffer_size); -} - -template -ostream -bulk_writer:: -prepare(std::size_t needed, error_code& ec) -{ - if(used_ + needed > buf_.size()) - { - flush(ec); - if(ec) - return{}; - } - if(needed > buf_.size()) - buf_.reserve(needed); - ostream os(buf_.get() + used_, needed); - used_ += needed; - return os; -} - -template -void -bulk_writer:: -flush(error_code& ec) -{ - if(used_) - { - auto const offset = offset_; - auto const used = used_; - offset_ += used_; - used_ = 0; - f_.write(offset, buf_.get(), used, ec); - if(ec) - return; - } -} - -} // detail -} // nudb - -#endif diff --git a/src/nudb/include/nudb/detail/cache.hpp b/src/nudb/include/nudb/detail/cache.hpp deleted file mode 100644 index 0606ae4233..0000000000 --- a/src/nudb/include/nudb/detail/cache.hpp +++ /dev/null @@ -1,236 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_DETAIL_CACHE_HPP -#define NUDB_DETAIL_CACHE_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace nudb { -namespace detail { - -// Associative container storing -// bucket blobs keyed by bucket index. -// -template -class cache_t -{ -public: - using value_type = std::pair; - -private: - using map_type = - std::unordered_map; - - struct transform - { - using argument_type = - typename map_type::value_type; - using result_type = value_type; - - cache_t* cache_; - - transform() - : cache_(nullptr) - { - } - - explicit - transform(cache_t& cache) - : cache_(&cache) - { - } - - value_type - operator()(argument_type const& e) const - { - return std::make_pair(e.first, - bucket{cache_->block_size_, e.second}); - } - }; - - nsize_t key_size_ = 0; - nsize_t block_size_ = 0; - arena arena_; - map_type map_; - -public: - using iterator = boost::transform_iterator< - transform, typename map_type::iterator, - value_type, value_type>; - - cache_t(cache_t const&) = delete; - cache_t& operator=(cache_t&&) = delete; - cache_t& operator=(cache_t const&) = delete; - - // Constructs a cache that will never have inserts - cache_t() = default; - - cache_t(cache_t&& other); - - explicit - cache_t(nsize_t key_size, - nsize_t block_size, char const* label); - - std::size_t - size() const - { - return map_.size(); - } - - iterator - begin() - { - return iterator{map_.begin(), transform{*this}}; - } - - iterator - end() - { - return iterator{map_.end(), transform{*this}}; - } - - bool - empty() const - { - return map_.empty(); - } - - void - clear(); - - void - reserve(std::size_t n); - - void - periodic_activity(); - - iterator - find(nbuck_t n); - - // Create an empty bucket - // - bucket - create(nbuck_t n); - - // Insert a copy of a bucket. - // - iterator - insert(nbuck_t n, bucket const& b); - - template - friend - void - swap(cache_t& lhs, cache_t& rhs); -}; - -template -cache_t<_>:: -cache_t(cache_t&& other) - : key_size_{other.key_size_} - , block_size_(other.block_size_) - , arena_(std::move(other.arena_)) - , map_(std::move(other.map_)) -{ -} - -template -cache_t<_>:: -cache_t(nsize_t key_size, - nsize_t block_size, char const* label) - : key_size_(key_size) - , block_size_(block_size) - , arena_(label) -{ -} - -template -void -cache_t<_>:: -reserve(std::size_t n) -{ - arena_.hint(n * block_size_); - map_.reserve(n); -} - -template -void -cache_t<_>:: -clear() -{ - arena_.clear(); - map_.clear(); -} - -template -void -cache_t<_>:: -periodic_activity() -{ - arena_.periodic_activity(); -} - -template -auto -cache_t<_>:: -find(nbuck_t n) -> - iterator -{ - auto const iter = map_.find(n); - if(iter == map_.end()) - return iterator{map_.end(), transform(*this)}; - return iterator{iter, transform(*this)}; -} - -template -bucket -cache_t<_>:: -create(nbuck_t n) -{ - auto const p = arena_.alloc(block_size_); - map_.emplace(n, p); - return bucket{block_size_, p, detail::empty}; -} - -template -auto -cache_t<_>:: -insert(nbuck_t n, bucket const& b) -> - iterator -{ - void* const p = arena_.alloc(b.block_size()); - ostream os{p, b.block_size()}; - b.write(os); - auto const result = map_.emplace(n, p); - return iterator{result.first, transform(*this)}; -} - -template -void -swap(cache_t& lhs, cache_t& rhs) -{ - using std::swap; - swap(lhs.key_size_, rhs.key_size_); - swap(lhs.block_size_, rhs.block_size_); - swap(lhs.arena_, rhs.arena_); - swap(lhs.map_, rhs.map_); -} - -using cache = cache_t<>; - -} // detail -} // nudb - -#endif diff --git a/src/nudb/include/nudb/detail/endian.hpp b/src/nudb/include/nudb/detail/endian.hpp deleted file mode 100644 index 37c0e06c9a..0000000000 --- a/src/nudb/include/nudb/detail/endian.hpp +++ /dev/null @@ -1,93 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_DETAIL_ENDIAN_HPP -#define NUDB_DETAIL_ENDIAN_HPP - -#include -#include - -namespace nudb { -namespace detail { - -// This is a modified work, original implementation -// by Howard Hinnant -// -// "This should be standardized" - Howard - -// Endian provides answers to the following questions: -// 1. Is this system big or little endian? -// 2. Is the "desired endian" of some class or function the same as the -// native endian? -enum class endian -{ -#ifdef _MSC_VER - big = 1, - little = 0, - native = little -#else - native = __BYTE_ORDER__, - little = __ORDER_LITTLE_ENDIAN__, - big = __ORDER_BIG_ENDIAN__ -#endif -}; - -using is_little_endian = - std::integral_constant; - -static_assert( - endian::native == endian::little || endian::native == endian::big, - "endian::native shall be one of endian::little or endian::big"); - -static_assert( - endian::big != endian::little, - "endian::big and endian::little shall have different values"); - -// The pepper got baked into the file format as -// the hash of the little endian salt so now we -// need this function. -// -template -std::uint64_t -to_little_endian(std::uint64_t v, std::false_type) -{ - union U - { - std::uint64_t vi; - std::uint8_t va[8]; - }; - U u; - u.va[0] = v & 0xff; - u.va[1] = (v >> 8) & 0xff; - u.va[2] = (v >> 16) & 0xff; - u.va[3] = (v >> 24) & 0xff; - u.va[4] = (v >> 32) & 0xff; - u.va[5] = (v >> 40) & 0xff; - u.va[6] = (v >> 48) & 0xff; - u.va[7] = (v >> 56) & 0xff; - return u.vi; -} - -inline -std::uint64_t -to_little_endian(std::uint64_t v, std::true_type) -{ - return v; -} - -inline -std::uint64_t -to_little_endian(std::uint64_t v) -{ - return to_little_endian(v, is_little_endian{}); -} - -} // detail -} // nudb - -#endif diff --git a/src/nudb/include/nudb/detail/field.hpp b/src/nudb/include/nudb/detail/field.hpp deleted file mode 100644 index e3101b128f..0000000000 --- a/src/nudb/include/nudb/detail/field.hpp +++ /dev/null @@ -1,265 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_FIELD_HPP -#define NUDB_FIELD_HPP - -#include -#include -#include -#include -#include -#include -#include - -namespace nudb { -namespace detail { - -// A 24-bit integer -struct uint24_t; - -// A 48-bit integer -struct uint48_t; - -// These metafunctions describe the binary format of fields on disk - -template -struct field; - -template<> -struct field -{ - static std::size_t constexpr size = 1; - static std::uint64_t constexpr max = 0xff; -}; - -template<> -struct field -{ - static std::size_t constexpr size = 2; - static std::uint64_t constexpr max = 0xffff; -}; - -template<> -struct field -{ - static std::size_t constexpr size = 3; - static std::uint64_t constexpr max = 0xffffff; -}; - -template<> -struct field -{ - static std::size_t constexpr size = 4; - static std::uint64_t constexpr max = 0xffffffff; -}; - -template<> -struct field -{ - static std::size_t constexpr size = 6; - static std::uint64_t constexpr max = 0x0000ffffffffffff; -}; - -template<> -struct field -{ - static std::size_t constexpr size = 8; - static std::uint64_t constexpr max = 0xffffffffffffffff; -}; - -// read field from memory - -template::value>::type* = nullptr> -void -readp(void const* v, U& u) -{ - auto p = reinterpret_cast(v); - u = *p; -} - -template::value>::type* = nullptr> -void -readp(void const* v, U& u) -{ - auto p = reinterpret_cast(v); - T t; - t = T(*p++)<< 8; - t = T(*p ) | t; - u = t; -} - -template::value>::type* = nullptr> -void -readp(void const* v, U& u) -{ - auto p = reinterpret_cast(v); - std::uint32_t t; - t = std::uint32_t(*p++)<<16; - t = (std::uint32_t(*p++)<< 8) | t; - t = std::uint32_t(*p ) | t; - u = t; -} - -template::value>::type* = nullptr> -void -readp(void const* v, U& u) -{ - auto const* p = reinterpret_cast(v); - T t; - t = T(*p++)<<24; - t = (T(*p++)<<16) | t; - t = (T(*p++)<< 8) | t; - t = T(*p ) | t; - u = t; -} - -template::value>::type* = nullptr> -void -readp(void const* v, U& u) -{ - auto p = reinterpret_cast(v); - std::uint64_t t; - t = (std::uint64_t(*p++)<<40); - t = (std::uint64_t(*p++)<<32) | t; - t = (std::uint64_t(*p++)<<24) | t; - t = (std::uint64_t(*p++)<<16) | t; - t = (std::uint64_t(*p++)<< 8) | t; - t = std::uint64_t(*p ) | t; - u = t; -} - -template::value>::type* = nullptr> -void -readp(void const* v, U& u) -{ - auto p = reinterpret_cast(v); - T t; - t = T(*p++)<<56; - t = (T(*p++)<<48) | t; - t = (T(*p++)<<40) | t; - t = (T(*p++)<<32) | t; - t = (T(*p++)<<24) | t; - t = (T(*p++)<<16) | t; - t = (T(*p++)<< 8) | t; - t = T(*p ) | t; - u = t; -} - -// read field from istream - -template -void -read(istream& is, U& u) -{ - readp(is.data(field::size), u); -} - -inline -void -read_size48(istream& is, std::size_t& u) -{ - std::uint64_t v; - read(is, v); - BOOST_ASSERT(v <= std::numeric_limits::max()); - u = static_cast(v); -} - -// write field to ostream - -template::value>::type* = nullptr> -void -write(ostream& os, U u) -{ - BOOST_ASSERT(u <= field::max); - std::uint8_t* p = os.data(field::size); - *p = static_cast(u); -} - -template::value>::type* = nullptr> -void -write(ostream& os, U u) -{ - BOOST_ASSERT(u <= field::max); - auto const t = static_cast(u); - std::uint8_t* p = os.data(field::size); - *p++ = (t>> 8)&0xff; - *p = t &0xff; -} - -template::value>::type* = nullptr> -void -write(ostream& os, U u) -{ - BOOST_ASSERT(u <= field::max); - auto const t = static_cast(u); - std::uint8_t* p = os.data(field::size); - *p++ = (t>>16)&0xff; - *p++ = (t>> 8)&0xff; - *p = t &0xff; -} - -template::value>::type* = nullptr> -void -write(ostream& os, U u) -{ - BOOST_ASSERT(u <= field::max); - auto const t = static_cast(u); - std::uint8_t* p = os.data(field::size); - *p++ = (t>>24)&0xff; - *p++ = (t>>16)&0xff; - *p++ = (t>> 8)&0xff; - *p = t &0xff; -} - -template::value>::type* = nullptr> -void -write(ostream& os, U u) -{ - BOOST_ASSERT(u <= field::max); - auto const t = static_cast(u); - std::uint8_t* p = os.data(field::size); - *p++ = (t>>40)&0xff; - *p++ = (t>>32)&0xff; - *p++ = (t>>24)&0xff; - *p++ = (t>>16)&0xff; - *p++ = (t>> 8)&0xff; - *p = t &0xff; -} - -template::value>::type* = nullptr> -void -write(ostream& os, U u) -{ - auto const t = static_cast(u); - std::uint8_t* p = os.data(field::size); - *p++ = (t>>56)&0xff; - *p++ = (t>>48)&0xff; - *p++ = (t>>40)&0xff; - *p++ = (t>>32)&0xff; - *p++ = (t>>24)&0xff; - *p++ = (t>>16)&0xff; - *p++ = (t>> 8)&0xff; - *p = t &0xff; -} - -} // detail -} // nudb - -#endif diff --git a/src/nudb/include/nudb/detail/format.hpp b/src/nudb/include/nudb/detail/format.hpp deleted file mode 100644 index c6ea314e7a..0000000000 --- a/src/nudb/include/nudb/detail/format.hpp +++ /dev/null @@ -1,629 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_DETAIL_FORMAT_HPP -#define NUDB_DETAIL_FORMAT_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace nudb { -namespace detail { - -// Format of the nudb files: - -/* - -Integer sizes - -block_size less than 32 bits (maybe restrict it to 16 bits) -buckets more than 32 bits -capacity (same as bucket index) -file offsets 63 bits -hash up to 64 bits (48 currently) -item index less than 32 bits (index of item in bucket) -modulus (same as buckets) -value size up to 32 bits (or 32-bit builds can't read it) - -*/ - -static std::size_t constexpr currentVersion = 2; - -struct dat_file_header -{ - static std::size_t constexpr size = - 8 + // Type - 2 + // Version - 8 + // UID - 8 + // Appnum - 2 + // KeySize - - 64; // (Reserved) - - char type[8]; - std::size_t version; - std::uint64_t uid; - std::uint64_t appnum; - nsize_t key_size; -}; - -struct key_file_header -{ - static std::size_t constexpr size = - 8 + // Type - 2 + // Version - 8 + // UID - 8 + // Appnum - 2 + // KeySize - - 8 + // Salt - 8 + // Pepper - 2 + // BlockSize - 2 + // LoadFactor - - 56; // (Reserved) - - char type[8]; - std::size_t version; - std::uint64_t uid; - std::uint64_t appnum; - nsize_t key_size; - - std::uint64_t salt; - std::uint64_t pepper; - nsize_t block_size; - std::size_t load_factor; - - // Computed values - nkey_t capacity; // Entries per bucket - nbuck_t buckets; // Number of buckets - nbuck_t modulus; // pow(2,ceil(log2(buckets))) -}; - -struct log_file_header -{ - static std::size_t constexpr size = - 8 + // Type - 2 + // Version - 8 + // UID - 8 + // Appnum - 2 + // KeySize - - 8 + // Salt - 8 + // Pepper - 2 + // BlockSize - - 8 + // KeyFileSize - 8; // DataFileSize - - char type[8]; - std::size_t version; - std::uint64_t uid; - std::uint64_t appnum; - nsize_t key_size; - std::uint64_t salt; - std::uint64_t pepper; - nsize_t block_size; - noff_t key_file_size; - noff_t dat_file_size; -}; - -// Type used to store hashes in buckets. -// This can be smaller than the output -// of the hash function. -// -using f_hash = uint48_t; - -static_assert(field::size <= - sizeof(nhash_t), ""); - -template -nhash_t -make_hash(nhash_t h); - -template<> -inline -nhash_t -make_hash(nhash_t h) -{ - return(h>>16)&0xffffffffffff; -} - -// Returns the hash of a key given the salt. -// Note: The hash is expressed in f_hash units -// -template -inline -nhash_t -hash(void const* key, nsize_t key_size, std::uint64_t salt) -{ - Hasher h{salt}; - return make_hash(h(key, key_size)); -} - -template -inline -nhash_t -hash(void const* key, nsize_t key_size, Hasher const& h) -{ - return make_hash(h(key, key_size)); -} - -// Computes pepper from salt -// -template -std::uint64_t -pepper(std::uint64_t salt) -{ - auto const v = to_little_endian(salt); - Hasher h{salt}; - return h(&v, sizeof(v)); -} - -// Returns the actual size of a bucket. -// This can be smaller than the block size. -// -template -nsize_t -bucket_size(nkey_t capacity) -{ - // Bucket Record - return - field::size + // Count - field::size + // Spill - capacity * ( - field::size + // Offset - field::size + // Size - field::size); // Hash -} - -// Returns the number of entries that fit in a bucket -// -template -nkey_t -bucket_capacity(nsize_t block_size) -{ - // Bucket Record - auto const size = - field::size + // Count - field::size; // Spill - auto const entry_size = - field::size + // Offset - field::size + // Size - field::size; // Hash - if(block_size < key_file_header::size || - block_size < size) - return 0; - auto const n = - (block_size - size) / entry_size; - BOOST_ASSERT(n <= std::numeric_limits::max()); - return static_cast(std::min( - std::numeric_limits::max(), n)); -} - -// Returns the number of bytes occupied by a value record -// VFALCO TODO Fix this -inline -std::size_t -value_size(std::size_t size, - std::size_t key_size) -{ - // Data Record - return - field::size + // Size - key_size + // Key - size; // Data -} - -// Returns the closest power of 2 not less than x -template -T -ceil_pow2(T x) -{ - static const unsigned long long t[6] = { - 0xFFFFFFFF00000000ull, - 0x00000000FFFF0000ull, - 0x000000000000FF00ull, - 0x00000000000000F0ull, - 0x000000000000000Cull, - 0x0000000000000002ull - }; - - int y =(((x &(x - 1)) == 0) ? 0 : 1); - int j = 32; - int i; - - for(i = 0; i < 6; i++) { - int k =(((x & t[i]) == 0) ? 0 : j); - y += k; - x >>= k; - j >>= 1; - } - - return T{1}< -void -read(istream& is, dat_file_header& dh) -{ - read(is, dh.type, sizeof(dh.type)); - read(is, dh.version); - read(is, dh.uid); - read(is, dh.appnum); - read(is, dh.key_size); - std::array reserved; - read(is, reserved.data(), reserved.size()); -} - -// Read data file header from file -template -void -read(File& f, dat_file_header& dh, error_code& ec) -{ - std::array buf; - f.read(0, buf.data(), buf.size(), ec); - if(ec) - return; - istream is(buf); - read(is, dh); -} - -// Write data file header to stream -template -void -write(ostream& os, dat_file_header const& dh) -{ - write(os, "nudb.dat", 8); - write(os, dh.version); - write(os, dh.uid); - write(os, dh.appnum); - write(os, dh.key_size); - std::array reserved; - reserved.fill(0); - write(os, reserved.data(), reserved.size()); -} - -// Write data file header to file -template -void -write(File& f, dat_file_header const& dh, error_code& ec) -{ - std::array buf; - ostream os(buf); - write(os, dh); - f.write(0, buf.data(), buf.size(), ec); -} - -// Read key file header from stream -template -void -read(istream& is, noff_t file_size, key_file_header& kh) -{ - read(is, kh.type, sizeof(kh.type)); - read(is, kh.version); - read(is, kh.uid); - read(is, kh.appnum); - read(is, kh.key_size); - read(is, kh.salt); - read(is, kh.pepper); - read(is, kh.block_size); - read(is, kh.load_factor); - std::array reserved; - read(is, reserved.data(), reserved.size()); - - // VFALCO These need to be checked to handle - // when the file size is too small - kh.capacity = bucket_capacity(kh.block_size); - if(file_size > kh.block_size) - { - if(kh.block_size > 0) - kh.buckets = static_cast( - (file_size - kh.block_size) / kh.block_size); - else - // VFALCO Corruption or logic error - kh.buckets = 0; - } - else - { - kh.buckets = 0; - } - kh.modulus = ceil_pow2(kh.buckets); -} - -// Read key file header from file -template -void -read(File& f, key_file_header& kh, error_code& ec) -{ - std::array buf; - f.read(0, buf.data(), buf.size(), ec); - if(ec) - return; - istream is{buf}; - auto const size = f.size(ec); - if(ec) - return; - read(is, size, kh); -} - -// Write key file header to stream -template -void -write(ostream& os, key_file_header const& kh) -{ - write(os, "nudb.key", 8); - write(os, kh.version); - write(os, kh.uid); - write(os, kh.appnum); - write(os, kh.key_size); - write(os, kh.salt); - write(os, kh.pepper); - write(os, kh.block_size); - write(os, kh.load_factor); - std::array reserved; - reserved.fill(0); - write(os, reserved.data(), reserved.size()); -} - -// Write key file header to file -template -void -write(File& f, key_file_header const& kh, error_code& ec) -{ - buffer buf; - buf.reserve(kh.block_size); - if(kh.block_size < key_file_header::size) - { - ec = error::invalid_block_size; - return; - } - std::fill(buf.get(), buf.get() + buf.size(), 0); - ostream os{buf.get(), buf.size()}; - write(os, kh); - f.write(0, buf.get(), buf.size(), ec); -} - -// Read log file header from stream -template -void -read(istream& is, log_file_header& lh) -{ - read(is, lh.type, sizeof(lh.type)); - read(is, lh.version); - read(is, lh.uid); - read(is, lh.appnum); - read(is, lh.key_size); - read(is, lh.salt); - read(is, lh.pepper); - read(is, lh.block_size); - read(is, lh.key_file_size); - read(is, lh.dat_file_size); -} - -// Read log file header from file -template -void -read(File& f, log_file_header& lh, error_code& ec) -{ - std::array buf; - f.read(0, buf.data(), buf.size(), ec); - if(ec) - return; - istream is{buf}; - read(is, lh); -} - -// Write log file header to stream -template -void -write(ostream& os, log_file_header const& lh) -{ - write(os, "nudb.log", 8); - write(os, lh.version); - write(os, lh.uid); - write(os, lh.appnum); - write(os, lh.key_size); - write(os, lh.salt); - write(os, lh.pepper); - write(os, lh.block_size); - write(os, lh.key_file_size); - write(os, lh.dat_file_size); -} - -// Write log file header to file -template -void -write(File& f, log_file_header const& lh, error_code& ec) -{ - std::array buf; - ostream os{buf}; - write(os, lh); - f.write(0, buf.data(), buf.size(), ec); -} - -// Verify contents of data file header -template -void -verify(dat_file_header const& dh, error_code& ec) -{ - std::string const type{dh.type, 8}; - if(type != "nudb.dat") - { - ec = error::not_data_file; - return; - } - if(dh.version != currentVersion) - { - ec = error::different_version; - return; - } - if(dh.key_size < 1) - { - ec = error::invalid_key_size; - return; - } -} - -// Verify contents of key file header -template -void -verify(key_file_header const& kh, error_code& ec) -{ - std::string const type{kh.type, 8}; - if(type != "nudb.key") - { - ec = error::not_key_file; - return; - } - if(kh.version != currentVersion) - { - ec = error::different_version; - return; - } - if(kh.key_size < 1) - { - ec = error::invalid_key_size; - return; - } - if(kh.pepper != pepper(kh.salt)) - { - ec = error::hash_mismatch; - return; - } - if(kh.load_factor < 1) - { - ec = error::invalid_load_factor; - return; - } - if(kh.capacity < 1) - { - ec = error::invalid_capacity; - return; - } - if(kh.buckets < 1) - { - ec = error::invalid_bucket_count; - return; - } -} - -// Verify contents of log file header -template -void -verify(log_file_header const& lh, error_code& ec) -{ - std::string const type{lh.type, 8}; - if(type != "nudb.log") - { - ec = error::not_log_file; - return; - } - if(lh.version != currentVersion) - { - ec = error::different_version; - return; - } - if(lh.pepper != pepper(lh.salt)) - { - ec = error::hash_mismatch; - return; - } - if(lh.key_size < 1) - { - ec = error::invalid_key_size; - return; - } -} - -// Make sure key file and value file headers match -template -void -verify(dat_file_header const& dh, - key_file_header const& kh, error_code& ec) -{ - verify(kh, ec); - if(ec) - return; - if(kh.uid != dh.uid) - { - ec = error::uid_mismatch; - return; - } - if(kh.appnum != dh.appnum) - { - ec = error::appnum_mismatch; - return; - } - if(kh.key_size != dh.key_size) - { - ec = error::key_size_mismatch; - return; - } -} - -// Make sure key file and log file headers match -template -void -verify(key_file_header const& kh, - log_file_header const& lh, error_code& ec) -{ - verify(lh, ec); - if(ec) - return; - if(kh.uid != lh.uid) - { - ec = error::uid_mismatch; - return; - } - if(kh.appnum != lh.appnum) - { - ec = error::appnum_mismatch; - return; - } - if(kh.key_size != lh.key_size) - { - ec = error::key_size_mismatch; - return; - } - if(kh.salt != lh.salt) - { - ec = error::salt_mismatch; - return; - } - if(kh.pepper != lh.pepper) - { - ec = error::pepper_mismatch; - return; - } - if(kh.block_size != lh.block_size) - { - ec = error::block_size_mismatch; - return; - } -} - -} // detail -} // nudb - -#endif diff --git a/src/nudb/include/nudb/detail/gentex.hpp b/src/nudb/include/nudb/detail/gentex.hpp deleted file mode 100644 index 9adeeb6d96..0000000000 --- a/src/nudb/include/nudb/detail/gentex.hpp +++ /dev/null @@ -1,259 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_DETAIL_GENTEX_HPP -#define NUDB_DETAIL_GENTEX_HPP - -#include -#include -#include -#include -#include - -namespace nudb { -namespace detail { - -// Generation counting mutex -// -template -class gentex_t -{ -private: - std::mutex m_; - std::size_t gen_ = 0; - std::size_t cur_ = 0; - std::size_t prev_ = 0; - std::condition_variable cond_; - -public: - gentex_t() = default; - gentex_t(gentex_t const&) = delete; - gentex_t& operator=(gentex_t const&) = delete; - - void - start(); - - void - finish(); - - std::size_t - lock_gen(); - - void - unlock_gen(std::size_t gen); -}; - -template -void -gentex_t<_>:: -start() -{ - std::unique_lock l{m_}; - prev_ += cur_; - cur_ = 0; - ++gen_; -} - -template -void -gentex_t<_>:: -finish() -{ - std::unique_lock l{m_}; - while(prev_ > 0) - cond_.wait(l); -} - -template -std::size_t -gentex_t<_>:: -lock_gen() -{ - std::lock_guard< - std::mutex> l{m_}; - ++cur_; - return gen_; -} - -template -void -gentex_t<_>:: -unlock_gen(std::size_t gen) -{ - std::unique_lock l{m_}; - if(gen == gen_) - { - --cur_; - } - else - { - --prev_; - if(prev_ == 0) - cond_.notify_all(); - } -} - -using gentex = gentex_t<>; - -//------------------------------------------------------------------------------ - -template -class genlock -{ -private: - bool owned_ = false; - GenerationLockable* g_ = nullptr; - std::size_t gen_; - -public: - using mutex_type = GenerationLockable; - - genlock() = default; - genlock(genlock const&) = delete; - genlock& operator=(genlock const&) = delete; - - genlock(genlock&& other); - - genlock& operator=(genlock&& other); - - explicit - genlock(mutex_type& g); - - genlock(mutex_type& g, std::defer_lock_t); - - ~genlock(); - - mutex_type* - mutex() noexcept - { - return g_; - } - - bool - owns_lock() const noexcept - { - return g_ && owned_; - } - - explicit - operator bool() const noexcept - { - return owns_lock(); - } - - void - lock(); - - void - unlock(); - - mutex_type* - release() noexcept; - - template - friend - void - swap(genlock& lhs, genlock& rhs) noexcept; -}; - -template -genlock:: -genlock(genlock&& other) - : owned_(other.owned_) - , g_(other.g_) -{ - other.owned_ = false; - other.g_ = nullptr; -} - -template -genlock& -genlock:: -operator=(genlock&& other) -{ - if(owns_lock()) - unlock(); - owned_ = other.owned_; - g_ = other.g_; - other.owned_ = false; - other.g_ = nullptr; - return *this; -} - -template -genlock:: -genlock(mutex_type& g) - : g_(&g) -{ - lock(); -} - -template -genlock:: -genlock(mutex_type& g, std::defer_lock_t) - : g_(&g) -{ -} - -template -genlock:: -~genlock() -{ - if(owns_lock()) - unlock(); -} - -template -void -genlock:: -lock() -{ - // no associated gentex - BOOST_ASSERT(g_ != nullptr); - // gentex is already owned - BOOST_ASSERT(! owned_); - gen_ = g_->lock_gen(); - owned_ = true; -} - -template -void -genlock:: -unlock() -{ - // no associated gentex - BOOST_ASSERT(g_ != nullptr); - // gentex is not owned - BOOST_ASSERT(owned_); - g_->unlock_gen(gen_); - owned_ = false; -} - -template -auto -genlock:: -release() noexcept -> - mutex_type* -{ - mutex_type* const g = g_; - g_ = nullptr; - return g; -} - -template -void -swap(genlock& lhs, genlock& rhs) noexcept -{ - using namespace std; - swap(lhs.owned_, rhs.owned_); - swap(lhs.g_, rhs.g_); -} - -} // detail -} // nudb - -#endif diff --git a/src/nudb/include/nudb/detail/mutex.hpp b/src/nudb/include/nudb/detail/mutex.hpp deleted file mode 100644 index 779e39fdc6..0000000000 --- a/src/nudb/include/nudb/detail/mutex.hpp +++ /dev/null @@ -1,26 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_DETAIL_MUTEX_HPP -#define NUDB_DETAIL_MUTEX_HPP - -#include -#include - -namespace nudb { -namespace detail { - -using shared_lock_type = - boost::shared_lock; - -using unique_lock_type = - boost::unique_lock; - -} // detail -} // nudb - -#endif diff --git a/src/nudb/include/nudb/detail/pool.hpp b/src/nudb/include/nudb/detail/pool.hpp deleted file mode 100644 index 0b0a5daa96..0000000000 --- a/src/nudb/include/nudb/detail/pool.hpp +++ /dev/null @@ -1,243 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_DETAIL_POOL_HPP -#define NUDB_DETAIL_POOL_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace nudb { -namespace detail { - -// Buffers key/value pairs in a map, associating -// them with a modifiable data file offset. -template -class pool_t -{ -public: - struct value_type; - class compare; - -private: - using map_type = std::map< - value_type, noff_t, compare>; - - arena arena_; - nsize_t key_size_; - nsize_t data_size_ = 0; - map_type map_; - -public: - using iterator = - typename map_type::iterator; - - pool_t(pool_t const&) = delete; - pool_t& operator=(pool_t const&) = delete; - - pool_t(pool_t&& other); - - pool_t(nsize_t key_size, char const* label); - - iterator - begin() - { - return map_.begin(); - } - - iterator - end() - { - return map_.end(); - } - - bool - empty() const - { - return map_.size() == 0; - } - - // Returns the number of elements in the pool - std::size_t - size() const - { - return map_.size(); - } - - // Returns the sum of data sizes in the pool - std::size_t - data_size() const - { - return data_size_; - } - - void - clear(); - - void - periodic_activity(); - - iterator - find(void const* key); - - // Insert a value - // @param h The hash of the key - void - insert(nhash_t h, void const* key, - void const* buffer, nsize_t size); - - template - friend - void - swap(pool_t& lhs, pool_t& rhs); -}; - -template -struct pool_t<_>::value_type -{ - nhash_t hash; - nsize_t size; - void const* key; - void const* data; - - value_type(value_type const&) = default; - value_type& operator=(value_type const&) = default; - - value_type(nhash_t hash_, nsize_t size_, - void const* key_, void const* data_) - : hash(hash_) - , size(size_) - , key(key_) - , data(data_) - { - } -}; - -template -class pool_t<_>::compare -{ - std::size_t key_size_; - -public: - using result_type = bool; - using first_argument_type = value_type; - using second_argument_type = value_type; - - compare(compare const&) = default; - compare& operator=(compare const&) = default; - - explicit - compare(nsize_t key_size) - : key_size_(key_size) - { - } - - bool - operator()(value_type const& lhs, - value_type const& rhs) const - { - return std::memcmp( - lhs.key, rhs.key, key_size_) < 0; - } -}; - -//------------------------------------------------------------------------------ - -template -pool_t<_>:: -pool_t(pool_t&& other) - : arena_(std::move(other.arena_)) - , key_size_(other.key_size_) - , data_size_(other.data_size_) - , map_(std::move(other.map_)) -{ -} - -template -pool_t<_>:: -pool_t(nsize_t key_size, char const* label) - : arena_(label) - , key_size_(key_size) - , map_(compare{key_size}) -{ -} - -template -void -pool_t<_>:: -clear() -{ - arena_.clear(); - data_size_ = 0; - map_.clear(); -} - -template -void -pool_t<_>:: -periodic_activity() -{ - arena_.periodic_activity(); -} - -template -auto -pool_t<_>:: -find(void const* key) -> - iterator -{ - // VFALCO need is_transparent here - value_type tmp{0, 0, key, nullptr}; - auto const iter = map_.find(tmp); - return iter; -} - -template -void -pool_t<_>:: -insert(nhash_t h, - void const* key, void const* data, nsize_t size) -{ - auto const k = arena_.alloc(key_size_); - auto const d = arena_.alloc(size); - std::memcpy(k, key, key_size_); - std::memcpy(d, data, size); - auto const result = map_.emplace( - std::piecewise_construct, - std::make_tuple(h, size, k, d), - std::make_tuple(0)); - (void)result.second; - // Must not already exist! - BOOST_ASSERT(result.second); - data_size_ += size; -} - -template -void -swap(pool_t<_>& lhs, pool_t<_>& rhs) -{ - using std::swap; - swap(lhs.arena_, rhs.arena_); - swap(lhs.key_size_, rhs.key_size_); - swap(lhs.data_size_, rhs.data_size_); - swap(lhs.map_, rhs.map_); -} - -using pool = pool_t<>; - -} // detail -} // nudb - -#endif diff --git a/src/nudb/include/nudb/detail/stream.hpp b/src/nudb/include/nudb/detail/stream.hpp deleted file mode 100644 index 6c07bf11b9..0000000000 --- a/src/nudb/include/nudb/detail/stream.hpp +++ /dev/null @@ -1,149 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_DETAIL_STREAM_HPP -#define NUDB_DETAIL_STREAM_HPP - -#include -#include -#include -#include -#include -#include - -namespace nudb { -namespace detail { - -// Input stream from bytes -template -class istream_t -{ - std::uint8_t const* buf_ = nullptr; - std::size_t size_ = 0; - -public: - istream_t() = default; - istream_t(istream_t const&) = default; - istream_t& operator=(istream_t const&) = default; - - istream_t(void const* data, std::size_t size) - : buf_(reinterpret_cast(data)) - , size_(size) - { - } - - template - istream_t(std::array const& a) - : buf_(a.data()) - , size_(a.size()) - { - } - - std::uint8_t const* - data(std::size_t bytes); - - std::uint8_t const* - operator()(std::size_t bytes) - { - return data(bytes); - } -}; - -// Precondition: bytes <= size_ -// -template -std::uint8_t const* -istream_t<_>::data(std::size_t bytes) -{ - BOOST_ASSERT(bytes <= size_); - if(size_ < bytes) - throw std::logic_error("short read from istream"); - auto const data = buf_; - buf_ = buf_ + bytes; - size_ -= bytes; - return data; -} - -using istream = istream_t<>; - -//------------------------------------------------------------------------------ - -// Output stream to bytes -// VFALCO Should this assert on overwriting the buffer? -template -class ostream_t -{ - std::uint8_t* buf_ = nullptr; - std::size_t size_ = 0; - -public: - ostream_t() = default; - ostream_t(ostream_t const&) = default; - ostream_t& operator=(ostream_t const&) = default; - - ostream_t(void* data, std::size_t) - : buf_(reinterpret_cast(data)) - { - } - - template - ostream_t(std::array& a) - : buf_(a.data()) - { - } - - // Returns the number of bytes written - std::size_t - size() const - { - return size_; - } - - std::uint8_t* - data(std::size_t bytes); - - std::uint8_t* - operator()(std::size_t bytes) - { - return data(bytes); - } -}; - -template -std::uint8_t* -ostream_t<_>::data(std::size_t bytes) -{ - auto const data = buf_; - buf_ = buf_ + bytes; - size_ += bytes; - return data; -} - -using ostream = ostream_t<>; - -//------------------------------------------------------------------------------ - -// read blob -inline -void -read(istream& is, void* buffer, std::size_t bytes) -{ - std::memcpy(buffer, is.data(bytes), bytes); -} - -// write blob -inline -void -write(ostream& os, void const* buffer, std::size_t bytes) -{ - std::memcpy(os.data(bytes), buffer, bytes); -} - -} // detail -} // nudb - -#endif diff --git a/src/nudb/include/nudb/detail/xxhash.hpp b/src/nudb/include/nudb/detail/xxhash.hpp deleted file mode 100644 index 648b2cf849..0000000000 --- a/src/nudb/include/nudb/detail/xxhash.hpp +++ /dev/null @@ -1,328 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// -// This is a derivative work based on xxHash 0.6.2, copyright below: -/* - xxHash - Extremely Fast Hash algorithm - Header File - Copyright (C) 2012-2016, Yann Collet. - - BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - You can contact the author at : - - xxHash source repository : https://github.com/Cyan4973/xxHash -*/ - -#ifndef NUDB_DETAIL_XXHASH_HPP -#define NUDB_DETAIL_XXHASH_HPP - -#include -#include -#include -#include - -namespace nudb { -namespace detail { - -#define NUDB_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) - -// minGW _rotl gives poor performance -#if defined(_MSC_VER) -# define NUDB_XXH_rotl64(x,r) _rotl64(x,r) -#else -# define NUDB_XXH_rotl64(x,r) ((x << r) | (x >> (64 - r))) -#endif - -#if defined(_MSC_VER) -# define NUDB_XXH_swap32 _byteswap_ulong -#elif NUDB_GCC_VERSION >= 403 -# define NUDB_XXH_swap32 __builtin_bswap32 -#endif - -#if defined(_MSC_VER) -# define NUDB_XXH_swap64 _byteswap_uint64 -#elif NUDB_GCC_VERSION >= 403 -# define NUDB_XXH_swap64 __builtin_bswap64 -#endif - -#ifndef NUDB_XXH_swap32 -inline -std::uint32_t -NUDB_XXH_swap32(std::uint32_t x) -{ - return ((x << 24) & 0xff000000 ) | - ((x << 8) & 0x00ff0000 ) | - ((x >> 8) & 0x0000ff00 ) | - ((x >> 24) & 0x000000ff ); -} -#endif - -#ifndef NUDB_XXH_swap64 -inline -std::uint64_t -NUDB_XXH_swap64(std::uint64_t x) -{ - return ((x << 56) & 0xff00000000000000ULL) | - ((x << 40) & 0x00ff000000000000ULL) | - ((x << 24) & 0x0000ff0000000000ULL) | - ((x << 8) & 0x000000ff00000000ULL) | - ((x >> 8) & 0x00000000ff000000ULL) | - ((x >> 24) & 0x0000000000ff0000ULL) | - ((x >> 40) & 0x000000000000ff00ULL) | - ((x >> 56) & 0x00000000000000ffULL); -} -#endif - -static std::uint64_t constexpr prime64_1 = 11400714785074694791ULL; -static std::uint64_t constexpr prime64_2 = 14029467366897019727ULL; -static std::uint64_t constexpr prime64_3 = 1609587929392839161ULL; -static std::uint64_t constexpr prime64_4 = 9650029242287828579ULL; -static std::uint64_t constexpr prime64_5 = 2870177450012600261ULL; - -// Portable and safe solution. Generally efficient. -// see : http://stackoverflow.com/a/32095106/646947 - -inline -std::uint32_t -XXH_read32(void const* p) -{ - std::uint32_t v; - memcpy(&v, p, sizeof(v)); - return v; -} - -inline -std::uint64_t -XXH_read64(void const* p) -{ - std::uint64_t v; - memcpy(&v, p, sizeof(v)); - return v; -} - -// little endian, aligned -inline -std::uint32_t -XXH_readLE32_align(void const* p, std::true_type, std::true_type) -{ - return *reinterpret_cast(p); -} - -// little endian, unaligned -inline -std::uint32_t -XXH_readLE32_align(void const* p, std::true_type, std::false_type) -{ - return XXH_read32(p); -} - -// big endian, aligned -inline -std::uint32_t -XXH_readLE32_align(void const* p, std::false_type, std::true_type) -{ - return NUDB_XXH_swap32( - *reinterpret_cast(p)); -} - -// big endian, unaligned -inline -std::uint32_t -XXH_readLE32_align(void const* p, std::false_type, std::false_type) -{ - return NUDB_XXH_swap32(XXH_read32(p)); -} - -// little endian, aligned -inline -std::uint64_t -XXH_readLE64_align(void const* p, std::true_type, std::true_type) -{ - return *reinterpret_cast(p); -} - -// little endian, unaligned -inline -std::uint64_t -XXH_readLE64_align(void const* p, std::true_type, std::false_type) -{ - return XXH_read64(p); -} - -// big endian, aligned -inline -std::uint64_t -XXH_readLE64_align(void const* p, std::false_type, std::true_type) -{ - return NUDB_XXH_swap64( - *reinterpret_cast(p)); -} - -// big endian, unaligned -inline -std::uint64_t -XXH_readLE64_align(void const* p, std::false_type, std::false_type) -{ - return NUDB_XXH_swap64(XXH_read64(p)); -} - -inline -std::uint64_t -XXH64_round(std::uint64_t acc, std::uint64_t input) -{ - acc += input * prime64_2; - acc = NUDB_XXH_rotl64(acc, 31); - acc *= prime64_1; - return acc; -} - -inline -std::uint64_t -XXH64_mergeRound(std::uint64_t acc, std::uint64_t val) -{ - val = XXH64_round(0, val); - acc ^= val; - acc = acc * prime64_1 + prime64_4; - return acc; -} - -template -std::uint64_t -XXH64_endian_align( - void const* input, std::size_t len, std::uint64_t seed, - std::integral_constant endian, - std::integral_constant align) -{ - const std::uint8_t* p = (const std::uint8_t*)input; - const std::uint8_t* const bEnd = p + len; - std::uint64_t h64; - auto const XXH_get32bits = - [](void const* p) - { - return XXH_readLE32_align(p, - decltype(endian){}, decltype(align){}); - }; - auto const XXH_get64bits = - [](void const* p) - { - return XXH_readLE64_align(p, - decltype(endian){}, decltype(align){}); - }; - if(len>=32) - { - const std::uint8_t* const limit = bEnd - 32; - std::uint64_t v1 = seed + prime64_1 + prime64_2; - std::uint64_t v2 = seed + prime64_2; - std::uint64_t v3 = seed + 0; - std::uint64_t v4 = seed - prime64_1; - - do - { - v1 = XXH64_round(v1, XXH_get64bits(p)); p+=8; - v2 = XXH64_round(v2, XXH_get64bits(p)); p+=8; - v3 = XXH64_round(v3, XXH_get64bits(p)); p+=8; - v4 = XXH64_round(v4, XXH_get64bits(p)); p+=8; - } - while(p<=limit); - - h64 = NUDB_XXH_rotl64(v1, 1) + - NUDB_XXH_rotl64(v2, 7) + - NUDB_XXH_rotl64(v3, 12) + - NUDB_XXH_rotl64(v4, 18); - h64 = XXH64_mergeRound(h64, v1); - h64 = XXH64_mergeRound(h64, v2); - h64 = XXH64_mergeRound(h64, v3); - h64 = XXH64_mergeRound(h64, v4); - } - else - { - h64 = seed + prime64_5; - } - h64 += len; - while(p + 8 <= bEnd) - { - std::uint64_t const k1 = XXH64_round(0, XXH_get64bits(p)); - h64 ^= k1; - h64 = NUDB_XXH_rotl64(h64,27) * prime64_1 + prime64_4; - p+=8; - } - if(p+4<=bEnd) - { - h64 ^= (std::uint64_t)(XXH_get32bits(p)) * prime64_1; - h64 = NUDB_XXH_rotl64(h64, 23) * prime64_2 + prime64_3; - p+=4; - } - while(p> 33; - h64 *= prime64_2; - h64 ^= h64 >> 29; - h64 *= prime64_3; - h64 ^= h64 >> 32; - return h64; -} - -/* Calculate the 64-bit hash of a block of memory. - - @param data A pointer to the buffer to compute the hash on. - The buffer may be unaligned. - - @note This function runs faster on 64-bits systems, but slower - on 32-bits systems (see benchmark). - - @param bytes The size of the buffer in bytes. - - @param seed A value which may be used to permute the output. - Using a different seed with the same input will produce a - different value. - - @return The 64-bit hash of the input data. -*/ -template -std::uint64_t -XXH64(void const* data, size_t bytes, std::uint64_t seed) -{ - // Use faster algorithm if aligned - if((reinterpret_cast(data) & 7) == 0) - return XXH64_endian_align(data, bytes, seed, - is_little_endian{}, std::false_type{}); - return XXH64_endian_align(data, bytes, seed, - is_little_endian{}, std::true_type{}); -} - -} // detail -} // nudb - -#endif - diff --git a/src/nudb/include/nudb/error.hpp b/src/nudb/include/nudb/error.hpp deleted file mode 100644 index 082ff41f50..0000000000 --- a/src/nudb/include/nudb/error.hpp +++ /dev/null @@ -1,263 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_ERROR_HPP -#define NUDB_ERROR_HPP - -#include -#include - -namespace nudb { - -/// The type of system-specific error code returned by the implementation -#if GENERATING_DOCS -class error_code{}; - -#else -using boost::system::error_code; - -#endif - -/// The type of cross-platform error code used by the implementation -#if GENERATING_DOCS -class error_condition{}; - -#else -using boost::system::error_condition; - -#endif - -/// The type of system-specific exception used when throwing -#if GENERATING_DOCS -class system_error{}; - -#else -using boost::system::system_error; - -#endif - -/// Returns the category used for system-specific error codes -#if GENERATING_DOCS -error_category const& -system_category(); - -#else -using boost::system::system_category; - -#endif - -/// Returns the category used for cross-platform error codes -#if GENERATING_DOCS -error_category const& -generic_category(); - -#else -using boost::system::generic_category; - -#endif - -/// The base class used for error categories -#if GENERATING_DOCS -class error_category{}; - -#else -using boost::system::error_category; - -#endif - -/// The set of constants used for cross-platform error codes -#if GENERATING_DOCS -enum errc{}; - -#else -namespace errc = boost::system::errc; - -#endif - -/// Database error codes. -enum class error -{ - /** No error. - - The operation completed successfully. - */ - success = 0, - - /** The specified key was not found. - - Returned when @ref basic_store::fetch does not - find the specified key. - */ - key_not_found, - - /** The specified key already exists. - - Returned when @ref basic_store::insert finds - the specified key already in the database. - */ - key_exists, - - /** A file read returned less data than expected. - - This can be caused by premature application - termination during a commit cycle. - */ - short_read, - - /** A log file is present. - - Indicates that the database needs to have the - associated log file applied to perform a recovery. - This error is returned by functions such as @ref rekey. - */ - log_file_exists, - - /** No key file exists. - - This error is returned by the recover process when - there is no valid key file. It happens when a - @ref rekey operation prematurely terminates. A - database without a key file cannot be opened. To - fix this error, it is necessary for an invocation of - @ref rekey to complete successfully. - */ - no_key_file, - - /// Too many buckets in key file - too_many_buckets, - - /// Not a data file - not_data_file, - - /// Not a key file - not_key_file, - - /// Not a log file - not_log_file, - - /// Different version - different_version, - - /// Invalid key size - invalid_key_size, - - /// Invalid block size - invalid_block_size, - - /// Short key file - short_key_file, - - /// Short bucket - short_bucket, - - /// Short spill - short_spill, - - /// Short record - short_data_record, - - /// Short value - short_value, - - /// Hash mismatch - hash_mismatch, - - /// Invalid load factor - invalid_load_factor, - - /// Invalid capacity - invalid_capacity, - - /// Invalid bucket count - invalid_bucket_count, - - /// Invalid bucket size - invalid_bucket_size, - - /// The data file header was incomplete - incomplete_data_file_header, - - /// The key file header was incomplete - incomplete_key_file_header, - - /// Invalid log record - invalid_log_record, - - /// Invalid spill in log record - invalid_log_spill, - - /// Invalid offset in log record - invalid_log_offset, - - /// Invalid index in log record - invalid_log_index, - - /// Invalid size in spill - invalid_spill_size, - - /// UID mismatch - uid_mismatch, - - /// appnum mismatch - appnum_mismatch, - - /// key size mismatch - key_size_mismatch, - - /// salt mismatch - salt_mismatch, - - /// pepper mismatch - pepper_mismatch, - - /// block size mismatch - block_size_mismatch, - - /// orphaned value - orphaned_value, - - /// missing value - missing_value, - - /// size mismatch - size_mismatch, - - /// duplicate value - duplicate_value -}; - -/// Returns the error category used for database error codes. -error_category const& -nudb_category(); - -/** Returns a database error code. - - This function is used by the implementation to convert - @ref error values into @ref error_code objects. -*/ -inline -error_code -make_error_code(error ev) -{ - return error_code{static_cast(ev), nudb_category()}; -} - -} // nudb - -namespace boost { -namespace system { -template<> -struct is_error_code_enum -{ - static bool const value = true; -}; -} // system -} // boost - -#include - -#endif diff --git a/src/nudb/include/nudb/file.hpp b/src/nudb/include/nudb/file.hpp deleted file mode 100644 index 409aa1981f..0000000000 --- a/src/nudb/include/nudb/file.hpp +++ /dev/null @@ -1,53 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_FILE_HPP -#define NUDB_FILE_HPP - -#include -#include - -namespace nudb { - -/// The type used to hold paths to files -using path_type = std::string; - -/** Returns the best guess at the volume's block size. - - @param path A path to a file on the device. The file does - not need to exist. -*/ -inline -std::size_t -block_size(path_type const& path) -{ - // A reasonable default for many SSD devices - return 4096; -} - -/** File create and open modes. - - These are used by @ref native_file. -*/ -enum class file_mode -{ - /// Open the file for sequential reads - scan, - - /// Open the file for random reads - read, - - /// Open the file for random reads and appending writes - append, - - /// Open the file for random reads and writes - write -}; - -} // nudb - -#endif diff --git a/src/nudb/include/nudb/impl/basic_store.ipp b/src/nudb/include/nudb/impl/basic_store.ipp deleted file mode 100644 index 404a4e3098..0000000000 --- a/src/nudb/include/nudb/impl/basic_store.ipp +++ /dev/null @@ -1,793 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_IMPL_BASIC_STORE_IPP -#define NUDB_IMPL_BASIC_STORE_IPP - -#include -#include -#include -#include -#include - -#ifndef NUDB_DEBUG_LOG -#define NUDB_DEBUG_LOG 0 -#endif -#if NUDB_DEBUG_LOG -#include -#include -#endif - -namespace nudb { - -template -basic_store::state:: -state(File&& df_, File&& kf_, File&& lf_, - path_type const& dp_, path_type const& kp_, - path_type const& lp_, - detail::key_file_header const& kh_) - : df(std::move(df_)) - , kf(std::move(kf_)) - , lf(std::move(lf_)) - , dp(dp_) - , kp(kp_) - , lp(lp_) - , hasher(kh_.salt) - , p0(kh_.key_size, "p0") - , p1(kh_.key_size, "p1") - , c1(kh_.key_size, kh_.block_size, "c1") - , kh(kh_) -{ - static_assert(is_File::value, - "File requirements not met"); -} - -//------------------------------------------------------------------------------ - -template -basic_store:: -~basic_store() -{ - error_code ec; - // We call close here to make sure data is intact - // if an exception destroys the basic_store, but callers - // should always call close manually to receive the - // error code. - close(ec); -} - -template -path_type const& -basic_store:: -dat_path() const -{ - BOOST_ASSERT(is_open()); - return s_->dp; -} - -template -path_type const& -basic_store:: -key_path() const -{ - BOOST_ASSERT(is_open()); - return s_->kp; -} - -template -path_type const& -basic_store:: -log_path() const -{ - BOOST_ASSERT(is_open()); - return s_->lp; -} - -template -std::uint64_t -basic_store:: -appnum() const -{ - BOOST_ASSERT(is_open()); - return s_->kh.appnum; -} - -template -std::size_t -basic_store:: -key_size() const -{ - BOOST_ASSERT(is_open()); - return s_->kh.key_size; -} - -template -std::size_t -basic_store:: -block_size() const -{ - BOOST_ASSERT(is_open()); - return s_->kh.block_size; -} - -template -template -void -basic_store:: -open( - path_type const& dat_path, - path_type const& key_path, - path_type const& log_path, - error_code& ec, - Args&&... args) -{ - static_assert(is_Hasher::value, - "Hasher requirements not met"); - using namespace detail; - BOOST_ASSERT(! is_open()); - ec_ = {}; - ecb_.store(false); - recover( - dat_path, key_path, log_path, ec, args...); - if(ec) - return; - File df(args...); - File kf(args...); - File lf(args...); - df.open(file_mode::append, dat_path, ec); - if(ec) - return; - kf.open(file_mode::write, key_path, ec); - if(ec) - return; - lf.create(file_mode::append, log_path, ec); - if(ec) - return; - // VFALCO TODO Erase empty log file if this - // function subsequently fails. - dat_file_header dh; - read(df, dh, ec); - if(ec) - return; - verify(dh, ec); - if(ec) - return; - key_file_header kh; - read(kf, kh, ec); - if(ec) - return; - verify(kh, ec); - if(ec) - return; - verify(dh, kh, ec); - if(ec) - return; - boost::optional s; - s.emplace(std::move(df), std::move(kf), std::move(lf), - dat_path, key_path, log_path, kh); - thresh_ = std::max(65536UL, - kh.load_factor * kh.capacity); - frac_ = thresh_ / 2; - buckets_ = kh.buckets; - modulus_ = ceil_pow2(kh.buckets); - // VFALCO TODO This could be better - if(buckets_ < 1) - { - ec = error::short_key_file; - return; - } - dataWriteSize_ = 32 * nudb::block_size(dat_path); - logWriteSize_ = 32 * nudb::block_size(log_path); - s_.emplace(std::move(*s)); - open_ = true; - t_ = std::thread(&basic_store::run, this); -} - -template -void -basic_store:: -close(error_code& ec) -{ - if(open_) - { - open_ = false; - cv_.notify_all(); - t_.join(); - if(ecb_) - { - ec = ec_; - return; - } - s_->lf.close(); - state s{std::move(*s_)}; - File::erase(s.lp, ec_); - if(ec_) - ec = ec_; - } -} - -template -template -void -basic_store:: -fetch( - void const* key, - Callback && callback, - error_code& ec) -{ - using namespace detail; - BOOST_ASSERT(is_open()); - if(ecb_) - { - ec = ec_; - return; - } - auto const h = - hash(key, s_->kh.key_size, s_->hasher); - shared_lock_type m{m_}; - { - auto iter = s_->p1.find(key); - if(iter == s_->p1.end()) - { - iter = s_->p0.find(key); - if(iter == s_->p0.end()) - goto cont; - } - callback(iter->first.data, iter->first.size); - return; - } -cont: - auto const n = bucket_index(h, buckets_, modulus_); - auto const iter = s_->c1.find(n); - if(iter != s_->c1.end()) - return fetch(h, key, iter->second, callback, ec); - genlock g{g_}; - m.unlock(); - buffer buf{s_->kh.block_size}; - // b constructs from uninitialized buf - bucket b{s_->kh.block_size, buf.get()}; - b.read(s_->kf, (n + 1) * b.block_size(), ec); - if(ec) - return; - fetch(h, key, b, callback, ec); -} - -template -void -basic_store:: -insert( - void const* key, - void const* data, - nsize_t size, - error_code& ec) -{ - using namespace detail; - using namespace std::chrono; - BOOST_ASSERT(is_open()); - if(ecb_) - { - ec = ec_; - return; - } - // Data Record - BOOST_ASSERT(size > 0); // zero disallowed - BOOST_ASSERT(size <= field::max); // too large - auto const h = - hash(key, s_->kh.key_size, s_->hasher); - std::lock_guard u{u_}; - { - shared_lock_type m{m_}; - if(s_->p1.find(key) != s_->p1.end() || - s_->p0.find(key) != s_->p0.end()) - { - ec = error::key_exists; - return; - } - auto const n = bucket_index(h, buckets_, modulus_); - auto const iter = s_->c1.find(n); - if(iter != s_->c1.end()) - { - auto const found = exists( - h, key, &m, iter->second, ec); - if(ec) - return; - if(found) - { - ec = error::key_exists; - return; - } - // m is now unlocked - } - else - { - // VFALCO Audit for concurrency - genlock g{g_}; - m.unlock(); - buffer buf; - buf.reserve(s_->kh.block_size); - bucket b{s_->kh.block_size, buf.get()}; - b.read(s_->kf, - static_cast(n + 1) * s_->kh.block_size, ec); - if(ec) - return; - auto const found = exists(h, key, nullptr, b, ec); - if(ec) - return; - if(found) - { - ec = error::key_exists; - return; - } - } - } - // Perform insert - unique_lock_type m{m_}; - s_->p1.insert(h, key, data, size); - auto const now = clock_type::now(); - auto const elapsed = duration_cast>( - now > s_->when ? now - s_->when : clock_type::duration{1}); - auto const work = s_->p1.data_size() + - 3 * s_->p1.size() * s_->kh.block_size; - auto const rate = static_cast( - std::ceil(work / elapsed.count())); - auto const sleep = - s_->rate && rate > s_->rate; - m.unlock(); - if(sleep) - std::this_thread::sleep_for(milliseconds{25}); -} - -// Fetch key in loaded bucket b or its spills. -// -template -template -void -basic_store:: -fetch( - detail::nhash_t h, - void const* key, - detail::bucket b, - Callback&& callback, - error_code& ec) -{ - using namespace detail; - buffer buf0; - buffer buf1; - for(;;) - { - for(auto i = b.lower_bound(h); i < b.size(); ++i) - { - auto const item = b[i]; - if(item.hash != h) - break; - // Data Record - auto const len = - s_->kh.key_size + // Key - item.size; // Value - buf0.reserve(len); - s_->df.read(item.offset + - field::size, // Size - buf0.get(), len, ec); - if(ec) - return; - if(std::memcmp(buf0.get(), key, - s_->kh.key_size) == 0) - { - callback( - buf0.get() + s_->kh.key_size, item.size); - return; - } - } - auto const spill = b.spill(); - if(! spill) - break; - buf1.reserve(s_->kh.block_size); - b = bucket(s_->kh.block_size, - buf1.get()); - b.read(s_->df, spill, ec); - if(ec) - return; - } - ec = error::key_not_found; -} - -// Returns `true` if the key exists -// lock is unlocked after the first bucket processed -// -template -bool -basic_store:: -exists( - detail::nhash_t h, - void const* key, - detail::shared_lock_type* lock, - detail::bucket b, - error_code& ec) -{ - using namespace detail; - buffer buf{s_->kh.key_size + s_->kh.block_size}; - void* pk = buf.get(); - void* pb = buf.get() + s_->kh.key_size; - for(;;) - { - for(auto i = b.lower_bound(h); i < b.size(); ++i) - { - auto const item = b[i]; - if(item.hash != h) - break; - // Data Record - s_->df.read(item.offset + - field::size, // Size - pk, s_->kh.key_size, ec); // Key - if(ec) - return false; - if(std::memcmp(pk, key, s_->kh.key_size) == 0) - return true; - } - auto spill = b.spill(); - if(lock && lock->owns_lock()) - lock->unlock(); - if(! spill) - break; - b = bucket(s_->kh.block_size, pb); - b.read(s_->df, spill, ec); - if(ec) - return false; - } - return false; -} - -// Split the bucket in b1 to b2 -// b1 must be loaded -// tmp is used as a temporary buffer -// splits are written but not the new buckets -// -template -void -basic_store:: -split( - detail::bucket& b1, - detail::bucket& b2, - detail::bucket& tmp, - nbuck_t n1, - nbuck_t n2, - nbuck_t buckets, - nbuck_t modulus, - detail::bulk_writer& w, - error_code& ec) -{ - using namespace detail; - // Trivial case: split empty bucket - if(b1.empty()) - return; - // Split - for(std::size_t i = 0; i < b1.size();) - { - auto const e = b1[i]; - auto const n = bucket_index(e.hash, buckets, modulus); - (void)n1; - (void)n2; - BOOST_ASSERT(n==n1 || n==n2); - if(n == n2) - { - b2.insert(e.offset, e.size, e.hash); - b1.erase(i); - } - else - { - ++i; - } - } - noff_t spill = b1.spill(); - if(spill) - { - b1.spill(0); - do - { - // If any part of the spill record is - // in the write buffer then flush first - if(spill + bucket_size(s_->kh.capacity) > - w.offset() - w.size()) - { - w.flush(ec); - if(ec) - return; - } - tmp.read(s_->df, spill, ec); - if(ec) - return; - for(std::size_t i = 0; i < tmp.size(); ++i) - { - auto const e = tmp[i]; - auto const n = bucket_index( - e.hash, buckets, modulus); - BOOST_ASSERT(n==n1 || n==n2); - if(n == n2) - { - maybe_spill(b2, w, ec); - if(ec) - return; - b2.insert(e.offset, e.size, e.hash); - } - else - { - maybe_spill(b1, w, ec); - if(ec) - return; - b1.insert(e.offset, e.size, e.hash); - } - } - spill = tmp.spill(); - } - while(spill); - } -} - -template -detail::bucket -basic_store:: -load( - nbuck_t n, - detail::cache& c1, - detail::cache& c0, - void* buf, - error_code& ec) -{ - using namespace detail; - auto iter = c1.find(n); - if(iter != c1.end()) - return iter->second; - iter = c0.find(n); - if(iter != c0.end()) - return c1.insert(n, iter->second)->second; - bucket tmp{s_->kh.block_size, buf}; - tmp.read(s_->kf, - static_cast(n + 1) * s_->kh.block_size, ec); - if(ec) - return {}; - c0.insert(n, tmp); - return c1.insert(n, tmp)->second; -} - -template -void -basic_store:: -commit(detail::unique_lock_type& m, - std::size_t& work, error_code& ec) -{ - using namespace detail; - BOOST_ASSERT(m.owns_lock()); - BOOST_ASSERT(! s_->p1.empty()); - swap(s_->p0, s_->p1); - m.unlock(); - work = s_->p0.data_size(); - cache c0(s_->kh.key_size, s_->kh.block_size, "c0"); - cache c1(s_->kh.key_size, s_->kh.block_size, "c1"); - // 0.63212 ~= 1 - 1/e - { - auto const size = static_cast( - std::ceil(0.63212 * s_->p0.size())); - c0.reserve(size); - c1.reserve(size); - } - buffer buf1{s_->kh.block_size}; - buffer buf2{s_->kh.block_size}; - bucket tmp{s_->kh.block_size, buf1.get()}; - // Prepare rollback information - log_file_header lh; - lh.version = currentVersion; // Version - lh.uid = s_->kh.uid; // UID - lh.appnum = s_->kh.appnum; // Appnum - lh.key_size = s_->kh.key_size; // Key Size - lh.salt = s_->kh.salt; // Salt - lh.pepper = pepper(lh.salt); // Pepper - lh.block_size = s_->kh.block_size; // Block Size - lh.key_file_size = s_->kf.size(ec); // Key File Size - if(ec) - return; - lh.dat_file_size = s_->df.size(ec); // Data File Size - if(ec) - return; - write(s_->lf, lh, ec); - if(ec) - return; - // Checkpoint - s_->lf.sync(ec); - if(ec) - return; - // Append data and spills to data file - auto modulus = modulus_; - auto buckets = buckets_; - { - // Bulk write to avoid write amplification - auto const size = s_->df.size(ec); - if(ec) - return; - bulk_writer w{s_->df, size, dataWriteSize_}; - // Write inserted data to the data file - for(auto& e : s_->p0) - { - // VFALCO This could be UB since other - // threads are reading other data members - // of this object in memory - e.second = w.offset(); - auto os = w.prepare(value_size( - e.first.size, s_->kh.key_size), ec); - if(ec) - return; - // Data Record - write(os, e.first.size); // Size - write(os, e.first.key, s_->kh.key_size); // Key - write(os, e.first.data, e.first.size); // Data - } - // Do inserts, splits, and build view - // of original and modified buckets - for(auto const e : s_->p0) - { - // VFALCO Should this be >= or > ? - if((frac_ += 65536) >= thresh_) - { - // split - frac_ -= thresh_; - if(buckets == modulus) - modulus *= 2; - auto const n1 = buckets - (modulus / 2); - auto const n2 = buckets++; - auto b1 = load(n1, c1, c0, buf2.get(), ec); - if(ec) - return; - auto b2 = c1.create(n2); - // If split spills, the writer is - // flushed which can amplify writes. - split(b1, b2, tmp, n1, n2, - buckets, modulus, w, ec); - if(ec) - return; - } - // Insert - auto const n = bucket_index( - e.first.hash, buckets, modulus); - auto b = load(n, c1, c0, buf2.get(), ec); - if(ec) - return; - // This can amplify writes if it spills. - maybe_spill(b, w, ec); - if(ec) - return; - b.insert(e.second, e.first.size, e.first.hash); - } - w.flush(ec); - if(ec) - return; - } - work += s_->kh.block_size * (2 * c0.size() + c1.size()); - // Give readers a view of the new buckets. - // This might be slightly better than the old - // view since there could be fewer spills. - m.lock(); - swap(c1, s_->c1); - s_->p0.clear(); - buckets_ = buckets; - modulus_ = modulus; - g_.start(); - m.unlock(); - // Write clean buckets to log file - { - auto const size = s_->lf.size(ec); - if(ec) - return; - bulk_writer w{s_->lf, size, logWriteSize_}; - for(auto const e : c0) - { - // Log Record - auto os = w.prepare( - field::size + // Index - e.second.actual_size(), ec); // Bucket - if(ec) - return; - // Log Record - write(os, e.first); // Index - e.second.write(os); // Bucket - } - c0.clear(); - w.flush(ec); - if(ec) - return; - s_->lf.sync(ec); - if(ec) - return; - } - g_.finish(); - // Write new buckets to key file - for(auto const e : s_->c1) - { - e.second.write(s_->kf, - (e.first + 1) * s_->kh.block_size, ec); - if(ec) - return; - } - // Finalize the commit - s_->df.sync(ec); - if(ec) - return; - s_->kf.sync(ec); - if(ec) - return; - s_->lf.trunc(0, ec); - if(ec) - return; - s_->lf.sync(ec); - if(ec) - return; - // Cache is no longer needed, all fetches will go straight - // to disk again. Do this after the sync, otherwise readers - // might get blocked longer due to the extra I/O. - m.lock(); - s_->c1.clear(); -} - -template -void -basic_store:: -run() -{ - using namespace std::chrono; - using namespace detail; - -#if NUDB_DEBUG_LOG - beast::unit_test::dstream dout{std::cout}; -#endif - for(;;) - { - unique_lock_type m{m_}; - if(! s_->p1.empty()) - { - std::size_t work; - commit(m, work, ec_); - if(ec_) - { - ecb_.store(true); - return; - } - BOOST_ASSERT(m.owns_lock()); - auto const now = clock_type::now(); - auto const elapsed = duration_cast>( - now > s_->when ? now - s_->when : clock_type::duration{1}); - s_->rate = static_cast( - std::ceil(work / elapsed.count())); - #if NUDB_DEBUG_LOG - dout << - "work=" << work << - ", time=" << elapsed.count() << - ", rate=" << s_->rate << - "\n"; - #endif - } - s_->p1.periodic_activity(); - - cv_.wait_until(m, s_->when + seconds{1}, - [this]{ return ! open_; }); - if(! open_) - break; - s_->when = clock_type::now(); - } - { - unique_lock_type m{m_}; - std::size_t work; - if(! s_->p1.empty()) - commit(m, work, ec_); - } - if(ec_) - { - ecb_.store(true); - return; - } -} - -} // nudb - -#endif diff --git a/src/nudb/include/nudb/impl/create.ipp b/src/nudb/include/nudb/impl/create.ipp deleted file mode 100644 index b0b8511fff..0000000000 --- a/src/nudb/include/nudb/impl/create.ipp +++ /dev/null @@ -1,163 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_IMPL_CREATE_IPP -#define NUDB_IMPL_CREATE_IPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace nudb { - -namespace detail { - -template -std::uint64_t -make_uid() -{ - std::random_device rng; - std::mt19937_64 gen {rng()}; - std::uniform_int_distribution dist; - return dist(gen); -} - -} // detail - -template -std::uint64_t -make_salt() -{ - std::random_device rng; - std::mt19937_64 gen {rng()}; - std::uniform_int_distribution dist; - return dist(gen); -} - -template< - class Hasher, - class File, - class... Args -> -void -create( - path_type const& dat_path, - path_type const& key_path, - path_type const& log_path, - std::uint64_t appnum, - std::uint64_t salt, - nsize_t key_size, - nsize_t blockSize, - float load_factor, - error_code& ec, - Args&&... args) -{ - static_assert(is_File::value, - "File requirements not met"); - - using namespace detail; - if(key_size < 1) - { - ec = error::invalid_key_size; - return; - } - if(blockSize > field::max) - { - ec = error::invalid_block_size; - return; - } - if(load_factor <= 0.f || load_factor >= 1.f) - { - ec = error::invalid_load_factor; - return; - } - auto const capacity = - bucket_capacity(blockSize); - if(capacity < 1) - { - ec = error::invalid_block_size; - return; - } - bool edf = false; - bool ekf = false; - bool elf = false; - { - File df(args...); - File kf(args...); - File lf(args...); - df.create(file_mode::append, dat_path, ec); - if(ec) - goto fail; - edf = true; - kf.create(file_mode::append, key_path, ec); - if(ec) - goto fail; - ekf = true; - lf.create(file_mode::append, log_path, ec); - if(ec) - goto fail; - elf = true; - dat_file_header dh; - dh.version = currentVersion; - dh.uid = make_uid(); - dh.appnum = appnum; - dh.key_size = key_size; - - key_file_header kh; - kh.version = currentVersion; - kh.uid = dh.uid; - kh.appnum = appnum; - kh.key_size = key_size; - kh.salt = salt; - kh.pepper = pepper(salt); - kh.block_size = blockSize; - kh.load_factor = std::min( - static_cast( - 65536.0 * load_factor), 65535); - write(df, dh, ec); - if(ec) - goto fail; - write(kf, kh, ec); - if(ec) - goto fail; - buffer buf{blockSize}; - std::memset(buf.get(), 0, blockSize); - bucket b(blockSize, buf.get(), empty); - b.write(kf, blockSize, ec); - if(ec) - goto fail; - // VFALCO Leave log file empty? - df.sync(ec); - if(ec) - goto fail; - kf.sync(ec); - if(ec) - goto fail; - lf.sync(ec); - if(ec) - goto fail; - // Success - return; - } -fail: - if(edf) - erase_file(dat_path); - if(ekf) - erase_file(key_path); - if(elf) - erase_file(log_path); -} - -} // nudb - -#endif diff --git a/src/nudb/include/nudb/impl/error.ipp b/src/nudb/include/nudb/impl/error.ipp deleted file mode 100644 index 9409a779e9..0000000000 --- a/src/nudb/include/nudb/impl/error.ipp +++ /dev/null @@ -1,180 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_IMPL_ERROR_IPP -#define NUDB_IMPL_ERROR_IPP - -namespace nudb { - -inline -error_category const& -nudb_category() -{ - struct cat_t : public error_category - { - char const* - name() const noexcept override - { - return "nudb"; - } - - std::string - message(int ev) const override - { - switch(static_cast(ev)) - { - case error::success: - return "the operation completed successfully"; - - case error::key_not_found: - return "key not found"; - - case error::key_exists: - return "key already exists"; - - case error::short_read: - return "short read"; - - case error::log_file_exists: - return "a log file exists"; - - case error::no_key_file: - return "no key file"; - - case error::too_many_buckets: - return "too many buckets"; - - case error::not_data_file: - return "not a data file"; - - case error::not_key_file: - return "not a key file"; - - case error::not_log_file: - return "not a log file"; - - case error::different_version: - return "different version"; - - case error::invalid_key_size: - return "invalid key size"; - - case error::invalid_block_size: - return "invalid block size"; - - case error::short_key_file: - return "short key file"; - - case error::short_bucket: - return "short bucket"; - - case error::short_spill: - return "short spill"; - - case error::short_data_record: - return "short data record"; - - case error::short_value: - return "short value"; - - case error::hash_mismatch: - return "hash mismatch"; - - case error::invalid_load_factor: - return "invalid load factor"; - - case error::invalid_capacity: - return "invalid capacity"; - - case error::invalid_bucket_count: - return "invalid bucket count"; - - case error::invalid_bucket_size: - return "invalid_bucket_size"; - - case error::incomplete_data_file_header: - return "incomplete data file header"; - - case error::incomplete_key_file_header: - return "incomplete key file header"; - - case error::invalid_log_record: - return "invalid log record"; - - case error::invalid_log_spill: - return "invalid spill in log"; - - case error::invalid_log_offset: - return "invalid offset in log"; - - case error::invalid_log_index: - return "invalid index in log"; - - case error::invalid_spill_size: - return "invalid size in spill"; - - case error::uid_mismatch: - return "uid mismatch"; - - case error::appnum_mismatch: - return "appnum mismatch"; - - case error::key_size_mismatch: - return "key size mismatch"; - - case error::salt_mismatch: - return "salt mismatch"; - - case error::pepper_mismatch: - return "pepper mismatch"; - - case error::block_size_mismatch: - return "block size mismatch"; - - case error::orphaned_value: - return "orphaned value"; - - case error::missing_value: - return "missing value"; - - case error::size_mismatch: - return "size mismatch"; - - case error::duplicate_value: - return "duplicate value"; - - default: - return "nudb error"; - } - } - - error_condition - default_error_condition(int ev) const noexcept override - { - return error_condition{ev, *this}; - } - - bool - equivalent(int ev, - error_condition const& ec) const noexcept override - { - return ec.value() == ev && &ec.category() == this; - } - - bool - equivalent(error_code const& ec, int ev) const noexcept override - { - return ec.value() == ev && &ec.category() == this; - } - }; - static cat_t const cat{}; - return cat; -} - -} // nudb - -#endif diff --git a/src/nudb/include/nudb/impl/posix_file.ipp b/src/nudb/include/nudb/impl/posix_file.ipp deleted file mode 100644 index a03262a304..0000000000 --- a/src/nudb/include/nudb/impl/posix_file.ipp +++ /dev/null @@ -1,259 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_IMPL_POSIX_FILE_IPP -#define NUDB_IMPL_POSIX_FILE_IPP - -#include -#include - -namespace nudb { - -inline -posix_file:: -~posix_file() -{ - close(); -} - -inline -posix_file:: -posix_file(posix_file &&other) - : fd_(other.fd_) -{ - other.fd_ = -1; -} - -inline -posix_file& -posix_file:: -operator=(posix_file&& other) -{ - if(&other == this) - return *this; - close(); - fd_ = other.fd_; - other.fd_ = -1; - return *this; -} - -inline -void -posix_file:: -close() -{ - if(fd_ != -1) - { - ::close(fd_); - fd_ = -1; - } -} - -inline -void -posix_file:: -create(file_mode mode, path_type const& path, error_code& ec) -{ - auto const result = flags(mode); - BOOST_ASSERT(! is_open()); - fd_ = ::open(path.c_str(), result.first); - if(fd_ != -1) - { - ::close(fd_); - fd_ = -1; - ec = error_code{errc::file_exists, generic_category()}; - return ; - } - int errnum = errno; - if(errnum != ENOENT) - return err(errnum, ec); - fd_ = ::open(path.c_str(), result.first | O_CREAT, 0644); - if(fd_ == -1) - return last_err(ec); -#ifndef __APPLE__ - if(::posix_fadvise(fd_, 0, 0, result.second) != 0) - return last_err(ec); -#endif -} - -inline -void -posix_file:: -open(file_mode mode, path_type const& path, error_code& ec) -{ - BOOST_ASSERT(! is_open()); - auto const result = flags(mode); - fd_ = ::open(path.c_str(), result.first); - if(fd_ == -1) - return last_err(ec); -#ifndef __APPLE__ - if(::posix_fadvise(fd_, 0, 0, result.second) != 0) - return last_err(ec); -#endif -} - -inline -void -posix_file:: -erase(path_type const& path, error_code& ec) -{ - if(::unlink(path.c_str()) != 0) - { - int const ev = errno; - return err(ev, ec); - } -} - -inline -std::uint64_t -posix_file:: -size(error_code& ec) const -{ - static_assert(sizeof(stat::st_size) == sizeof(std::uint64_t), ""); - struct stat st; - if(::fstat(fd_, &st) != 0) - { - last_err(ec); - return 0; - } - return st.st_size; -} -inline -void -posix_file:: -read(std::uint64_t offset, - void* buffer, std::size_t bytes, error_code& ec) -{ - static_assert(sizeof(off_t) >= sizeof(offset), ""); - while(bytes > 0) - { - auto const amount = static_cast( - std::min(bytes, static_cast(SSIZE_MAX))); - auto const n = ::pread(fd_, buffer, amount, offset); - if(n == -1) - { - auto const ev = errno; - if(ev == EINTR) - continue; - return err(ev, ec); - } - if(n == 0) - { - ec = error::short_read; - return; - } - offset += n; - bytes -= n; - buffer = reinterpret_cast(buffer) + n; - } -} - -inline -void -posix_file:: -write(std::uint64_t offset, - void const* buffer, std::size_t bytes, error_code& ec) -{ - static_assert(sizeof(off_t) >= sizeof(offset), ""); - while(bytes > 0) - { - auto const amount = static_cast( - std::min(bytes, static_cast(SSIZE_MAX))); - auto const n = ::pwrite(fd_, buffer, amount, offset); - if(n == -1) - { - auto const ev = errno; - if(ev == EINTR) - continue; - return err(ev, ec); - } - offset += n; - bytes -= n; - buffer = reinterpret_cast(buffer) + n; - } -} - -inline -void -posix_file:: -sync(error_code& ec) -{ - for(;;) - { - if(::fsync(fd_) == 0) - break; - auto const ev = errno; - if(ev == EINTR) - continue; - return err(ev, ec); - } -} - -inline -void -posix_file:: -trunc(std::uint64_t length, error_code& ec) -{ - for(;;) - { - if(::ftruncate(fd_, length) == 0) - break; - auto const ev = errno; - if(ev == EINTR) - continue; - return err(ev, ec); - } -} - -inline -std::pair -posix_file:: -flags(file_mode mode) -{ - std::pair result; - switch(mode) - { - case file_mode::scan: - result.first = - O_RDONLY; - #ifndef __APPLE__ - result.second = - POSIX_FADV_SEQUENTIAL; - #endif - break; - case file_mode::read: - result.first = - O_RDONLY; - #ifndef __APPLE__ - result.second = - POSIX_FADV_RANDOM; - #endif - break; - case file_mode::append: - result.first = - O_RDWR | - O_APPEND; - #ifndef __APPLE__ - result.second = - POSIX_FADV_RANDOM; - #endif - break; - case file_mode::write: - result.first = - O_RDWR; - #ifndef __APPLE__ - result.second = - POSIX_FADV_NORMAL; - #endif - break; - } - return result; -} - -} // nudb - -#endif diff --git a/src/nudb/include/nudb/impl/recover.ipp b/src/nudb/include/nudb/impl/recover.ipp deleted file mode 100644 index e449c36f28..0000000000 --- a/src/nudb/include/nudb/impl/recover.ipp +++ /dev/null @@ -1,209 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_IMPL_RECOVER_IPP -#define NUDB_IMPL_RECOVER_IPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace nudb { - -template< - class Hasher, - class File, - class... Args> -void -recover( - path_type const& dat_path, - path_type const& key_path, - path_type const& log_path, - error_code& ec, - Args&&... args) -{ - static_assert(is_File::value, - "File requirements not met"); - static_assert(is_Hasher::value, - "Hasher requirements not met"); - using namespace detail; - - // Open data file - File df{args...}; - df.open(file_mode::write, dat_path, ec); - if(ec) - return; - auto const dataFileSize = df.size(ec); - if(ec) - return; - dat_file_header dh; - read(df, dh, ec); - if(ec) - return; - verify(dh, ec); - if(ec) - return; - - // Open key file - File kf{args...}; - kf.open(file_mode::write, key_path, ec); - if(ec) - return; - auto const keyFileSize = kf.size(ec); - if(ec) - return; - if(keyFileSize <= key_file_header::size) - { - kf.close(); - erase_file(log_path, ec); - if(ec) - return; - File::erase(key_path, ec); - if(ec) - return; - ec = error::no_key_file; - return; - } - - // Open log file - File lf{args...}; - lf.open(file_mode::append, log_path, ec); - if(ec == errc::no_such_file_or_directory) - { - ec = {}; - return; - } - if(ec) - return; - auto const logFileSize = lf.size(ec); - if(ec) - return; - // Read log file header - log_file_header lh; - read(lf, lh, ec); - if(ec == error::short_read) - { - BOOST_ASSERT(keyFileSize > key_file_header::size); - ec = {}; - goto clear_log; - } - if(ec) - return; - verify(lh, ec); - if(ec) - return; - if(lh.key_file_size == 0) - goto trunc_files; - { - // Read key file header - key_file_header kh; - read(kf, kh, ec); - if(ec) - return; - verify(kh, ec); - if(ec) - return; - verify(dh, kh, ec); - if(ec) - return; - verify(kh, lh, ec); - if(ec) - return; - - auto const readSize = 1024 * kh.block_size; - auto const bucketSize = bucket_size(kh.capacity); - buffer buf{kh.block_size}; - bucket b{kh.block_size, buf.get()}; - bulk_reader r{lf, - log_file_header::size, logFileSize, readSize}; - while(! r.eof()) - { - // Log Record - auto is = r.prepare(field::size, ec); - // Log file is incomplete, so roll back. - if(ec == error::short_read) - { - ec = {}; - break; - } - if(ec) - return; - nsize_t n; - { - std::uint64_t v; - // VFALCO This should have been a uint32_t - read(is, v); // Index - BOOST_ASSERT(v <= std::numeric_limits::max()); - n = static_cast(v); - } - b.read(r, ec); // Bucket - if(ec == error::short_read) - { - ec = {}; - break; - } - if(b.spill() && b.spill() + bucketSize > dataFileSize) - { - ec = error::invalid_log_spill; - return; - } - if(n > kh.buckets) - { - ec = error::invalid_log_index; - return; - } - b.write(kf, static_cast(n + 1) * kh.block_size, ec); - if(ec) - return; - } - } -trunc_files: - df.trunc(lh.dat_file_size, ec); - if(ec) - return; - df.sync(ec); - if(ec) - return; - if(lh.key_file_size != 0) - { - kf.trunc(lh.key_file_size, ec); - if(ec) - return; - kf.sync(ec); - if(ec) - return; - } - else - { - kf.close(); - File::erase(key_path, ec); - if(ec) - return; - } -clear_log: - lf.trunc(0, ec); - if(ec) - return; - lf.sync(ec); - if(ec) - return; - lf.close(); - File::erase(log_path, ec); - if(ec) - return; -} - -} // nudb - -#endif diff --git a/src/nudb/include/nudb/impl/rekey.ipp b/src/nudb/include/nudb/impl/rekey.ipp deleted file mode 100644 index ab247c77db..0000000000 --- a/src/nudb/include/nudb/impl/rekey.ipp +++ /dev/null @@ -1,248 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_IMPL_REKEY_IPP -#define NUDB_IMPL_REKEY_IPP - -#include -#include -#include -#include -#include -#include - -namespace nudb { - -// VFALCO Should this delete the key file on an error? -template< - class Hasher, - class File, - class Progress, - class... Args -> -void -rekey( - path_type const& dat_path, - path_type const& key_path, - path_type const& log_path, - std::size_t blockSize, - float loadFactor, - std::uint64_t itemCount, - std::size_t bufferSize, - error_code& ec, - Progress&& progress, - Args&&... args) -{ - static_assert(is_File::value, - "File requirements not met"); - static_assert(is_Hasher::value, - "Hasher requirements not met"); - static_assert(is_Progress::value, - "Progress requirements not met"); - using namespace detail; - auto const readSize = 1024 * block_size(dat_path); - auto const writeSize = 16 * block_size(key_path); - - // Open data file for reading and appending - File df{args...}; - df.open(file_mode::append, dat_path, ec); - if(ec) - return; - dat_file_header dh; - read(df, dh, ec); - if(ec) - return; - verify(dh, ec); - if(ec) - return; - auto const dataFileSize = df.size(ec); - if(ec) - return; - - // Make sure log file doesn't exist - File lf{args...}; - lf.open(file_mode::read, log_path, ec); - if(! ec) - ec = error::log_file_exists; - if(ec != errc::no_such_file_or_directory) - return; - ec = {}; - - // Set up key file header - key_file_header kh; - kh.version = currentVersion; - kh.uid = dh.uid; - kh.appnum = dh.appnum; - kh.key_size = dh.key_size; - kh.salt = make_salt(); - kh.pepper = pepper(kh.salt); - kh.block_size = blockSize; - kh.load_factor = std::min( - static_cast(65536.0 * loadFactor), 65535); - kh.buckets = static_cast( - std::ceil(itemCount /( - bucket_capacity(kh.block_size) * loadFactor))); - kh.modulus = ceil_pow2(kh.buckets); - // Create key file - File kf{args...}; - kf.create(file_mode::write, key_path, ec); - if(ec) - return; - // Write key file header - // Note, file size is less than any valid block_size here - { - std::array buf; - ostream os{buf.data(), buf.size()}; - write(os, kh); - kf.write(0, buf.data(), buf.size(), ec); - if(ec) - return; - kf.sync(ec); - if(ec) - return; - } - - // Create log file - lf.create(file_mode::append, log_path, ec); - if(ec) - return; - // Write log file header - { - log_file_header lh; - lh.version = currentVersion; // Version - lh.uid = kh.uid; // UID - lh.appnum = kh.appnum; // Appnum - lh.key_size = kh.key_size; // Key Size - lh.salt = kh.salt; // Salt - lh.pepper = pepper(kh.salt); // Pepper - lh.block_size = kh.block_size; // Block Size - lh.key_file_size = 0; // Key File Size - lh.dat_file_size = dataFileSize; // Data File Size - write(lf, lh, ec); - if(ec) - return; - lf.sync(ec); - if(ec) - return; - } - - // Create full key file - buffer buf{kh.block_size}; - { - // Write key file header - std::memset(buf.get(), 0, kh.block_size); - ostream os{buf.get(), kh.block_size}; - write(os, kh); - kf.write(0, buf.get(), buf.size(), ec); - if(ec) - return; - kf.sync(ec); - if(ec) - return; - // Pre-allocate space for the entire key file - std::uint8_t zero = 0; - kf.write( - static_cast(kh.buckets + 1) * kh.block_size - 1, - &zero, 1, ec); - if(ec) - return; - kf.sync(ec); - if(ec) - return; - } - - // Build contiguous sequential sections of the - // key file using multiple passes over the data. - // - auto const chunkSize = std::max(1, - bufferSize / kh.block_size); - // Calculate work required - auto const passes = - (kh.buckets + chunkSize - 1) / chunkSize; - auto const nwork = passes * dataFileSize; - progress(0, nwork); - - buf.reserve(chunkSize * kh.block_size); - bulk_writer dw{df, dataFileSize, writeSize}; - for(nbuck_t b0 = 0; b0 < kh.buckets; b0 += chunkSize) - { - auto const b1 = std::min(b0 + chunkSize, kh.buckets); - // Buffered range is [b0, b1) - auto const bn = b1 - b0; - // Create empty buckets - for(std::size_t i = 0; i < bn; ++i) - bucket b{kh.block_size, - buf.get() + i * kh.block_size, empty}; - // Insert all keys into buckets - // Iterate Data File - bulk_reader r{df, - dat_file_header::size, dataFileSize, readSize}; - while(! r.eof()) - { - auto const offset = r.offset(); - // Data Record or Spill Record - nsize_t size; - auto is = r.prepare( - field::size, ec); // Size - if(ec) - return; - progress((b0 / chunkSize) * dataFileSize + r.offset(), nwork); - read_size48(is, size); - if(size > 0) - { - // Data Record - is = r.prepare( - dh.key_size + // Key - size, ec); // Data - if(ec) - return; - std::uint8_t const* const key = - is.data(dh.key_size); - auto const h = hash( - key, dh.key_size, kh.salt); - auto const n = bucket_index( - h, kh.buckets, kh.modulus); - if(n < b0 || n >= b1) - continue; - bucket b{kh.block_size, buf.get() + - (n - b0) * kh.block_size}; - maybe_spill(b, dw, ec); - if(ec) - return; - b.insert(offset, size, h); - } - else - { - // VFALCO Should never get here - // Spill Record - is = r.prepare( - field::size, ec); - if(ec) - return; - read(is, size); // Size - r.prepare(size, ec); // skip - if(ec) - return; - } - } - kf.write((b0 + 1) * kh.block_size, buf.get(), - static_cast(bn * kh.block_size), ec); - if(ec) - return; - } - dw.flush(ec); - if(ec) - return; - lf.close(); - File::erase(log_path, ec); - if(ec) - return; -} - -} // nudb - -#endif diff --git a/src/nudb/include/nudb/impl/verify.ipp b/src/nudb/include/nudb/impl/verify.ipp deleted file mode 100644 index c1d221eebb..0000000000 --- a/src/nudb/include/nudb/impl/verify.ipp +++ /dev/null @@ -1,630 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_IMPL_VERIFY_IPP -#define NUDB_IMPL_VERIFY_IPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace nudb { - -namespace detail { - -// Normal verify that does not require a buffer -// -template< - class Hasher, - class File, - class Progress> -void -verify_normal( - verify_info& info, - File& df, - File& kf, - dat_file_header& dh, - key_file_header& kh, - Progress&& progress, - error_code& ec) -{ - static_assert(is_File::value, - "File requirements not met"); - static_assert(is_Hasher::value, - "Hasher requirements not met"); - static_assert(is_Progress::value, - "Progress requirements not met"); - info.algorithm = 0; - auto const readSize = 1024 * kh.block_size; - - // This ratio balances the 2 work phases. - // The number is determined empirically. - auto const adjust = 1.75; - - // Calculate the work required - auto const keys = static_cast( - double(kh.load_factor) / 65536.0 * kh.buckets * kh.capacity); - std::uint64_t const nwork = static_cast( - info.dat_file_size + keys * kh.block_size + - adjust * (info.key_file_size + keys * kh.block_size)); - std::uint64_t work = 0; - progress(0, nwork); - - // Iterate Data File - // Data Record - auto const dh_len = - field::size + // Size - kh.key_size; // Key - std::uint64_t fetches = 0; - buffer buf{kh.block_size + dh_len}; - bucket b{kh.block_size, buf.get()}; - std::uint8_t* pd = buf.get() + kh.block_size; - { - bulk_reader r{df, dat_file_header::size, - info.dat_file_size, readSize}; - while(! r.eof()) - { - auto const offset = r.offset(); - // Data Record or Spill Record - auto is = r.prepare( - field::size, ec); // Size - if(ec) - return; - nsize_t size; - read_size48(is, size); - if(size > 0) - { - // Data Record - is = r.prepare( - kh.key_size + // Key - size, ec); // Data - if(ec) - return; - std::uint8_t const* const key = - is.data(kh.key_size); - std::uint8_t const* const data = - is.data(size); - (void)data; - auto const h = hash( - key, kh.key_size, kh.salt); - // Check bucket and spills - auto const n = bucket_index( - h, kh.buckets, kh.modulus); - b.read(kf, - static_cast(n + 1) * kh.block_size, ec); - if(ec) - return; - work += kh.block_size; - ++fetches; - for(;;) - { - for(auto i = b.lower_bound(h); - i < b.size(); ++i) - { - auto const item = b[i]; - if(item.hash != h) - break; - if(item.offset == offset) - goto found; - ++fetches; - } - auto const spill = b.spill(); - if(! spill) - { - ec = error::orphaned_value; - return; - } - b.read(df, spill, ec); - if(ec == error::short_read) - { - ec = error::short_spill; - return; - } - if(ec) - return; - ++fetches; - } - found: - // Update - ++info.value_count; - info.value_bytes += size; - } - else - { - // Spill Record - is = r.prepare( - field::size, ec); - if(ec == error::short_read) - { - ec = error::short_spill; - return; - } - if(ec) - return; - read(is, size); // Size - if(size != info.bucket_size) - { - ec = error::invalid_spill_size; - return; - } - if(ec) - return; - b.read(r, ec); // Bucket - if(ec == error::short_read) - { - ec = error::short_spill; - return; - } - if(ec) - return; - ++info.spill_count_tot; - info.spill_bytes_tot += - field::size + // Zero - field::size + // Size - b.actual_size(); // Bucket - } - progress(work + offset, nwork); - } - work += info.dat_file_size; - } - - // Iterate Key File - { - for(std::size_t n = 0; n < kh.buckets; ++n) - { - std::size_t nspill = 0; - b.read(kf, static_cast( - n + 1) * kh.block_size, ec); - if(ec) - return; - work += static_cast( - adjust * kh.block_size); - bool spill = false; - for(;;) - { - info.key_count += b.size(); - for(nkey_t i = 0; i < b.size(); ++i) - { - auto const e = b[i]; - df.read(e.offset, pd, dh_len, ec); - if(ec == error::short_read) - { - ec = error::missing_value; - return; - } - if(ec) - return; - if(! spill) - work += static_cast( - adjust * kh.block_size); - // Data Record - istream is{pd, dh_len}; - std::uint64_t size; - // VFALCO This should really be a 32-bit field - read(is, size); // Size - void const* key = - is.data(kh.key_size); // Key - if(size != e.size) - { - ec = error::size_mismatch; - return; - } - auto const h = hash(key, - kh.key_size, kh.salt); - if(h != e.hash) - { - ec = error::hash_mismatch; - return; - } - } - if(! b.spill()) - break; - b.read(df, b.spill(), ec); - if(ec) - return; - spill = true; - ++nspill; - ++info.spill_count; - info.spill_bytes += - field::size + // Zero - field::size + // Size - b.actual_size(); // SpillBucket - } - if(nspill >= info.hist.size()) - nspill = info.hist.size() - 1; - ++info.hist[nspill]; - progress(work, nwork); - } - } - float sum = 0; - for(size_t i = 0; i < info.hist.size(); ++i) - sum += info.hist[i] * (i + 1); - if(info.value_count) - info.avg_fetch = - float(fetches) / info.value_count; - else - info.avg_fetch = 0; - info.waste = (info.spill_bytes_tot - info.spill_bytes) / - float(info.dat_file_size); - if(info.value_count) - info.overhead = - float(info.key_file_size + info.dat_file_size) / - ( - info.value_bytes + - info.key_count * - (info.key_size + - // Data Record - field::size) // Size - ) - 1; - else - info.overhead = 0; - info.actual_load = info.key_count / float( - info.capacity * info.buckets); -} - -// Fast version of verify that uses a buffer -// -template -void -verify_fast( - verify_info& info, - File& df, - File& kf, - dat_file_header& dh, - key_file_header& kh, - std::size_t bufferSize, - Progress&& progress, - error_code& ec) -{ - info.algorithm = 1; - auto const readSize = 1024 * kh.block_size; - - // Counts unverified keys per bucket - if(kh.buckets > std::numeric_limits::max()) - { - ec = error::too_many_buckets; - return; - } - std::unique_ptr nkeys( - new nkey_t[kh.buckets]); - - // Verify contiguous sequential sections of the - // key file using multiple passes over the data. - // - if(bufferSize < 2 * kh.block_size + sizeof(nkey_t)) - throw std::logic_error("invalid buffer size"); - auto chunkSize = std::min(kh.buckets, - (bufferSize - kh.block_size) / - (kh.block_size + sizeof(nkey_t))); - auto const passes = - (kh.buckets + chunkSize - 1) / chunkSize; - - // Calculate the work required - std::uint64_t work = 0; - std::uint64_t const nwork = - passes * info.dat_file_size + info.key_file_size; - progress(0, nwork); - - std::uint64_t fetches = 0; - buffer buf{(chunkSize + 1) * kh.block_size}; - bucket tmp{kh.block_size, - buf.get() + chunkSize * kh.block_size}; - for(nsize_t b0 = 0; b0 < kh.buckets; b0 += chunkSize) - { - // Load key file chunk to buffer - auto const b1 = std::min(b0 + chunkSize, kh.buckets); - // Buffered range is [b0, b1) - auto const bn = b1 - b0; - kf.read( - static_cast(b0 + 1) * kh.block_size, - buf.get(), - static_cast(bn * kh.block_size), - ec); - if(ec) - return; - work += bn * kh.block_size; - progress(work, nwork); - // Count keys in buckets, including spills - for(nbuck_t i = 0 ; i < bn; ++i) - { - bucket b{kh.block_size, - buf.get() + i * kh.block_size}; - nkeys[i] = b.size(); - std::size_t nspill = 0; - auto spill = b.spill(); - while(spill != 0) - { - tmp.read(df, spill, ec); - if(ec == error::short_read) - { - ec = error::short_spill; - return; - } - if(ec) - return; - nkeys[i] += tmp.size(); - spill = tmp.spill(); - ++nspill; - ++info.spill_count; - info.spill_bytes += - field::size + // Zero - field::size + // Size - tmp.actual_size(); // SpillBucket - } - if(nspill >= info.hist.size()) - nspill = info.hist.size() - 1; - ++info.hist[nspill]; - info.key_count += nkeys[i]; - } - // Iterate Data File - bulk_reader r(df, dat_file_header::size, - info.dat_file_size, readSize); - while(! r.eof()) - { - auto const offset = r.offset(); - // Data Record or Spill Record - auto is = r.prepare( - field::size, ec); // Size - if(ec == error::short_read) - { - ec = error::short_data_record; - return; - } - if(ec) - return; - nsize_t size; - detail::read_size48(is, size); - if(size > 0) - { - // Data Record - is = r.prepare( - kh.key_size + // Key - size, ec); // Data - if(ec == error::short_read) - { - ec = error::short_value; - return; - } - if(ec) - return; - std::uint8_t const* const key = - is.data(kh.key_size); - std::uint8_t const* const data = - is.data(size); - (void)data; - auto const h = hash( - key, kh.key_size, kh.salt); - auto const n = bucket_index( - h, kh.buckets, kh.modulus); - if(n < b0 || n >= b1) - continue; - // Check bucket and spills - bucket b{kh.block_size, buf.get() + - (n - b0) * kh.block_size}; - ++fetches; - for(;;) - { - for(auto i = b.lower_bound(h); - i < b.size(); ++i) - { - auto const item = b[i]; - if(item.hash != h) - break; - if(item.offset == offset) - goto found; - ++fetches; - } - auto const spill = b.spill(); - if(! spill) - { - ec = error::orphaned_value; - return; - } - b = tmp; - b.read(df, spill, ec); - if(ec == error::short_read) - { - ec = error::short_spill; - return; - } - if(ec) - return; - ++fetches; - } - found: - // Update - ++info.value_count; - info.value_bytes += size; - if(nkeys[n - b0]-- == 0) - { - ec = error::orphaned_value; - return; - } - } - else - { - // Spill Record - is = r.prepare( - field::size, ec); - if(ec == error::short_read) - { - ec = error::short_spill; - return; - } - if(ec) - return; - read(is, size); // Size - if(bucket_size( - bucket_capacity(size)) != size) - { - ec = error::invalid_spill_size; - return; - } - r.prepare(size, ec); // Bucket - if(ec == error::short_read) - { - ec = error::short_spill; - return; - } - if(ec) - return; - if(b0 == 0) - { - ++info.spill_count_tot; - info.spill_bytes_tot += - field::size + // Zero - field::size + // Size - tmp.actual_size(); // Bucket - } - } - progress(work + offset, nwork); - } - // Make sure every key in every bucket was visited - for(std::size_t i = 0; i < bn; ++i) - { - if(nkeys[i] != 0) - { - ec = error::missing_value; - return; - } - } - work += info.dat_file_size; - } - - float sum = 0; - for(std::size_t i = 0; i < info.hist.size(); ++i) - sum += info.hist[i] * (i + 1); - if(info.value_count) - info.avg_fetch = - float(fetches) / info.value_count; - else - info.avg_fetch = 0; - info.waste = (info.spill_bytes_tot - info.spill_bytes) / - float(info.dat_file_size); - if(info.value_count) - info.overhead = - float(info.key_file_size + info.dat_file_size) / - ( - info.value_bytes + - info.key_count * - (info.key_size + - // Data Record - field::size) // Size - ) - 1; - else - info.overhead = 0; - info.actual_load = info.key_count / float( - info.capacity * info.buckets); -} - -} // detail - -template -void -verify( - verify_info& info, - path_type const& dat_path, - path_type const& key_path, - std::size_t bufferSize, - Progress&& progress, - error_code& ec) -{ - static_assert(is_Hasher::value, - "Hasher requirements not met"); - static_assert(is_Progress::value, - "Progress requirements not met"); - info = {}; - using namespace detail; - using File = native_file; - File df; - df.open(file_mode::scan, dat_path, ec); - if(ec) - return; - File kf; - kf.open (file_mode::read, key_path, ec); - if(ec) - return; - dat_file_header dh; - read(df, dh, ec); - if(ec) - return; - verify(dh, ec); - if(ec) - return; - key_file_header kh; - read(kf, kh, ec); - if(ec) - return; - verify(kh, ec); - if(ec) - return; - verify(dh, kh, ec); - if(ec) - return; - info.dat_path = dat_path; - info.key_path = key_path; - info.version = dh.version; - info.uid = dh.uid; - info.appnum = dh.appnum; - info.key_size = dh.key_size; - info.salt = kh.salt; - info.pepper = kh.pepper; - info.block_size = kh.block_size; - info.load_factor = kh.load_factor / 65536.f; - info.capacity = kh.capacity; - info.buckets = kh.buckets; - info.bucket_size = bucket_size(kh.capacity); - info.key_file_size = kf.size(ec); - if(ec) - return; - info.dat_file_size = df.size(ec); - if(ec) - return; - - // Determine which algorithm requires the least amount - // of file I/O given the available buffer size - std::size_t chunkSize; - if(bufferSize >= 2 * kh.block_size + sizeof(nkey_t)) - chunkSize = std::min(kh.buckets, - (bufferSize - kh.block_size) / - (kh.block_size + sizeof(nkey_t))); - else - chunkSize = 0; - std::size_t passes; - if(chunkSize > 0) - passes = (kh.buckets + chunkSize - 1) / chunkSize; - else - passes = 0; - if(! chunkSize || - (( - info.dat_file_size + - (kh.buckets * kh.load_factor * kh.capacity * kh.block_size) + - info.key_file_size - ) < ( - passes * info.dat_file_size + info.key_file_size - ))) - { - detail::verify_normal(info, - df, kf, dh, kh, progress, ec); - } - else - { - detail::verify_fast(info, - df, kf, dh, kh, bufferSize, progress, ec); - } -} - -} // nudb - -#endif diff --git a/src/nudb/include/nudb/impl/visit.ipp b/src/nudb/include/nudb/impl/visit.ipp deleted file mode 100644 index 4d57b9595a..0000000000 --- a/src/nudb/include/nudb/impl/visit.ipp +++ /dev/null @@ -1,96 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_IMPL_VISIT_IPP -#define NUDB_IMPL_VISIT_IPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace nudb { - -template< - class Callback, - class Progress> -void -visit( - path_type const& path, - Callback&& callback, - Progress&& progress, - error_code& ec) -{ - // VFALCO Need concept check for Callback - static_assert(is_Progress::value, - "Progress requirements not met"); - using namespace detail; - using File = native_file; - auto const readSize = 1024 * block_size(path); - File df; - df.open(file_mode::scan, path, ec); - if(ec) - return; - dat_file_header dh; - read(df, dh, ec); - if(ec) - return; - verify(dh, ec); - if(ec) - return; - auto const fileSize = df.size(ec); - if(ec) - return; - bulk_reader r(df, - dat_file_header::size, fileSize, readSize); - progress(0, fileSize); - while(! r.eof()) - { - // Data Record or Spill Record - nsize_t size; - auto is = r.prepare( - field::size, ec); // Size - if(ec) - return; - detail::read_size48(is, size); - if(size > 0) - { - // Data Record - is = r.prepare( - dh.key_size + // Key - size, ec); // Data - std::uint8_t const* const key = - is.data(dh.key_size); - callback(key, dh.key_size, - is.data(size), size, ec); - if(ec) - return; - } - else - { - // Spill Record - is = r.prepare( - field::size, ec); - if(ec) - return; - read(is, size); // Size - r.prepare(size, ec); // skip bucket - if(ec) - return; - } - progress(r.offset(), fileSize); - } -} - -} // nudb - -#endif diff --git a/src/nudb/include/nudb/impl/win32_file.ipp b/src/nudb/include/nudb/impl/win32_file.ipp deleted file mode 100644 index c0e5cdae65..0000000000 --- a/src/nudb/include/nudb/impl/win32_file.ipp +++ /dev/null @@ -1,264 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_IMPL_WIN32_FILE_IPP -#define NUDB_IMPL_WIN32_FILE_IPP - -#include - -namespace nudb { - -inline -win32_file:: -~win32_file() -{ - close(); -} - -inline -win32_file:: -win32_file(win32_file&& other) - : hf_(other.hf_) -{ - other.hf_ = INVALID_HANDLE_VALUE; -} - -inline -win32_file& -win32_file:: -operator=(win32_file&& other) -{ - if(&other == this) - return *this; - close(); - hf_ = other.hf_; - other.hf_ = INVALID_HANDLE_VALUE; - return *this; -} - -inline -void -win32_file:: -close() -{ - if(hf_ != INVALID_HANDLE_VALUE) - { - ::CloseHandle(hf_); - hf_ = INVALID_HANDLE_VALUE; - } -} - -inline -void -win32_file:: -create(file_mode mode, path_type const& path, error_code& ec) -{ - BOOST_ASSERT(! is_open()); - auto const f = flags(mode); - hf_ = ::CreateFileA(path.c_str(), - f.first, - 0, - NULL, - CREATE_NEW, - f.second, - NULL); - if(hf_ == INVALID_HANDLE_VALUE) - return last_err(ec); -} - -inline -void -win32_file:: -open(file_mode mode, path_type const& path, error_code& ec) -{ - BOOST_ASSERT(! is_open()); - auto const f = flags(mode); - hf_ = ::CreateFileA(path.c_str(), - f.first, - 0, - NULL, - OPEN_EXISTING, - f.second, - NULL); - if(hf_ == INVALID_HANDLE_VALUE) - return last_err(ec); -} - -inline -void -win32_file:: -erase(path_type const& path, error_code& ec) -{ - BOOL const bSuccess = - ::DeleteFileA(path.c_str()); - if(! bSuccess) - return last_err(ec); -} - -inline -std::uint64_t -win32_file:: -size(error_code& ec) const -{ - BOOST_ASSERT(is_open()); - LARGE_INTEGER fileSize; - if(! ::GetFileSizeEx(hf_, &fileSize)) - { - last_err(ec); - return 0; - } - return fileSize.QuadPart; -} - -inline -void -win32_file:: -read(std::uint64_t offset, void* buffer, std::size_t bytes, error_code& ec) -{ - while(bytes > 0) - { - DWORD bytesRead; - LARGE_INTEGER li; - li.QuadPart = static_cast(offset); - OVERLAPPED ov; - ov.Offset = li.LowPart; - ov.OffsetHigh = li.HighPart; - ov.hEvent = NULL; - DWORD amount; - if(bytes > std::numeric_limits::max()) - amount = std::numeric_limits::max(); - else - amount = static_cast(bytes); - BOOL const bSuccess = ::ReadFile( - hf_, buffer, amount, &bytesRead, &ov); - if(! bSuccess) - { - DWORD const dwError = ::GetLastError(); - if(dwError != ERROR_HANDLE_EOF) - return err(dwError, ec); - ec = make_error_code(error::short_read); - return; - } - if(bytesRead == 0) - { - ec = make_error_code(error::short_read); - return; - } - offset += bytesRead; - bytes -= bytesRead; - buffer = reinterpret_cast( - buffer) + bytesRead; - } -} - -inline -void -win32_file:: -write(std::uint64_t offset, - void const* buffer, std::size_t bytes, error_code& ec) -{ - while(bytes > 0) - { - LARGE_INTEGER li; - li.QuadPart = static_cast(offset); - OVERLAPPED ov; - ov.Offset = li.LowPart; - ov.OffsetHigh = li.HighPart; - ov.hEvent = NULL; - DWORD amount; - if(bytes > std::numeric_limits::max()) - amount = std::numeric_limits::max(); - else - amount = static_cast(bytes); - DWORD bytesWritten; - BOOL const bSuccess = ::WriteFile( - hf_, buffer, amount, &bytesWritten, &ov); - if(! bSuccess) - return last_err(ec); - if(bytesWritten == 0) - { - ec = error_code{errc::no_space_on_device, - generic_category()};; - return; - } - offset += bytesWritten; - bytes -= bytesWritten; - buffer = reinterpret_cast( - buffer) + bytesWritten; - } -} - -inline -void -win32_file:: -sync(error_code& ec) -{ - if(! ::FlushFileBuffers(hf_)) - return last_err(ec); -} - -inline -void -win32_file:: -trunc(std::uint64_t length, error_code& ec) -{ - LARGE_INTEGER li; - li.QuadPart = length; - BOOL bSuccess; - bSuccess = ::SetFilePointerEx( - hf_, li, NULL, FILE_BEGIN); - if(bSuccess) - bSuccess = ::SetEndOfFile(hf_); - if(! bSuccess) - return last_err(ec); -} - -inline -std::pair -win32_file:: -flags(file_mode mode) -{ - std::pair result{0, 0}; - switch(mode) - { - case file_mode::scan: - result.first = - GENERIC_READ; - result.second = - FILE_FLAG_SEQUENTIAL_SCAN; - break; - - case file_mode::read: - result.first = - GENERIC_READ; - result.second = - FILE_FLAG_RANDOM_ACCESS; - break; - - case file_mode::append: - result.first = - GENERIC_READ | GENERIC_WRITE; - result.second = - FILE_FLAG_RANDOM_ACCESS - //| FILE_FLAG_NO_BUFFERING - //| FILE_FLAG_WRITE_THROUGH - ; - break; - - case file_mode::write: - result.first = - GENERIC_READ | GENERIC_WRITE; - result.second = - FILE_FLAG_RANDOM_ACCESS; - break; - } - return result; -} - -} // nudb - -#endif diff --git a/src/nudb/include/nudb/native_file.hpp b/src/nudb/include/nudb/native_file.hpp deleted file mode 100644 index 241119ab6d..0000000000 --- a/src/nudb/include/nudb/native_file.hpp +++ /dev/null @@ -1,76 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_NATIVE_FILE_HPP -#define NUDB_NATIVE_FILE_HPP - -#include -#include -#include -#include -#include - -namespace nudb { - -/** A native file handle. - - This type is set to the appropriate platform-specific - implementation to meet the file wrapper requirements. -*/ -using native_file = -#ifdef _MSC_VER - win32_file; -#else - posix_file; -#endif - -/** Erase a file if it exists. - - This function attempts to erase the specified file. - No error is generated if the file does not already - exist. - - @param path The path to the file to erase. - - @param ec Set to the error, if any occurred. - - @tparam File A type meeting the requirements of @b File. - If this type is unspecified, @ref native_file is used. -*/ -template -inline -void -erase_file(path_type const& path, error_code& ec) -{ - native_file::erase(path, ec); - if(ec == errc::no_such_file_or_directory) - ec = {}; -} - -/** Erase a file without returnign an error. - - This function attempts to erase the specified file. - Any errors are ignored, including if the file does - not exist. - - @param path The path to the file to erase. - - @tparam File A type meeting the requirements of @b File. - If this type is unspecified, @ref native_file is used. -*/ -template -inline -void -erase_file(path_type const& path) -{ - error_code ec; - File::erase(path, ec); -} - -} // nudb - -#endif diff --git a/src/nudb/include/nudb/nudb.hpp b/src/nudb/include/nudb/nudb.hpp deleted file mode 100644 index d62801d2de..0000000000 --- a/src/nudb/include/nudb/nudb.hpp +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_HPP -#define NUDB_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#endif diff --git a/src/nudb/include/nudb/posix_file.hpp b/src/nudb/include/nudb/posix_file.hpp deleted file mode 100644 index 8d3b8e5b75..0000000000 --- a/src/nudb/include/nudb/posix_file.hpp +++ /dev/null @@ -1,228 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_DETAIL_POSIX_FILE_HPP -#define NUDB_DETAIL_POSIX_FILE_HPP - -#include -#include -#include -#include -#include -#include - -#ifndef NUDB_POSIX_FILE -# ifdef _MSC_VER -# define NUDB_POSIX_FILE 0 -# else -# define NUDB_POSIX_FILE 1 -# endif -#endif - -#if NUDB_POSIX_FILE -# include -# include -# include -# include -# include -#endif - -#if NUDB_POSIX_FILE - -namespace nudb { - -class posix_file -{ - int fd_ = -1; - -public: - /// Constructor - posix_file() = default; - - /// Copy constructor (disallowed) - posix_file(posix_file const&) = delete; - - // Copy assignment (disallowed) - posix_file& operator=(posix_file const&) = delete; - - /** Destructor. - - If open, the file is closed. - */ - ~posix_file(); - - /** Move constructor. - - @note The state of the moved-from object is as if default constructed. - */ - posix_file(posix_file&&); - - /** Move assignment. - - @note The state of the moved-from object is as if default constructed. - */ - posix_file& - operator=(posix_file&& other); - - /// Returns `true` if the file is open. - bool - is_open() const - { - return fd_ != -1; - } - - /// Close the file if it is open. - void - close(); - - /** Create a new file. - - After the file is created, it is opened as if by `open(mode, path, ec)`. - - @par Requirements - - The file must not already exist, or else `errc::file_exists` - is returned. - - @param mode The open mode, which must be a valid @ref file_mode. - - @param path The path of the file to create. - - @param ec Set to the error, if any occurred. - */ - void - create(file_mode mode, path_type const& path, error_code& ec); - - /** Open a file. - - @par Requirements - - The file must not already be open. - - @param mode The open mode, which must be a valid @ref file_mode. - - @param path The path of the file to open. - - @param ec Set to the error, if any occurred. - */ - void - open(file_mode mode, path_type const& path, error_code& ec); - - /** Remove a file from the file system. - - It is not an error to attempt to erase a file that does not exist. - - @param path The path of the file to remove. - - @param ec Set to the error, if any occurred. - */ - static - void - erase(path_type const& path, error_code& ec); - - /** Return the size of the file. - - @par Requirements - - The file must be open. - - @param ec Set to the error, if any occurred. - - @return The size of the file, in bytes. - */ - std::uint64_t - size(error_code& ec) const; - - /** Read data from a location in the file. - - @par Requirements - - The file must be open. - - @param offset The position in the file to read from, - expressed as a byte offset from the beginning. - - @param buffer The location to store the data. - - @param bytes The number of bytes to read. - - @param ec Set to the error, if any occurred. - */ - void - read(std::uint64_t offset, - void* buffer, std::size_t bytes, error_code& ec); - - /** Write data to a location in the file. - - @par Requirements - - The file must be open with a mode allowing writes. - - @param offset The position in the file to write from, - expressed as a byte offset from the beginning. - - @param buffer The data the write. - - @param bytes The number of bytes to write. - - @param ec Set to the error, if any occurred. - */ - void - write(std::uint64_t offset, - void const* buffer, std::size_t bytes, error_code& ec); - - /** Perform a low level file synchronization. - - @par Requirements - - The file must be open with a mode allowing writes. - - @param ec Set to the error, if any occurred. - */ - void - sync(error_code& ec); - - /** Truncate the file at a specific size. - - @par Requirements - - The file must be open with a mode allowing writes. - - @param length The new file size. - - @param ec Set to the error, if any occurred. - */ - void - trunc(std::uint64_t length, error_code& ec); - -private: - static - void - err(int ev, error_code& ec) - { - ec = error_code{ev, system_category()}; - } - - static - void - last_err(error_code& ec) - { - err(errno, ec); - } - - static - std::pair - flags(file_mode mode); -}; - -} // nudb - -#include - -#endif - -#endif diff --git a/src/nudb/include/nudb/progress.hpp b/src/nudb/include/nudb/progress.hpp deleted file mode 100644 index df417a0b2b..0000000000 --- a/src/nudb/include/nudb/progress.hpp +++ /dev/null @@ -1,32 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_PROGRESS_HPP -#define NUDB_PROGRESS_HPP - -namespace nudb { - -/** Progress function that does nothing. - - This type meets the requirements of @b Progress, - and does nothing when invoked. -*/ -struct -no_progress -{ - no_progress() = default; - - /// Called to indicate progress - void - operator()(std::uint64_t, std::uint64_t) const noexcept - { - }; -}; - -} // nudb - -#endif diff --git a/src/nudb/include/nudb/recover.hpp b/src/nudb/include/nudb/recover.hpp deleted file mode 100644 index b6b69c1df5..0000000000 --- a/src/nudb/include/nudb/recover.hpp +++ /dev/null @@ -1,73 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_RECOVER_HPP -#define NUDB_RECOVER_HPP - -#include -#include - -namespace nudb { - -/** Perform recovery on a database. - - This implements the recovery algorithm by rolling back - any partially committed data. If no log file is present, - the function does nothing. - - During the commit phase of a NuDB database, a log file - is generated with information that may be used to roll - back the results of a partial commit. This function - checks for the presence of a log file. If present, the - log file is replayed on the key and data files belonging - to the database, restoring the database to its state - before the partial commit. When @ref recover is - successful, it erases the log file. - - It is normally not necessary to call this function - directly, it is called automatically when a database is - opened in a call to @ref basic_store::open. Callers may - use this function to implement auxiliary tools for - manipulating the database. - - @par Template Parameters - - @tparam Hasher The hash function to use. This type must - meet the requirements of @b Hasher. The hash function - must be the same as that used to create the database, or - else an error is returned. - - @tparam File The type of file to use. Use the default of - @ref native_file unless customizing the file behavior. - - @param dat_path The path to the data file. - - @param key_path The path to the key file. - - @param log_path The path to the log file. - - @param args Optional parameters passed to File constructors. - - @param ec Set to the error, if any occurred. -*/ -template< - class Hasher, - class File = native_file, - class... Args> -void -recover( - path_type const& dat_path, - path_type const& key_path, - path_type const& log_path, - error_code& ec, - Args&&... args); - -} // nudb - -#include - -#endif diff --git a/src/nudb/include/nudb/rekey.hpp b/src/nudb/include/nudb/rekey.hpp deleted file mode 100644 index 429cd1ac85..0000000000 --- a/src/nudb/include/nudb/rekey.hpp +++ /dev/null @@ -1,110 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_REKEY_HPP -#define NUDB_REKEY_HPP - -#include -#include -#include -#include - -namespace nudb { - -/** Create a new key file from a data file. - - This algorithm rebuilds a key file for the given data file. - It works efficiently by iterating the data file multiple times. - During the iteration, a contiguous block of the key file is - rendered in memory, then flushed to disk when the iteration is - complete. The size of this memory buffer is controlled by the - `bufferSize` parameter, larger is better. The algorithm works - the fastest when `bufferSize` is large enough to hold the entire - key file in memory; only a single iteration of the data file - is needed in this case. - - During the rekey, spill records may be appended to the data - file. If the rekey operation is abnormally terminated, this - would normally result in a corrupted data file. To prevent this, - the function creates a log file using the specified path so - that the database can be fixed in a subsequent call to - @ref recover. - - @note If a log file is already present, this function will - fail with @ref error::log_file_exists. - - @par Template Parameters - - @tparam Hasher The hash function to use. This type must - meet the requirements of @b Hasher. The hash function - must be the same as that used to create the database, or - else an error is returned. - - @tparam File The type of file to use. This type must meet - the requirements of @b File. - - @param dat_path The path to the data file. - - @param key_path The path to the key file. - - @param log_path The path to the log file. - - @param blockSize The size of a key file block. Larger - blocks hold more keys but require more I/O cycles per - operation. The ideal block size the largest size that - may be read in a single I/O cycle, and device dependent. - The return value of @ref block_size returns a suitable - value for the volume of a given path. - - @param loadFactor A number between zero and one - representing the average bucket occupancy (number of - items). A value of 0.5 is perfect. Lower numbers - waste space, and higher numbers produce negligible - savings at the cost of increased I/O cycles. - - @param itemCount The number of items in the data file. - - @param bufferSize The number of bytes to allocate for the buffer. - - @param ec Set to the error if any occurred. - - @param progress A function which will be called periodically - as the algorithm proceeds. The equivalent signature of the - progress function must be: - @code - void progress( - std::uint64_t amount, // Amount of work done so far - std::uint64_t total // Total amount of work to do - ); - @endcode - - @param args Optional arguments passed to @b File constructors. -*/ -template< - class Hasher, - class File, - class Progress, - class... Args -> -void -rekey( - path_type const& dat_path, - path_type const& key_path, - path_type const& log_path, - std::size_t blockSize, - float loadFactor, - std::uint64_t itemCount, - std::size_t bufferSize, - error_code& ec, - Progress&& progress, - Args&&... args); - -} // nudb - -#include - -#endif diff --git a/src/nudb/include/nudb/store.hpp b/src/nudb/include/nudb/store.hpp deleted file mode 100644 index 5853c7bead..0000000000 --- a/src/nudb/include/nudb/store.hpp +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_STORE_HPP -#define NUDB_STORE_HPP - -#include -#include -#include - -namespace nudb { - -/** A key/value database. - - The @b Hasher used is is @ref xxhasher, which works very - well for almost all cases. The @b File is @ref native_file which - works on Windows and POSIX platforms. -*/ -using store = basic_store; - -} // nudb - -#endif diff --git a/src/nudb/include/nudb/type_traits.hpp b/src/nudb/include/nudb/type_traits.hpp deleted file mode 100644 index f20c4d4c9e..0000000000 --- a/src/nudb/include/nudb/type_traits.hpp +++ /dev/null @@ -1,63 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_TYPE_TRAITS_HPP -#define NUDB_TYPE_TRAITS_HPP - -#include -#include - -namespace nudb { - -#if ! GENERATING_DOCS - -namespace detail { - -// Holds a full digest -using nhash_t = std::uint64_t; - -} // detail - -/** Holds a bucket index or bucket count. - - The maximum number of buckets in a key file is 2^32-1. -*/ -//using nbuck_t = std::uint32_t; -using nbuck_t = std::size_t; - -/** Holds a key index or count in bucket. - - A bucket is limited to 2^16-1 items. The practical - limit is lower, since a bucket cannot be larger than - the block size. -*/ -//using nkey_t = std::uint16_t; -using nkey_t = std::size_t; - -/** Holds a file size or offset. - - Operating system support for large files is required. - Practically, data files cannot exceed 2^48 since offsets - are stored as 48 bit unsigned values. -*/ -using noff_t = std::uint64_t; - -/** Holds a block, key, or value size. - - Block size is limited to 2^16 - - Key file blocks are limited to the block size. - - Value sizes are limited to 2^31-1. -*/ -using nsize_t = std::size_t; - -#endif - -} // nudb - -#endif diff --git a/src/nudb/include/nudb/verify.hpp b/src/nudb/include/nudb/verify.hpp deleted file mode 100644 index 4069a65f04..0000000000 --- a/src/nudb/include/nudb/verify.hpp +++ /dev/null @@ -1,200 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_VERIFY_HPP -#define NUDB_VERIFY_HPP - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace nudb { - -/// Describes database statistics calculated by @ref verify. -struct verify_info -{ - /** Indicates the verify algorithm used. - - @li @b 0 Normal algorithm - @li @b 1 Fast algorith - */ - int algorithm{}; // 0 = normal, 1 = fast - - /// The path to the data file - path_type dat_path; - - /// The path to the key file - path_type key_path; - - /// The API version used to create the database - std::size_t version = 0; - - /// The unique identifier - std::uint64_t uid = 0; - - /// The application-defined constant - std::uint64_t appnum = 0; - - /// The size of each key, in bytes - nsize_t key_size = 0; - - /// The salt used in the key file - std::uint64_t salt = 0; - - /// The salt fingerprint - std::uint64_t pepper = 0; - - /// The block size used in the key file - nsize_t block_size = 0; - - /// The target load factor used in the key file - float load_factor = 0; - - /// The maximum number of keys each bucket can hold - nkey_t capacity = 0; - - /// The number of buckets in the key file - nbuck_t buckets = 0; - - /// The size of a bucket in bytes - nsize_t bucket_size = 0; - - /// The size of the key file - noff_t key_file_size = 0; - - /// The size of the data file - noff_t dat_file_size = 0; - - /// The number of keys found - std::uint64_t key_count = 0; - - /// The number of values found - std::uint64_t value_count = 0; - - /// The total number of bytes occupied by values - std::uint64_t value_bytes = 0; - - /// The number of spill records in use - std::uint64_t spill_count = 0; - - /// The total number of spill records - std::uint64_t spill_count_tot = 0; - - /// The number of bytes occupied by spill records in use - std::uint64_t spill_bytes = 0; - - /// The number of bytes occupied by all spill records - std::uint64_t spill_bytes_tot = 0; - - /// Average number of key file reads per fetch - float avg_fetch = 0; - - /// The fraction of the data file that is wasted - float waste = 0; - - /// The data amplification ratio - float overhead = 0; - - /// The measured bucket load fraction - float actual_load = 0; - - /// A histogram of the number of buckets having N spill records - std::array hist; - - /// Default constructor - verify_info() - { - hist.fill(0); - } -}; - -/** Verify consistency of the key and data files. - - This function opens the key and data files, and - performs the following checks on the contents: - - @li Data file header validity - - @li Key file header validity - - @li Data and key file header agreements - - @li Check that each value is contained in a bucket - - @li Check that each bucket item reflects a value - - @li Ensure no values with duplicate keys - - Undefined behavior results when verifying a database - that still has a log file. Use @ref recover on such - databases first. - - This function selects one of two algorithms to use, the - normal version, and a faster version that can take advantage - of a buffer of sufficient size. Depending on the value of - the bufferSize argument, the appropriate algorithm is chosen. - - A good value of bufferSize is one that is a large fraction - of the key file size. For example, 20% of the size of the - key file. Larger is better, with the highest usable value - depending on the size of the key file. If presented with - a buffer size that is too large to be of extra use, the - fast algorithm will simply allocate what it needs. - - @par Template Parameters - - @tparam Hasher The hash function to use. This type must - meet the requirements of @b HashFunction. The hash function - must be the same as that used to create the database, or - else an error is returned. - - @param info A structure which will be default constructed - inside this function, and filled in if the operation completes - successfully. If an error is indicated, the contents of this - variable are undefined. - - @param dat_path The path to the data file. - - @param key_path The path to the key file. - - @param bufferSize The number of bytes to allocate for the buffer. - If this number is too small, or zero, a slower algorithm will be - used that does not require a buffer. - - @param progress A function which will be called periodically - as the algorithm proceeds. The equivalent signature of the - progress function must be: - @code - void progress( - std::uint64_t amount, // Amount of work done so far - std::uint64_t total // Total amount of work to do - ); - @endcode - - @param ec Set to the error, if any occurred. -*/ -template -void -verify( - verify_info& info, - path_type const& dat_path, - path_type const& key_path, - std::size_t bufferSize, - Progress&& progress, - error_code& ec); - -} // nudb - -#include - -#endif diff --git a/src/nudb/include/nudb/version.hpp b/src/nudb/include/nudb/version.hpp deleted file mode 100644 index 9ccab10634..0000000000 --- a/src/nudb/include/nudb/version.hpp +++ /dev/null @@ -1,21 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_VERSION_HPP -#define NUDB_VERSION_HPP - -// follows http://semver.org - -// NUDB_VERSION % 100 is the patch level -// NUDB_VERSION / 100 % 1000 is the minor version -// NUDB_VERSION / 100000 is the major version -// -#define NUDB_VERSION 100000 - -#define NUDB_VERSION_STRING "1.0.0-b6" - -#endif diff --git a/src/nudb/include/nudb/visit.hpp b/src/nudb/include/nudb/visit.hpp deleted file mode 100644 index abb0c91a97..0000000000 --- a/src/nudb/include/nudb/visit.hpp +++ /dev/null @@ -1,63 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_VISIT_HPP -#define NUDB_VISIT_HPP - -#include -#include - -namespace nudb { - -/** Visit each key/data pair in a data file. - - This function will open and iterate the contents of a - data file, invoking the callback for each key/value - pair found. Only a data file is necessary, the key - file may be omitted. - - @param path The path to the data file. - - @param callback A function which will be called with - each item found in the data file. The equivalent signature - of the callback must be: - @code - void callback( - void const* key, // A pointer to the item key - std::size_t key_size, // The size of the key (always the same) - void const* data, // A pointer to the item data - std::size_t data_size, // The size of the item data - error_code& ec // Indicates an error (out parameter) - ); - @endcode - If the callback sets ec to an error, the visit is terminated. - - @param progress A function which will be called periodically - as the algorithm proceeds. The equivalent signature of the - progress function must be: - @code - void progress( - std::uint64_t amount, // Amount of work done so far - std::uint64_t total // Total amount of work to do - ); - @endcode - - @param ec Set to the error, if any occurred. -*/ -template -void -visit( - path_type const& path, - Callback&& callback, - Progress&& progress, - error_code& ec); - -} // nudb - -#include - -#endif diff --git a/src/nudb/include/nudb/win32_file.hpp b/src/nudb/include/nudb/win32_file.hpp deleted file mode 100644 index d225ae9421..0000000000 --- a/src/nudb/include/nudb/win32_file.hpp +++ /dev/null @@ -1,246 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_DETAIL_WIN32_FILE_HPP -#define NUDB_DETAIL_WIN32_FILE_HPP - -#include -#include -#include -#include -#include - -#ifndef NUDB_WIN32_FILE -# ifdef _MSC_VER -# define NUDB_WIN32_FILE 1 -# else -# define NUDB_WIN32_FILE 0 -# endif -#endif - -#if NUDB_WIN32_FILE -#pragma push_macro("NOMINMAX") -#pragma push_macro("UNICODE") -#pragma push_macro("STRICT") -# ifndef NOMINMAX -# define NOMINMAX -# endif -# ifndef UNICODE -# define UNICODE -# endif -# ifndef STRICT -# define STRICT -# endif -# ifndef WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN -# endif -# include -#pragma pop_macro("STRICT") -#pragma pop_macro("UNICODE") -#pragma pop_macro("NOMINMAX") -#endif - -#if NUDB_WIN32_FILE - -namespace nudb { - -/** A descriptor to a Win32 file. - - This class provides a Win32 implementation of the @b File - concept. -*/ -class win32_file -{ - HANDLE hf_ = INVALID_HANDLE_VALUE; - -public: - /// Constructor - win32_file() = default; - - /// Copy constructor (disallowed) - win32_file(win32_file const&) = delete; - - // Copy assignment (disallowed) - win32_file& operator=(win32_file const&) = delete; - - /** Destructor. - - If open, the file is closed. - */ - ~win32_file(); - - /** Move constructor. - - @note The state of the moved-from object is as if default constructed. - */ - win32_file(win32_file&&); - - /** Move assignment. - - @note The state of the moved-from object is as if default constructed. - */ - win32_file& - operator=(win32_file&& other); - - /// Returns `true` if the file is open. - bool - is_open() const - { - return hf_ != INVALID_HANDLE_VALUE; - } - - /// Close the file if it is open. - void - close(); - - /** Create a new file. - - After the file is created, it is opened as if by `open(mode, path, ec)`. - - @par Requirements - - The file must not already exist, or else `errc::file_exists` - is returned. - - @param mode The open mode, which must be a valid @ref file_mode. - - @param path The path of the file to create. - - @param ec Set to the error, if any occurred. - */ - void - create(file_mode mode, path_type const& path, error_code& ec); - - /** Open a file. - - @par Requirements - - The file must not already be open. - - @param mode The open mode, which must be a valid @ref file_mode. - - @param path The path of the file to open. - - @param ec Set to the error, if any occurred. - */ - void - open(file_mode mode, path_type const& path, error_code& ec); - - /** Remove a file from the file system. - - It is not an error to attempt to erase a file that does not exist. - - @param path The path of the file to remove. - - @param ec Set to the error, if any occurred. - */ - static - void - erase(path_type const& path, error_code& ec); - - /** Return the size of the file. - - @par Requirements - - The file must be open. - - @param ec Set to the error, if any occurred. - - @return The size of the file, in bytes. - */ - std::uint64_t - size(error_code& ec) const; - - /** Read data from a location in the file. - - @par Requirements - - The file must be open. - - @param offset The position in the file to read from, - expressed as a byte offset from the beginning. - - @param buffer The location to store the data. - - @param bytes The number of bytes to read. - - @param ec Set to the error, if any occurred. - */ - void - read(std::uint64_t offset, - void* buffer, std::size_t bytes, error_code& ec); - - /** Write data to a location in the file. - - @par Requirements - - The file must be open with a mode allowing writes. - - @param offset The position in the file to write from, - expressed as a byte offset from the beginning. - - @param buffer The data the write. - - @param bytes The number of bytes to write. - - @param ec Set to the error, if any occurred. - */ - void - write(std::uint64_t offset, - void const* buffer, std::size_t bytes, error_code& ec); - - /** Perform a low level file synchronization. - - @par Requirements - - The file must be open with a mode allowing writes. - - @param ec Set to the error, if any occurred. - */ - void - sync(error_code& ec); - - /** Truncate the file at a specific size. - - @par Requirements - - The file must be open with a mode allowing writes. - - @param length The new file size. - - @param ec Set to the error, if any occurred. - */ - void - trunc(std::uint64_t length, error_code& ec); - -private: - static - void - err(DWORD dwError, error_code& ec) - { - ec = error_code{static_cast(dwError), system_category()}; - } - - static - void - last_err(error_code& ec) - { - err(::GetLastError(), ec); - } - - static - std::pair - flags(file_mode mode); -}; - -} // nudb - -#include - -#endif - -#endif diff --git a/src/nudb/include/nudb/xxhasher.hpp b/src/nudb/include/nudb/xxhasher.hpp deleted file mode 100644 index 5fe1e93c27..0000000000 --- a/src/nudb/include/nudb/xxhasher.hpp +++ /dev/null @@ -1,45 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef NUDB_XXHASHER_HPP -#define NUDB_XXHASHER_HPP - -#include -#include -#include -#include - -namespace nudb { - -/** A Hasher that uses xxHash. - - This object meets the requirements of @b Hasher. It is - the default hash function unless otherwise specified. -*/ -class xxhasher -{ - std::uint64_t seed_; - -public: - using result_type = std::uint64_t; - - explicit - xxhasher(std::uint64_t seed) - : seed_(seed) - { - } - - result_type - operator()(void const* data, std::size_t bytes) const noexcept - { - return detail::XXH64(data, bytes, seed_); - } -}; - -} // nudb - -#endif diff --git a/src/nudb/scripts/blacklist.supp b/src/nudb/scripts/blacklist.supp deleted file mode 100644 index e161cb10c8..0000000000 --- a/src/nudb/scripts/blacklist.supp +++ /dev/null @@ -1,38 +0,0 @@ -# Remember that this blacklist file is GLOBAL to all sanitizers -# Be therefore extremely careful when considering to add a sanitizer -# filter here instead of using a runtime suppression -# -# Remember also that filters here quite literally completely -# remove instrumentation altogether, so filtering here means -# that sanitizers such as tsan will false positive on problems -# introduced by code filtered here. -# -# The main use for this file is ubsan, as it's the only sanitizer -# without a runtime suppression facility. -# -# Be ESPECIALLY careful when filtering out entire source files! -# Try if at all possible to filter only functions using fun:regex -# Remember you must use mangled symbol names with fun:regex - -#### Compile time filters for ubsan #### - -## The well known ubsan failure in libstdc++ extant for years :) -# Line 96:24: runtime error: load of value 4294967221, which is not a valid value for type 'std::_Ios_Fmtflags' -fun:*_Ios_Fmtflags* - -# boost/any.hpp:259:16: runtime error: downcast of address 0x000004392e70 which does not point to an object of type 'any::holder' -fun:*any_cast* - -# boost/lexical_cast.hpp:1625:43: runtime error: downcast of address 0x7fbb4fffbce8 which does not point to an object of type 'buffer_t' (aka 'parser_buf >, char>') -fun:*shl_input_streamable* - - - - -#### Compile time filters for asan #### - - -#### Compile time filters for msan #### - - -#### Compile time filters for tsan #### diff --git a/src/nudb/scripts/build-and-test.sh b/src/nudb/scripts/build-and-test.sh deleted file mode 100755 index c7aa08a716..0000000000 --- a/src/nudb/scripts/build-and-test.sh +++ /dev/null @@ -1,150 +0,0 @@ -#!/usr/bin/env bash - -set -euxo pipefail -# The above bash options do the following: - -# -e When this option is on, if a simple command fails for any of the reasons -# listed in Consequences of Shell Errors or returns an exit status value >0, -# and is not part of the compound list following a while, until, or if -# keyword, and is not a part of an AND or OR list, and is not a pipeline -# preceded by the ! reserved word, then the shell shall immediately exit. -# -u The shell shall write a message to standard error when it tries to expand a -# variable that is not set and immediately exit. An interactive shell shall -# not exit. -# -x The shell shall write to standard error a trace for each command after it -# expands the command and before it executes it. It is unspecified -# whether the command that turns tracing off is traced. -# -o pipefail -# Pipelines fail on the first command which fails instead of dying later on -# down the pipeline. - -shopt -s globstar - -################################## ENVIRONMENT ################################# - -# If not CI, then set some defaults -if [[ -z ${CI:-} ]]; then - : ${TRAVIS_BRANCH:=feature} - : ${CC:=gcc} - : ${ADDRESS_MODEL:=64} - : ${VARIANT:=debug} - # If running locally we assume we have lcov/valgrind on PATH -else - export PATH=${VALGRIND_ROOT}/bin:${LCOV_ROOT}/usr/bin:${PATH} -fi - -MAIN_BRANCH=0 -# For builds not triggered by a pull request TRAVIS_BRANCH is the name of the -# branch currently being built; whereas for builds triggered by a pull request -# it is the name of the branch targeted by the pull request (in many cases this -# will be master). -if [[ ${TRAVIS_BRANCH} == master || ${TRAVIS_BRANCH} == develop ]]; then - MAIN_BRANCH=1 -fi - -num_jobs=1 -if [[ $(uname) == Darwin ]]; then - num_jobs=$(sysctl -n hw.physicalcpu) -elif [[ $(uname -s) == Linux ]]; then - # CircleCI returns 32 phys procs, but 2 virt proc - num_proc_units=$(nproc) - # Physical cores - num_jobs=$(lscpu -p | grep -v '^#' | sort -u -t, -k 2,4 | wc -l) - if ((${num_proc_units} < ${num_jobs})); then - num_jobs=${num_proc_units} - fi -fi - -echo "using toolset: ${CC}" -echo "using variant: ${VARIANT}" -echo "using address-model: ${ADDRESS_MODEL}" -echo "using PATH: ${PATH}" -echo "using MAIN_BRANCH: ${MAIN_BRANCH}" -echo "using BOOST_ROOT: ${BOOST_ROOT}" - -#################################### HELPERS ################################### - -function run_tests_with_debugger { - for x in bin/**/${VARIANT}/**/test-all; do - scripts/run-with-debugger.sh "${x}" - done -} - -function run_tests { - for x in bin/**/${VARIANT}/**/test-all; do - ${x} - done -} - -function run_benchmark { - for x in bin/**/${VARIANT}/**/bench; do - ${x} --inserts=10000 - done -} - -function run_tests_with_valgrind { - for x in bin/**/${VARIANT}/**/test-all; do - # TODO --max-stackframe=8388608 - # see: https://travis-ci.org/vinniefalco/Beast/jobs/132486245 - valgrind --error-exitcode=1 "${x}" - done -} - -function build_bjam { - ${BOOST_ROOT}/bjam toolset=${CC} \ - variant=${VARIANT} \ - address-model=${ADDRESS_MODEL} \ - -j${num_jobs} -} - -function build_cmake { - mkdir -p build - pushd build > /dev/null - cmake -DVARIANT=${VARIANT} .. - make -j${num_jobs} - mkdir -p ../bin/${VARIANT} - find . -executable -type f -exec cp {} ../bin/${VARIANT}/. \; - popd > /dev/null -} - -##################################### BUILD #################################### - -if [[ ${BUILD_SYSTEM:-} == cmake ]]; then - build_cmake -else - build_bjam -fi - -##################################### TESTS #################################### - -if [[ ${VARIANT} == coverage ]]; then - find . -name "*.gcda" | xargs rm -f - rm *.info -f - # Create baseline coverage data file - lcov --no-external -c -i -d . -o baseline.info > /dev/null - - # Perform test - if [[ ${MAIN_BRANCH} == 1 ]]; then - run_tests_with_valgrind - else - run_tests - fi - - # Create test coverage data file - lcov --no-external -c -d . -o testrun.info > /dev/null - - # Combine baseline and test coverage data - lcov -a baseline.info -a testrun.info -o lcov-all.info > /dev/null - - # Extract only include/*, and don\'t report on examples or test - lcov -e "lcov-all.info" "${PWD}/include/nudb/*" -o lcov.info > /dev/null - - ~/.local/bin/codecov -X gcov - cat lcov.info | node_modules/.bin/coveralls - - # Clean up these stragglers so BOOST_ROOT cache is clean - find ${BOOST_ROOT}/bin.v2 -name "*.gcda" | xargs rm -f -else - run_tests_with_debugger - run_benchmark -fi diff --git a/src/nudb/scripts/install-boost.sh b/src/nudb/scripts/install-boost.sh deleted file mode 100755 index 8365c2d544..0000000000 --- a/src/nudb/scripts/install-boost.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env bash -# Assumptions: -# 1) BOOST_ROOT and BOOST_URL are already defined, -# and contain valid values. -# 2) The last namepart of BOOST_ROOT matches the -# folder name internal to boost's .tar.gz -# When testing you can force a boost build by clearing travis caches: -# https://travis-ci.org/ripple/rippled/caches -set -eu -if [ ! -d "$BOOST_ROOT/lib" ] -then - wget $BOOST_URL -O /tmp/boost.tar.gz - cd `dirname $BOOST_ROOT` - rm -fr ${BOOST_ROOT} - tar xzf /tmp/boost.tar.gz - - params="define=_GLIBCXX_USE_CXX11_ABI=0 \ - address-model=$ADDRESS_MODEL --with-program_options \ - --with-system --with-coroutine --with-filesystem" - cd $BOOST_ROOT && \ - ./bootstrap.sh --prefix=$BOOST_ROOT && \ - ./b2 -d1 $params && \ - ./b2 -d0 $params install -else - echo "Using cached boost at $BOOST_ROOT" -fi - diff --git a/src/nudb/scripts/install-dependencies.sh b/src/nudb/scripts/install-dependencies.sh deleted file mode 100755 index 5c26b26a3d..0000000000 --- a/src/nudb/scripts/install-dependencies.sh +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/env bash - -set -euxo pipefail -# The above bash options do the following: - -# -e When this option is on, if a simple command fails for any of the reasons -# listed in Consequences of Shell Errors or returns an exit status value >0, -# and is not part of the compound list following a while, until, or if -# keyword, and is not a part of an AND or OR list, and is not a pipeline -# preceded by the ! reserved word, then the shell shall immediately exit. -# -u The shell shall write a message to standard error when it tries to expand a -# variable that is not set and immediately exit. An interactive shell shall -# not exit. -# -x The shell shall write to standard error a trace for each command after it -# expands the command and before it executes it. It is unspecified -# whether the command that turns tracing off is traced. -# -o pipefail -# Pipelines fail on the first command which fails instead of dying later on -# down the pipeline. - -HERE=${PWD} - -# Override gcc version to $GCC_VER. -# Put an appropriate symlink at the front of the path. -mkdir -v ${HOME}/bin -for g in gcc g++ gcov gcc-ar gcc-nm gcc-ranlib -do - test -x $( type -p ${g}-${GCC_VER} ) - ln -sv $(type -p ${g}-${GCC_VER}) $HOME/bin/${g} -done - -if [[ -n ${CLANG_VER:-} ]]; then - # There are cases where the directory exists, but the exe is not available. - # Use this workaround for now. - if [[ ! -x llvm-${LLVM_VERSION}/bin/llvm-config ]] && [[ -d llvm-${LLVM_VERSION} ]]; then - rm -fr llvm-${LLVM_VERSION} - fi - if [[ ! -d llvm-${LLVM_VERSION} ]]; then - mkdir llvm-${LLVM_VERSION} - LLVM_URL="http://llvm.org/releases/${LLVM_VERSION}/clang+llvm-${LLVM_VERSION}-x86_64-linux-gnu-ubuntu-14.04.tar.xz" - wget -O - ${LLVM_URL} | tar -Jxvf - --strip 1 -C llvm-${LLVM_VERSION} - fi - llvm-${LLVM_VERSION}/bin/llvm-config --version; - export LLVM_CONFIG="llvm-${LLVM_VERSION}/bin/llvm-config"; -fi - -# There are cases where the directory exists, but the exe is not available. -# Use this workaround for now. -if [[ ! -x cmake/bin/cmake && -d cmake ]]; then - rm -fr cmake -fi -if [[ ! -d cmake && ${BUILD_SYSTEM:-} == cmake ]]; then - CMAKE_URL="http://www.cmake.org/files/v3.5/cmake-3.5.2-Linux-x86_64.tar.gz" - mkdir cmake && wget --no-check-certificate -O - ${CMAKE_URL} | tar --strip-components=1 -xz -C cmake -fi - -# NOTE, changed from PWD -> HOME -export PATH=${HOME}/bin:${PATH} - -# What versions are we ACTUALLY running? -if [ -x $HOME/bin/g++ ]; then - ${HOME}/bin/g++ -v -fi -if [ -x ${HOME}/bin/clang ]; then - ${HOME}/bin/clang -v -fi -# Avoid `spurious errors` caused by ~/.npm permission issues -# Does it already exist? Who owns? What permissions? -ls -lah ~/.npm || mkdir ~/.npm -# Make sure we own it -chown -Rc ${USER} ~/.npm -# We use this so we can filter the subtrees from our coverage report -pip install --user https://github.com/codecov/codecov-python/archive/master.zip - -bash scripts/install-boost.sh -bash scripts/install-valgrind.sh - -# Install lcov -# Download the archive -wget http://downloads.sourceforge.net/ltp/lcov-1.12.tar.gz -# Extract to ~/lcov-1.12 -tar xfvz lcov-1.12.tar.gz -C ${HOME} -# Set install path -mkdir -p ${LCOV_ROOT} -cd ${HOME}/lcov-1.12 && make install PREFIX=${LCOV_ROOT} - -# Install coveralls reporter -cd ${HERE} -mkdir -p node_modules -npm install coveralls diff --git a/src/nudb/scripts/install-valgrind.sh b/src/nudb/scripts/install-valgrind.sh deleted file mode 100755 index 943eb86730..0000000000 --- a/src/nudb/scripts/install-valgrind.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env bash -# Assumptions: -# 1) VALGRIND_ROOT is already defined, and contains a valid values -set -eu -if [ ! -d "$VALGRIND_ROOT/bin" ] -then - # These are specified in the addons/apt section of .travis.yml - # sudo apt-get install subversion automake autotools-dev libc6-dbg - export PATH=$PATH:$VALGRIND_ROOT/bin - svn co svn://svn.valgrind.org/valgrind/trunk valgrind-co - cd valgrind-co - ./autogen.sh - ./configure --prefix=$VALGRIND_ROOT - make - make install - # test it - valgrind ls -l -else - echo "Using cached valgrind at $VALGRIND_ROOT" -fi diff --git a/src/nudb/scripts/run-with-debugger.sh b/src/nudb/scripts/run-with-debugger.sh deleted file mode 100755 index 6a8b55d85d..0000000000 --- a/src/nudb/scripts/run-with-debugger.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env bash -set -eu - -if [[ $(uname) == "Darwin" ]]; then - # -o runs after loading the binary - # -k runs after any crash - # We use a ghetto appromixation of --return-child-result, exiting with - # 1 on a crash - lldb --batch \ - -o 'run' \ - -k 'thread backtrace all' \ - -k 'script import os; os._exit(1)' \ - $@ -else - gdb --silent \ - --batch \ - --return-child-result \ - -ex="set print thread-events off" \ - -ex=run \ - -ex="thread apply all bt full" \ - --args $@ -fi diff --git a/src/nudb/scripts/run-with-gdb.sh b/src/nudb/scripts/run-with-gdb.sh deleted file mode 100755 index f7ff0bc726..0000000000 --- a/src/nudb/scripts/run-with-gdb.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/bash -u -set -e -gdb --silent \ - --batch \ - --return-child-result \ - -ex="set print thread-events off" \ - -ex=run \ - -ex="thread apply all bt full" \ - --args $@ diff --git a/src/nudb/test/CMakeLists.txt b/src/nudb/test/CMakeLists.txt deleted file mode 100644 index 628c618f28..0000000000 --- a/src/nudb/test/CMakeLists.txt +++ /dev/null @@ -1,38 +0,0 @@ -# Part of nudb - -GroupSources(test "/") -GroupSources(include/nudb nudb) -GroupSources(extras/nudb extras) -GroupSources(extras/beast/include/beast beast) -GroupSources(extras/beast/extras/beast beast) - -add_executable(test-all - ${EXTRAS_INCLUDES} - ${NUDB_INCLUDES} - ${BEAST_INCLUDES} - ../extras/beast/extras/beast/unit_test/main.cpp - basic_store.cpp - buffer.cpp - callgrind_test.cpp - concepts.cpp - create.cpp - error.cpp - file.cpp - native_file.cpp - posix_file.cpp - recover.cpp - rekey.cpp - store.cpp - type_traits.cpp - verify.cpp - version.cpp - visit.cpp - win32_file.cpp - xxhasher.cpp -) - -if (WIN32) - target_link_libraries(test-all ${Boost_LIBRARIES}) -else () - target_link_libraries(test-all ${Boost_LIBRARIES} rt Threads::Threads) -endif () diff --git a/src/nudb/test/Jamfile b/src/nudb/test/Jamfile deleted file mode 100644 index 41bfa97365..0000000000 --- a/src/nudb/test/Jamfile +++ /dev/null @@ -1,30 +0,0 @@ -# -# Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -# -# Distributed under the Boost Software License, Version 1.0. (See accompanying -# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -# - -import os ; - -unit-test test-all : - ../extras/beast/extras/beast/unit_test/main.cpp - basic_store.cpp - buffer.cpp - callgrind_test.cpp - concepts.cpp - create.cpp - error.cpp - file.cpp - native_file.cpp - posix_file.cpp - recover.cpp - rekey.cpp - store.cpp - type_traits.cpp - verify.cpp - version.cpp - visit.cpp - win32_file.cpp - xxhasher.cpp - ; diff --git a/src/nudb/test/basic_store.cpp b/src/nudb/test/basic_store.cpp deleted file mode 100644 index 38892ee373..0000000000 --- a/src/nudb/test/basic_store.cpp +++ /dev/null @@ -1,250 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -// Test that header file is self-contained -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace nudb { - -namespace detail { - -static_assert(!std::is_copy_constructible {}, ""); -static_assert(!std::is_copy_assignable {}, ""); -static_assert( std::is_move_constructible {}, ""); -static_assert(!std::is_move_assignable {}, ""); - -static_assert(!std::is_copy_constructible {}, ""); -static_assert(!std::is_copy_assignable {}, ""); -static_assert( std::is_move_constructible {}, ""); -static_assert(!std::is_move_assignable {}, ""); - -static_assert(!std::is_copy_constructible {}, ""); -static_assert(!std::is_copy_assignable {}, ""); -static_assert( std::is_move_constructible {}, ""); -static_assert(!std::is_move_assignable {}, ""); - -} // detail - -namespace test { - -class basic_store_test : public beast::unit_test::suite -{ -public: - void - test_members() - { - std::size_t const keySize = 4; - std::size_t const blockSize = 4096; - float loadFactor = 0.5f; - - error_code ec; - test_store ts{keySize, blockSize, loadFactor}; - - // Files not found - ts.open(ec); - if(! BEAST_EXPECTS(ec == - errc::no_such_file_or_directory, ec.message())) - return; - ec = {}; - ts.create(ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - ts.open(ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - BEAST_EXPECT(ts.db.dat_path() == ts.dp); - BEAST_EXPECT(ts.db.key_path() == ts.kp); - BEAST_EXPECT(ts.db.log_path() == ts.lp); - BEAST_EXPECT(ts.db.appnum() == ts.appnum); - BEAST_EXPECT(ts.db.key_size() == ts.keySize); - BEAST_EXPECT(ts.db.block_size() == ts.blockSize); - } - - // Inserts a bunch of values then fetches them - void - do_insert_fetch( - std::size_t N, - std::size_t keySize, - std::size_t blockSize, - float loadFactor, - bool sleep) - { - testcase << - "N=" << N << ", " - "keySize=" << keySize << ", " - "blockSize=" << blockSize; - error_code ec; - test_store ts{keySize, blockSize, loadFactor}; - ts.create(ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - ts.open(ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - // Insert - for(std::size_t n = 0; n < N; ++n) - { - auto const item = ts[n]; - ts.db.insert(item.key, item.data, item.size, ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - } - // Fetch - for(std::size_t n = 0; n < N; ++n) - { - auto const item = ts[n]; - ts.db.fetch(item.key, - [&](void const* data, std::size_t size) - { - if(! BEAST_EXPECT(size == item.size)) - return; - BEAST_EXPECT( - std::memcmp(data, item.data, size) == 0); - }, ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - } - // Insert Duplicate - for(std::size_t n = 0; n < N; ++n) - { - auto const item = ts[n]; - ts.db.insert(item.key, item.data, item.size, ec); - if(! BEAST_EXPECTS( - ec == error::key_exists, ec.message())) - return; - ec = {}; - } - // Insert and Fetch - if(keySize > 1) - { - for(std::size_t n = 0; n < N; ++n) - { - auto item = ts[n]; - ts.db.fetch(item.key, - [&](void const* data, std::size_t size) - { - if(! BEAST_EXPECT(size == item.size)) - return; - BEAST_EXPECT( - std::memcmp(data, item.data, size) == 0); - }, ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - item = ts[N + n]; - ts.db.insert(item.key, item.data, item.size, ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - ts.db.fetch(item.key, - [&](void const* data, std::size_t size) - { - if(! BEAST_EXPECT(size == item.size)) - return; - BEAST_EXPECT( - std::memcmp(data, item.data, size) == 0); - }, ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - } - } - if(sleep) - { - // Make sure we run periodic activity - std::this_thread::sleep_for( - std::chrono::milliseconds{3000}); - } - ts.close(ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - } - - // Perform insert/fetch test across a range of parameters - void - test_insert_fetch() - { - for(auto const keySize : { - 1, 2, 3, 31, 32, 33, 63, 64, 65, 95, 96, 97 }) - { - std::size_t N; - std::size_t constexpr blockSize = 4096; - float loadFactor = 0.95f; - switch(keySize) - { - case 1: N = 10; break; - case 2: N = 100; break; - case 3: N = 250; break; - default: - N = 5000; - break; - }; - do_insert_fetch(N, keySize, blockSize, loadFactor, - keySize == 97); - } - } - - void - test_bulk_insert(std::size_t N, std::size_t keySize, - std::size_t blockSize, float loadFactor) - { - testcase << - "bulk_insert N=" << N << ", " - "keySize=" << keySize << ", " - "blockSize=" << blockSize; - error_code ec; - test_store ts{keySize, blockSize, loadFactor}; - ts.create(ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - ts.open(ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - // Insert - for(std::size_t n = 0; n < N; ++n) - { - auto const item = ts[n]; - ts.db.insert(item.key, item.data, item.size, ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - } - ts.close(ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - verify_info info; - verify(info, ts.dp, ts.kp, - 64 * 1024 * 1024 , no_progress{}, ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - log << info; - } - - void - run() override - { -#if 1 - test_members(); - test_insert_fetch(); -#else - // bulk-insert performance test - test_bulk_insert(10000000, 8, 4096, 0.5f); -#endif - } -}; - -BEAST_DEFINE_TESTSUITE(basic_store, test, nudb); - -} // test -} // nudb - diff --git a/src/nudb/test/buffer.cpp b/src/nudb/test/buffer.cpp deleted file mode 100644 index e86a5688e8..0000000000 --- a/src/nudb/test/buffer.cpp +++ /dev/null @@ -1,77 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -// Test that header file is self-contained -#include - -#include -#include - -namespace nudb { -namespace test { - -class buffer_test : public beast::unit_test::suite -{ -public: - void - run() - { - using buffer = nudb::detail::buffer; - static_assert(std::is_default_constructible::value, ""); -#if 0 - static_assert(std::is_copy_constructible::value, ""); - static_assert(std::is_copy_assignable::value, ""); -#else - static_assert(! std::is_copy_constructible::value, ""); - static_assert(! std::is_copy_assignable::value, ""); -#endif - static_assert(std::is_move_constructible::value, ""); - static_assert(std::is_move_assignable::value, ""); - - { - buffer b; - } - { - buffer b1(1024); - BEAST_EXPECT(b1.size() == 1024); - buffer b2(std::move(b1)); - BEAST_EXPECT(b1.size() == 0); - BEAST_EXPECT(b2.size() == 1024); - } - { - buffer b1(1024); - BEAST_EXPECT(b1.size() == 1024); - buffer b2; - b2 = std::move(b1); - BEAST_EXPECT(b1.size() == 0); - BEAST_EXPECT(b2.size() == 1024); - } - -#if 0 - { - buffer b1(1024); - BEAST_EXPECT(b1.size() == 1024); - buffer b2(b1); - BEAST_EXPECT(b1.size() == 1024); - BEAST_EXPECT(b2.size() == 1024); - } - { - buffer b1(1024); - BEAST_EXPECT(b1.size() == 1024); - buffer b2; - b2 = b1; - BEAST_EXPECT(b1.size() == 1024); - BEAST_EXPECT(b2.size() == 1024); - } -#endif - } -}; - -BEAST_DEFINE_TESTSUITE(buffer, test, nudb); - -} // test -} // nudb diff --git a/src/nudb/test/callgrind_test.cpp b/src/nudb/test/callgrind_test.cpp deleted file mode 100644 index c10644ea98..0000000000 --- a/src/nudb/test/callgrind_test.cpp +++ /dev/null @@ -1,92 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#include -#include -#include -#include -#include -#include -#include - -namespace nudb { -namespace test { - -// This test is designed for callgrind runs to find hotspots - -class callgrind_test : public beast::unit_test::suite -{ -public: - // Creates and opens a database, performs a bunch - // of inserts, then alternates fetching all the keys - // with keys not present. - // - void - testCallgrind(std::size_t N) - { - using key_type = std::uint64_t; - std::size_t const blockSize = 4096; - float const loadFactor = 0.5; - - error_code ec; - test_store ts{sizeof(key_type), blockSize, loadFactor}; - ts.create(ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - ts.open(ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - for(std::size_t i = 0; i < N; ++i) - { - auto const item = ts[i]; - ts.db.insert(item.key, item.data, item.size, ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - } - Buffer b; - for(std::size_t i = 0; i < N * 2; ++i) - { - if(! (i%2)) - { - auto const item = ts[i/2]; - ts.db.fetch(item.key, b, ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - if(! BEAST_EXPECT(b.size() == item.size)) - return; - if(! BEAST_EXPECT(std::memcmp(b.data(), - item.data, item.size) == 0)) - return; - } - else - { - auto const item = ts[N + i/2]; - ts.db.fetch(item.key, b, ec); - if(! BEAST_EXPECTS(ec == - error::key_not_found, ec.message())) - return; - ec = {}; - } - } - ts.close(ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - } - - void run() - { - // higher numbers, more pain - std::size_t constexpr N = 100000; - - testCallgrind(N); - } -}; - -BEAST_DEFINE_TESTSUITE(callgrind, test, nudb); - -} // test -} // nudb diff --git a/src/nudb/test/concepts.cpp b/src/nudb/test/concepts.cpp deleted file mode 100644 index 34dbd74ab2..0000000000 --- a/src/nudb/test/concepts.cpp +++ /dev/null @@ -1,9 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -// Test that header file is self-contained -#include diff --git a/src/nudb/test/create.cpp b/src/nudb/test/create.cpp deleted file mode 100644 index 2762908c9b..0000000000 --- a/src/nudb/test/create.cpp +++ /dev/null @@ -1,49 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -// Test that header file is self-contained -#include - -#include -#include -#include - -namespace nudb { -namespace test { - -class create_test : public beast::unit_test::suite -{ -public: - void - test_create() - { - std::size_t const keySize = 8; - std::size_t const blockSize = 256; - float const loadFactor = 0.5f; - - error_code ec; - test_store ts{keySize, blockSize, loadFactor}; - ts.create(ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - ts.create(ec); - if(! BEAST_EXPECTS( - ec == errc::file_exists, ec.message())) - return; - } - - void - run() override - { - test_create(); - } -}; - -BEAST_DEFINE_TESTSUITE(create, test, nudb); - -} // test -} // nudb diff --git a/src/nudb/test/error.cpp b/src/nudb/test/error.cpp deleted file mode 100644 index ba73bc96fa..0000000000 --- a/src/nudb/test/error.cpp +++ /dev/null @@ -1,83 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -// Test that header file is self-contained -#include - -#include - -namespace nudb { -namespace test { - -class error_test : public beast::unit_test::suite -{ -public: - void check(char const* name, error ev) - { - auto const ec = make_error_code(ev); - BEAST_EXPECT(std::string{ec.category().name()} == name); - BEAST_EXPECT(! ec.message().empty()); - BEAST_EXPECT(std::addressof(ec.category()) == - std::addressof(nudb_category())); - BEAST_EXPECT(nudb_category().equivalent(static_cast(ev), - ec.category().default_error_condition(static_cast(ev)))); - BEAST_EXPECT(nudb_category().equivalent( - ec, static_cast(ev))); - } - - void run() override - { - nudb_category().message(0); - nudb_category().message(99999); - check("nudb", error::success); - check("nudb", error::key_not_found); - check("nudb", error::key_exists); - check("nudb", error::short_read); - check("nudb", error::log_file_exists); - check("nudb", error::no_key_file); - check("nudb", error::too_many_buckets); - check("nudb", error::not_data_file); - check("nudb", error::not_key_file); - check("nudb", error::not_log_file); - check("nudb", error::different_version); - check("nudb", error::invalid_key_size); - check("nudb", error::invalid_block_size); - check("nudb", error::short_key_file); - check("nudb", error::short_bucket); - check("nudb", error::short_spill); - check("nudb", error::short_data_record); - check("nudb", error::short_value); - check("nudb", error::hash_mismatch); - check("nudb", error::invalid_load_factor); - check("nudb", error::invalid_capacity); - check("nudb", error::invalid_bucket_count); - check("nudb", error::invalid_bucket_size); - check("nudb", error::incomplete_data_file_header); - check("nudb", error::incomplete_key_file_header); - check("nudb", error::invalid_log_record); - check("nudb", error::invalid_log_spill); - check("nudb", error::invalid_log_offset); - check("nudb", error::invalid_log_index); - check("nudb", error::invalid_spill_size); - check("nudb", error::uid_mismatch); - check("nudb", error::appnum_mismatch); - check("nudb", error::key_size_mismatch); - check("nudb", error::salt_mismatch); - check("nudb", error::pepper_mismatch); - check("nudb", error::block_size_mismatch); - check("nudb", error::orphaned_value); - check("nudb", error::missing_value); - check("nudb", error::size_mismatch); - check("nudb", error::duplicate_value); - } -}; - -BEAST_DEFINE_TESTSUITE(error, test, nudb); - -} // test -} // nudb - diff --git a/src/nudb/test/file.cpp b/src/nudb/test/file.cpp deleted file mode 100644 index 2a5f075771..0000000000 --- a/src/nudb/test/file.cpp +++ /dev/null @@ -1,9 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -// Test that header file is self-contained -#include diff --git a/src/nudb/test/native_file.cpp b/src/nudb/test/native_file.cpp deleted file mode 100644 index 726d2bbbe6..0000000000 --- a/src/nudb/test/native_file.cpp +++ /dev/null @@ -1,9 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -// Test that header file is self-contained -#include diff --git a/src/nudb/test/posix_file.cpp b/src/nudb/test/posix_file.cpp deleted file mode 100644 index eff0d831a5..0000000000 --- a/src/nudb/test/posix_file.cpp +++ /dev/null @@ -1,9 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -// Test that header file is self-contained -#include diff --git a/src/nudb/test/recover.cpp b/src/nudb/test/recover.cpp deleted file mode 100644 index fbd481959b..0000000000 --- a/src/nudb/test/recover.cpp +++ /dev/null @@ -1,191 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -// Test that header file is self-contained -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace nudb { -namespace test { - -class basic_recover_test : public beast::unit_test::suite -{ -public: - using key_type = std::uint32_t; - - void - test_ok() - { - std::size_t const keySize = 8; - std::size_t const blockSize = 256; - float const loadFactor = 0.5f; - - error_code ec; - test_store ts{keySize, blockSize, loadFactor}; - ts.create(ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - recover(ts.dp, ts.kp, ts.lp, ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - } - - // Creates and opens a database, performs a bunch - // of inserts, then fetches all of them to make sure - // they are there. Uses a fail_file that causes the n-th - // I/O to fail, causing an exception. - void - do_work( - test_store& ts, - std::size_t N, - fail_counter& c, - error_code& ec) - { - ts.create(ec); - if(ec) - return; - basic_store> db; - db.open(ts.dp, ts.kp, ts.lp, ec, c); - if(ec) - return; - if(! BEAST_EXPECT(db.appnum() == ts.appnum)) - return; - // Insert - for(std::size_t i = 0; i < N; ++i) - { - auto const item = ts[i]; - db.insert(item.key, item.data, item.size, ec); - if(ec == test_error::failure) - return; - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - } - // Fetch - Buffer b; - for(std::size_t i = 0; i < N; ++i) - { - auto const item = ts[i]; - db.fetch(item.key, b, ec); - if(ec == test_error::failure) - return; - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - if(! BEAST_EXPECT(b.size() == item.size)) - return; - if(! BEAST_EXPECT(std::memcmp(b.data(), - item.data, item.size) == 0)) - return; - } - db.close(ec); - if(ec == test_error::failure) - return; - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - // Verify - verify_info info; - verify(info, ts.dp, ts.kp, - 0, no_progress{}, ec); - if(ec) - { - log << info; - return; - } - } - - void - do_recover( - test_store& ts, fail_counter& c, error_code& ec) - { - recover>( - ts.dp, ts.kp, ts.lp, ec, c); - if(ec) - return; - // Verify - verify_info info; - verify(info, ts.dp, ts.kp, - 0, no_progress{}, ec); - if(ec) - return; - ts.erase(); - } - - void - test_recover(std::size_t blockSize, - float loadFactor, std::size_t N) - { - testcase(std::to_string(N) + " inserts", - beast::unit_test::abort_on_fail); - test_store ts{sizeof(key_type), blockSize, loadFactor}; - for(std::size_t n = 1;; ++n) - { - { - error_code ec; - fail_counter c{n}; - do_work(ts, N, c, ec); - if(! ec) - { - ts.close(ec); - ts.erase(); - break; - } - if(! BEAST_EXPECTS(ec == - test::test_error::failure, ec.message())) - return; - } - for(std::size_t m = 1;; ++m) - { - error_code ec; - fail_counter c{m}; - do_recover(ts, c, ec); - if(! ec) - break; - if(! BEAST_EXPECTS(ec == - test::test_error::failure, ec.message())) - return; - } - } - } -}; - -class recover_test : public basic_recover_test -{ -public: - void - run() override - { - test_ok(); - test_recover(128, 0.55f, 0); - test_recover(128, 0.55f, 10); - test_recover(128, 0.55f, 100); - } -}; - -class recover_big_test : public basic_recover_test -{ -public: - void - run() override - { - test_recover(256, 0.55f, 1000); - test_recover(256, 0.90f, 10000); - } -}; - -BEAST_DEFINE_TESTSUITE(recover, test, nudb); -//BEAST_DEFINE_TESTSUITE_MANUAL(recover_big, test, nudb); - -} // test -} // nudb diff --git a/src/nudb/test/rekey.cpp b/src/nudb/test/rekey.cpp deleted file mode 100644 index 8b333ec2a5..0000000000 --- a/src/nudb/test/rekey.cpp +++ /dev/null @@ -1,136 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -// Test that header file is self-contained -#include - -#include -#include -#include -#include -#include - -namespace nudb { -namespace test { - -// Simple test to check that rekey works, and -// also to exercise all its failure paths. -// -class rekey_test : public beast::unit_test::suite -{ -public: - void - do_recover( - std::size_t N, nsize_t blockSize, float loadFactor) - { - using key_type = std::uint32_t; - - auto const keys = static_cast( - loadFactor * detail::bucket_capacity(blockSize)); - std::size_t const bufferSize = - (blockSize * (1 + ((N + keys - 1) / keys))) - / 2; - error_code ec; - test_store ts{sizeof(key_type), blockSize, loadFactor}; - ts.create(ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - ts.open(ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - // Insert - for(std::size_t i = 0; i < N; ++i) - { - auto const item = ts[i]; - ts.db.insert(item.key, item.data, item.size, ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - } - ts.close(ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - // Verify - verify_info info; - verify( - info, ts.dp, ts.kp, bufferSize, no_progress{}, ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - if(! BEAST_EXPECT(info.value_count == N)) - return; - if(! BEAST_EXPECT(info.spill_count > 0)) - return; - // Rekey - auto const kp2 = ts.kp + "2"; - for(std::size_t n = 1;; ++n) - { - fail_counter fc{n}; - rekey>( - ts.dp, kp2, ts.lp, blockSize, loadFactor, - N, bufferSize, ec, no_progress{}, fc); - if(! ec) - break; - if(! BEAST_EXPECTS(ec == - test::test_error::failure, ec.message())) - return; - ec = {}; - recover( - ts.dp, kp2, ts.lp, ec); - if(ec == error::no_key_file || - ec == errc::no_such_file_or_directory) - { - ec = {}; - continue; - } - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - native_file::erase(kp2, ec); - if(ec == errc::no_such_file_or_directory) - ec = {}; - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - // Verify - verify(info, ts.dp, ts.kp, - bufferSize, no_progress{}, ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - if(! BEAST_EXPECT(info.value_count == N)) - return; - } - // Verify - verify(info, ts.dp, ts.kp, - bufferSize, no_progress{}, ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - if(! BEAST_EXPECT(info.value_count == N)) - return; - verify(info, ts.dp, kp2, - bufferSize, no_progress{}, ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - if(! BEAST_EXPECT(info.value_count == N)) - return; - } - - void - run() override - { - enum - { - N = 50000, - blockSize = 256 - }; - - float const loadFactor = 0.95f; - - do_recover(N, blockSize, loadFactor); - } -}; - -BEAST_DEFINE_TESTSUITE(rekey, test, nudb); - -} // test -} // nudb diff --git a/src/nudb/test/store.cpp b/src/nudb/test/store.cpp deleted file mode 100644 index e0016e0c2b..0000000000 --- a/src/nudb/test/store.cpp +++ /dev/null @@ -1,9 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -// Test that header file is self-contained -#include diff --git a/src/nudb/test/type_traits.cpp b/src/nudb/test/type_traits.cpp deleted file mode 100644 index 050ee72e1b..0000000000 --- a/src/nudb/test/type_traits.cpp +++ /dev/null @@ -1,9 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -// Test that header file is self-contained -#include diff --git a/src/nudb/test/verify.cpp b/src/nudb/test/verify.cpp deleted file mode 100644 index e3a6f1c8cf..0000000000 --- a/src/nudb/test/verify.cpp +++ /dev/null @@ -1,94 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -// Test that header file is self-contained -#include - -#include -#include -#include -#include - -namespace nudb { -namespace test { - -class verify_test : public beast::unit_test::suite -{ -public: - // File doesn't exist - void - test_missing() - { - error_code ec; - test_store ts{4, 4096, 0.5f}; - verify_info info; - verify(info, - ts.dp, ts.kp, 0, no_progress{}, ec); - BEAST_EXPECTS(ec == - errc::no_such_file_or_directory, ec.message()); - } - - void - test_verify( - std::size_t N, - std::size_t keySize, - std::size_t blockSize, - float loadFactor) - { - testcase << - "N=" << N << ", " - "keySize=" << keySize << ", " - "blockSize=" << blockSize; - error_code ec; - test_store ts{keySize, blockSize, loadFactor}; - ts.create(ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - ts.open(ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - // Insert - for(std::size_t n = 0; n < N; ++n) - { - auto const item = ts[n]; - ts.db.insert(item.key, item.data, item.size, ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - } - ts.close(ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - - // Verify - verify_info info; - verify(info, ts.dp, ts.kp, - 0, no_progress{}, ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - BEAST_EXPECT(info.hist[1] > 0); - - // Verify fast - verify(info, ts.dp, ts.kp, - 10 * 1024 * 1024, no_progress{}, ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - BEAST_EXPECT(info.hist[1] > 0); - } - - void - run() override - { - float const loadFactor = 0.95f; - test_missing(); - test_verify(5000, 4, 256, loadFactor); - } -}; - -BEAST_DEFINE_TESTSUITE(verify, test, nudb); - -} // test -} // nudb diff --git a/src/nudb/test/version.cpp b/src/nudb/test/version.cpp deleted file mode 100644 index 7604c89a2b..0000000000 --- a/src/nudb/test/version.cpp +++ /dev/null @@ -1,9 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -// Test that header file is self-contained -#include diff --git a/src/nudb/test/visit.cpp b/src/nudb/test/visit.cpp deleted file mode 100644 index 405710382b..0000000000 --- a/src/nudb/test/visit.cpp +++ /dev/null @@ -1,114 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -// Test that header file is self-contained -#include - -#include -#include -#include -#include - -namespace nudb { -namespace test { - -class visit_test : public beast::unit_test::suite -{ -public: - void - do_visit( - std::size_t N, - std::size_t blockSize, - float loadFactor) - { - using key_type = std::uint32_t; - - error_code ec; - test_store ts{sizeof(key_type), blockSize, loadFactor}; - - // File not present - visit(ts.dp, - [&](void const* key, std::size_t keySize, - void const* data, std::size_t dataSize, - error_code& ec) - { - }, no_progress{}, ec); - if(! BEAST_EXPECTS(ec == - errc::no_such_file_or_directory, ec.message())) - return; - ec = {}; - - ts.create(ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - ts.open(ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - std::unordered_map map; - // Insert - for(std::size_t i = 0; i < N; ++i) - { - auto const item = ts[i]; - key_type const k = item.key[0] + - (static_cast(item.key[1]) << 8) + - (static_cast(item.key[2]) << 16) + - (static_cast(item.key[3]) << 24); - map[k] = i; - ts.db.insert(item.key, item.data, item.size, ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - } - ts.close(ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - // Visit - visit(ts.dp, - [&](void const* key, std::size_t keySize, - void const* data, std::size_t dataSize, - error_code& ec) - { - auto const fail = - [&ec] - { - ec = error_code{ - errc::invalid_argument, generic_category()}; - }; - if(! BEAST_EXPECT(keySize == sizeof(key_type))) - return fail(); - auto const p = - reinterpret_cast(key); - key_type const k = p[0] + - (static_cast(p[1]) << 8) + - (static_cast(p[2]) << 16) + - (static_cast(p[3]) << 24); - auto const it = map.find(k); - if(it == map.end()) - return fail(); - auto const item = ts[it->second]; - if(! BEAST_EXPECT(dataSize == item.size)) - return fail(); - auto const result = - std::memcmp(data, item.data, item.size); - if(result != 0) - return fail(); - }, no_progress{}, ec); - if(! BEAST_EXPECTS(! ec, ec.message())) - return; - } - - void - run() override - { - float const loadFactor = 0.95f; - do_visit(5000, 4096, loadFactor); - } -}; - -BEAST_DEFINE_TESTSUITE(visit, test, nudb); - -} // test -} // nudb diff --git a/src/nudb/test/win32_file.cpp b/src/nudb/test/win32_file.cpp deleted file mode 100644 index ca6d9337e4..0000000000 --- a/src/nudb/test/win32_file.cpp +++ /dev/null @@ -1,9 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -// Test that header file is self-contained -#include diff --git a/src/nudb/test/xxhasher.cpp b/src/nudb/test/xxhasher.cpp deleted file mode 100644 index 6c4c9b9608..0000000000 --- a/src/nudb/test/xxhasher.cpp +++ /dev/null @@ -1,9 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -// Test that header file is self-contained -#include diff --git a/src/nudb/tools/CMakeLists.txt b/src/nudb/tools/CMakeLists.txt deleted file mode 100644 index 8a82003ff6..0000000000 --- a/src/nudb/tools/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -# Part of nudb - -GroupSources (include/nudb nudb) -GroupSources (extras/nudb extras) -GroupSources (tools "/") - -add_executable (nudb - ${NUDB_INCLUDES} - ${EXTRAS_INCLUDES} - nudb.cpp -) - -if (WIN32) - target_link_libraries (nudb ${Boost_LIBRARIES}) -else () - target_link_libraries (nudb ${Boost_LIBRARIES} rt Threads::Threads) -endif () diff --git a/src/nudb/tools/Jamfile b/src/nudb/tools/Jamfile deleted file mode 100644 index 384c33f34b..0000000000 --- a/src/nudb/tools/Jamfile +++ /dev/null @@ -1,12 +0,0 @@ -# -# Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -# -# Distributed under the Boost Software License, Version 1.0. (See accompanying -# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -# - -import os ; - -exe nudb : - nudb.cpp - ; diff --git a/src/nudb/tools/nudb.cpp b/src/nudb/tools/nudb.cpp deleted file mode 100644 index 5a06a03a3c..0000000000 --- a/src/nudb/tools/nudb.cpp +++ /dev/null @@ -1,514 +0,0 @@ -// -// Copyright (c) 2015-2016 Vinnie Falco (vinnie dot falco at gmail dot com) -// -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// - -#include -#include -#include -#include -#include -#include -#include - -namespace nudb { - -namespace detail { - -std::ostream& -operator<<(std::ostream& os, dat_file_header const h) -{ - os << - "type: '" << std::string{h.type, h.type + sizeof(h.type)} << "'\n" - "version: " << h.version << "\n" - "uid: " << fhex(h.uid) << "\n" - "appnum: " << fhex(h.appnum) << "\n" - "key_size: " << h.key_size << "\n" - ; - return os; -} - -std::ostream& -operator<<(std::ostream& os, key_file_header const h) -{ - os << - "type: '" << std::string{h.type, h.type + sizeof(h.type)} << "'\n" - "version: " << h.version << "\n" - "uid: " << fhex(h.uid) << "\n" - "appnum: " << fhex(h.appnum) << "\n" - "key_size: " << h.key_size << "\n" - "salt: " << fhex(h.salt) << "\n" - "pepper: " << fhex(h.pepper) << "\n" - "block_size: " << fdec(h.block_size) << "\n" - ; - return os; -} - -std::ostream& -operator<<(std::ostream& os, log_file_header const h) -{ - os << std::setfill('0') << std::internal << std::showbase << - "type: '" << std::string{h.type, h.type + sizeof(h.type)} << "'\n" - "version: " << h.version << "\n" - "uid: " << fhex(h.uid) << "\n" - "appnum: " << fhex(h.appnum) << "\n" - "key_size: " << h.key_size << "\n" - "salt: " << fhex(h.salt) << "\n" - "pepper: " << fhex(h.pepper) << "\n" - "block_size: " << fdec(h.block_size) << "\n" - "key_file_size: " << fdec(h.key_file_size) << "\n" - "dat_file_size: " << fdec(h.dat_file_size) << "\n" - ; - return os; -} - -} // detail - -std::ostream& -operator<<(std::ostream& os, verify_info const& info) -{ - os << - "dat_path " << info.dat_path << "\n" - "key_path " << info.key_path << "\n" - "algorithm " <<(info.algorithm ? "fast" : "normal") << "\n" - "avg_fetch: " << std::fixed << std::setprecision(3) << info.avg_fetch << "\n" << - "waste: " << std::fixed << std::setprecision(3) << info.waste * 100 << "%" << "\n" << - "overhead: " << std::fixed << std::setprecision(1) << info.overhead * 100 << "%" << "\n" << - "actual_load: " << std::fixed << std::setprecision(0) << info.actual_load * 100 << "%" << "\n" << - "version: " << fdec(info.version) << "\n" << - "uid: " << fhex(info.uid) << "\n" << - "appnum: " << fhex(info.appnum) << "\n" << - "key_size: " << fdec(info.key_size) << "\n" << - "salt: " << fhex(info.salt) << "\n" << - "pepper: " << fhex(info.pepper) << "\n" << - "block_size: " << fdec(info.block_size) << "\n" << - "bucket_size: " << fdec(info.bucket_size) << "\n" << - "load_factor: " << std::fixed << std::setprecision(0) << info.load_factor * 100 << "%" << "\n" << - "capacity: " << fdec(info.capacity) << "\n" << - "buckets: " << fdec(info.buckets) << "\n" << - "key_count: " << fdec(info.key_count) << "\n" << - "value_count: " << fdec(info.value_count) << "\n" << - "value_bytes: " << fdec(info.value_bytes) << "\n" << - "spill_count: " << fdec(info.spill_count) << "\n" << - "spill_count_tot: " << fdec(info.spill_count_tot) << "\n" << - "spill_bytes: " << fdec(info.spill_bytes) << "\n" << - "spill_bytes_tot: " << fdec(info.spill_bytes_tot) << "\n" << - "key_file_size: " << fdec(info.key_file_size) << "\n" << - "dat_file_size: " << fdec(info.dat_file_size) << "\n" << - "hist: " << fhist(info.hist) << "\n" - ; - return os; -} - -template -class admin_tool -{ - int ac_ = 0; - char const* const* av_ = nullptr; - boost::program_options::options_description desc_; - -public: - admin_tool() - : desc_("Options") - { - namespace po = boost::program_options; - desc_.add_options() - ("buffer,b", po::value(), - "Set the buffer size in bytes (larger is faster).") - ("dat,d", po::value(), - "Path to data file.") - ("key,k", po::value(), - "Path to key file.") - ("log,l", po::value(), - "Path to log file.") - ("count,n", po::value(), - "The number of items in the data file.") - ("command", "Command to run.") - ; - } - - std::string - progname() const - { - using namespace boost::filesystem; - return path{av_[0]}.stem().string(); - } - - std::string - filename(std::string const& s) - { - using namespace boost::filesystem; - return path{s}.filename().string(); - } - - void - help() - { - std::cout << - "usage: " << progname() << " [file...] \n"; - std::cout << - "\n" - "Commands:\n" - "\n" - " help\n" - "\n" - " Print this help information.\n" - "\n" - " info [ []]\n" - "\n" - " Show metadata and header information for database files.\n" - "\n" - " recover \n" - "\n" - " Perform a database recovery. A recovery is necessary if a log\n" - " file is present. Running commands on an unrecovered database\n" - " may result in lost or corrupted data.\n" - "\n" - " rekey --count= --buffer=\n" - "\n" - " Generate the key file for a data file. The buffer option is\n" - " required, larger buffers process faster. A buffer equal to\n" - " the size of the key file processes the fastest. This command\n" - " must be passed the count of items in the data file, which\n" - " can be calculated with the 'visit' command.\n" - "\n" - " If the rekey is aborted before completion, the database must\n" - " be subsequently restored by running the 'recover' command.\n" - "\n" - " verify [--buffer=]\n" - "\n" - " Verify the integrity of a database. The buffer option is\n" - " optional, if omitted a slow algorithm is used. When a buffer\n" - " size is provided, a fast algorithm is used with larger\n" - " buffers resulting in bigger speedups. A buffer equal to the\n" - " size of the key file provides the fastest speedup.\n" - "\n" - " visit \n" - "\n" - " Iterate a data file and show information, including the count\n" - " of items in the file and a histogram of their log base2 size.\n" - "\n" - "Notes:\n" - "\n" - " Paths may be full or relative, and should include the extension.\n" - " The recover algorithm should be invoked before running any\n" - " operation which can modify the database.\n" - "\n" - ; - desc_.print(std::cout); - }; - - int - error(std::string const& why) - { - std::cerr << - progname() << ": " << why << ".\n" - "Use '" << progname() << " help' for usage.\n"; - return EXIT_FAILURE; - }; - - int - operator()(int ac, char const* const* av) - { - namespace po = boost::program_options; - - ac_ = ac; - av_ = av; - - try - { - po::positional_options_description pod; - pod.add("command", 1); - pod.add("dat", 1); - pod.add("key", 1); - pod.add("log", 1); - - po::variables_map vm; - po::store(po::command_line_parser(ac, av) - .options(desc_) - .positional(pod) - .run() - ,vm); - po::notify(vm); - - std::string cmd; - - if(vm.count("command")) - cmd = vm["command"].as(); - - if(cmd == "help") - { - help(); - return EXIT_SUCCESS; - } - - if(cmd == "info") - return do_info(vm); - - if(cmd == "recover") - return do_recover(vm); - - if(cmd == "rekey") - return do_rekey(vm); - - if(cmd == "verify") - return do_verify(vm); - - if(cmd == "visit") - return do_visit(vm); - - return error("Unknown command '" + cmd + "'"); - } - catch(std::exception const& e) - { - return error(e.what()); - } - } - -private: - int - do_info(boost::program_options::variables_map const& vm) - { - if(! vm.count("dat") && ! vm.count("key") && ! vm.count("log")) - return error("No files specified"); - if(vm.count("dat")) - do_info(vm["dat"].as()); - if(vm.count("key")) - do_info(vm["key"].as()); - if(vm.count("log")) - do_info(vm["log"].as()); - return EXIT_SUCCESS; - } - - void - do_info(path_type const& path) - { - error_code ec; - auto const err = - [&] - { - std::cout << path << ": " << ec.message() << "\n"; - }; - native_file f; - f.open(file_mode::read, path, ec); - if(ec) - return err(); - auto const size = f.size(ec); - if(ec) - return err(); - if(size < 8) - { - std::cout << "File " << path << " is too small to be a database file.\n"; - return; - } - std::array ta; - f.read(0, ta.data(), ta.size(), ec); - if(ec) - return err(); - std::string ts{ta.data(), ta.size()}; - - if(ts == "nudb.dat") - { - detail::dat_file_header h; - detail::read(f, h, ec); - if(ec) - return err(); - f.close(); - std::cout << - "data file: " << path << "\n" - "file size: " << fdec(size) << "\n" << - h << "\n"; - return; - } - - if(ts == "nudb.key") - { - detail::key_file_header h; - detail::read(f, h, ec); - if(ec) - return err(); - f.close(); - std::cout << - "key file: " << path << "\n" - "file size: " << fdec(size) << "\n" << - h << "\n"; - return; - } - - if(ts == "nudb.log") - { - detail::log_file_header h; - detail::read(f, h, ec); - if(ec) - return err(); - f.close(); - std::cout << - "log file: " << path << "\n" - "file size: " << fdec(size) << "\n" << - h << "\n"; - return; - } - - std::cout << "File " << path << " has unknown type '" << ts << "'.\n"; - } - - int - do_recover(boost::program_options::variables_map const& vm) - { - if(! vm.count("dat") || ! vm.count("key") || ! vm.count("log")) - return error("Missing file specifications"); - error_code ec; - recover( - vm["dat"].as(), - vm["key"].as(), - vm["log"].as(), - ec); - if(ec) - { - std::cerr << "recover: " << ec.message() << "\n"; - return EXIT_FAILURE; - } - return EXIT_SUCCESS; - } - - int - do_rekey(boost::program_options::variables_map const& vm) - { - if(! vm.count("dat")) - return error("Missing data file path"); - if(! vm.count("key")) - return error("Missing key file path"); - if(! vm.count("log")) - return error("Missing log file path"); - if(! vm.count("count")) - return error("Missing item count"); - if(! vm.count("buffer")) - return error("Missing buffer size"); - auto const dp = vm["dat"].as(); - auto const kp = vm["key"].as(); - auto const lp = vm["log"].as(); - auto const itemCount = vm["count"].as(); - auto const bufferSize = vm["buffer"].as(); - error_code ec; - progress p{std::cout}; - rekey(dp, kp, lp, - block_size(kp), 0.5f, itemCount, - bufferSize, ec, p); - if(ec) - { - std::cerr << "rekey: " << ec.message() << "\n"; - return EXIT_FAILURE; - } - return EXIT_SUCCESS; - } - - int - do_verify(boost::program_options::variables_map const& vm) - { - if(! vm.count("dat")) - return error("Missing data file path"); - if(! vm.count("key")) - return error("Missing key file path"); - - auto const bufferSize = vm.count("buffer") ? - vm["buffer"].as() : 0; - auto const dp = vm["dat"].as(); - auto const kp = vm.count("key") ? - vm["key"].as() : std::string{}; - - if(! vm.count("key")) - { - // todo - std::cerr << "unimplemented: dat-only verify\n"; - return EXIT_FAILURE; - } - - error_code ec; - progress p(std::cout); - { - verify_info info; - verify(info, dp, kp, bufferSize, p, ec); - if(! ec) - std::cout << info; - } - if(ec) - { - std::cerr << "verify: " << ec.message() << "\n"; - return EXIT_FAILURE; - } - return EXIT_SUCCESS; - } - - int - do_visit(boost::program_options::variables_map const& vm) - { - if(! vm.count("dat")) - return error("Missing dat path"); - auto const path = vm["dat"].as(); - error_code ec; - auto const err = - [&] - { - std::cout << path << ": " << ec.message() << "\n"; - return EXIT_FAILURE; - }; - { - native_file f; - f.open(file_mode::read, path, ec); - if(ec) - return err(); - auto const fileSize = f.size(ec); - if(ec) - return err(); - detail::dat_file_header h; - detail::read(f, h, ec); - if(ec) - return err(); - f.close(); - std::cout << - "data file: " << path << "\n" - "file size: " << fdec(fileSize) << "\n" << - h; - std::cout.flush(); - } - - std::uint64_t n = 0; - std::array hist; - hist.fill(0); - progress p{std::cout}; - visit(path, - [&](void const*, std::size_t, - void const*, std::size_t data_size, - error_code& ec) - { - ++n; - ++hist[log2(data_size)]; - //std::this_thread::sleep_for(std::chrono::milliseconds{1}); - }, p, ec); - if(! ec) - std::cout << - "value_count " << fdec(n) << "\n" << - "sizes: " << fhist(hist) << "\n"; - if(ec) - { - std::cerr << "visit: " << ec.message() << "\n"; - return EXIT_FAILURE; - } - return EXIT_SUCCESS; - } -}; - -} // nudb - -int -main(int ac, char const* const* av) -{ - using namespace nudb; - admin_tool t; - auto const rv = t(ac, av); - std::cout.flush(); - basic_seconds_clock_main_hook(); - return rv; -} diff --git a/src/ripple/unity/soci.cpp b/src/ripple/unity/soci.cpp deleted file mode 100644 index a72cf1d2a0..0000000000 --- a/src/ripple/unity/soci.cpp +++ /dev/null @@ -1,61 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of rippled: https://github.com/ripple/rippled - Copyright (c) 2012-2015 Ripple Labs Inc. - - Permission to use, copy, modify, and/or 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 THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR 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. -*/ -//============================================================================== - -#if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated" -#endif - - -// Core soci -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#if defined(__clang__) -#pragma clang diagnostic pop -#endif diff --git a/src/snappy/config/snappy-stubs-public.h b/src/snappy/config/snappy-stubs-public.h deleted file mode 100644 index 2e20481963..0000000000 --- a/src/snappy/config/snappy-stubs-public.h +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2011 Google Inc. All Rights Reserved. -// Author: sesse@google.com (Steinar H. Gunderson) -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Various type stubs for the open-source version of Snappy. -// -// This file cannot include config.h, as it is included from snappy.h, -// which is a public header. Instead, snappy-stubs-public.h is generated by -// from snappy-stubs-public.h.in at configure time. - -#ifndef UTIL_SNAPPY_OPENSOURCE_SNAPPY_STUBS_PUBLIC_H_ -#define UTIL_SNAPPY_OPENSOURCE_SNAPPY_STUBS_PUBLIC_H_ - -#include -#include - -#ifndef _MSC_VER -#include -#endif - -#define SNAPPY_MAJOR 1 // @SNAPPY_MAJOR@ -#define SNAPPY_MINOR 1 // @SNAPPY_MINOR@ -#define SNAPPY_PATCHLEVEL 7 // @SNAPPY_PATCHLEVEL@ -#define SNAPPY_VERSION \ - ((SNAPPY_MAJOR << 16) | (SNAPPY_MINOR << 8) | SNAPPY_PATCHLEVEL) - -#include - -namespace snappy { - -typedef std::int8_t int8; -typedef std::int16_t int16; -typedef std::int32_t int32; -typedef std::int64_t int64; -typedef std::uint8_t uint8; -typedef std::uint16_t uint16; -typedef std::uint32_t uint32; -typedef std::uint64_t uint64; - -typedef std::string string; - - -#ifdef _MSC_VER -// Windows does not have an iovec type, yet the concept is universally useful. -// It is simple to define it ourselves, so we put it inside our own namespace. -struct iovec { - void* iov_base; - size_t iov_len; -}; -#endif - -} // namespace snappy - -#endif // UTIL_SNAPPY_OPENSOURCE_SNAPPY_STUBS_PUBLIC_H_ \ No newline at end of file diff --git a/src/snappy/snappy/.appveyor.yml b/src/snappy/snappy/.appveyor.yml deleted file mode 100644 index 2ed49f95f2..0000000000 --- a/src/snappy/snappy/.appveyor.yml +++ /dev/null @@ -1,41 +0,0 @@ -# Build matrix / environment variables are explained on: -# https://www.appveyor.com/docs/appveyor-yml/ -# This file can be validated on: https://ci.appveyor.com/tools/validate-yaml - -version: "{build}" - -environment: - matrix: - # AppVeyor currently has no custom job name feature. - # http://help.appveyor.com/discussions/questions/1623-can-i-provide-a-friendly-name-for-jobs - - JOB: Visual Studio 2017 - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 - CMAKE_GENERATOR: Visual Studio 15 2017 - - JOB: Visual Studio 2015 - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015 - CMAKE_GENERATOR: Visual Studio 14 2015 - -platform: - - x86 - - x64 - -configuration: - - RelWithDebInfo - - Debug - -build: - verbosity: minimal - -build_script: - - git submodule update --init --recursive - - mkdir out - - cd out - - if "%platform%"=="x64" set CMAKE_GENERATOR=%CMAKE_GENERATOR% Win64 - - cmake --version - - cmake .. -G "%CMAKE_GENERATOR%" - -DCMAKE_CONFIGURATION_TYPES="%CONFIGURATION%" - - cmake --build . --config %CONFIGURATION% - - cd .. - -test_script: - - out\%CONFIGURATION%\snappy_unittest \ No newline at end of file diff --git a/src/snappy/snappy/.travis.yml b/src/snappy/snappy/.travis.yml deleted file mode 100644 index 9841e9a7e7..0000000000 --- a/src/snappy/snappy/.travis.yml +++ /dev/null @@ -1,59 +0,0 @@ -# Build matrix / environment variables are explained on: -# http://about.travis-ci.org/docs/user/build-configuration/ -# This file can be validated on: http://lint.travis-ci.org/ - -sudo: false -dist: trusty -language: cpp - -compiler: - - gcc - - clang -os: - - linux - - osx - -env: - - BUILD_TYPE=Debug - - BUILD_TYPE=RelWithDebInfo - -matrix: - allow_failures: - - compiler: clang - env: BUILD_TYPE=RelWithDebInfo - -addons: - apt: - # List of whitelisted in travis packages for ubuntu-trusty can be found here: - # https://github.com/travis-ci/apt-package-whitelist/blob/master/ubuntu-trusty - # List of whitelisted in travis apt-sources: - # https://github.com/travis-ci/apt-source-whitelist/blob/master/ubuntu.json - sources: - - ubuntu-toolchain-r-test - - llvm-toolchain-trusty-4.0 - packages: - - cmake - - gcc-6 - - g++-6 - - clang-4.0 - -install: -# Travis doesn't have a nice way to install homebrew packages yet. -# https://github.com/travis-ci/travis-ci/issues/5377 -- if [ "$TRAVIS_OS_NAME" == "osx" ]; then brew update; fi -- if [ "$TRAVIS_OS_NAME" == "osx" ]; then brew install gcc@6; fi -# /usr/bin/gcc is stuck to old versions by on both Linux and OSX. -- if [ "$CXX" = "g++" ]; then export CXX="g++-6" CC="gcc-6"; fi -- echo ${CC} -- echo ${CXX} -- ${CXX} --version -- cmake --version - -before_script: -- mkdir -p build && cd build -- cmake .. -DCMAKE_BUILD_TYPE=$BUILD_TYPE -- cmake --build . -- cd .. - -script: -- build/snappy_unittest \ No newline at end of file diff --git a/src/snappy/snappy/AUTHORS b/src/snappy/snappy/AUTHORS deleted file mode 100644 index 4858b377c7..0000000000 --- a/src/snappy/snappy/AUTHORS +++ /dev/null @@ -1 +0,0 @@ -opensource@google.com diff --git a/src/snappy/snappy/CMakeLists.txt b/src/snappy/snappy/CMakeLists.txt deleted file mode 100644 index 3f534b134e..0000000000 --- a/src/snappy/snappy/CMakeLists.txt +++ /dev/null @@ -1,174 +0,0 @@ -cmake_minimum_required(VERSION 3.1) -project(Snappy VERSION 1.1.7 LANGUAGES C CXX) - -# BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to make -# it prominent in the GUI. -option(BUILD_SHARED_LIBS "Build shared libraries(DLLs)." OFF) - -option(SNAPPY_BUILD_TESTS "Build Snappy's own tests." ON) - -include(TestBigEndian) -test_big_endian(SNAPPY_IS_BIG_ENDIAN) - -include(CheckIncludeFile) -check_include_file("byteswap.h" HAVE_BYTESWAP_H) -check_include_file("stddef.h" HAVE_STDDEF_H) -check_include_file("stdint.h" HAVE_STDINT_H) -check_include_file("sys/endian.h" HAVE_SYS_ENDIAN_H) -check_include_file("sys/mman.h" HAVE_SYS_MMAN_H) -check_include_file("sys/resource.h" HAVE_SYS_RESOURCE_H) -check_include_file("sys/time.h" HAVE_SYS_TIME_H) -check_include_file("sys/uio.h" HAVE_SYS_UIO_H) -check_include_file("unistd.h" HAVE_UNISTD_H) -check_include_file("windows.h" HAVE_WINDOWS_H) - -include(CheckLibraryExists) -check_library_exists(z zlibVersion "" HAVE_LIBZ) -check_library_exists(lzo2 lzo1x_1_15_compress "" HAVE_LIBLZO2) - -include(CheckCXXSourceCompiles) -check_cxx_source_compiles( - "int main(void) { return __builtin_expect(0, 1); }" HAVE_BUILTIN_EXPECT) - -check_cxx_source_compiles( - "int main(void) { return __builtin_ctzll(0); }" HAVE_BUILTIN_CTZ) - -include(CheckSymbolExists) -check_symbol_exists("mmap" "sys/mman.h" HAVE_FUNC_MMAP) -check_symbol_exists("sysconf" "unistd.h" HAVE_FUNC_SYSCONF) - -find_package(GTest QUIET) -if(GTEST_FOUND) - set(HAVE_GTEST 1) -endif(GTEST_FOUND) - -find_package(Gflags QUIET) -if(GFLAGS_FOUND) - set(HAVE_GFLAGS 1) -endif(GFLAGS_FOUND) - -configure_file( - "${PROJECT_SOURCE_DIR}/cmake/config.h.in" - "${PROJECT_BINARY_DIR}/config.h" -) - -# We don't want to define HAVE_ macros in public headers. Instead, we use -# CMake's variable substitution with 0/1 variables, which will be seen by the -# preprocessor as constants. -set(HAVE_STDINT_H_01 ${HAVE_STDINT_H}) -set(HAVE_STDDEF_H_01 ${HAVE_STDDEF_H}) -set(HAVE_SYS_UIO_H_01 ${HAVE_SYS_UIO_H}) -if(NOT HAVE_STDINT_H_01) - set(HAVE_STDINT_H_01 0) -endif(NOT HAVE_STDINT_H_01) -if(NOT HAVE_STDDEF_H_01) - set(HAVE_STDDEF_H_01 0) -endif(NOT HAVE_STDDEF_H_01) -if(NOT HAVE_SYS_UIO_H_01) - set(HAVE_SYS_UIO_H_01 0) -endif(NOT HAVE_SYS_UIO_H_01) - -configure_file( - "${PROJECT_SOURCE_DIR}/snappy-stubs-public.h.in" - "${PROJECT_BINARY_DIR}/snappy-stubs-public.h") - -add_library(snappy "") -target_sources(snappy - PRIVATE - "${PROJECT_SOURCE_DIR}/snappy-internal.h" - "${PROJECT_SOURCE_DIR}/snappy-stubs-internal.h" - "${PROJECT_SOURCE_DIR}/snappy-c.cc" - "${PROJECT_SOURCE_DIR}/snappy-sinksource.cc" - "${PROJECT_SOURCE_DIR}/snappy-stubs-internal.cc" - "${PROJECT_SOURCE_DIR}/snappy.cc" - "${PROJECT_BINARY_DIR}/config.h" - - # Only CMake 3.3+ supports PUBLIC sources in targets exported by "install". - $<$:PUBLIC> - $ - $ - $ - $ - $ - $ - $ - $ -) -target_include_directories(snappy - PUBLIC - $ - $ - $ -) -set_target_properties(snappy - PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR}) - -target_compile_definitions(snappy PRIVATE -DHAVE_CONFIG_H) -if(BUILD_SHARED_LIBS) - set_target_properties(snappy PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS ON) -endif(BUILD_SHARED_LIBS) - -if(SNAPPY_BUILD_TESTS) - enable_testing() - - add_executable(snappy_unittest "") - target_sources(snappy_unittest - PRIVATE - "${PROJECT_SOURCE_DIR}/snappy_unittest.cc" - "${PROJECT_SOURCE_DIR}/snappy-test.cc" - ) - target_compile_definitions(snappy_unittest PRIVATE -DHAVE_CONFIG_H) - target_link_libraries(snappy_unittest snappy ${GFLAGS_LIBRARIES}) - - if(HAVE_LIBZ) - target_link_libraries(snappy_unittest z) - endif(HAVE_LIBZ) - if(HAVE_LIBLZO2) - target_link_libraries(snappy_unittest lzo2) - endif(HAVE_LIBLZO2) - - target_include_directories(snappy_unittest - BEFORE PRIVATE - "${PROJECT_SOURCE_DIR}" - "${GTEST_INCLUDE_DIRS}" - "${GFLAGS_INCLUDE_DIRS}" - ) - - add_test( - NAME snappy_unittest - WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}" - COMMAND "${PROJECT_BINARY_DIR}/snappy_unittest") -endif(SNAPPY_BUILD_TESTS) - -include(GNUInstallDirs) -install(TARGETS snappy - EXPORT SnappyTargets - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} -) -install( - FILES - "${PROJECT_SOURCE_DIR}/snappy-c.h" - "${PROJECT_SOURCE_DIR}/snappy-sinksource.h" - "${PROJECT_SOURCE_DIR}/snappy.h" - "${PROJECT_BINARY_DIR}/snappy-stubs-public.h" - DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} -) - -include(CMakePackageConfigHelpers) -write_basic_package_version_file( - "${PROJECT_BINARY_DIR}/SnappyConfigVersion.cmake" - COMPATIBILITY SameMajorVersion -) -install( - EXPORT SnappyTargets - NAMESPACE Snappy:: - DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/Snappy" -) -install( - FILES - "${PROJECT_SOURCE_DIR}/cmake/SnappyConfig.cmake" - "${PROJECT_BINARY_DIR}/SnappyConfigVersion.cmake" - DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/Snappy" -) diff --git a/src/snappy/snappy/CONTRIBUTING.md b/src/snappy/snappy/CONTRIBUTING.md deleted file mode 100644 index c7b84516c2..0000000000 --- a/src/snappy/snappy/CONTRIBUTING.md +++ /dev/null @@ -1,26 +0,0 @@ -# How to Contribute - -We'd love to accept your patches and contributions to this project. There are -just a few small guidelines you need to follow. - -## Contributor License Agreement - -Contributions to this project must be accompanied by a Contributor License -Agreement. You (or your employer) retain the copyright to your contribution, -this simply gives us permission to use and redistribute your contributions as -part of the project. Head over to to see -your current agreements on file or to sign a new one. - -You generally only need to submit a CLA once, so if you've already submitted one -(even if it was for a different project), you probably don't need to do it -again. - -## Code reviews - -All submissions, including submissions by project members, require review. We -use GitHub pull requests for this purpose. Consult -[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more -information on using pull requests. - -Please make sure that all the automated checks (CLA, AppVeyor, Travis) pass for -your pull requests. Pull requests whose checks fail may be ignored. diff --git a/src/snappy/snappy/COPYING b/src/snappy/snappy/COPYING deleted file mode 100644 index bd0e5971db..0000000000 --- a/src/snappy/snappy/COPYING +++ /dev/null @@ -1,54 +0,0 @@ -Copyright 2011, Google Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -=== - -Some of the benchmark data in testdata/ is licensed differently: - - - fireworks.jpeg is Copyright 2013 Steinar H. Gunderson, and - is licensed under the Creative Commons Attribution 3.0 license - (CC-BY-3.0). See https://creativecommons.org/licenses/by/3.0/ - for more information. - - - kppkn.gtb is taken from the Gaviota chess tablebase set, and - is licensed under the MIT License. See - https://sites.google.com/site/gaviotachessengine/Home/endgame-tablebases-1 - for more information. - - - paper-100k.pdf is an excerpt (bytes 92160 to 194560) from the paper - “Combinatorial Modeling of Chromatin Features Quantitatively Predicts DNA - Replication Timing in _Drosophila_†by Federico Comoglio and Renato Paro, - which is licensed under the CC-BY license. See - http://www.ploscompbiol.org/static/license for more ifnormation. - - - alice29.txt, asyoulik.txt, plrabn12.txt and lcet10.txt are from Project - Gutenberg. The first three have expired copyrights and are in the public - domain; the latter does not have expired copyright, but is still in the - public domain according to the license information - (http://www.gutenberg.org/ebooks/53). diff --git a/src/snappy/snappy/NEWS b/src/snappy/snappy/NEWS deleted file mode 100644 index db70b44885..0000000000 --- a/src/snappy/snappy/NEWS +++ /dev/null @@ -1,180 +0,0 @@ -Snappy v1.1.7, August 24th 2017: - - * Improved CMake build support for 64-bit Linux distributions. - - * MSVC builds now use MSVC-specific intrinsics that map to clzll. - - * ARM64 (AArch64) builds use the code paths optimized for 64-bit processors. - -Snappy v1.1.6, July 12th 2017: - -This is a re-release of v1.1.5 with proper SONAME / SOVERSION values. - -Snappy v1.1.5, June 28th 2017: - -This release has broken SONAME / SOVERSION values. Users of snappy as a shared -library should avoid 1.1.5 and use 1.1.6 instead. SONAME / SOVERSION errors will -manifest as the dynamic library loader complaining that it cannot find snappy's -shared library file (libsnappy.so / libsnappy.dylib), or that the library it -found does not have the required version. 1.1.6 has the same code as 1.1.5, but -carries build configuration fixes for the issues above. - - * Add CMake build support. The autoconf build support is now deprecated, and - will be removed in the next release. - - * Add AppVeyor configuration, for Windows CI coverage. - - * Small performance improvement on little-endian PowerPC. - - * Small performance improvement on LLVM with position-independent executables. - - * Fix a few issues with various build environments. - -Snappy v1.1.4, January 25th 2017: - - * Fix a 1% performance regression when snappy is used in PIE executables. - - * Improve compression performance by 5%. - - * Improve decompression performance by 20%. - -Snappy v1.1.3, July 6th 2015: - -This is the first release to be done from GitHub, which means that -some minor things like the ChangeLog format has changed (git log -format instead of svn log). - - * Add support for Uncompress() from a Source to a Sink. - - * Various minor changes to improve MSVC support; in particular, - the unit tests now compile and run under MSVC. - - -Snappy v1.1.2, February 28th 2014: - -This is a maintenance release with no changes to the actual library -source code. - - * Stop distributing benchmark data files that have unclear - or unsuitable licensing. - - * Add support for padding chunks in the framing format. - - -Snappy v1.1.1, October 15th 2013: - - * Add support for uncompressing to iovecs (scatter I/O). - The bulk of this patch was contributed by Mohit Aron. - - * Speed up decompression by ~2%; much more so (~13-20%) on - a few benchmarks on given compilers and CPUs. - - * Fix a few issues with MSVC compilation. - - * Support truncated test data in the benchmark. - - -Snappy v1.1.0, January 18th 2013: - - * Snappy now uses 64 kB block size instead of 32 kB. On average, - this means it compresses about 3% denser (more so for some - inputs), at the same or better speeds. - - * libsnappy no longer depends on iostream. - - * Some small performance improvements in compression on x86 - (0.5–1%). - - * Various portability fixes for ARM-based platforms, for MSVC, - and for GNU/Hurd. - - -Snappy v1.0.5, February 24th 2012: - - * More speed improvements. Exactly how big will depend on - the architecture: - - - 3–10% faster decompression for the base case (x86-64). - - - ARMv7 and higher can now use unaligned accesses, - and will see about 30% faster decompression and - 20–40% faster compression. - - - 32-bit platforms (ARM and 32-bit x86) will see 2–5% - faster compression. - - These are all cumulative (e.g., ARM gets all three speedups). - - * Fixed an issue where the unit test would crash on system - with less than 256 MB address space available, - e.g. some embedded platforms. - - * Added a framing format description, for use over e.g. HTTP, - or for a command-line compressor. We do not have any - implementations of this at the current point, but there seems - to be enough of a general interest in the topic. - Also make the format description slightly clearer. - - * Remove some compile-time warnings in -Wall - (mostly signed/unsigned comparisons), for easier embedding - into projects that use -Wall -Werror. - - -Snappy v1.0.4, September 15th 2011: - - * Speeded up the decompressor somewhat; typically about 2–8% - for Core i7, in 64-bit mode (comparable for Opteron). - Somewhat more for some tests, almost no gain for others. - - * Make Snappy compile on certain platforms it didn't before - (Solaris with SunPro C++, HP-UX, AIX). - - * Correct some minor errors in the format description. - - -Snappy v1.0.3, June 2nd 2011: - - * Speeded up the decompressor somewhat; about 3-6% for Core 2, - 6-13% for Core i7, and 5-12% for Opteron (all in 64-bit mode). - - * Added compressed format documentation. This text is new, - but an earlier version from Zeev Tarantov was used as reference. - - * Only link snappy_unittest against -lz and other autodetected - libraries, not libsnappy.so (which doesn't need any such dependency). - - * Fixed some display issues in the microbenchmarks, one of which would - frequently make the test crash on GNU/Hurd. - - -Snappy v1.0.2, April 29th 2011: - - * Relicense to a BSD-type license. - - * Added C bindings, contributed by Martin Gieseking. - - * More Win32 fixes, in particular for MSVC. - - * Replace geo.protodata with a newer version. - - * Fix timing inaccuracies in the unit test when comparing Snappy - to other algorithms. - - -Snappy v1.0.1, March 25th 2011: - -This is a maintenance release, mostly containing minor fixes. -There is no new functionality. The most important fixes include: - - * The COPYING file and all licensing headers now correctly state that - Snappy is licensed under the Apache 2.0 license. - - * snappy_unittest should now compile natively under Windows, - as well as on embedded systems with no mmap(). - - * Various autotools nits have been fixed. - - -Snappy v1.0, March 17th 2011: - - * Initial version. diff --git a/src/snappy/snappy/README.md b/src/snappy/snappy/README.md deleted file mode 100644 index b9db833dd5..0000000000 --- a/src/snappy/snappy/README.md +++ /dev/null @@ -1,149 +0,0 @@ -Snappy, a fast compressor/decompressor. - - -Introduction -============ - -Snappy is a compression/decompression library. It does not aim for maximum -compression, or compatibility with any other compression library; instead, -it aims for very high speeds and reasonable compression. For instance, -compared to the fastest mode of zlib, Snappy is an order of magnitude faster -for most inputs, but the resulting compressed files are anywhere from 20% to -100% bigger. (For more information, see "Performance", below.) - -Snappy has the following properties: - - * Fast: Compression speeds at 250 MB/sec and beyond, with no assembler code. - See "Performance" below. - * Stable: Over the last few years, Snappy has compressed and decompressed - petabytes of data in Google's production environment. The Snappy bitstream - format is stable and will not change between versions. - * Robust: The Snappy decompressor is designed not to crash in the face of - corrupted or malicious input. - * Free and open source software: Snappy is licensed under a BSD-type license. - For more information, see the included COPYING file. - -Snappy has previously been called "Zippy" in some Google presentations -and the like. - - -Performance -=========== - -Snappy is intended to be fast. On a single core of a Core i7 processor -in 64-bit mode, it compresses at about 250 MB/sec or more and decompresses at -about 500 MB/sec or more. (These numbers are for the slowest inputs in our -benchmark suite; others are much faster.) In our tests, Snappy usually -is faster than algorithms in the same class (e.g. LZO, LZF, QuickLZ, -etc.) while achieving comparable compression ratios. - -Typical compression ratios (based on the benchmark suite) are about 1.5-1.7x -for plain text, about 2-4x for HTML, and of course 1.0x for JPEGs, PNGs and -other already-compressed data. Similar numbers for zlib in its fastest mode -are 2.6-2.8x, 3-7x and 1.0x, respectively. More sophisticated algorithms are -capable of achieving yet higher compression rates, although usually at the -expense of speed. Of course, compression ratio will vary significantly with -the input. - -Although Snappy should be fairly portable, it is primarily optimized -for 64-bit x86-compatible processors, and may run slower in other environments. -In particular: - - - Snappy uses 64-bit operations in several places to process more data at - once than would otherwise be possible. - - Snappy assumes unaligned 32- and 64-bit loads and stores are cheap. - On some platforms, these must be emulated with single-byte loads - and stores, which is much slower. - - Snappy assumes little-endian throughout, and needs to byte-swap data in - several places if running on a big-endian platform. - -Experience has shown that even heavily tuned code can be improved. -Performance optimizations, whether for 64-bit x86 or other platforms, -are of course most welcome; see "Contact", below. - - -Building -======== - -CMake is supported and autotools will soon be deprecated. -You need CMake 3.4 or above to build: - - mkdir build - cd build && cmake ../ && make - - -Usage -===== - -Note that Snappy, both the implementation and the main interface, -is written in C++. However, several third-party bindings to other languages -are available; see the home page at http://google.github.io/snappy/ -for more information. Also, if you want to use Snappy from C code, you can -use the included C bindings in snappy-c.h. - -To use Snappy from your own C++ program, include the file "snappy.h" from -your calling file, and link against the compiled library. - -There are many ways to call Snappy, but the simplest possible is - - snappy::Compress(input.data(), input.size(), &output); - -and similarly - - snappy::Uncompress(input.data(), input.size(), &output); - -where "input" and "output" are both instances of std::string. - -There are other interfaces that are more flexible in various ways, including -support for custom (non-array) input sources. See the header file for more -information. - - -Tests and benchmarks -==================== - -When you compile Snappy, snappy_unittest is compiled in addition to the -library itself. You do not need it to use the compressor from your own library, -but it contains several useful components for Snappy development. - -First of all, it contains unit tests, verifying correctness on your machine in -various scenarios. If you want to change or optimize Snappy, please run the -tests to verify you have not broken anything. Note that if you have the -Google Test library installed, unit test behavior (especially failures) will be -significantly more user-friendly. You can find Google Test at - - http://github.com/google/googletest - -You probably also want the gflags library for handling of command-line flags; -you can find it at - - http://gflags.github.io/gflags/ - -In addition to the unit tests, snappy contains microbenchmarks used to -tune compression and decompression performance. These are automatically run -before the unit tests, but you can disable them using the flag ---run_microbenchmarks=false if you have gflags installed (otherwise you will -need to edit the source). - -Finally, snappy can benchmark Snappy against a few other compression libraries -(zlib, LZO, LZF, and QuickLZ), if they were detected at configure time. -To benchmark using a given file, give the compression algorithm you want to test -Snappy against (e.g. --zlib) and then a list of one or more file names on the -command line. The testdata/ directory contains the files used by the -microbenchmark, which should provide a reasonably balanced starting point for -benchmarking. (Note that baddata[1-3].snappy are not intended as benchmarks; they -are used to verify correctness in the presence of corrupted data in the unit -test.) - - -Contact -======= - -Snappy is distributed through GitHub. For the latest version, a bug tracker, -and other information, see - - http://google.github.io/snappy/ - -or the repository at - - https://github.com/google/snappy diff --git a/src/snappy/snappy/cmake/SnappyConfig.cmake b/src/snappy/snappy/cmake/SnappyConfig.cmake deleted file mode 100644 index dc308ae265..0000000000 --- a/src/snappy/snappy/cmake/SnappyConfig.cmake +++ /dev/null @@ -1 +0,0 @@ -include("${CMAKE_CURRENT_LIST_DIR}/SnappyTargets.cmake") \ No newline at end of file diff --git a/src/snappy/snappy/cmake/config.h.in b/src/snappy/snappy/cmake/config.h.in deleted file mode 100644 index 97cd8185f2..0000000000 --- a/src/snappy/snappy/cmake/config.h.in +++ /dev/null @@ -1,62 +0,0 @@ -#ifndef THIRD_PARTY_SNAPPY_OPENSOURCE_CMAKE_CONFIG_H_ -#define THIRD_PARTY_SNAPPY_OPENSOURCE_CMAKE_CONFIG_H_ - -/* Define to 1 if the compiler supports __builtin_ctz and friends. */ -#cmakedefine HAVE_BUILTIN_CTZ 1 - -/* Define to 1 if the compiler supports __builtin_expect. */ -#cmakedefine HAVE_BUILTIN_EXPECT 1 - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_BYTESWAP_H 1 - -/* Define to 1 if you have a definition for mmap() in . */ -#cmakedefine HAVE_FUNC_MMAP 1 - -/* Define to 1 if you have a definition for sysconf() in . */ -#cmakedefine HAVE_FUNC_SYSCONF 1 - -/* Define to 1 to use the gflags package for command-line parsing. */ -#cmakedefine HAVE_GFLAGS 1 - -/* Define to 1 if you have Google Test. */ -#cmakedefine HAVE_GTEST 1 - -/* Define to 1 if you have the `lzo2' library (-llzo2). */ -#cmakedefine HAVE_LIBLZO2 1 - -/* Define to 1 if you have the `z' library (-lz). */ -#cmakedefine HAVE_LIBZ 1 - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_STDDEF_H 1 - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_STDINT_H 1 - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_SYS_ENDIAN_H 1 - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_SYS_MMAN_H 1 - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_SYS_RESOURCE_H 1 - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_SYS_TIME_H 1 - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_SYS_UIO_H 1 - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_UNISTD_H 1 - -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_WINDOWS_H 1 - -/* Define to 1 if your processor stores words with the most significant byte - first (like Motorola and SPARC, unlike Intel and VAX). */ -#cmakedefine SNAPPY_IS_BIG_ENDIAN 1 - -#endif // THIRD_PARTY_SNAPPY_OPENSOURCE_CMAKE_CONFIG_H_ diff --git a/src/snappy/snappy/format_description.txt b/src/snappy/snappy/format_description.txt deleted file mode 100644 index 20db66c1f2..0000000000 --- a/src/snappy/snappy/format_description.txt +++ /dev/null @@ -1,110 +0,0 @@ -Snappy compressed format description -Last revised: 2011-10-05 - - -This is not a formal specification, but should suffice to explain most -relevant parts of how the Snappy format works. It is originally based on -text by Zeev Tarantov. - -Snappy is a LZ77-type compressor with a fixed, byte-oriented encoding. -There is no entropy encoder backend nor framing layer -- the latter is -assumed to be handled by other parts of the system. - -This document only describes the format, not how the Snappy compressor nor -decompressor actually works. The correctness of the decompressor should not -depend on implementation details of the compressor, and vice versa. - - -1. Preamble - -The stream starts with the uncompressed length (up to a maximum of 2^32 - 1), -stored as a little-endian varint. Varints consist of a series of bytes, -where the lower 7 bits are data and the upper bit is set iff there are -more bytes to be read. In other words, an uncompressed length of 64 would -be stored as 0x40, and an uncompressed length of 2097150 (0x1FFFFE) -would be stored as 0xFE 0xFF 0x7F. - - -2. The compressed stream itself - -There are two types of elements in a Snappy stream: Literals and -copies (backreferences). There is no restriction on the order of elements, -except that the stream naturally cannot start with a copy. (Having -two literals in a row is never optimal from a compression point of -view, but nevertheless fully permitted.) Each element starts with a tag byte, -and the lower two bits of this tag byte signal what type of element will -follow: - - 00: Literal - 01: Copy with 1-byte offset - 10: Copy with 2-byte offset - 11: Copy with 4-byte offset - -The interpretation of the upper six bits are element-dependent. - - -2.1. Literals (00) - -Literals are uncompressed data stored directly in the byte stream. -The literal length is stored differently depending on the length -of the literal: - - - For literals up to and including 60 bytes in length, the upper - six bits of the tag byte contain (len-1). The literal follows - immediately thereafter in the bytestream. - - For longer literals, the (len-1) value is stored after the tag byte, - little-endian. The upper six bits of the tag byte describe how - many bytes are used for the length; 60, 61, 62 or 63 for - 1-4 bytes, respectively. The literal itself follows after the - length. - - -2.2. Copies - -Copies are references back into previous decompressed data, telling -the decompressor to reuse data it has previously decoded. -They encode two values: The _offset_, saying how many bytes back -from the current position to read, and the _length_, how many bytes -to copy. Offsets of zero can be encoded, but are not legal; -similarly, it is possible to encode backreferences that would -go past the end of the block (offset > current decompressed position), -which is also nonsensical and thus not allowed. - -As in most LZ77-based compressors, the length can be larger than the offset, -yielding a form of run-length encoding (RLE). For instance, -"xababab" could be encoded as - - - -Note that since the current Snappy compressor works in 32 kB -blocks and does not do matching across blocks, it will never produce -a bitstream with offsets larger than about 32768. However, the -decompressor should not rely on this, as it may change in the future. - -There are several different kinds of copy elements, depending on -the amount of bytes to be copied (length), and how far back the -data to be copied is (offset). - - -2.2.1. Copy with 1-byte offset (01) - -These elements can encode lengths between [4..11] bytes and offsets -between [0..2047] bytes. (len-4) occupies three bits and is stored -in bits [2..4] of the tag byte. The offset occupies 11 bits, of which the -upper three are stored in the upper three bits ([5..7]) of the tag byte, -and the lower eight are stored in a byte following the tag byte. - - -2.2.2. Copy with 2-byte offset (10) - -These elements can encode lengths between [1..64] and offsets from -[0..65535]. (len-1) occupies six bits and is stored in the upper -six bits ([2..7]) of the tag byte. The offset is stored as a -little-endian 16-bit integer in the two bytes following the tag byte. - - -2.2.3. Copy with 4-byte offset (11) - -These are like the copies with 2-byte offsets (see previous subsection), -except that the offset is stored as a 32-bit integer instead of a -16-bit integer (and thus will occupy four bytes). diff --git a/src/snappy/snappy/framing_format.txt b/src/snappy/snappy/framing_format.txt deleted file mode 100644 index 9764e83de6..0000000000 --- a/src/snappy/snappy/framing_format.txt +++ /dev/null @@ -1,135 +0,0 @@ -Snappy framing format description -Last revised: 2013-10-25 - -This format decribes a framing format for Snappy, allowing compressing to -files or streams that can then more easily be decompressed without having -to hold the entire stream in memory. It also provides data checksums to -help verify integrity. It does not provide metadata checksums, so it does -not protect against e.g. all forms of truncations. - -Implementation of the framing format is optional for Snappy compressors and -decompressor; it is not part of the Snappy core specification. - - -1. General structure - -The file consists solely of chunks, lying back-to-back with no padding -in between. Each chunk consists first a single byte of chunk identifier, -then a three-byte little-endian length of the chunk in bytes (from 0 to -16777215, inclusive), and then the data if any. The four bytes of chunk -header is not counted in the data length. - -The different chunk types are listed below. The first chunk must always -be the stream identifier chunk (see section 4.1, below). The stream -ends when the file ends -- there is no explicit end-of-file marker. - - -2. File type identification - -The following identifiers for this format are recommended where appropriate. -However, note that none have been registered officially, so this is only to -be taken as a guideline. We use "Snappy framed" to distinguish between this -format and raw Snappy data. - - File extension: .sz - MIME type: application/x-snappy-framed - HTTP Content-Encoding: x-snappy-framed - - -3. Checksum format - -Some chunks have data protected by a checksum (the ones that do will say so -explicitly). The checksums are always masked CRC-32Cs. - -A description of CRC-32C can be found in RFC 3720, section 12.1, with -examples in section B.4. - -Checksums are not stored directly, but masked, as checksumming data and -then its own checksum can be problematic. The masking is the same as used -in Apache Hadoop: Rotate the checksum by 15 bits, then add the constant -0xa282ead8 (using wraparound as normal for unsigned integers). This is -equivalent to the following C code: - - uint32_t mask_checksum(uint32_t x) { - return ((x >> 15) | (x << 17)) + 0xa282ead8; - } - -Note that the masking is reversible. - -The checksum is always stored as a four bytes long integer, in little-endian. - - -4. Chunk types - -The currently supported chunk types are described below. The list may -be extended in the future. - - -4.1. Stream identifier (chunk type 0xff) - -The stream identifier is always the first element in the stream. -It is exactly six bytes long and contains "sNaPpY" in ASCII. This means that -a valid Snappy framed stream always starts with the bytes - - 0xff 0x06 0x00 0x00 0x73 0x4e 0x61 0x50 0x70 0x59 - -The stream identifier chunk can come multiple times in the stream besides -the first; if such a chunk shows up, it should simply be ignored, assuming -it has the right length and contents. This allows for easy concatenation of -compressed files without the need for re-framing. - - -4.2. Compressed data (chunk type 0x00) - -Compressed data chunks contain a normal Snappy compressed bitstream; -see the compressed format specification. The compressed data is preceded by -the CRC-32C (see section 3) of the _uncompressed_ data. - -Note that the data portion of the chunk, i.e., the compressed contents, -can be at most 16777211 bytes (2^24 - 1, minus the checksum). -However, we place an additional restriction that the uncompressed data -in a chunk must be no longer than 65536 bytes. This allows consumers to -easily use small fixed-size buffers. - - -4.3. Uncompressed data (chunk type 0x01) - -Uncompressed data chunks allow a compressor to send uncompressed, -raw data; this is useful if, for instance, uncompressible or -near-incompressible data is detected, and faster decompression is desired. - -As in the compressed chunks, the data is preceded by its own masked -CRC-32C (see section 3). - -An uncompressed data chunk, like compressed data chunks, should contain -no more than 65536 data bytes, so the maximum legal chunk length with the -checksum is 65540. - - -4.4. Padding (chunk type 0xfe) - -Padding chunks allow a compressor to increase the size of the data stream -so that it complies with external demands, e.g. that the total number of -bytes is a multiple of some value. - -All bytes of the padding chunk, except the chunk byte itself and the length, -should be zero, but decompressors must not try to interpret or verify the -padding data in any way. - - -4.5. Reserved unskippable chunks (chunk types 0x02-0x7f) - -These are reserved for future expansion. A decoder that sees such a chunk -should immediately return an error, as it must assume it cannot decode the -stream correctly. - -Future versions of this specification may define meanings for these chunks. - - -4.6. Reserved skippable chunks (chunk types 0x80-0xfd) - -These are also reserved for future expansion, but unlike the chunks -described in 4.5, a decoder seeing these must skip them and continue -decoding. - -Future versions of this specification may define meanings for these chunks. diff --git a/src/snappy/snappy/snappy-c.cc b/src/snappy/snappy/snappy-c.cc deleted file mode 100644 index 473a0b0978..0000000000 --- a/src/snappy/snappy/snappy-c.cc +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2011 Martin Gieseking . -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#include "snappy.h" -#include "snappy-c.h" - -extern "C" { - -snappy_status snappy_compress(const char* input, - size_t input_length, - char* compressed, - size_t *compressed_length) { - if (*compressed_length < snappy_max_compressed_length(input_length)) { - return SNAPPY_BUFFER_TOO_SMALL; - } - snappy::RawCompress(input, input_length, compressed, compressed_length); - return SNAPPY_OK; -} - -snappy_status snappy_uncompress(const char* compressed, - size_t compressed_length, - char* uncompressed, - size_t* uncompressed_length) { - size_t real_uncompressed_length; - if (!snappy::GetUncompressedLength(compressed, - compressed_length, - &real_uncompressed_length)) { - return SNAPPY_INVALID_INPUT; - } - if (*uncompressed_length < real_uncompressed_length) { - return SNAPPY_BUFFER_TOO_SMALL; - } - if (!snappy::RawUncompress(compressed, compressed_length, uncompressed)) { - return SNAPPY_INVALID_INPUT; - } - *uncompressed_length = real_uncompressed_length; - return SNAPPY_OK; -} - -size_t snappy_max_compressed_length(size_t source_length) { - return snappy::MaxCompressedLength(source_length); -} - -snappy_status snappy_uncompressed_length(const char *compressed, - size_t compressed_length, - size_t *result) { - if (snappy::GetUncompressedLength(compressed, - compressed_length, - result)) { - return SNAPPY_OK; - } else { - return SNAPPY_INVALID_INPUT; - } -} - -snappy_status snappy_validate_compressed_buffer(const char *compressed, - size_t compressed_length) { - if (snappy::IsValidCompressedBuffer(compressed, compressed_length)) { - return SNAPPY_OK; - } else { - return SNAPPY_INVALID_INPUT; - } -} - -} // extern "C" diff --git a/src/snappy/snappy/snappy-c.h b/src/snappy/snappy/snappy-c.h deleted file mode 100644 index 32aa0c6b8b..0000000000 --- a/src/snappy/snappy/snappy-c.h +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright 2011 Martin Gieseking . - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Plain C interface (a wrapper around the C++ implementation). - */ - -#ifndef THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_C_H_ -#define THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_C_H_ - -#ifdef __cplusplus -extern "C" { -#endif - -#include - -/* - * Return values; see the documentation for each function to know - * what each can return. - */ -typedef enum { - SNAPPY_OK = 0, - SNAPPY_INVALID_INPUT = 1, - SNAPPY_BUFFER_TOO_SMALL = 2 -} snappy_status; - -/* - * Takes the data stored in "input[0..input_length-1]" and stores - * it in the array pointed to by "compressed". - * - * signals the space available in "compressed". - * If it is not at least equal to "snappy_max_compressed_length(input_length)", - * SNAPPY_BUFFER_TOO_SMALL is returned. After successful compression, - * contains the true length of the compressed output, - * and SNAPPY_OK is returned. - * - * Example: - * size_t output_length = snappy_max_compressed_length(input_length); - * char* output = (char*)malloc(output_length); - * if (snappy_compress(input, input_length, output, &output_length) - * == SNAPPY_OK) { - * ... Process(output, output_length) ... - * } - * free(output); - */ -snappy_status snappy_compress(const char* input, - size_t input_length, - char* compressed, - size_t* compressed_length); - -/* - * Given data in "compressed[0..compressed_length-1]" generated by - * calling the snappy_compress routine, this routine stores - * the uncompressed data to - * uncompressed[0..uncompressed_length-1]. - * Returns failure (a value not equal to SNAPPY_OK) if the message - * is corrupted and could not be decrypted. - * - * signals the space available in "uncompressed". - * If it is not at least equal to the value returned by - * snappy_uncompressed_length for this stream, SNAPPY_BUFFER_TOO_SMALL - * is returned. After successful decompression, - * contains the true length of the decompressed output. - * - * Example: - * size_t output_length; - * if (snappy_uncompressed_length(input, input_length, &output_length) - * != SNAPPY_OK) { - * ... fail ... - * } - * char* output = (char*)malloc(output_length); - * if (snappy_uncompress(input, input_length, output, &output_length) - * == SNAPPY_OK) { - * ... Process(output, output_length) ... - * } - * free(output); - */ -snappy_status snappy_uncompress(const char* compressed, - size_t compressed_length, - char* uncompressed, - size_t* uncompressed_length); - -/* - * Returns the maximal size of the compressed representation of - * input data that is "source_length" bytes in length. - */ -size_t snappy_max_compressed_length(size_t source_length); - -/* - * REQUIRES: "compressed[]" was produced by snappy_compress() - * Returns SNAPPY_OK and stores the length of the uncompressed data in - * *result normally. Returns SNAPPY_INVALID_INPUT on parsing error. - * This operation takes O(1) time. - */ -snappy_status snappy_uncompressed_length(const char* compressed, - size_t compressed_length, - size_t* result); - -/* - * Check if the contents of "compressed[]" can be uncompressed successfully. - * Does not return the uncompressed data; if so, returns SNAPPY_OK, - * or if not, returns SNAPPY_INVALID_INPUT. - * Takes time proportional to compressed_length, but is usually at least a - * factor of four faster than actual decompression. - */ -snappy_status snappy_validate_compressed_buffer(const char* compressed, - size_t compressed_length); - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif /* THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_C_H_ */ diff --git a/src/snappy/snappy/snappy-internal.h b/src/snappy/snappy/snappy-internal.h deleted file mode 100644 index 4b53d596f4..0000000000 --- a/src/snappy/snappy/snappy-internal.h +++ /dev/null @@ -1,224 +0,0 @@ -// Copyright 2008 Google Inc. All Rights Reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Internals shared between the Snappy implementation and its unittest. - -#ifndef THIRD_PARTY_SNAPPY_SNAPPY_INTERNAL_H_ -#define THIRD_PARTY_SNAPPY_SNAPPY_INTERNAL_H_ - -#include "snappy-stubs-internal.h" - -namespace snappy { -namespace internal { - -class WorkingMemory { - public: - WorkingMemory() : large_table_(NULL) { } - ~WorkingMemory() { delete[] large_table_; } - - // Allocates and clears a hash table using memory in "*this", - // stores the number of buckets in "*table_size" and returns a pointer to - // the base of the hash table. - uint16* GetHashTable(size_t input_size, int* table_size); - - private: - uint16 small_table_[1<<10]; // 2KB - uint16* large_table_; // Allocated only when needed - - // No copying - WorkingMemory(const WorkingMemory&); - void operator=(const WorkingMemory&); -}; - -// Flat array compression that does not emit the "uncompressed length" -// prefix. Compresses "input" string to the "*op" buffer. -// -// REQUIRES: "input_length <= kBlockSize" -// REQUIRES: "op" points to an array of memory that is at least -// "MaxCompressedLength(input_length)" in size. -// REQUIRES: All elements in "table[0..table_size-1]" are initialized to zero. -// REQUIRES: "table_size" is a power of two -// -// Returns an "end" pointer into "op" buffer. -// "end - op" is the compressed size of "input". -char* CompressFragment(const char* input, - size_t input_length, - char* op, - uint16* table, - const int table_size); - -// Find the largest n such that -// -// s1[0,n-1] == s2[0,n-1] -// and n <= (s2_limit - s2). -// -// Return make_pair(n, n < 8). -// Does not read *s2_limit or beyond. -// Does not read *(s1 + (s2_limit - s2)) or beyond. -// Requires that s2_limit >= s2. -// -// Separate implementation for 64-bit, little-endian cpus. -#if !defined(SNAPPY_IS_BIG_ENDIAN) && \ - (defined(ARCH_K8) || defined(ARCH_PPC) || defined(ARCH_ARM)) -static inline std::pair FindMatchLength(const char* s1, - const char* s2, - const char* s2_limit) { - assert(s2_limit >= s2); - size_t matched = 0; - - // This block isn't necessary for correctness; we could just start looping - // immediately. As an optimization though, it is useful. It creates some not - // uncommon code paths that determine, without extra effort, whether the match - // length is less than 8. In short, we are hoping to avoid a conditional - // branch, and perhaps get better code layout from the C++ compiler. - if (SNAPPY_PREDICT_TRUE(s2 <= s2_limit - 8)) { - uint64 a1 = UNALIGNED_LOAD64(s1); - uint64 a2 = UNALIGNED_LOAD64(s2); - if (a1 != a2) { - return std::pair(Bits::FindLSBSetNonZero64(a1 ^ a2) >> 3, - true); - } else { - matched = 8; - s2 += 8; - } - } - - // Find out how long the match is. We loop over the data 64 bits at a - // time until we find a 64-bit block that doesn't match; then we find - // the first non-matching bit and use that to calculate the total - // length of the match. - while (SNAPPY_PREDICT_TRUE(s2 <= s2_limit - 8)) { - if (UNALIGNED_LOAD64(s2) == UNALIGNED_LOAD64(s1 + matched)) { - s2 += 8; - matched += 8; - } else { - uint64 x = UNALIGNED_LOAD64(s2) ^ UNALIGNED_LOAD64(s1 + matched); - int matching_bits = Bits::FindLSBSetNonZero64(x); - matched += matching_bits >> 3; - assert(matched >= 8); - return std::pair(matched, false); - } - } - while (SNAPPY_PREDICT_TRUE(s2 < s2_limit)) { - if (s1[matched] == *s2) { - ++s2; - ++matched; - } else { - return std::pair(matched, matched < 8); - } - } - return std::pair(matched, matched < 8); -} -#else -static inline std::pair FindMatchLength(const char* s1, - const char* s2, - const char* s2_limit) { - // Implementation based on the x86-64 version, above. - assert(s2_limit >= s2); - int matched = 0; - - while (s2 <= s2_limit - 4 && - UNALIGNED_LOAD32(s2) == UNALIGNED_LOAD32(s1 + matched)) { - s2 += 4; - matched += 4; - } - if (LittleEndian::IsLittleEndian() && s2 <= s2_limit - 4) { - uint32 x = UNALIGNED_LOAD32(s2) ^ UNALIGNED_LOAD32(s1 + matched); - int matching_bits = Bits::FindLSBSetNonZero(x); - matched += matching_bits >> 3; - } else { - while ((s2 < s2_limit) && (s1[matched] == *s2)) { - ++s2; - ++matched; - } - } - return std::pair(matched, matched < 8); -} -#endif - -// Lookup tables for decompression code. Give --snappy_dump_decompression_table -// to the unit test to recompute char_table. - -enum { - LITERAL = 0, - COPY_1_BYTE_OFFSET = 1, // 3 bit length + 3 bits of offset in opcode - COPY_2_BYTE_OFFSET = 2, - COPY_4_BYTE_OFFSET = 3 -}; -static const int kMaximumTagLength = 5; // COPY_4_BYTE_OFFSET plus the actual offset. - -// Data stored per entry in lookup table: -// Range Bits-used Description -// ------------------------------------ -// 1..64 0..7 Literal/copy length encoded in opcode byte -// 0..7 8..10 Copy offset encoded in opcode byte / 256 -// 0..4 11..13 Extra bytes after opcode -// -// We use eight bits for the length even though 7 would have sufficed -// because of efficiency reasons: -// (1) Extracting a byte is faster than a bit-field -// (2) It properly aligns copy offset so we do not need a <<8 -static const uint16 char_table[256] = { - 0x0001, 0x0804, 0x1001, 0x2001, 0x0002, 0x0805, 0x1002, 0x2002, - 0x0003, 0x0806, 0x1003, 0x2003, 0x0004, 0x0807, 0x1004, 0x2004, - 0x0005, 0x0808, 0x1005, 0x2005, 0x0006, 0x0809, 0x1006, 0x2006, - 0x0007, 0x080a, 0x1007, 0x2007, 0x0008, 0x080b, 0x1008, 0x2008, - 0x0009, 0x0904, 0x1009, 0x2009, 0x000a, 0x0905, 0x100a, 0x200a, - 0x000b, 0x0906, 0x100b, 0x200b, 0x000c, 0x0907, 0x100c, 0x200c, - 0x000d, 0x0908, 0x100d, 0x200d, 0x000e, 0x0909, 0x100e, 0x200e, - 0x000f, 0x090a, 0x100f, 0x200f, 0x0010, 0x090b, 0x1010, 0x2010, - 0x0011, 0x0a04, 0x1011, 0x2011, 0x0012, 0x0a05, 0x1012, 0x2012, - 0x0013, 0x0a06, 0x1013, 0x2013, 0x0014, 0x0a07, 0x1014, 0x2014, - 0x0015, 0x0a08, 0x1015, 0x2015, 0x0016, 0x0a09, 0x1016, 0x2016, - 0x0017, 0x0a0a, 0x1017, 0x2017, 0x0018, 0x0a0b, 0x1018, 0x2018, - 0x0019, 0x0b04, 0x1019, 0x2019, 0x001a, 0x0b05, 0x101a, 0x201a, - 0x001b, 0x0b06, 0x101b, 0x201b, 0x001c, 0x0b07, 0x101c, 0x201c, - 0x001d, 0x0b08, 0x101d, 0x201d, 0x001e, 0x0b09, 0x101e, 0x201e, - 0x001f, 0x0b0a, 0x101f, 0x201f, 0x0020, 0x0b0b, 0x1020, 0x2020, - 0x0021, 0x0c04, 0x1021, 0x2021, 0x0022, 0x0c05, 0x1022, 0x2022, - 0x0023, 0x0c06, 0x1023, 0x2023, 0x0024, 0x0c07, 0x1024, 0x2024, - 0x0025, 0x0c08, 0x1025, 0x2025, 0x0026, 0x0c09, 0x1026, 0x2026, - 0x0027, 0x0c0a, 0x1027, 0x2027, 0x0028, 0x0c0b, 0x1028, 0x2028, - 0x0029, 0x0d04, 0x1029, 0x2029, 0x002a, 0x0d05, 0x102a, 0x202a, - 0x002b, 0x0d06, 0x102b, 0x202b, 0x002c, 0x0d07, 0x102c, 0x202c, - 0x002d, 0x0d08, 0x102d, 0x202d, 0x002e, 0x0d09, 0x102e, 0x202e, - 0x002f, 0x0d0a, 0x102f, 0x202f, 0x0030, 0x0d0b, 0x1030, 0x2030, - 0x0031, 0x0e04, 0x1031, 0x2031, 0x0032, 0x0e05, 0x1032, 0x2032, - 0x0033, 0x0e06, 0x1033, 0x2033, 0x0034, 0x0e07, 0x1034, 0x2034, - 0x0035, 0x0e08, 0x1035, 0x2035, 0x0036, 0x0e09, 0x1036, 0x2036, - 0x0037, 0x0e0a, 0x1037, 0x2037, 0x0038, 0x0e0b, 0x1038, 0x2038, - 0x0039, 0x0f04, 0x1039, 0x2039, 0x003a, 0x0f05, 0x103a, 0x203a, - 0x003b, 0x0f06, 0x103b, 0x203b, 0x003c, 0x0f07, 0x103c, 0x203c, - 0x0801, 0x0f08, 0x103d, 0x203d, 0x1001, 0x0f09, 0x103e, 0x203e, - 0x1801, 0x0f0a, 0x103f, 0x203f, 0x2001, 0x0f0b, 0x1040, 0x2040 -}; - -} // end namespace internal -} // end namespace snappy - -#endif // THIRD_PARTY_SNAPPY_SNAPPY_INTERNAL_H_ diff --git a/src/snappy/snappy/snappy-sinksource.cc b/src/snappy/snappy/snappy-sinksource.cc deleted file mode 100644 index 369a13215b..0000000000 --- a/src/snappy/snappy/snappy-sinksource.cc +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright 2011 Google Inc. All Rights Reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#include - -#include "snappy-sinksource.h" - -namespace snappy { - -Source::~Source() { } - -Sink::~Sink() { } - -char* Sink::GetAppendBuffer(size_t length, char* scratch) { - return scratch; -} - -char* Sink::GetAppendBufferVariable( - size_t min_size, size_t desired_size_hint, char* scratch, - size_t scratch_size, size_t* allocated_size) { - *allocated_size = scratch_size; - return scratch; -} - -void Sink::AppendAndTakeOwnership( - char* bytes, size_t n, - void (*deleter)(void*, const char*, size_t), - void *deleter_arg) { - Append(bytes, n); - (*deleter)(deleter_arg, bytes, n); -} - -ByteArraySource::~ByteArraySource() { } - -size_t ByteArraySource::Available() const { return left_; } - -const char* ByteArraySource::Peek(size_t* len) { - *len = left_; - return ptr_; -} - -void ByteArraySource::Skip(size_t n) { - left_ -= n; - ptr_ += n; -} - -UncheckedByteArraySink::~UncheckedByteArraySink() { } - -void UncheckedByteArraySink::Append(const char* data, size_t n) { - // Do no copying if the caller filled in the result of GetAppendBuffer() - if (data != dest_) { - memcpy(dest_, data, n); - } - dest_ += n; -} - -char* UncheckedByteArraySink::GetAppendBuffer(size_t len, char* scratch) { - return dest_; -} - -void UncheckedByteArraySink::AppendAndTakeOwnership( - char* data, size_t n, - void (*deleter)(void*, const char*, size_t), - void *deleter_arg) { - if (data != dest_) { - memcpy(dest_, data, n); - (*deleter)(deleter_arg, data, n); - } - dest_ += n; -} - -char* UncheckedByteArraySink::GetAppendBufferVariable( - size_t min_size, size_t desired_size_hint, char* scratch, - size_t scratch_size, size_t* allocated_size) { - *allocated_size = desired_size_hint; - return dest_; -} - -} // namespace snappy diff --git a/src/snappy/snappy/snappy-sinksource.h b/src/snappy/snappy/snappy-sinksource.h deleted file mode 100644 index 8afcdaaa2c..0000000000 --- a/src/snappy/snappy/snappy-sinksource.h +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2011 Google Inc. All Rights Reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#ifndef THIRD_PARTY_SNAPPY_SNAPPY_SINKSOURCE_H_ -#define THIRD_PARTY_SNAPPY_SNAPPY_SINKSOURCE_H_ - -#include - -namespace snappy { - -// A Sink is an interface that consumes a sequence of bytes. -class Sink { - public: - Sink() { } - virtual ~Sink(); - - // Append "bytes[0,n-1]" to this. - virtual void Append(const char* bytes, size_t n) = 0; - - // Returns a writable buffer of the specified length for appending. - // May return a pointer to the caller-owned scratch buffer which - // must have at least the indicated length. The returned buffer is - // only valid until the next operation on this Sink. - // - // After writing at most "length" bytes, call Append() with the - // pointer returned from this function and the number of bytes - // written. Many Append() implementations will avoid copying - // bytes if this function returned an internal buffer. - // - // If a non-scratch buffer is returned, the caller may only pass a - // prefix of it to Append(). That is, it is not correct to pass an - // interior pointer of the returned array to Append(). - // - // The default implementation always returns the scratch buffer. - virtual char* GetAppendBuffer(size_t length, char* scratch); - - // For higher performance, Sink implementations can provide custom - // AppendAndTakeOwnership() and GetAppendBufferVariable() methods. - // These methods can reduce the number of copies done during - // compression/decompression. - - // Append "bytes[0,n-1] to the sink. Takes ownership of "bytes" - // and calls the deleter function as (*deleter)(deleter_arg, bytes, n) - // to free the buffer. deleter function must be non NULL. - // - // The default implementation just calls Append and frees "bytes". - // Other implementations may avoid a copy while appending the buffer. - virtual void AppendAndTakeOwnership( - char* bytes, size_t n, void (*deleter)(void*, const char*, size_t), - void *deleter_arg); - - // Returns a writable buffer for appending and writes the buffer's capacity to - // *allocated_size. Guarantees *allocated_size >= min_size. - // May return a pointer to the caller-owned scratch buffer which must have - // scratch_size >= min_size. - // - // The returned buffer is only valid until the next operation - // on this ByteSink. - // - // After writing at most *allocated_size bytes, call Append() with the - // pointer returned from this function and the number of bytes written. - // Many Append() implementations will avoid copying bytes if this function - // returned an internal buffer. - // - // If the sink implementation allocates or reallocates an internal buffer, - // it should use the desired_size_hint if appropriate. If a caller cannot - // provide a reasonable guess at the desired capacity, it should set - // desired_size_hint = 0. - // - // If a non-scratch buffer is returned, the caller may only pass - // a prefix to it to Append(). That is, it is not correct to pass an - // interior pointer to Append(). - // - // The default implementation always returns the scratch buffer. - virtual char* GetAppendBufferVariable( - size_t min_size, size_t desired_size_hint, char* scratch, - size_t scratch_size, size_t* allocated_size); - - private: - // No copying - Sink(const Sink&); - void operator=(const Sink&); -}; - -// A Source is an interface that yields a sequence of bytes -class Source { - public: - Source() { } - virtual ~Source(); - - // Return the number of bytes left to read from the source - virtual size_t Available() const = 0; - - // Peek at the next flat region of the source. Does not reposition - // the source. The returned region is empty iff Available()==0. - // - // Returns a pointer to the beginning of the region and store its - // length in *len. - // - // The returned region is valid until the next call to Skip() or - // until this object is destroyed, whichever occurs first. - // - // The returned region may be larger than Available() (for example - // if this ByteSource is a view on a substring of a larger source). - // The caller is responsible for ensuring that it only reads the - // Available() bytes. - virtual const char* Peek(size_t* len) = 0; - - // Skip the next n bytes. Invalidates any buffer returned by - // a previous call to Peek(). - // REQUIRES: Available() >= n - virtual void Skip(size_t n) = 0; - - private: - // No copying - Source(const Source&); - void operator=(const Source&); -}; - -// A Source implementation that yields the contents of a flat array -class ByteArraySource : public Source { - public: - ByteArraySource(const char* p, size_t n) : ptr_(p), left_(n) { } - virtual ~ByteArraySource(); - virtual size_t Available() const; - virtual const char* Peek(size_t* len); - virtual void Skip(size_t n); - private: - const char* ptr_; - size_t left_; -}; - -// A Sink implementation that writes to a flat array without any bound checks. -class UncheckedByteArraySink : public Sink { - public: - explicit UncheckedByteArraySink(char* dest) : dest_(dest) { } - virtual ~UncheckedByteArraySink(); - virtual void Append(const char* data, size_t n); - virtual char* GetAppendBuffer(size_t len, char* scratch); - virtual char* GetAppendBufferVariable( - size_t min_size, size_t desired_size_hint, char* scratch, - size_t scratch_size, size_t* allocated_size); - virtual void AppendAndTakeOwnership( - char* bytes, size_t n, void (*deleter)(void*, const char*, size_t), - void *deleter_arg); - - // Return the current output pointer so that a caller can see how - // many bytes were produced. - // Note: this is not a Sink method. - char* CurrentDestination() const { return dest_; } - private: - char* dest_; -}; - -} // namespace snappy - -#endif // THIRD_PARTY_SNAPPY_SNAPPY_SINKSOURCE_H_ diff --git a/src/snappy/snappy/snappy-stubs-internal.cc b/src/snappy/snappy/snappy-stubs-internal.cc deleted file mode 100644 index 6ed334371f..0000000000 --- a/src/snappy/snappy/snappy-stubs-internal.cc +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2011 Google Inc. All Rights Reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#include -#include - -#include "snappy-stubs-internal.h" - -namespace snappy { - -void Varint::Append32(string* s, uint32 value) { - char buf[Varint::kMax32]; - const char* p = Varint::Encode32(buf, value); - s->append(buf, p - buf); -} - -} // namespace snappy diff --git a/src/snappy/snappy/snappy-stubs-internal.h b/src/snappy/snappy/snappy-stubs-internal.h deleted file mode 100644 index cb605f82d0..0000000000 --- a/src/snappy/snappy/snappy-stubs-internal.h +++ /dev/null @@ -1,561 +0,0 @@ -// Copyright 2011 Google Inc. All Rights Reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Various stubs for the open-source version of Snappy. - -#ifndef THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_STUBS_INTERNAL_H_ -#define THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_STUBS_INTERNAL_H_ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include - -#include -#include -#include - -#ifdef HAVE_SYS_MMAN_H -#include -#endif - -#ifdef HAVE_UNISTD_H -#include -#endif - -#if defined(_MSC_VER) -#include -#endif // defined(_MSC_VER) - -#include "snappy-stubs-public.h" - -#if defined(__x86_64__) - -// Enable 64-bit optimized versions of some routines. -#define ARCH_K8 1 - -#elif defined(__ppc64__) - -#define ARCH_PPC 1 - -#elif defined(__aarch64__) - -#define ARCH_ARM 1 - -#endif - -// Needed by OS X, among others. -#ifndef MAP_ANONYMOUS -#define MAP_ANONYMOUS MAP_ANON -#endif - -// The size of an array, if known at compile-time. -// Will give unexpected results if used on a pointer. -// We undefine it first, since some compilers already have a definition. -#ifdef ARRAYSIZE -#undef ARRAYSIZE -#endif -#define ARRAYSIZE(a) (sizeof(a) / sizeof(*(a))) - -// Static prediction hints. -#ifdef HAVE_BUILTIN_EXPECT -#define SNAPPY_PREDICT_FALSE(x) (__builtin_expect(x, 0)) -#define SNAPPY_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1)) -#else -#define SNAPPY_PREDICT_FALSE(x) x -#define SNAPPY_PREDICT_TRUE(x) x -#endif - -// This is only used for recomputing the tag byte table used during -// decompression; for simplicity we just remove it from the open-source -// version (anyone who wants to regenerate it can just do the call -// themselves within main()). -#define DEFINE_bool(flag_name, default_value, description) \ - bool FLAGS_ ## flag_name = default_value -#define DECLARE_bool(flag_name) \ - extern bool FLAGS_ ## flag_name - -namespace snappy { - -static const uint32 kuint32max = static_cast(0xFFFFFFFF); -static const int64 kint64max = static_cast(0x7FFFFFFFFFFFFFFFLL); - -// Potentially unaligned loads and stores. - -// x86, PowerPC, and ARM64 can simply do these loads and stores native. - -#if defined(__i386__) || defined(__x86_64__) || defined(__powerpc__) || \ - defined(__aarch64__) - -#define UNALIGNED_LOAD16(_p) (*reinterpret_cast(_p)) -#define UNALIGNED_LOAD32(_p) (*reinterpret_cast(_p)) -#define UNALIGNED_LOAD64(_p) (*reinterpret_cast(_p)) - -#define UNALIGNED_STORE16(_p, _val) (*reinterpret_cast(_p) = (_val)) -#define UNALIGNED_STORE32(_p, _val) (*reinterpret_cast(_p) = (_val)) -#define UNALIGNED_STORE64(_p, _val) (*reinterpret_cast(_p) = (_val)) - -// ARMv7 and newer support native unaligned accesses, but only of 16-bit -// and 32-bit values (not 64-bit); older versions either raise a fatal signal, -// do an unaligned read and rotate the words around a bit, or do the reads very -// slowly (trip through kernel mode). There's no simple #define that says just -// “ARMv7 or higherâ€, so we have to filter away all ARMv5 and ARMv6 -// sub-architectures. -// -// This is a mess, but there's not much we can do about it. -// -// To further complicate matters, only LDR instructions (single reads) are -// allowed to be unaligned, not LDRD (two reads) or LDM (many reads). Unless we -// explicitly tell the compiler that these accesses can be unaligned, it can and -// will combine accesses. On armcc, the way to signal this is done by accessing -// through the type (uint32 __packed *), but GCC has no such attribute -// (it ignores __attribute__((packed)) on individual variables). However, -// we can tell it that a _struct_ is unaligned, which has the same effect, -// so we do that. - -#elif defined(__arm__) && \ - !defined(__ARM_ARCH_4__) && \ - !defined(__ARM_ARCH_4T__) && \ - !defined(__ARM_ARCH_5__) && \ - !defined(__ARM_ARCH_5T__) && \ - !defined(__ARM_ARCH_5TE__) && \ - !defined(__ARM_ARCH_5TEJ__) && \ - !defined(__ARM_ARCH_6__) && \ - !defined(__ARM_ARCH_6J__) && \ - !defined(__ARM_ARCH_6K__) && \ - !defined(__ARM_ARCH_6Z__) && \ - !defined(__ARM_ARCH_6ZK__) && \ - !defined(__ARM_ARCH_6T2__) - -#if __GNUC__ -#define ATTRIBUTE_PACKED __attribute__((__packed__)) -#else -#define ATTRIBUTE_PACKED -#endif - -namespace base { -namespace internal { - -struct Unaligned16Struct { - uint16 value; - uint8 dummy; // To make the size non-power-of-two. -} ATTRIBUTE_PACKED; - -struct Unaligned32Struct { - uint32 value; - uint8 dummy; // To make the size non-power-of-two. -} ATTRIBUTE_PACKED; - -} // namespace internal -} // namespace base - -#define UNALIGNED_LOAD16(_p) \ - ((reinterpret_cast(_p))->value) -#define UNALIGNED_LOAD32(_p) \ - ((reinterpret_cast(_p))->value) - -#define UNALIGNED_STORE16(_p, _val) \ - ((reinterpret_cast< ::snappy::base::internal::Unaligned16Struct *>(_p))->value = \ - (_val)) -#define UNALIGNED_STORE32(_p, _val) \ - ((reinterpret_cast< ::snappy::base::internal::Unaligned32Struct *>(_p))->value = \ - (_val)) - -// TODO(user): NEON supports unaligned 64-bit loads and stores. -// See if that would be more efficient on platforms supporting it, -// at least for copies. - -inline uint64 UNALIGNED_LOAD64(const void *p) { - uint64 t; - memcpy(&t, p, sizeof t); - return t; -} - -inline void UNALIGNED_STORE64(void *p, uint64 v) { - memcpy(p, &v, sizeof v); -} - -#else - -// These functions are provided for architectures that don't support -// unaligned loads and stores. - -inline uint16 UNALIGNED_LOAD16(const void *p) { - uint16 t; - memcpy(&t, p, sizeof t); - return t; -} - -inline uint32 UNALIGNED_LOAD32(const void *p) { - uint32 t; - memcpy(&t, p, sizeof t); - return t; -} - -inline uint64 UNALIGNED_LOAD64(const void *p) { - uint64 t; - memcpy(&t, p, sizeof t); - return t; -} - -inline void UNALIGNED_STORE16(void *p, uint16 v) { - memcpy(p, &v, sizeof v); -} - -inline void UNALIGNED_STORE32(void *p, uint32 v) { - memcpy(p, &v, sizeof v); -} - -inline void UNALIGNED_STORE64(void *p, uint64 v) { - memcpy(p, &v, sizeof v); -} - -#endif - -// The following guarantees declaration of the byte swap functions. -#if defined(SNAPPY_IS_BIG_ENDIAN) - -#ifdef HAVE_SYS_BYTEORDER_H -#include -#endif - -#ifdef HAVE_SYS_ENDIAN_H -#include -#endif - -#ifdef _MSC_VER -#include -#define bswap_16(x) _byteswap_ushort(x) -#define bswap_32(x) _byteswap_ulong(x) -#define bswap_64(x) _byteswap_uint64(x) - -#elif defined(__APPLE__) -// Mac OS X / Darwin features -#include -#define bswap_16(x) OSSwapInt16(x) -#define bswap_32(x) OSSwapInt32(x) -#define bswap_64(x) OSSwapInt64(x) - -#elif defined(HAVE_BYTESWAP_H) -#include - -#elif defined(bswap32) -// FreeBSD defines bswap{16,32,64} in (already #included). -#define bswap_16(x) bswap16(x) -#define bswap_32(x) bswap32(x) -#define bswap_64(x) bswap64(x) - -#elif defined(BSWAP_64) -// Solaris 10 defines BSWAP_{16,32,64} in (already #included). -#define bswap_16(x) BSWAP_16(x) -#define bswap_32(x) BSWAP_32(x) -#define bswap_64(x) BSWAP_64(x) - -#else - -inline uint16 bswap_16(uint16 x) { - return (x << 8) | (x >> 8); -} - -inline uint32 bswap_32(uint32 x) { - x = ((x & 0xff00ff00UL) >> 8) | ((x & 0x00ff00ffUL) << 8); - return (x >> 16) | (x << 16); -} - -inline uint64 bswap_64(uint64 x) { - x = ((x & 0xff00ff00ff00ff00ULL) >> 8) | ((x & 0x00ff00ff00ff00ffULL) << 8); - x = ((x & 0xffff0000ffff0000ULL) >> 16) | ((x & 0x0000ffff0000ffffULL) << 16); - return (x >> 32) | (x << 32); -} - -#endif - -#endif // defined(SNAPPY_IS_BIG_ENDIAN) - -// Convert to little-endian storage, opposite of network format. -// Convert x from host to little endian: x = LittleEndian.FromHost(x); -// convert x from little endian to host: x = LittleEndian.ToHost(x); -// -// Store values into unaligned memory converting to little endian order: -// LittleEndian.Store16(p, x); -// -// Load unaligned values stored in little endian converting to host order: -// x = LittleEndian.Load16(p); -class LittleEndian { - public: - // Conversion functions. -#if defined(SNAPPY_IS_BIG_ENDIAN) - - static uint16 FromHost16(uint16 x) { return bswap_16(x); } - static uint16 ToHost16(uint16 x) { return bswap_16(x); } - - static uint32 FromHost32(uint32 x) { return bswap_32(x); } - static uint32 ToHost32(uint32 x) { return bswap_32(x); } - - static bool IsLittleEndian() { return false; } - -#else // !defined(SNAPPY_IS_BIG_ENDIAN) - - static uint16 FromHost16(uint16 x) { return x; } - static uint16 ToHost16(uint16 x) { return x; } - - static uint32 FromHost32(uint32 x) { return x; } - static uint32 ToHost32(uint32 x) { return x; } - - static bool IsLittleEndian() { return true; } - -#endif // !defined(SNAPPY_IS_BIG_ENDIAN) - - // Functions to do unaligned loads and stores in little-endian order. - static uint16 Load16(const void *p) { - return ToHost16(UNALIGNED_LOAD16(p)); - } - - static void Store16(void *p, uint16 v) { - UNALIGNED_STORE16(p, FromHost16(v)); - } - - static uint32 Load32(const void *p) { - return ToHost32(UNALIGNED_LOAD32(p)); - } - - static void Store32(void *p, uint32 v) { - UNALIGNED_STORE32(p, FromHost32(v)); - } -}; - -// Some bit-manipulation functions. -class Bits { - public: - // Return floor(log2(n)) for positive integer n. Returns -1 iff n == 0. - static int Log2Floor(uint32 n); - - // Return the first set least / most significant bit, 0-indexed. Returns an - // undefined value if n == 0. FindLSBSetNonZero() is similar to ffs() except - // that it's 0-indexed. - static int FindLSBSetNonZero(uint32 n); - -#if defined(ARCH_K8) || defined(ARCH_PPC) || defined(ARCH_ARM) - static int FindLSBSetNonZero64(uint64 n); -#endif // defined(ARCH_K8) || defined(ARCH_PPC) || defined(ARCH_ARM) - - private: - // No copying - Bits(const Bits&); - void operator=(const Bits&); -}; - -#ifdef HAVE_BUILTIN_CTZ - -inline int Bits::Log2Floor(uint32 n) { - return n == 0 ? -1 : 31 ^ __builtin_clz(n); -} - -inline int Bits::FindLSBSetNonZero(uint32 n) { - return __builtin_ctz(n); -} - -#if defined(ARCH_K8) || defined(ARCH_PPC) || defined(ARCH_ARM) -inline int Bits::FindLSBSetNonZero64(uint64 n) { - return __builtin_ctzll(n); -} -#endif // defined(ARCH_K8) || defined(ARCH_PPC) || defined(ARCH_ARM) - -#elif defined(_MSC_VER) - -inline int Bits::Log2Floor(uint32 n) { - unsigned long where; - if (_BitScanReverse(&where, n)) { - return where; - } else { - return -1; - } -} - -inline int Bits::FindLSBSetNonZero(uint32 n) { - unsigned long where; - if (_BitScanForward(&where, n)) return static_cast(where); - return 32; -} - -#if defined(ARCH_K8) || defined(ARCH_PPC) || defined(ARCH_ARM) -inline int Bits::FindLSBSetNonZero64(uint64 n) { - unsigned long where; - if (_BitScanForward64(&where, n)) return static_cast(where); - return 64; -} -#endif // defined(ARCH_K8) || defined(ARCH_PPC) || defined(ARCH_ARM) - -#else // Portable versions. - -inline int Bits::Log2Floor(uint32 n) { - if (n == 0) - return -1; - int log = 0; - uint32 value = n; - for (int i = 4; i >= 0; --i) { - int shift = (1 << i); - uint32 x = value >> shift; - if (x != 0) { - value = x; - log += shift; - } - } - assert(value == 1); - return log; -} - -inline int Bits::FindLSBSetNonZero(uint32 n) { - int rc = 31; - for (int i = 4, shift = 1 << 4; i >= 0; --i) { - const uint32 x = n << shift; - if (x != 0) { - n = x; - rc -= shift; - } - shift >>= 1; - } - return rc; -} - -#if defined(ARCH_K8) || defined(ARCH_PPC) || defined(ARCH_ARM) -// FindLSBSetNonZero64() is defined in terms of FindLSBSetNonZero(). -inline int Bits::FindLSBSetNonZero64(uint64 n) { - const uint32 bottombits = static_cast(n); - if (bottombits == 0) { - // Bottom bits are zero, so scan in top bits - return 32 + FindLSBSetNonZero(static_cast(n >> 32)); - } else { - return FindLSBSetNonZero(bottombits); - } -} -#endif // defined(ARCH_K8) || defined(ARCH_PPC) || defined(ARCH_ARM) - -#endif // End portable versions. - -// Variable-length integer encoding. -class Varint { - public: - // Maximum lengths of varint encoding of uint32. - static const int kMax32 = 5; - - // Attempts to parse a varint32 from a prefix of the bytes in [ptr,limit-1]. - // Never reads a character at or beyond limit. If a valid/terminated varint32 - // was found in the range, stores it in *OUTPUT and returns a pointer just - // past the last byte of the varint32. Else returns NULL. On success, - // "result <= limit". - static const char* Parse32WithLimit(const char* ptr, const char* limit, - uint32* OUTPUT); - - // REQUIRES "ptr" points to a buffer of length sufficient to hold "v". - // EFFECTS Encodes "v" into "ptr" and returns a pointer to the - // byte just past the last encoded byte. - static char* Encode32(char* ptr, uint32 v); - - // EFFECTS Appends the varint representation of "value" to "*s". - static void Append32(string* s, uint32 value); -}; - -inline const char* Varint::Parse32WithLimit(const char* p, - const char* l, - uint32* OUTPUT) { - const unsigned char* ptr = reinterpret_cast(p); - const unsigned char* limit = reinterpret_cast(l); - uint32 b, result; - if (ptr >= limit) return NULL; - b = *(ptr++); result = b & 127; if (b < 128) goto done; - if (ptr >= limit) return NULL; - b = *(ptr++); result |= (b & 127) << 7; if (b < 128) goto done; - if (ptr >= limit) return NULL; - b = *(ptr++); result |= (b & 127) << 14; if (b < 128) goto done; - if (ptr >= limit) return NULL; - b = *(ptr++); result |= (b & 127) << 21; if (b < 128) goto done; - if (ptr >= limit) return NULL; - b = *(ptr++); result |= (b & 127) << 28; if (b < 16) goto done; - return NULL; // Value is too long to be a varint32 - done: - *OUTPUT = result; - return reinterpret_cast(ptr); -} - -inline char* Varint::Encode32(char* sptr, uint32 v) { - // Operate on characters as unsigneds - unsigned char* ptr = reinterpret_cast(sptr); - static const int B = 128; - if (v < (1<<7)) { - *(ptr++) = v; - } else if (v < (1<<14)) { - *(ptr++) = v | B; - *(ptr++) = v>>7; - } else if (v < (1<<21)) { - *(ptr++) = v | B; - *(ptr++) = (v>>7) | B; - *(ptr++) = v>>14; - } else if (v < (1<<28)) { - *(ptr++) = v | B; - *(ptr++) = (v>>7) | B; - *(ptr++) = (v>>14) | B; - *(ptr++) = v>>21; - } else { - *(ptr++) = v | B; - *(ptr++) = (v>>7) | B; - *(ptr++) = (v>>14) | B; - *(ptr++) = (v>>21) | B; - *(ptr++) = v>>28; - } - return reinterpret_cast(ptr); -} - -// If you know the internal layout of the std::string in use, you can -// replace this function with one that resizes the string without -// filling the new space with zeros (if applicable) -- -// it will be non-portable but faster. -inline void STLStringResizeUninitialized(string* s, size_t new_size) { - s->resize(new_size); -} - -// Return a mutable char* pointing to a string's internal buffer, -// which may not be null-terminated. Writing through this pointer will -// modify the string. -// -// string_as_array(&str)[i] is valid for 0 <= i < str.size() until the -// next call to a string method that invalidates iterators. -// -// As of 2006-04, there is no standard-blessed way of getting a -// mutable reference to a string's internal buffer. However, issue 530 -// (http://www.open-std.org/JTC1/SC22/WG21/docs/lwg-defects.html#530) -// proposes this as the method. It will officially be part of the standard -// for C++0x. This should already work on all current implementations. -inline char* string_as_array(string* str) { - return str->empty() ? NULL : &*str->begin(); -} - -} // namespace snappy - -#endif // THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_STUBS_INTERNAL_H_ diff --git a/src/snappy/snappy/snappy-stubs-public.h.in b/src/snappy/snappy/snappy-stubs-public.h.in deleted file mode 100644 index 3fd79bb157..0000000000 --- a/src/snappy/snappy/snappy-stubs-public.h.in +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2011 Google Inc. All Rights Reserved. -// Author: sesse@google.com (Steinar H. Gunderson) -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Various type stubs for the open-source version of Snappy. -// -// This file cannot include config.h, as it is included from snappy.h, -// which is a public header. Instead, snappy-stubs-public.h is generated by -// from snappy-stubs-public.h.in at configure time. - -#ifndef THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_STUBS_PUBLIC_H_ -#define THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_STUBS_PUBLIC_H_ - -#if ${HAVE_STDINT_H_01} // HAVE_STDINT_H -#include -#endif // HAVE_STDDEF_H - -#if ${HAVE_STDDEF_H_01} // HAVE_STDDEF_H -#include -#endif // HAVE_STDDEF_H - -#if ${HAVE_SYS_UIO_H_01} // HAVE_SYS_UIO_H -#include -#endif // HAVE_SYS_UIO_H - -#define SNAPPY_MAJOR ${SNAPPY_MAJOR} -#define SNAPPY_MINOR ${SNAPPY_MINOR} -#define SNAPPY_PATCHLEVEL ${SNAPPY_PATCHLEVEL} -#define SNAPPY_VERSION \ - ((SNAPPY_MAJOR << 16) | (SNAPPY_MINOR << 8) | SNAPPY_PATCHLEVEL) - -#include - -namespace snappy { - -#if ${HAVE_STDINT_H_01} // HAVE_STDINT_H -typedef int8_t int8; -typedef uint8_t uint8; -typedef int16_t int16; -typedef uint16_t uint16; -typedef int32_t int32; -typedef uint32_t uint32; -typedef int64_t int64; -typedef uint64_t uint64; -#else -typedef signed char int8; -typedef unsigned char uint8; -typedef short int16; -typedef unsigned short uint16; -typedef int int32; -typedef unsigned int uint32; -typedef long long int64; -typedef unsigned long long uint64; -#endif // HAVE_STDINT_H - -typedef std::string string; - -#if !${HAVE_SYS_UIO_H_01} // !HAVE_SYS_UIO_H -// Windows does not have an iovec type, yet the concept is universally useful. -// It is simple to define it ourselves, so we put it inside our own namespace. -struct iovec { - void* iov_base; - size_t iov_len; -}; -#endif // !HAVE_SYS_UIO_H - -} // namespace snappy - -#endif // THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_STUBS_PUBLIC_H_ diff --git a/src/snappy/snappy/snappy-test.cc b/src/snappy/snappy/snappy-test.cc deleted file mode 100644 index 01d5541fd2..0000000000 --- a/src/snappy/snappy/snappy-test.cc +++ /dev/null @@ -1,612 +0,0 @@ -// Copyright 2011 Google Inc. All Rights Reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Various stubs for the unit tests for the open-source version of Snappy. - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#ifdef HAVE_WINDOWS_H -// Needed to be able to use std::max without workarounds in the source code. -// https://support.microsoft.com/en-us/help/143208/prb-using-stl-in-windows-program-can-cause-min-max-conflicts -#define NOMINMAX -#include -#endif - -#include "snappy-test.h" - -#include - -DEFINE_bool(run_microbenchmarks, true, - "Run microbenchmarks before doing anything else."); - -namespace snappy { - -string ReadTestDataFile(const string& base, size_t size_limit) { - string contents; - const char* srcdir = getenv("srcdir"); // This is set by Automake. - string prefix; - if (srcdir) { - prefix = string(srcdir) + "/"; - } - file::GetContents(prefix + "testdata/" + base, &contents, file::Defaults() - ).CheckSuccess(); - if (size_limit > 0) { - contents = contents.substr(0, size_limit); - } - return contents; -} - -string ReadTestDataFile(const string& base) { - return ReadTestDataFile(base, 0); -} - -string StringPrintf(const char* format, ...) { - char buf[4096]; - va_list ap; - va_start(ap, format); - vsnprintf(buf, sizeof(buf), format, ap); - va_end(ap); - return buf; -} - -bool benchmark_running = false; -int64 benchmark_real_time_us = 0; -int64 benchmark_cpu_time_us = 0; -string *benchmark_label = NULL; -int64 benchmark_bytes_processed = 0; - -void ResetBenchmarkTiming() { - benchmark_real_time_us = 0; - benchmark_cpu_time_us = 0; -} - -#ifdef WIN32 -LARGE_INTEGER benchmark_start_real; -FILETIME benchmark_start_cpu; -#else // WIN32 -struct timeval benchmark_start_real; -struct rusage benchmark_start_cpu; -#endif // WIN32 - -void StartBenchmarkTiming() { -#ifdef WIN32 - QueryPerformanceCounter(&benchmark_start_real); - FILETIME dummy; - CHECK(GetProcessTimes( - GetCurrentProcess(), &dummy, &dummy, &dummy, &benchmark_start_cpu)); -#else - gettimeofday(&benchmark_start_real, NULL); - if (getrusage(RUSAGE_SELF, &benchmark_start_cpu) == -1) { - perror("getrusage(RUSAGE_SELF)"); - exit(1); - } -#endif - benchmark_running = true; -} - -void StopBenchmarkTiming() { - if (!benchmark_running) { - return; - } - -#ifdef WIN32 - LARGE_INTEGER benchmark_stop_real; - LARGE_INTEGER benchmark_frequency; - QueryPerformanceCounter(&benchmark_stop_real); - QueryPerformanceFrequency(&benchmark_frequency); - - double elapsed_real = static_cast( - benchmark_stop_real.QuadPart - benchmark_start_real.QuadPart) / - benchmark_frequency.QuadPart; - benchmark_real_time_us += elapsed_real * 1e6 + 0.5; - - FILETIME benchmark_stop_cpu, dummy; - CHECK(GetProcessTimes( - GetCurrentProcess(), &dummy, &dummy, &dummy, &benchmark_stop_cpu)); - - ULARGE_INTEGER start_ulargeint; - start_ulargeint.LowPart = benchmark_start_cpu.dwLowDateTime; - start_ulargeint.HighPart = benchmark_start_cpu.dwHighDateTime; - - ULARGE_INTEGER stop_ulargeint; - stop_ulargeint.LowPart = benchmark_stop_cpu.dwLowDateTime; - stop_ulargeint.HighPart = benchmark_stop_cpu.dwHighDateTime; - - benchmark_cpu_time_us += - (stop_ulargeint.QuadPart - start_ulargeint.QuadPart + 5) / 10; -#else // WIN32 - struct timeval benchmark_stop_real; - gettimeofday(&benchmark_stop_real, NULL); - benchmark_real_time_us += - 1000000 * (benchmark_stop_real.tv_sec - benchmark_start_real.tv_sec); - benchmark_real_time_us += - (benchmark_stop_real.tv_usec - benchmark_start_real.tv_usec); - - struct rusage benchmark_stop_cpu; - if (getrusage(RUSAGE_SELF, &benchmark_stop_cpu) == -1) { - perror("getrusage(RUSAGE_SELF)"); - exit(1); - } - benchmark_cpu_time_us += 1000000 * (benchmark_stop_cpu.ru_utime.tv_sec - - benchmark_start_cpu.ru_utime.tv_sec); - benchmark_cpu_time_us += (benchmark_stop_cpu.ru_utime.tv_usec - - benchmark_start_cpu.ru_utime.tv_usec); -#endif // WIN32 - - benchmark_running = false; -} - -void SetBenchmarkLabel(const string& str) { - if (benchmark_label) { - delete benchmark_label; - } - benchmark_label = new string(str); -} - -void SetBenchmarkBytesProcessed(int64 bytes) { - benchmark_bytes_processed = bytes; -} - -struct BenchmarkRun { - int64 real_time_us; - int64 cpu_time_us; -}; - -struct BenchmarkCompareCPUTime { - bool operator() (const BenchmarkRun& a, const BenchmarkRun& b) const { - return a.cpu_time_us < b.cpu_time_us; - } -}; - -void Benchmark::Run() { - for (int test_case_num = start_; test_case_num <= stop_; ++test_case_num) { - // Run a few iterations first to find out approximately how fast - // the benchmark is. - const int kCalibrateIterations = 100; - ResetBenchmarkTiming(); - StartBenchmarkTiming(); - (*function_)(kCalibrateIterations, test_case_num); - StopBenchmarkTiming(); - - // Let each test case run for about 200ms, but at least as many - // as we used to calibrate. - // Run five times and pick the median. - const int kNumRuns = 5; - const int kMedianPos = kNumRuns / 2; - int num_iterations = 0; - if (benchmark_real_time_us > 0) { - num_iterations = 200000 * kCalibrateIterations / benchmark_real_time_us; - } - num_iterations = std::max(num_iterations, kCalibrateIterations); - BenchmarkRun benchmark_runs[kNumRuns]; - - for (int run = 0; run < kNumRuns; ++run) { - ResetBenchmarkTiming(); - StartBenchmarkTiming(); - (*function_)(num_iterations, test_case_num); - StopBenchmarkTiming(); - - benchmark_runs[run].real_time_us = benchmark_real_time_us; - benchmark_runs[run].cpu_time_us = benchmark_cpu_time_us; - } - - string heading = StringPrintf("%s/%d", name_.c_str(), test_case_num); - string human_readable_speed; - - std::nth_element(benchmark_runs, - benchmark_runs + kMedianPos, - benchmark_runs + kNumRuns, - BenchmarkCompareCPUTime()); - int64 real_time_us = benchmark_runs[kMedianPos].real_time_us; - int64 cpu_time_us = benchmark_runs[kMedianPos].cpu_time_us; - if (cpu_time_us <= 0) { - human_readable_speed = "?"; - } else { - int64 bytes_per_second = - benchmark_bytes_processed * 1000000 / cpu_time_us; - if (bytes_per_second < 1024) { - human_readable_speed = StringPrintf("%dB/s", bytes_per_second); - } else if (bytes_per_second < 1024 * 1024) { - human_readable_speed = StringPrintf( - "%.1fkB/s", bytes_per_second / 1024.0f); - } else if (bytes_per_second < 1024 * 1024 * 1024) { - human_readable_speed = StringPrintf( - "%.1fMB/s", bytes_per_second / (1024.0f * 1024.0f)); - } else { - human_readable_speed = StringPrintf( - "%.1fGB/s", bytes_per_second / (1024.0f * 1024.0f * 1024.0f)); - } - } - - fprintf(stderr, -#ifdef WIN32 - "%-18s %10I64d %10I64d %10d %s %s\n", -#else - "%-18s %10lld %10lld %10d %s %s\n", -#endif - heading.c_str(), - static_cast(real_time_us * 1000 / num_iterations), - static_cast(cpu_time_us * 1000 / num_iterations), - num_iterations, - human_readable_speed.c_str(), - benchmark_label->c_str()); - } -} - -#ifdef HAVE_LIBZ - -ZLib::ZLib() - : comp_init_(false), - uncomp_init_(false) { - Reinit(); -} - -ZLib::~ZLib() { - if (comp_init_) { deflateEnd(&comp_stream_); } - if (uncomp_init_) { inflateEnd(&uncomp_stream_); } -} - -void ZLib::Reinit() { - compression_level_ = Z_DEFAULT_COMPRESSION; - window_bits_ = MAX_WBITS; - mem_level_ = 8; // DEF_MEM_LEVEL - if (comp_init_) { - deflateEnd(&comp_stream_); - comp_init_ = false; - } - if (uncomp_init_) { - inflateEnd(&uncomp_stream_); - uncomp_init_ = false; - } - first_chunk_ = true; -} - -void ZLib::Reset() { - first_chunk_ = true; -} - -// --------- COMPRESS MODE - -// Initialization method to be called if we hit an error while -// compressing. On hitting an error, call this method before returning -// the error. -void ZLib::CompressErrorInit() { - deflateEnd(&comp_stream_); - comp_init_ = false; - Reset(); -} - -int ZLib::DeflateInit() { - return deflateInit2(&comp_stream_, - compression_level_, - Z_DEFLATED, - window_bits_, - mem_level_, - Z_DEFAULT_STRATEGY); -} - -int ZLib::CompressInit(Bytef *dest, uLongf *destLen, - const Bytef *source, uLong *sourceLen) { - int err; - - comp_stream_.next_in = (Bytef*)source; - comp_stream_.avail_in = (uInt)*sourceLen; - if ((uLong)comp_stream_.avail_in != *sourceLen) return Z_BUF_ERROR; - comp_stream_.next_out = dest; - comp_stream_.avail_out = (uInt)*destLen; - if ((uLong)comp_stream_.avail_out != *destLen) return Z_BUF_ERROR; - - if ( !first_chunk_ ) // only need to set up stream the first time through - return Z_OK; - - if (comp_init_) { // we've already initted it - err = deflateReset(&comp_stream_); - if (err != Z_OK) { - LOG(WARNING) << "ERROR: Can't reset compress object; creating a new one"; - deflateEnd(&comp_stream_); - comp_init_ = false; - } - } - if (!comp_init_) { // first use - comp_stream_.zalloc = (alloc_func)0; - comp_stream_.zfree = (free_func)0; - comp_stream_.opaque = (voidpf)0; - err = DeflateInit(); - if (err != Z_OK) return err; - comp_init_ = true; - } - return Z_OK; -} - -// In a perfect world we'd always have the full buffer to compress -// when the time came, and we could just call Compress(). Alas, we -// want to do chunked compression on our webserver. In this -// application, we compress the header, send it off, then compress the -// results, send them off, then compress the footer. Thus we need to -// use the chunked compression features of zlib. -int ZLib::CompressAtMostOrAll(Bytef *dest, uLongf *destLen, - const Bytef *source, uLong *sourceLen, - int flush_mode) { // Z_FULL_FLUSH or Z_FINISH - int err; - - if ( (err=CompressInit(dest, destLen, source, sourceLen)) != Z_OK ) - return err; - - // This is used to figure out how many bytes we wrote *this chunk* - int compressed_size = comp_stream_.total_out; - - // Some setup happens only for the first chunk we compress in a run - if ( first_chunk_ ) { - first_chunk_ = false; - } - - // flush_mode is Z_FINISH for all mode, Z_SYNC_FLUSH for incremental - // compression. - err = deflate(&comp_stream_, flush_mode); - - *sourceLen = comp_stream_.avail_in; - - if ((err == Z_STREAM_END || err == Z_OK) - && comp_stream_.avail_in == 0 - && comp_stream_.avail_out != 0 ) { - // we processed everything ok and the output buffer was large enough. - ; - } else if (err == Z_STREAM_END && comp_stream_.avail_in > 0) { - return Z_BUF_ERROR; // should never happen - } else if (err != Z_OK && err != Z_STREAM_END && err != Z_BUF_ERROR) { - // an error happened - CompressErrorInit(); - return err; - } else if (comp_stream_.avail_out == 0) { // not enough space - err = Z_BUF_ERROR; - } - - assert(err == Z_OK || err == Z_STREAM_END || err == Z_BUF_ERROR); - if (err == Z_STREAM_END) - err = Z_OK; - - // update the crc and other metadata - compressed_size = comp_stream_.total_out - compressed_size; // delta - *destLen = compressed_size; - - return err; -} - -int ZLib::CompressChunkOrAll(Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen, - int flush_mode) { // Z_FULL_FLUSH or Z_FINISH - const int ret = - CompressAtMostOrAll(dest, destLen, source, &sourceLen, flush_mode); - if (ret == Z_BUF_ERROR) - CompressErrorInit(); - return ret; -} - -// This routine only initializes the compression stream once. Thereafter, it -// just does a deflateReset on the stream, which should be faster. -int ZLib::Compress(Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen) { - int err; - if ( (err=CompressChunkOrAll(dest, destLen, source, sourceLen, - Z_FINISH)) != Z_OK ) - return err; - Reset(); // reset for next call to Compress - - return Z_OK; -} - - -// --------- UNCOMPRESS MODE - -int ZLib::InflateInit() { - return inflateInit2(&uncomp_stream_, MAX_WBITS); -} - -// Initialization method to be called if we hit an error while -// uncompressing. On hitting an error, call this method before -// returning the error. -void ZLib::UncompressErrorInit() { - inflateEnd(&uncomp_stream_); - uncomp_init_ = false; - Reset(); -} - -int ZLib::UncompressInit(Bytef *dest, uLongf *destLen, - const Bytef *source, uLong *sourceLen) { - int err; - - uncomp_stream_.next_in = (Bytef*)source; - uncomp_stream_.avail_in = (uInt)*sourceLen; - // Check for source > 64K on 16-bit machine: - if ((uLong)uncomp_stream_.avail_in != *sourceLen) return Z_BUF_ERROR; - - uncomp_stream_.next_out = dest; - uncomp_stream_.avail_out = (uInt)*destLen; - if ((uLong)uncomp_stream_.avail_out != *destLen) return Z_BUF_ERROR; - - if ( !first_chunk_ ) // only need to set up stream the first time through - return Z_OK; - - if (uncomp_init_) { // we've already initted it - err = inflateReset(&uncomp_stream_); - if (err != Z_OK) { - LOG(WARNING) - << "ERROR: Can't reset uncompress object; creating a new one"; - UncompressErrorInit(); - } - } - if (!uncomp_init_) { - uncomp_stream_.zalloc = (alloc_func)0; - uncomp_stream_.zfree = (free_func)0; - uncomp_stream_.opaque = (voidpf)0; - err = InflateInit(); - if (err != Z_OK) return err; - uncomp_init_ = true; - } - return Z_OK; -} - -// If you compressed your data a chunk at a time, with CompressChunk, -// you can uncompress it a chunk at a time with UncompressChunk. -// Only difference bewteen chunked and unchunked uncompression -// is the flush mode we use: Z_SYNC_FLUSH (chunked) or Z_FINISH (unchunked). -int ZLib::UncompressAtMostOrAll(Bytef *dest, uLongf *destLen, - const Bytef *source, uLong *sourceLen, - int flush_mode) { // Z_SYNC_FLUSH or Z_FINISH - int err = Z_OK; - - if ( (err=UncompressInit(dest, destLen, source, sourceLen)) != Z_OK ) { - LOG(WARNING) << "UncompressInit: Error: " << err << " SourceLen: " - << *sourceLen; - return err; - } - - // This is used to figure out how many output bytes we wrote *this chunk*: - const uLong old_total_out = uncomp_stream_.total_out; - - // This is used to figure out how many input bytes we read *this chunk*: - const uLong old_total_in = uncomp_stream_.total_in; - - // Some setup happens only for the first chunk we compress in a run - if ( first_chunk_ ) { - first_chunk_ = false; // so we don't do this again - - // For the first chunk *only* (to avoid infinite troubles), we let - // there be no actual data to uncompress. This sometimes triggers - // when the input is only the gzip header, say. - if ( *sourceLen == 0 ) { - *destLen = 0; - return Z_OK; - } - } - - // We'll uncompress as much as we can. If we end OK great, otherwise - // if we get an error that seems to be the gzip footer, we store the - // gzip footer and return OK, otherwise we return the error. - - // flush_mode is Z_SYNC_FLUSH for chunked mode, Z_FINISH for all mode. - err = inflate(&uncomp_stream_, flush_mode); - - // Figure out how many bytes of the input zlib slurped up: - const uLong bytes_read = uncomp_stream_.total_in - old_total_in; - CHECK_LE(source + bytes_read, source + *sourceLen); - *sourceLen = uncomp_stream_.avail_in; - - if ((err == Z_STREAM_END || err == Z_OK) // everything went ok - && uncomp_stream_.avail_in == 0) { // and we read it all - ; - } else if (err == Z_STREAM_END && uncomp_stream_.avail_in > 0) { - LOG(WARNING) - << "UncompressChunkOrAll: Received some extra data, bytes total: " - << uncomp_stream_.avail_in << " bytes: " - << std::string(reinterpret_cast(uncomp_stream_.next_in), - std::min(int(uncomp_stream_.avail_in), 20)); - UncompressErrorInit(); - return Z_DATA_ERROR; // what's the extra data for? - } else if (err != Z_OK && err != Z_STREAM_END && err != Z_BUF_ERROR) { - // an error happened - LOG(WARNING) << "UncompressChunkOrAll: Error: " << err - << " avail_out: " << uncomp_stream_.avail_out; - UncompressErrorInit(); - return err; - } else if (uncomp_stream_.avail_out == 0) { - err = Z_BUF_ERROR; - } - - assert(err == Z_OK || err == Z_BUF_ERROR || err == Z_STREAM_END); - if (err == Z_STREAM_END) - err = Z_OK; - - *destLen = uncomp_stream_.total_out - old_total_out; // size for this call - - return err; -} - -int ZLib::UncompressChunkOrAll(Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen, - int flush_mode) { // Z_SYNC_FLUSH or Z_FINISH - const int ret = - UncompressAtMostOrAll(dest, destLen, source, &sourceLen, flush_mode); - if (ret == Z_BUF_ERROR) - UncompressErrorInit(); - return ret; -} - -int ZLib::UncompressAtMost(Bytef *dest, uLongf *destLen, - const Bytef *source, uLong *sourceLen) { - return UncompressAtMostOrAll(dest, destLen, source, sourceLen, Z_SYNC_FLUSH); -} - -// We make sure we've uncompressed everything, that is, the current -// uncompress stream is at a compressed-buffer-EOF boundary. In gzip -// mode, we also check the gzip footer to make sure we pass the gzip -// consistency checks. We RETURN true iff both types of checks pass. -bool ZLib::UncompressChunkDone() { - assert(!first_chunk_ && uncomp_init_); - // Make sure we're at the end-of-compressed-data point. This means - // if we call inflate with Z_FINISH we won't consume any input or - // write any output - Bytef dummyin, dummyout; - uLongf dummylen = 0; - if ( UncompressChunkOrAll(&dummyout, &dummylen, &dummyin, 0, Z_FINISH) - != Z_OK ) { - return false; - } - - // Make sure that when we exit, we can start a new round of chunks later - Reset(); - - return true; -} - -// Uncompresses the source buffer into the destination buffer. -// The destination buffer must be long enough to hold the entire -// decompressed contents. -// -// We only initialize the uncomp_stream once. Thereafter, we use -// inflateReset, which should be faster. -// -// Returns Z_OK on success, otherwise, it returns a zlib error code. -int ZLib::Uncompress(Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen) { - int err; - if ( (err=UncompressChunkOrAll(dest, destLen, source, sourceLen, - Z_FINISH)) != Z_OK ) { - Reset(); // let us try to compress again - return err; - } - if ( !UncompressChunkDone() ) // calls Reset() - return Z_DATA_ERROR; - return Z_OK; // stream_end is ok -} - -#endif // HAVE_LIBZ - -} // namespace snappy diff --git a/src/snappy/snappy/snappy-test.h b/src/snappy/snappy/snappy-test.h deleted file mode 100644 index 078f321104..0000000000 --- a/src/snappy/snappy/snappy-test.h +++ /dev/null @@ -1,573 +0,0 @@ -// Copyright 2011 Google Inc. All Rights Reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Various stubs for the unit tests for the open-source version of Snappy. - -#ifndef THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_TEST_H_ -#define THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_TEST_H_ - -#include -#include - -#include "snappy-stubs-internal.h" - -#include -#include - -#ifdef HAVE_SYS_MMAN_H -#include -#endif - -#ifdef HAVE_SYS_RESOURCE_H -#include -#endif - -#ifdef HAVE_SYS_TIME_H -#include -#endif - -#ifdef HAVE_WINDOWS_H -#include -#endif - -#include - -#ifdef HAVE_GTEST - -#include -#undef TYPED_TEST -#define TYPED_TEST TEST -#define INIT_GTEST(argc, argv) ::testing::InitGoogleTest(argc, *argv) - -#else - -// Stubs for if the user doesn't have Google Test installed. - -#define TEST(test_case, test_subcase) \ - void Test_ ## test_case ## _ ## test_subcase() -#define INIT_GTEST(argc, argv) - -#define TYPED_TEST TEST -#define EXPECT_EQ CHECK_EQ -#define EXPECT_NE CHECK_NE -#define EXPECT_FALSE(cond) CHECK(!(cond)) - -#endif - -#ifdef HAVE_GFLAGS - -#include - -// This is tricky; both gflags and Google Test want to look at the command line -// arguments. Google Test seems to be the most happy with unknown arguments, -// though, so we call it first and hope for the best. -#define InitGoogle(argv0, argc, argv, remove_flags) \ - INIT_GTEST(argc, argv); \ - google::ParseCommandLineFlags(argc, argv, remove_flags); - -#else - -// If we don't have the gflags package installed, these can only be -// changed at compile time. -#define DEFINE_int32(flag_name, default_value, description) \ - static int FLAGS_ ## flag_name = default_value; - -#define InitGoogle(argv0, argc, argv, remove_flags) \ - INIT_GTEST(argc, argv) - -#endif - -#ifdef HAVE_LIBZ -#include "zlib.h" -#endif - -#ifdef HAVE_LIBLZO2 -#include "lzo/lzo1x.h" -#endif - -namespace { - -namespace file { - int Defaults() { return 0; } - - class DummyStatus { - public: - void CheckSuccess() { } - }; - - DummyStatus GetContents( - const std::string& filename, std::string* data, int unused) { - FILE* fp = fopen(filename.c_str(), "rb"); - if (fp == NULL) { - perror(filename.c_str()); - exit(1); - } - - data->clear(); - while (!feof(fp)) { - char buf[4096]; - size_t ret = fread(buf, 1, 4096, fp); - if (ret == 0 && ferror(fp)) { - perror("fread"); - exit(1); - } - data->append(std::string(buf, ret)); - } - - fclose(fp); - - return DummyStatus(); - } - - inline DummyStatus SetContents( - const std::string& filename, const std::string& str, int unused) { - FILE* fp = fopen(filename.c_str(), "wb"); - if (fp == NULL) { - perror(filename.c_str()); - exit(1); - } - - int ret = fwrite(str.data(), str.size(), 1, fp); - if (ret != 1) { - perror("fwrite"); - exit(1); - } - - fclose(fp); - - return DummyStatus(); - } -} // namespace file - -} // namespace - -namespace snappy { - -#define FLAGS_test_random_seed 301 -typedef string TypeParam; - -void Test_CorruptedTest_VerifyCorrupted(); -void Test_Snappy_SimpleTests(); -void Test_Snappy_MaxBlowup(); -void Test_Snappy_RandomData(); -void Test_Snappy_FourByteOffset(); -void Test_SnappyCorruption_TruncatedVarint(); -void Test_SnappyCorruption_UnterminatedVarint(); -void Test_SnappyCorruption_OverflowingVarint(); -void Test_Snappy_ReadPastEndOfBuffer(); -void Test_Snappy_FindMatchLength(); -void Test_Snappy_FindMatchLengthRandom(); - -string ReadTestDataFile(const string& base, size_t size_limit); - -string ReadTestDataFile(const string& base); - -// A sprintf() variant that returns a std::string. -// Not safe for general use due to truncation issues. -string StringPrintf(const char* format, ...); - -// A simple, non-cryptographically-secure random generator. -class ACMRandom { - public: - explicit ACMRandom(uint32 seed) : seed_(seed) {} - - int32 Next(); - - int32 Uniform(int32 n) { - return Next() % n; - } - uint8 Rand8() { - return static_cast((Next() >> 1) & 0x000000ff); - } - bool OneIn(int X) { return Uniform(X) == 0; } - - // Skewed: pick "base" uniformly from range [0,max_log] and then - // return "base" random bits. The effect is to pick a number in the - // range [0,2^max_log-1] with bias towards smaller numbers. - int32 Skewed(int max_log); - - private: - static const uint32 M = 2147483647L; // 2^31-1 - uint32 seed_; -}; - -inline int32 ACMRandom::Next() { - static const uint64 A = 16807; // bits 14, 8, 7, 5, 2, 1, 0 - // We are computing - // seed_ = (seed_ * A) % M, where M = 2^31-1 - // - // seed_ must not be zero or M, or else all subsequent computed values - // will be zero or M respectively. For all other values, seed_ will end - // up cycling through every number in [1,M-1] - uint64 product = seed_ * A; - - // Compute (product % M) using the fact that ((x << 31) % M) == x. - seed_ = (product >> 31) + (product & M); - // The first reduction may overflow by 1 bit, so we may need to repeat. - // mod == M is not possible; using > allows the faster sign-bit-based test. - if (seed_ > M) { - seed_ -= M; - } - return seed_; -} - -inline int32 ACMRandom::Skewed(int max_log) { - const int32 base = (Next() - 1) % (max_log+1); - return (Next() - 1) & ((1u << base)-1); -} - -// A wall-time clock. This stub is not super-accurate, nor resistant to the -// system time changing. -class CycleTimer { - public: - CycleTimer() : real_time_us_(0) {} - - void Start() { -#ifdef WIN32 - QueryPerformanceCounter(&start_); -#else - gettimeofday(&start_, NULL); -#endif - } - - void Stop() { -#ifdef WIN32 - LARGE_INTEGER stop; - LARGE_INTEGER frequency; - QueryPerformanceCounter(&stop); - QueryPerformanceFrequency(&frequency); - - double elapsed = static_cast(stop.QuadPart - start_.QuadPart) / - frequency.QuadPart; - real_time_us_ += elapsed * 1e6 + 0.5; -#else - struct timeval stop; - gettimeofday(&stop, NULL); - - real_time_us_ += 1000000 * (stop.tv_sec - start_.tv_sec); - real_time_us_ += (stop.tv_usec - start_.tv_usec); -#endif - } - - double Get() { - return real_time_us_ * 1e-6; - } - - private: - int64 real_time_us_; -#ifdef WIN32 - LARGE_INTEGER start_; -#else - struct timeval start_; -#endif -}; - -// Minimalistic microbenchmark framework. - -typedef void (*BenchmarkFunction)(int, int); - -class Benchmark { - public: - Benchmark(const string& name, BenchmarkFunction function) : - name_(name), function_(function) {} - - Benchmark* DenseRange(int start, int stop) { - start_ = start; - stop_ = stop; - return this; - } - - void Run(); - - private: - const string name_; - const BenchmarkFunction function_; - int start_, stop_; -}; -#define BENCHMARK(benchmark_name) \ - Benchmark* Benchmark_ ## benchmark_name = \ - (new Benchmark(#benchmark_name, benchmark_name)) - -extern Benchmark* Benchmark_BM_UFlat; -extern Benchmark* Benchmark_BM_UIOVec; -extern Benchmark* Benchmark_BM_UValidate; -extern Benchmark* Benchmark_BM_ZFlat; - -void ResetBenchmarkTiming(); -void StartBenchmarkTiming(); -void StopBenchmarkTiming(); -void SetBenchmarkLabel(const string& str); -void SetBenchmarkBytesProcessed(int64 bytes); - -#ifdef HAVE_LIBZ - -// Object-oriented wrapper around zlib. -class ZLib { - public: - ZLib(); - ~ZLib(); - - // Wipe a ZLib object to a virgin state. This differs from Reset() - // in that it also breaks any state. - void Reinit(); - - // Call this to make a zlib buffer as good as new. Here's the only - // case where they differ: - // CompressChunk(a); CompressChunk(b); CompressChunkDone(); vs - // CompressChunk(a); Reset(); CompressChunk(b); CompressChunkDone(); - // You'll want to use Reset(), then, when you interrupt a compress - // (or uncompress) in the middle of a chunk and want to start over. - void Reset(); - - // According to the zlib manual, when you Compress, the destination - // buffer must have size at least src + .1%*src + 12. This function - // helps you calculate that. Augment this to account for a potential - // gzip header and footer, plus a few bytes of slack. - static int MinCompressbufSize(int uncompress_size) { - return uncompress_size + uncompress_size/1000 + 40; - } - - // Compresses the source buffer into the destination buffer. - // sourceLen is the byte length of the source buffer. - // Upon entry, destLen is the total size of the destination buffer, - // which must be of size at least MinCompressbufSize(sourceLen). - // Upon exit, destLen is the actual size of the compressed buffer. - // - // This function can be used to compress a whole file at once if the - // input file is mmap'ed. - // - // Returns Z_OK if success, Z_MEM_ERROR if there was not - // enough memory, Z_BUF_ERROR if there was not enough room in the - // output buffer. Note that if the output buffer is exactly the same - // size as the compressed result, we still return Z_BUF_ERROR. - // (check CL#1936076) - int Compress(Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen); - - // Uncompresses the source buffer into the destination buffer. - // The destination buffer must be long enough to hold the entire - // decompressed contents. - // - // Returns Z_OK on success, otherwise, it returns a zlib error code. - int Uncompress(Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen); - - // Uncompress data one chunk at a time -- ie you can call this - // more than once. To get this to work you need to call per-chunk - // and "done" routines. - // - // Returns Z_OK if success, Z_MEM_ERROR if there was not - // enough memory, Z_BUF_ERROR if there was not enough room in the - // output buffer. - - int UncompressAtMost(Bytef *dest, uLongf *destLen, - const Bytef *source, uLong *sourceLen); - - // Checks gzip footer information, as needed. Mostly this just - // makes sure the checksums match. Whenever you call this, it - // will assume the last 8 bytes from the previous UncompressChunk - // call are the footer. Returns true iff everything looks ok. - bool UncompressChunkDone(); - - private: - int InflateInit(); // sets up the zlib inflate structure - int DeflateInit(); // sets up the zlib deflate structure - - // These init the zlib data structures for compressing/uncompressing - int CompressInit(Bytef *dest, uLongf *destLen, - const Bytef *source, uLong *sourceLen); - int UncompressInit(Bytef *dest, uLongf *destLen, - const Bytef *source, uLong *sourceLen); - // Initialization method to be called if we hit an error while - // uncompressing. On hitting an error, call this method before - // returning the error. - void UncompressErrorInit(); - - // Helper function for Compress - int CompressChunkOrAll(Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen, - int flush_mode); - int CompressAtMostOrAll(Bytef *dest, uLongf *destLen, - const Bytef *source, uLong *sourceLen, - int flush_mode); - - // Likewise for UncompressAndUncompressChunk - int UncompressChunkOrAll(Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen, - int flush_mode); - - int UncompressAtMostOrAll(Bytef *dest, uLongf *destLen, - const Bytef *source, uLong *sourceLen, - int flush_mode); - - // Initialization method to be called if we hit an error while - // compressing. On hitting an error, call this method before - // returning the error. - void CompressErrorInit(); - - int compression_level_; // compression level - int window_bits_; // log base 2 of the window size used in compression - int mem_level_; // specifies the amount of memory to be used by - // compressor (1-9) - z_stream comp_stream_; // Zlib stream data structure - bool comp_init_; // True if we have initialized comp_stream_ - z_stream uncomp_stream_; // Zlib stream data structure - bool uncomp_init_; // True if we have initialized uncomp_stream_ - - // These are used only with chunked compression. - bool first_chunk_; // true if we need to emit headers with this chunk -}; - -#endif // HAVE_LIBZ - -} // namespace snappy - -DECLARE_bool(run_microbenchmarks); - -static inline void RunSpecifiedBenchmarks() { - if (!FLAGS_run_microbenchmarks) { - return; - } - - fprintf(stderr, "Running microbenchmarks.\n"); -#ifndef NDEBUG - fprintf(stderr, "WARNING: Compiled with assertions enabled, will be slow.\n"); -#endif -#ifndef __OPTIMIZE__ - fprintf(stderr, "WARNING: Compiled without optimization, will be slow.\n"); -#endif - fprintf(stderr, "Benchmark Time(ns) CPU(ns) Iterations\n"); - fprintf(stderr, "---------------------------------------------------\n"); - - snappy::Benchmark_BM_UFlat->Run(); - snappy::Benchmark_BM_UIOVec->Run(); - snappy::Benchmark_BM_UValidate->Run(); - snappy::Benchmark_BM_ZFlat->Run(); - - fprintf(stderr, "\n"); -} - -#ifndef HAVE_GTEST - -static inline int RUN_ALL_TESTS() { - fprintf(stderr, "Running correctness tests.\n"); - snappy::Test_CorruptedTest_VerifyCorrupted(); - snappy::Test_Snappy_SimpleTests(); - snappy::Test_Snappy_MaxBlowup(); - snappy::Test_Snappy_RandomData(); - snappy::Test_Snappy_FourByteOffset(); - snappy::Test_SnappyCorruption_TruncatedVarint(); - snappy::Test_SnappyCorruption_UnterminatedVarint(); - snappy::Test_SnappyCorruption_OverflowingVarint(); - snappy::Test_Snappy_ReadPastEndOfBuffer(); - snappy::Test_Snappy_FindMatchLength(); - snappy::Test_Snappy_FindMatchLengthRandom(); - fprintf(stderr, "All tests passed.\n"); - - return 0; -} - -#endif // HAVE_GTEST - -// For main(). -namespace snappy { - -// Logging. - -#define LOG(level) LogMessage() -#define VLOG(level) true ? (void)0 : \ - snappy::LogMessageVoidify() & snappy::LogMessage() - -class LogMessage { - public: - LogMessage() { } - ~LogMessage() { - std::cerr << std::endl; - } - - LogMessage& operator<<(const std::string& msg) { - std::cerr << msg; - return *this; - } - LogMessage& operator<<(int x) { - std::cerr << x; - return *this; - } -}; - -// Asserts, both versions activated in debug mode only, -// and ones that are always active. - -#define CRASH_UNLESS(condition) \ - SNAPPY_PREDICT_TRUE(condition) ? (void)0 : \ - snappy::LogMessageVoidify() & snappy::LogMessageCrash() - -#ifdef _MSC_VER -// ~LogMessageCrash calls abort() and therefore never exits. This is by design -// so temporarily disable warning C4722. -#pragma warning(push) -#pragma warning(disable:4722) -#endif - -class LogMessageCrash : public LogMessage { - public: - LogMessageCrash() { } - ~LogMessageCrash() { - std::cerr << std::endl; - abort(); - } -}; - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -// This class is used to explicitly ignore values in the conditional -// logging macros. This avoids compiler warnings like "value computed -// is not used" and "statement has no effect". - -class LogMessageVoidify { - public: - LogMessageVoidify() { } - // This has to be an operator with a precedence lower than << but - // higher than ?: - void operator&(const LogMessage&) { } -}; - -#define CHECK(cond) CRASH_UNLESS(cond) -#define CHECK_LE(a, b) CRASH_UNLESS((a) <= (b)) -#define CHECK_GE(a, b) CRASH_UNLESS((a) >= (b)) -#define CHECK_EQ(a, b) CRASH_UNLESS((a) == (b)) -#define CHECK_NE(a, b) CRASH_UNLESS((a) != (b)) -#define CHECK_LT(a, b) CRASH_UNLESS((a) < (b)) -#define CHECK_GT(a, b) CRASH_UNLESS((a) > (b)) -#define CHECK_OK(cond) (cond).CheckSuccess() - -} // namespace snappy - -#endif // THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_TEST_H_ diff --git a/src/snappy/snappy/snappy.cc b/src/snappy/snappy/snappy.cc deleted file mode 100644 index fd519e5a06..0000000000 --- a/src/snappy/snappy/snappy.cc +++ /dev/null @@ -1,1515 +0,0 @@ -// Copyright 2005 Google Inc. All Rights Reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#include "snappy.h" -#include "snappy-internal.h" -#include "snappy-sinksource.h" - -#ifndef SNAPPY_HAVE_SSE2 -#if defined(__SSE2__) || defined(_M_X64) || \ - (defined(_M_IX86_FP) && _M_IX86_FP >= 2) -#define SNAPPY_HAVE_SSE2 1 -#else -#define SNAPPY_HAVE_SSE2 0 -#endif -#endif - -#if SNAPPY_HAVE_SSE2 -#include -#endif -#include - -#include -#include -#include - - -namespace snappy { - -using internal::COPY_1_BYTE_OFFSET; -using internal::COPY_2_BYTE_OFFSET; -using internal::LITERAL; -using internal::char_table; -using internal::kMaximumTagLength; - -// Any hash function will produce a valid compressed bitstream, but a good -// hash function reduces the number of collisions and thus yields better -// compression for compressible input, and more speed for incompressible -// input. Of course, it doesn't hurt if the hash function is reasonably fast -// either, as it gets called a lot. -static inline uint32 HashBytes(uint32 bytes, int shift) { - uint32 kMul = 0x1e35a7bd; - return (bytes * kMul) >> shift; -} -static inline uint32 Hash(const char* p, int shift) { - return HashBytes(UNALIGNED_LOAD32(p), shift); -} - -size_t MaxCompressedLength(size_t source_len) { - // Compressed data can be defined as: - // compressed := item* literal* - // item := literal* copy - // - // The trailing literal sequence has a space blowup of at most 62/60 - // since a literal of length 60 needs one tag byte + one extra byte - // for length information. - // - // Item blowup is trickier to measure. Suppose the "copy" op copies - // 4 bytes of data. Because of a special check in the encoding code, - // we produce a 4-byte copy only if the offset is < 65536. Therefore - // the copy op takes 3 bytes to encode, and this type of item leads - // to at most the 62/60 blowup for representing literals. - // - // Suppose the "copy" op copies 5 bytes of data. If the offset is big - // enough, it will take 5 bytes to encode the copy op. Therefore the - // worst case here is a one-byte literal followed by a five-byte copy. - // I.e., 6 bytes of input turn into 7 bytes of "compressed" data. - // - // This last factor dominates the blowup, so the final estimate is: - return 32 + source_len + source_len/6; -} - -namespace { - -void UnalignedCopy64(const void* src, void* dst) { - char tmp[8]; - memcpy(tmp, src, 8); - memcpy(dst, tmp, 8); -} - -void UnalignedCopy128(const void* src, void* dst) { - // TODO(alkis): Remove this when we upgrade to a recent compiler that emits - // SSE2 moves for memcpy(dst, src, 16). -#if SNAPPY_HAVE_SSE2 - __m128i x = _mm_loadu_si128(static_cast(src)); - _mm_storeu_si128(static_cast<__m128i*>(dst), x); -#else - char tmp[16]; - memcpy(tmp, src, 16); - memcpy(dst, tmp, 16); -#endif -} - -// Copy [src, src+(op_limit-op)) to [op, (op_limit-op)) a byte at a time. Used -// for handling COPY operations where the input and output regions may overlap. -// For example, suppose: -// src == "ab" -// op == src + 2 -// op_limit == op + 20 -// After IncrementalCopySlow(src, op, op_limit), the result will have eleven -// copies of "ab" -// ababababababababababab -// Note that this does not match the semantics of either memcpy() or memmove(). -inline char* IncrementalCopySlow(const char* src, char* op, - char* const op_limit) { - while (op < op_limit) { - *op++ = *src++; - } - return op_limit; -} - -// Copy [src, src+(op_limit-op)) to [op, (op_limit-op)) but faster than -// IncrementalCopySlow. buf_limit is the address past the end of the writable -// region of the buffer. -inline char* IncrementalCopy(const char* src, char* op, char* const op_limit, - char* const buf_limit) { - // Terminology: - // - // slop = buf_limit - op - // pat = op - src - // len = limit - op - assert(src < op); - assert(op_limit <= buf_limit); - // NOTE: The compressor always emits 4 <= len <= 64. It is ok to assume that - // to optimize this function but we have to also handle these cases in case - // the input does not satisfy these conditions. - - size_t pattern_size = op - src; - // The cases are split into different branches to allow the branch predictor, - // FDO, and static prediction hints to work better. For each input we list the - // ratio of invocations that match each condition. - // - // input slop < 16 pat < 8 len > 16 - // ------------------------------------------ - // html|html4|cp 0% 1.01% 27.73% - // urls 0% 0.88% 14.79% - // jpg 0% 64.29% 7.14% - // pdf 0% 2.56% 58.06% - // txt[1-4] 0% 0.23% 0.97% - // pb 0% 0.96% 13.88% - // bin 0.01% 22.27% 41.17% - // - // It is very rare that we don't have enough slop for doing block copies. It - // is also rare that we need to expand a pattern. Small patterns are common - // for incompressible formats and for those we are plenty fast already. - // Lengths are normally not greater than 16 but they vary depending on the - // input. In general if we always predict len <= 16 it would be an ok - // prediction. - // - // In order to be fast we want a pattern >= 8 bytes and an unrolled loop - // copying 2x 8 bytes at a time. - - // Handle the uncommon case where pattern is less than 8 bytes. - if (SNAPPY_PREDICT_FALSE(pattern_size < 8)) { - // Expand pattern to at least 8 bytes. The worse case scenario in terms of - // buffer usage is when the pattern is size 3. ^ is the original position - // of op. x are irrelevant bytes copied by the last UnalignedCopy64. - // - // abc - // abcabcxxxxx - // abcabcabcabcxxxxx - // ^ - // The last x is 14 bytes after ^. - if (SNAPPY_PREDICT_TRUE(op <= buf_limit - 14)) { - while (pattern_size < 8) { - UnalignedCopy64(src, op); - op += pattern_size; - pattern_size *= 2; - } - if (SNAPPY_PREDICT_TRUE(op >= op_limit)) return op_limit; - } else { - return IncrementalCopySlow(src, op, op_limit); - } - } - assert(pattern_size >= 8); - - // Copy 2x 8 bytes at a time. Because op - src can be < 16, a single - // UnalignedCopy128 might overwrite data in op. UnalignedCopy64 is safe - // because expanding the pattern to at least 8 bytes guarantees that - // op - src >= 8. - while (op <= buf_limit - 16) { - UnalignedCopy64(src, op); - UnalignedCopy64(src + 8, op + 8); - src += 16; - op += 16; - if (SNAPPY_PREDICT_TRUE(op >= op_limit)) return op_limit; - } - // We only take this branch if we didn't have enough slop and we can do a - // single 8 byte copy. - if (SNAPPY_PREDICT_FALSE(op <= buf_limit - 8)) { - UnalignedCopy64(src, op); - src += 8; - op += 8; - } - return IncrementalCopySlow(src, op, op_limit); -} - -} // namespace - -static inline char* EmitLiteral(char* op, - const char* literal, - int len, - bool allow_fast_path) { - // The vast majority of copies are below 16 bytes, for which a - // call to memcpy is overkill. This fast path can sometimes - // copy up to 15 bytes too much, but that is okay in the - // main loop, since we have a bit to go on for both sides: - // - // - The input will always have kInputMarginBytes = 15 extra - // available bytes, as long as we're in the main loop, and - // if not, allow_fast_path = false. - // - The output will always have 32 spare bytes (see - // MaxCompressedLength). - assert(len > 0); // Zero-length literals are disallowed - int n = len - 1; - if (allow_fast_path && len <= 16) { - // Fits in tag byte - *op++ = LITERAL | (n << 2); - - UnalignedCopy128(literal, op); - return op + len; - } - - if (n < 60) { - // Fits in tag byte - *op++ = LITERAL | (n << 2); - } else { - // Encode in upcoming bytes - char* base = op; - int count = 0; - op++; - while (n > 0) { - *op++ = n & 0xff; - n >>= 8; - count++; - } - assert(count >= 1); - assert(count <= 4); - *base = LITERAL | ((59+count) << 2); - } - memcpy(op, literal, len); - return op + len; -} - -static inline char* EmitCopyAtMost64(char* op, size_t offset, size_t len, - bool len_less_than_12) { - assert(len <= 64); - assert(len >= 4); - assert(offset < 65536); - assert(len_less_than_12 == (len < 12)); - - if (len_less_than_12 && SNAPPY_PREDICT_TRUE(offset < 2048)) { - // offset fits in 11 bits. The 3 highest go in the top of the first byte, - // and the rest go in the second byte. - *op++ = COPY_1_BYTE_OFFSET + ((len - 4) << 2) + ((offset >> 3) & 0xe0); - *op++ = offset & 0xff; - } else { - // Write 4 bytes, though we only care about 3 of them. The output buffer - // is required to have some slack, so the extra byte won't overrun it. - uint32 u = COPY_2_BYTE_OFFSET + ((len - 1) << 2) + (offset << 8); - LittleEndian::Store32(op, u); - op += 3; - } - return op; -} - -static inline char* EmitCopy(char* op, size_t offset, size_t len, - bool len_less_than_12) { - assert(len_less_than_12 == (len < 12)); - if (len_less_than_12) { - return EmitCopyAtMost64(op, offset, len, true); - } else { - // A special case for len <= 64 might help, but so far measurements suggest - // it's in the noise. - - // Emit 64 byte copies but make sure to keep at least four bytes reserved. - while (SNAPPY_PREDICT_FALSE(len >= 68)) { - op = EmitCopyAtMost64(op, offset, 64, false); - len -= 64; - } - - // One or two copies will now finish the job. - if (len > 64) { - op = EmitCopyAtMost64(op, offset, 60, false); - len -= 60; - } - - // Emit remainder. - op = EmitCopyAtMost64(op, offset, len, len < 12); - return op; - } -} - -bool GetUncompressedLength(const char* start, size_t n, size_t* result) { - uint32 v = 0; - const char* limit = start + n; - if (Varint::Parse32WithLimit(start, limit, &v) != NULL) { - *result = v; - return true; - } else { - return false; - } -} - -namespace internal { -uint16* WorkingMemory::GetHashTable(size_t input_size, int* table_size) { - // Use smaller hash table when input.size() is smaller, since we - // fill the table, incurring O(hash table size) overhead for - // compression, and if the input is short, we won't need that - // many hash table entries anyway. - assert(kMaxHashTableSize >= 256); - size_t htsize = 256; - while (htsize < kMaxHashTableSize && htsize < input_size) { - htsize <<= 1; - } - - uint16* table; - if (htsize <= ARRAYSIZE(small_table_)) { - table = small_table_; - } else { - if (large_table_ == NULL) { - large_table_ = new uint16[kMaxHashTableSize]; - } - table = large_table_; - } - - *table_size = htsize; - memset(table, 0, htsize * sizeof(*table)); - return table; -} -} // end namespace internal - -// For 0 <= offset <= 4, GetUint32AtOffset(GetEightBytesAt(p), offset) will -// equal UNALIGNED_LOAD32(p + offset). Motivation: On x86-64 hardware we have -// empirically found that overlapping loads such as -// UNALIGNED_LOAD32(p) ... UNALIGNED_LOAD32(p+1) ... UNALIGNED_LOAD32(p+2) -// are slower than UNALIGNED_LOAD64(p) followed by shifts and casts to uint32. -// -// We have different versions for 64- and 32-bit; ideally we would avoid the -// two functions and just inline the UNALIGNED_LOAD64 call into -// GetUint32AtOffset, but GCC (at least not as of 4.6) is seemingly not clever -// enough to avoid loading the value multiple times then. For 64-bit, the load -// is done when GetEightBytesAt() is called, whereas for 32-bit, the load is -// done at GetUint32AtOffset() time. - -#ifdef ARCH_K8 - -typedef uint64 EightBytesReference; - -static inline EightBytesReference GetEightBytesAt(const char* ptr) { - return UNALIGNED_LOAD64(ptr); -} - -static inline uint32 GetUint32AtOffset(uint64 v, int offset) { - assert(offset >= 0); - assert(offset <= 4); - return v >> (LittleEndian::IsLittleEndian() ? 8 * offset : 32 - 8 * offset); -} - -#else - -typedef const char* EightBytesReference; - -static inline EightBytesReference GetEightBytesAt(const char* ptr) { - return ptr; -} - -static inline uint32 GetUint32AtOffset(const char* v, int offset) { - assert(offset >= 0); - assert(offset <= 4); - return UNALIGNED_LOAD32(v + offset); -} - -#endif - -// Flat array compression that does not emit the "uncompressed length" -// prefix. Compresses "input" string to the "*op" buffer. -// -// REQUIRES: "input" is at most "kBlockSize" bytes long. -// REQUIRES: "op" points to an array of memory that is at least -// "MaxCompressedLength(input.size())" in size. -// REQUIRES: All elements in "table[0..table_size-1]" are initialized to zero. -// REQUIRES: "table_size" is a power of two -// -// Returns an "end" pointer into "op" buffer. -// "end - op" is the compressed size of "input". -namespace internal { -char* CompressFragment(const char* input, - size_t input_size, - char* op, - uint16* table, - const int table_size) { - // "ip" is the input pointer, and "op" is the output pointer. - const char* ip = input; - assert(input_size <= kBlockSize); - assert((table_size & (table_size - 1)) == 0); // table must be power of two - const int shift = 32 - Bits::Log2Floor(table_size); - assert(static_cast(kuint32max >> shift) == table_size - 1); - const char* ip_end = input + input_size; - const char* base_ip = ip; - // Bytes in [next_emit, ip) will be emitted as literal bytes. Or - // [next_emit, ip_end) after the main loop. - const char* next_emit = ip; - - const size_t kInputMarginBytes = 15; - if (SNAPPY_PREDICT_TRUE(input_size >= kInputMarginBytes)) { - const char* ip_limit = input + input_size - kInputMarginBytes; - - for (uint32 next_hash = Hash(++ip, shift); ; ) { - assert(next_emit < ip); - // The body of this loop calls EmitLiteral once and then EmitCopy one or - // more times. (The exception is that when we're close to exhausting - // the input we goto emit_remainder.) - // - // In the first iteration of this loop we're just starting, so - // there's nothing to copy, so calling EmitLiteral once is - // necessary. And we only start a new iteration when the - // current iteration has determined that a call to EmitLiteral will - // precede the next call to EmitCopy (if any). - // - // Step 1: Scan forward in the input looking for a 4-byte-long match. - // If we get close to exhausting the input then goto emit_remainder. - // - // Heuristic match skipping: If 32 bytes are scanned with no matches - // found, start looking only at every other byte. If 32 more bytes are - // scanned (or skipped), look at every third byte, etc.. When a match is - // found, immediately go back to looking at every byte. This is a small - // loss (~5% performance, ~0.1% density) for compressible data due to more - // bookkeeping, but for non-compressible data (such as JPEG) it's a huge - // win since the compressor quickly "realizes" the data is incompressible - // and doesn't bother looking for matches everywhere. - // - // The "skip" variable keeps track of how many bytes there are since the - // last match; dividing it by 32 (ie. right-shifting by five) gives the - // number of bytes to move ahead for each iteration. - uint32 skip = 32; - - const char* next_ip = ip; - const char* candidate; - do { - ip = next_ip; - uint32 hash = next_hash; - assert(hash == Hash(ip, shift)); - uint32 bytes_between_hash_lookups = skip >> 5; - skip += bytes_between_hash_lookups; - next_ip = ip + bytes_between_hash_lookups; - if (SNAPPY_PREDICT_FALSE(next_ip > ip_limit)) { - goto emit_remainder; - } - next_hash = Hash(next_ip, shift); - candidate = base_ip + table[hash]; - assert(candidate >= base_ip); - assert(candidate < ip); - - table[hash] = ip - base_ip; - } while (SNAPPY_PREDICT_TRUE(UNALIGNED_LOAD32(ip) != - UNALIGNED_LOAD32(candidate))); - - // Step 2: A 4-byte match has been found. We'll later see if more - // than 4 bytes match. But, prior to the match, input - // bytes [next_emit, ip) are unmatched. Emit them as "literal bytes." - assert(next_emit + 16 <= ip_end); - op = EmitLiteral(op, next_emit, ip - next_emit, true); - - // Step 3: Call EmitCopy, and then see if another EmitCopy could - // be our next move. Repeat until we find no match for the - // input immediately after what was consumed by the last EmitCopy call. - // - // If we exit this loop normally then we need to call EmitLiteral next, - // though we don't yet know how big the literal will be. We handle that - // by proceeding to the next iteration of the main loop. We also can exit - // this loop via goto if we get close to exhausting the input. - EightBytesReference input_bytes; - uint32 candidate_bytes = 0; - - do { - // We have a 4-byte match at ip, and no need to emit any - // "literal bytes" prior to ip. - const char* base = ip; - std::pair p = - FindMatchLength(candidate + 4, ip + 4, ip_end); - size_t matched = 4 + p.first; - ip += matched; - size_t offset = base - candidate; - assert(0 == memcmp(base, candidate, matched)); - op = EmitCopy(op, offset, matched, p.second); - next_emit = ip; - if (SNAPPY_PREDICT_FALSE(ip >= ip_limit)) { - goto emit_remainder; - } - // We are now looking for a 4-byte match again. We read - // table[Hash(ip, shift)] for that. To improve compression, - // we also update table[Hash(ip - 1, shift)] and table[Hash(ip, shift)]. - input_bytes = GetEightBytesAt(ip - 1); - uint32 prev_hash = HashBytes(GetUint32AtOffset(input_bytes, 0), shift); - table[prev_hash] = ip - base_ip - 1; - uint32 cur_hash = HashBytes(GetUint32AtOffset(input_bytes, 1), shift); - candidate = base_ip + table[cur_hash]; - candidate_bytes = UNALIGNED_LOAD32(candidate); - table[cur_hash] = ip - base_ip; - } while (GetUint32AtOffset(input_bytes, 1) == candidate_bytes); - - next_hash = HashBytes(GetUint32AtOffset(input_bytes, 2), shift); - ++ip; - } - } - - emit_remainder: - // Emit the remaining bytes as a literal - if (next_emit < ip_end) { - op = EmitLiteral(op, next_emit, ip_end - next_emit, false); - } - - return op; -} -} // end namespace internal - -// Called back at avery compression call to trace parameters and sizes. -static inline void Report(const char *algorithm, size_t compressed_size, - size_t uncompressed_size) {} - -// Signature of output types needed by decompression code. -// The decompression code is templatized on a type that obeys this -// signature so that we do not pay virtual function call overhead in -// the middle of a tight decompression loop. -// -// class DecompressionWriter { -// public: -// // Called before decompression -// void SetExpectedLength(size_t length); -// -// // Called after decompression -// bool CheckLength() const; -// -// // Called repeatedly during decompression -// bool Append(const char* ip, size_t length); -// bool AppendFromSelf(uint32 offset, size_t length); -// -// // The rules for how TryFastAppend differs from Append are somewhat -// // convoluted: -// // -// // - TryFastAppend is allowed to decline (return false) at any -// // time, for any reason -- just "return false" would be -// // a perfectly legal implementation of TryFastAppend. -// // The intention is for TryFastAppend to allow a fast path -// // in the common case of a small append. -// // - TryFastAppend is allowed to read up to bytes -// // from the input buffer, whereas Append is allowed to read -// // . However, if it returns true, it must leave -// // at least five (kMaximumTagLength) bytes in the input buffer -// // afterwards, so that there is always enough space to read the -// // next tag without checking for a refill. -// // - TryFastAppend must always return decline (return false) -// // if is 61 or more, as in this case the literal length is not -// // decoded fully. In practice, this should not be a big problem, -// // as it is unlikely that one would implement a fast path accepting -// // this much data. -// // -// bool TryFastAppend(const char* ip, size_t available, size_t length); -// }; - -namespace internal { - -// Mapping from i in range [0,4] to a mask to extract the bottom 8*i bits -static const uint32 wordmask[] = { - 0u, 0xffu, 0xffffu, 0xffffffu, 0xffffffffu -}; - -} // end namespace internal - -// Helper class for decompression -class SnappyDecompressor { - private: - Source* reader_; // Underlying source of bytes to decompress - const char* ip_; // Points to next buffered byte - const char* ip_limit_; // Points just past buffered bytes - uint32 peeked_; // Bytes peeked from reader (need to skip) - bool eof_; // Hit end of input without an error? - char scratch_[kMaximumTagLength]; // See RefillTag(). - - // Ensure that all of the tag metadata for the next tag is available - // in [ip_..ip_limit_-1]. Also ensures that [ip,ip+4] is readable even - // if (ip_limit_ - ip_ < 5). - // - // Returns true on success, false on error or end of input. - bool RefillTag(); - - public: - explicit SnappyDecompressor(Source* reader) - : reader_(reader), - ip_(NULL), - ip_limit_(NULL), - peeked_(0), - eof_(false) { - } - - ~SnappyDecompressor() { - // Advance past any bytes we peeked at from the reader - reader_->Skip(peeked_); - } - - // Returns true iff we have hit the end of the input without an error. - bool eof() const { - return eof_; - } - - // Read the uncompressed length stored at the start of the compressed data. - // On succcess, stores the length in *result and returns true. - // On failure, returns false. - bool ReadUncompressedLength(uint32* result) { - assert(ip_ == NULL); // Must not have read anything yet - // Length is encoded in 1..5 bytes - *result = 0; - uint32 shift = 0; - while (true) { - if (shift >= 32) return false; - size_t n; - const char* ip = reader_->Peek(&n); - if (n == 0) return false; - const unsigned char c = *(reinterpret_cast(ip)); - reader_->Skip(1); - uint32 val = c & 0x7f; - if (((val << shift) >> shift) != val) return false; - *result |= val << shift; - if (c < 128) { - break; - } - shift += 7; - } - return true; - } - - // Process the next item found in the input. - // Returns true if successful, false on error or end of input. - template - void DecompressAllTags(Writer* writer) { - const char* ip = ip_; - // For position-independent executables, accessing global arrays can be - // slow. Move wordmask array onto the stack to mitigate this. - uint32 wordmask[sizeof(internal::wordmask)/sizeof(uint32)]; - // Do not use memcpy to copy internal::wordmask to - // wordmask. LLVM converts stack arrays to global arrays if it detects - // const stack arrays and this hurts the performance of position - // independent code. This change is temporary and can be reverted when - // https://reviews.llvm.org/D30759 is approved. - wordmask[0] = internal::wordmask[0]; - wordmask[1] = internal::wordmask[1]; - wordmask[2] = internal::wordmask[2]; - wordmask[3] = internal::wordmask[3]; - wordmask[4] = internal::wordmask[4]; - - // We could have put this refill fragment only at the beginning of the loop. - // However, duplicating it at the end of each branch gives the compiler more - // scope to optimize the expression based on the local - // context, which overall increases speed. - #define MAYBE_REFILL() \ - if (ip_limit_ - ip < kMaximumTagLength) { \ - ip_ = ip; \ - if (!RefillTag()) return; \ - ip = ip_; \ - } - - MAYBE_REFILL(); - // Add loop alignment directive. Without this directive, we observed - // significant performance degradation on several intel architectures - // in snappy benchmark built with LLVM. The degradation was caused by - // increased branch miss prediction. -#if defined(__clang__) && defined(__x86_64__) - asm volatile (".p2align 5"); -#endif - for ( ;; ) { - const unsigned char c = *(reinterpret_cast(ip++)); - - // Ratio of iterations that have LITERAL vs non-LITERAL for different - // inputs. - // - // input LITERAL NON_LITERAL - // ----------------------------------- - // html|html4|cp 23% 77% - // urls 36% 64% - // jpg 47% 53% - // pdf 19% 81% - // txt[1-4] 25% 75% - // pb 24% 76% - // bin 24% 76% - if (SNAPPY_PREDICT_FALSE((c & 0x3) == LITERAL)) { - size_t literal_length = (c >> 2) + 1u; - if (writer->TryFastAppend(ip, ip_limit_ - ip, literal_length)) { - assert(literal_length < 61); - ip += literal_length; - // NOTE(user): There is no MAYBE_REFILL() here, as TryFastAppend() - // will not return true unless there's already at least five spare - // bytes in addition to the literal. - continue; - } - if (SNAPPY_PREDICT_FALSE(literal_length >= 61)) { - // Long literal. - const size_t literal_length_length = literal_length - 60; - literal_length = - (LittleEndian::Load32(ip) & wordmask[literal_length_length]) + 1; - ip += literal_length_length; - } - - size_t avail = ip_limit_ - ip; - while (avail < literal_length) { - if (!writer->Append(ip, avail)) return; - literal_length -= avail; - reader_->Skip(peeked_); - size_t n; - ip = reader_->Peek(&n); - avail = n; - peeked_ = avail; - if (avail == 0) return; // Premature end of input - ip_limit_ = ip + avail; - } - if (!writer->Append(ip, literal_length)) { - return; - } - ip += literal_length; - MAYBE_REFILL(); - } else { - const size_t entry = char_table[c]; - const size_t trailer = LittleEndian::Load32(ip) & wordmask[entry >> 11]; - const size_t length = entry & 0xff; - ip += entry >> 11; - - // copy_offset/256 is encoded in bits 8..10. By just fetching - // those bits, we get copy_offset (since the bit-field starts at - // bit 8). - const size_t copy_offset = entry & 0x700; - if (!writer->AppendFromSelf(copy_offset + trailer, length)) { - return; - } - MAYBE_REFILL(); - } - } - -#undef MAYBE_REFILL - } -}; - -bool SnappyDecompressor::RefillTag() { - const char* ip = ip_; - if (ip == ip_limit_) { - // Fetch a new fragment from the reader - reader_->Skip(peeked_); // All peeked bytes are used up - size_t n; - ip = reader_->Peek(&n); - peeked_ = n; - eof_ = (n == 0); - if (eof_) return false; - ip_limit_ = ip + n; - } - - // Read the tag character - assert(ip < ip_limit_); - const unsigned char c = *(reinterpret_cast(ip)); - const uint32 entry = char_table[c]; - const uint32 needed = (entry >> 11) + 1; // +1 byte for 'c' - assert(needed <= sizeof(scratch_)); - - // Read more bytes from reader if needed - uint32 nbuf = ip_limit_ - ip; - if (nbuf < needed) { - // Stitch together bytes from ip and reader to form the word - // contents. We store the needed bytes in "scratch_". They - // will be consumed immediately by the caller since we do not - // read more than we need. - memmove(scratch_, ip, nbuf); - reader_->Skip(peeked_); // All peeked bytes are used up - peeked_ = 0; - while (nbuf < needed) { - size_t length; - const char* src = reader_->Peek(&length); - if (length == 0) return false; - uint32 to_add = std::min(needed - nbuf, length); - memcpy(scratch_ + nbuf, src, to_add); - nbuf += to_add; - reader_->Skip(to_add); - } - assert(nbuf == needed); - ip_ = scratch_; - ip_limit_ = scratch_ + needed; - } else if (nbuf < kMaximumTagLength) { - // Have enough bytes, but move into scratch_ so that we do not - // read past end of input - memmove(scratch_, ip, nbuf); - reader_->Skip(peeked_); // All peeked bytes are used up - peeked_ = 0; - ip_ = scratch_; - ip_limit_ = scratch_ + nbuf; - } else { - // Pass pointer to buffer returned by reader_. - ip_ = ip; - } - return true; -} - -template -static bool InternalUncompress(Source* r, Writer* writer) { - // Read the uncompressed length from the front of the compressed input - SnappyDecompressor decompressor(r); - uint32 uncompressed_len = 0; - if (!decompressor.ReadUncompressedLength(&uncompressed_len)) return false; - - return InternalUncompressAllTags(&decompressor, writer, r->Available(), - uncompressed_len); -} - -template -static bool InternalUncompressAllTags(SnappyDecompressor* decompressor, - Writer* writer, - uint32 compressed_len, - uint32 uncompressed_len) { - Report("snappy_uncompress", compressed_len, uncompressed_len); - - writer->SetExpectedLength(uncompressed_len); - - // Process the entire input - decompressor->DecompressAllTags(writer); - writer->Flush(); - return (decompressor->eof() && writer->CheckLength()); -} - -bool GetUncompressedLength(Source* source, uint32* result) { - SnappyDecompressor decompressor(source); - return decompressor.ReadUncompressedLength(result); -} - -size_t Compress(Source* reader, Sink* writer) { - size_t written = 0; - size_t N = reader->Available(); - const size_t uncompressed_size = N; - char ulength[Varint::kMax32]; - char* p = Varint::Encode32(ulength, N); - writer->Append(ulength, p-ulength); - written += (p - ulength); - - internal::WorkingMemory wmem; - char* scratch = NULL; - char* scratch_output = NULL; - - while (N > 0) { - // Get next block to compress (without copying if possible) - size_t fragment_size; - const char* fragment = reader->Peek(&fragment_size); - assert(fragment_size != 0); // premature end of input - const size_t num_to_read = std::min(N, kBlockSize); - size_t bytes_read = fragment_size; - - size_t pending_advance = 0; - if (bytes_read >= num_to_read) { - // Buffer returned by reader is large enough - pending_advance = num_to_read; - fragment_size = num_to_read; - } else { - // Read into scratch buffer - if (scratch == NULL) { - // If this is the last iteration, we want to allocate N bytes - // of space, otherwise the max possible kBlockSize space. - // num_to_read contains exactly the correct value - scratch = new char[num_to_read]; - } - memcpy(scratch, fragment, bytes_read); - reader->Skip(bytes_read); - - while (bytes_read < num_to_read) { - fragment = reader->Peek(&fragment_size); - size_t n = std::min(fragment_size, num_to_read - bytes_read); - memcpy(scratch + bytes_read, fragment, n); - bytes_read += n; - reader->Skip(n); - } - assert(bytes_read == num_to_read); - fragment = scratch; - fragment_size = num_to_read; - } - assert(fragment_size == num_to_read); - - // Get encoding table for compression - int table_size; - uint16* table = wmem.GetHashTable(num_to_read, &table_size); - - // Compress input_fragment and append to dest - const int max_output = MaxCompressedLength(num_to_read); - - // Need a scratch buffer for the output, in case the byte sink doesn't - // have room for us directly. - if (scratch_output == NULL) { - scratch_output = new char[max_output]; - } else { - // Since we encode kBlockSize regions followed by a region - // which is <= kBlockSize in length, a previously allocated - // scratch_output[] region is big enough for this iteration. - } - char* dest = writer->GetAppendBuffer(max_output, scratch_output); - char* end = internal::CompressFragment(fragment, fragment_size, - dest, table, table_size); - writer->Append(dest, end - dest); - written += (end - dest); - - N -= num_to_read; - reader->Skip(pending_advance); - } - - Report("snappy_compress", written, uncompressed_size); - - delete[] scratch; - delete[] scratch_output; - - return written; -} - -// ----------------------------------------------------------------------- -// IOVec interfaces -// ----------------------------------------------------------------------- - -// A type that writes to an iovec. -// Note that this is not a "ByteSink", but a type that matches the -// Writer template argument to SnappyDecompressor::DecompressAllTags(). -class SnappyIOVecWriter { - private: - const struct iovec* output_iov_; - const size_t output_iov_count_; - - // We are currently writing into output_iov_[curr_iov_index_]. - size_t curr_iov_index_; - - // Bytes written to output_iov_[curr_iov_index_] so far. - size_t curr_iov_written_; - - // Total bytes decompressed into output_iov_ so far. - size_t total_written_; - - // Maximum number of bytes that will be decompressed into output_iov_. - size_t output_limit_; - - inline char* GetIOVecPointer(size_t index, size_t offset) { - return reinterpret_cast(output_iov_[index].iov_base) + - offset; - } - - public: - // Does not take ownership of iov. iov must be valid during the - // entire lifetime of the SnappyIOVecWriter. - inline SnappyIOVecWriter(const struct iovec* iov, size_t iov_count) - : output_iov_(iov), - output_iov_count_(iov_count), - curr_iov_index_(0), - curr_iov_written_(0), - total_written_(0), - output_limit_(-1) { - } - - inline void SetExpectedLength(size_t len) { - output_limit_ = len; - } - - inline bool CheckLength() const { - return total_written_ == output_limit_; - } - - inline bool Append(const char* ip, size_t len) { - if (total_written_ + len > output_limit_) { - return false; - } - - while (len > 0) { - assert(curr_iov_written_ <= output_iov_[curr_iov_index_].iov_len); - if (curr_iov_written_ >= output_iov_[curr_iov_index_].iov_len) { - // This iovec is full. Go to the next one. - if (curr_iov_index_ + 1 >= output_iov_count_) { - return false; - } - curr_iov_written_ = 0; - ++curr_iov_index_; - } - - const size_t to_write = std::min( - len, output_iov_[curr_iov_index_].iov_len - curr_iov_written_); - memcpy(GetIOVecPointer(curr_iov_index_, curr_iov_written_), - ip, - to_write); - curr_iov_written_ += to_write; - total_written_ += to_write; - ip += to_write; - len -= to_write; - } - - return true; - } - - inline bool TryFastAppend(const char* ip, size_t available, size_t len) { - const size_t space_left = output_limit_ - total_written_; - if (len <= 16 && available >= 16 + kMaximumTagLength && space_left >= 16 && - output_iov_[curr_iov_index_].iov_len - curr_iov_written_ >= 16) { - // Fast path, used for the majority (about 95%) of invocations. - char* ptr = GetIOVecPointer(curr_iov_index_, curr_iov_written_); - UnalignedCopy128(ip, ptr); - curr_iov_written_ += len; - total_written_ += len; - return true; - } - - return false; - } - - inline bool AppendFromSelf(size_t offset, size_t len) { - if (offset > total_written_ || offset == 0) { - return false; - } - const size_t space_left = output_limit_ - total_written_; - if (len > space_left) { - return false; - } - - // Locate the iovec from which we need to start the copy. - size_t from_iov_index = curr_iov_index_; - size_t from_iov_offset = curr_iov_written_; - while (offset > 0) { - if (from_iov_offset >= offset) { - from_iov_offset -= offset; - break; - } - - offset -= from_iov_offset; - assert(from_iov_index > 0); - --from_iov_index; - from_iov_offset = output_iov_[from_iov_index].iov_len; - } - - // Copy bytes starting from the iovec pointed to by from_iov_index to - // the current iovec. - while (len > 0) { - assert(from_iov_index <= curr_iov_index_); - if (from_iov_index != curr_iov_index_) { - const size_t to_copy = std::min( - output_iov_[from_iov_index].iov_len - from_iov_offset, - len); - Append(GetIOVecPointer(from_iov_index, from_iov_offset), to_copy); - len -= to_copy; - if (len > 0) { - ++from_iov_index; - from_iov_offset = 0; - } - } else { - assert(curr_iov_written_ <= output_iov_[curr_iov_index_].iov_len); - size_t to_copy = std::min(output_iov_[curr_iov_index_].iov_len - - curr_iov_written_, - len); - if (to_copy == 0) { - // This iovec is full. Go to the next one. - if (curr_iov_index_ + 1 >= output_iov_count_) { - return false; - } - ++curr_iov_index_; - curr_iov_written_ = 0; - continue; - } - if (to_copy > len) { - to_copy = len; - } - IncrementalCopySlow( - GetIOVecPointer(from_iov_index, from_iov_offset), - GetIOVecPointer(curr_iov_index_, curr_iov_written_), - GetIOVecPointer(curr_iov_index_, curr_iov_written_) + to_copy); - curr_iov_written_ += to_copy; - from_iov_offset += to_copy; - total_written_ += to_copy; - len -= to_copy; - } - } - - return true; - } - - inline void Flush() {} -}; - -bool RawUncompressToIOVec(const char* compressed, size_t compressed_length, - const struct iovec* iov, size_t iov_cnt) { - ByteArraySource reader(compressed, compressed_length); - return RawUncompressToIOVec(&reader, iov, iov_cnt); -} - -bool RawUncompressToIOVec(Source* compressed, const struct iovec* iov, - size_t iov_cnt) { - SnappyIOVecWriter output(iov, iov_cnt); - return InternalUncompress(compressed, &output); -} - -// ----------------------------------------------------------------------- -// Flat array interfaces -// ----------------------------------------------------------------------- - -// A type that writes to a flat array. -// Note that this is not a "ByteSink", but a type that matches the -// Writer template argument to SnappyDecompressor::DecompressAllTags(). -class SnappyArrayWriter { - private: - char* base_; - char* op_; - char* op_limit_; - - public: - inline explicit SnappyArrayWriter(char* dst) - : base_(dst), - op_(dst), - op_limit_(dst) { - } - - inline void SetExpectedLength(size_t len) { - op_limit_ = op_ + len; - } - - inline bool CheckLength() const { - return op_ == op_limit_; - } - - inline bool Append(const char* ip, size_t len) { - char* op = op_; - const size_t space_left = op_limit_ - op; - if (space_left < len) { - return false; - } - memcpy(op, ip, len); - op_ = op + len; - return true; - } - - inline bool TryFastAppend(const char* ip, size_t available, size_t len) { - char* op = op_; - const size_t space_left = op_limit_ - op; - if (len <= 16 && available >= 16 + kMaximumTagLength && space_left >= 16) { - // Fast path, used for the majority (about 95%) of invocations. - UnalignedCopy128(ip, op); - op_ = op + len; - return true; - } else { - return false; - } - } - - inline bool AppendFromSelf(size_t offset, size_t len) { - char* const op_end = op_ + len; - - // Check if we try to append from before the start of the buffer. - // Normally this would just be a check for "produced < offset", - // but "produced <= offset - 1u" is equivalent for every case - // except the one where offset==0, where the right side will wrap around - // to a very big number. This is convenient, as offset==0 is another - // invalid case that we also want to catch, so that we do not go - // into an infinite loop. - if (Produced() <= offset - 1u || op_end > op_limit_) return false; - op_ = IncrementalCopy(op_ - offset, op_, op_end, op_limit_); - - return true; - } - inline size_t Produced() const { - assert(op_ >= base_); - return op_ - base_; - } - inline void Flush() {} -}; - -bool RawUncompress(const char* compressed, size_t n, char* uncompressed) { - ByteArraySource reader(compressed, n); - return RawUncompress(&reader, uncompressed); -} - -bool RawUncompress(Source* compressed, char* uncompressed) { - SnappyArrayWriter output(uncompressed); - return InternalUncompress(compressed, &output); -} - -bool Uncompress(const char* compressed, size_t n, string* uncompressed) { - size_t ulength; - if (!GetUncompressedLength(compressed, n, &ulength)) { - return false; - } - // On 32-bit builds: max_size() < kuint32max. Check for that instead - // of crashing (e.g., consider externally specified compressed data). - if (ulength > uncompressed->max_size()) { - return false; - } - STLStringResizeUninitialized(uncompressed, ulength); - return RawUncompress(compressed, n, string_as_array(uncompressed)); -} - -// A Writer that drops everything on the floor and just does validation -class SnappyDecompressionValidator { - private: - size_t expected_; - size_t produced_; - - public: - inline SnappyDecompressionValidator() : expected_(0), produced_(0) { } - inline void SetExpectedLength(size_t len) { - expected_ = len; - } - inline bool CheckLength() const { - return expected_ == produced_; - } - inline bool Append(const char* ip, size_t len) { - produced_ += len; - return produced_ <= expected_; - } - inline bool TryFastAppend(const char* ip, size_t available, size_t length) { - return false; - } - inline bool AppendFromSelf(size_t offset, size_t len) { - // See SnappyArrayWriter::AppendFromSelf for an explanation of - // the "offset - 1u" trick. - if (produced_ <= offset - 1u) return false; - produced_ += len; - return produced_ <= expected_; - } - inline void Flush() {} -}; - -bool IsValidCompressedBuffer(const char* compressed, size_t n) { - ByteArraySource reader(compressed, n); - SnappyDecompressionValidator writer; - return InternalUncompress(&reader, &writer); -} - -bool IsValidCompressed(Source* compressed) { - SnappyDecompressionValidator writer; - return InternalUncompress(compressed, &writer); -} - -void RawCompress(const char* input, - size_t input_length, - char* compressed, - size_t* compressed_length) { - ByteArraySource reader(input, input_length); - UncheckedByteArraySink writer(compressed); - Compress(&reader, &writer); - - // Compute how many bytes were added - *compressed_length = (writer.CurrentDestination() - compressed); -} - -size_t Compress(const char* input, size_t input_length, string* compressed) { - // Pre-grow the buffer to the max length of the compressed output - STLStringResizeUninitialized(compressed, MaxCompressedLength(input_length)); - - size_t compressed_length; - RawCompress(input, input_length, string_as_array(compressed), - &compressed_length); - compressed->resize(compressed_length); - return compressed_length; -} - -// ----------------------------------------------------------------------- -// Sink interface -// ----------------------------------------------------------------------- - -// A type that decompresses into a Sink. The template parameter -// Allocator must export one method "char* Allocate(int size);", which -// allocates a buffer of "size" and appends that to the destination. -template -class SnappyScatteredWriter { - Allocator allocator_; - - // We need random access into the data generated so far. Therefore - // we keep track of all of the generated data as an array of blocks. - // All of the blocks except the last have length kBlockSize. - std::vector blocks_; - size_t expected_; - - // Total size of all fully generated blocks so far - size_t full_size_; - - // Pointer into current output block - char* op_base_; // Base of output block - char* op_ptr_; // Pointer to next unfilled byte in block - char* op_limit_; // Pointer just past block - - inline size_t Size() const { - return full_size_ + (op_ptr_ - op_base_); - } - - bool SlowAppend(const char* ip, size_t len); - bool SlowAppendFromSelf(size_t offset, size_t len); - - public: - inline explicit SnappyScatteredWriter(const Allocator& allocator) - : allocator_(allocator), - full_size_(0), - op_base_(NULL), - op_ptr_(NULL), - op_limit_(NULL) { - } - - inline void SetExpectedLength(size_t len) { - assert(blocks_.empty()); - expected_ = len; - } - - inline bool CheckLength() const { - return Size() == expected_; - } - - // Return the number of bytes actually uncompressed so far - inline size_t Produced() const { - return Size(); - } - - inline bool Append(const char* ip, size_t len) { - size_t avail = op_limit_ - op_ptr_; - if (len <= avail) { - // Fast path - memcpy(op_ptr_, ip, len); - op_ptr_ += len; - return true; - } else { - return SlowAppend(ip, len); - } - } - - inline bool TryFastAppend(const char* ip, size_t available, size_t length) { - char* op = op_ptr_; - const int space_left = op_limit_ - op; - if (length <= 16 && available >= 16 + kMaximumTagLength && - space_left >= 16) { - // Fast path, used for the majority (about 95%) of invocations. - UnalignedCopy128(ip, op); - op_ptr_ = op + length; - return true; - } else { - return false; - } - } - - inline bool AppendFromSelf(size_t offset, size_t len) { - char* const op_end = op_ptr_ + len; - // See SnappyArrayWriter::AppendFromSelf for an explanation of - // the "offset - 1u" trick. - if (SNAPPY_PREDICT_TRUE(offset - 1u < op_ptr_ - op_base_ && - op_end <= op_limit_)) { - // Fast path: src and dst in current block. - op_ptr_ = IncrementalCopy(op_ptr_ - offset, op_ptr_, op_end, op_limit_); - return true; - } - return SlowAppendFromSelf(offset, len); - } - - // Called at the end of the decompress. We ask the allocator - // write all blocks to the sink. - inline void Flush() { allocator_.Flush(Produced()); } -}; - -template -bool SnappyScatteredWriter::SlowAppend(const char* ip, size_t len) { - size_t avail = op_limit_ - op_ptr_; - while (len > avail) { - // Completely fill this block - memcpy(op_ptr_, ip, avail); - op_ptr_ += avail; - assert(op_limit_ - op_ptr_ == 0); - full_size_ += (op_ptr_ - op_base_); - len -= avail; - ip += avail; - - // Bounds check - if (full_size_ + len > expected_) { - return false; - } - - // Make new block - size_t bsize = std::min(kBlockSize, expected_ - full_size_); - op_base_ = allocator_.Allocate(bsize); - op_ptr_ = op_base_; - op_limit_ = op_base_ + bsize; - blocks_.push_back(op_base_); - avail = bsize; - } - - memcpy(op_ptr_, ip, len); - op_ptr_ += len; - return true; -} - -template -bool SnappyScatteredWriter::SlowAppendFromSelf(size_t offset, - size_t len) { - // Overflow check - // See SnappyArrayWriter::AppendFromSelf for an explanation of - // the "offset - 1u" trick. - const size_t cur = Size(); - if (offset - 1u >= cur) return false; - if (expected_ - cur < len) return false; - - // Currently we shouldn't ever hit this path because Compress() chops the - // input into blocks and does not create cross-block copies. However, it is - // nice if we do not rely on that, since we can get better compression if we - // allow cross-block copies and thus might want to change the compressor in - // the future. - size_t src = cur - offset; - while (len-- > 0) { - char c = blocks_[src >> kBlockLog][src & (kBlockSize-1)]; - Append(&c, 1); - src++; - } - return true; -} - -class SnappySinkAllocator { - public: - explicit SnappySinkAllocator(Sink* dest): dest_(dest) {} - ~SnappySinkAllocator() {} - - char* Allocate(int size) { - Datablock block(new char[size], size); - blocks_.push_back(block); - return block.data; - } - - // We flush only at the end, because the writer wants - // random access to the blocks and once we hand the - // block over to the sink, we can't access it anymore. - // Also we don't write more than has been actually written - // to the blocks. - void Flush(size_t size) { - size_t size_written = 0; - size_t block_size; - for (int i = 0; i < blocks_.size(); ++i) { - block_size = std::min(blocks_[i].size, size - size_written); - dest_->AppendAndTakeOwnership(blocks_[i].data, block_size, - &SnappySinkAllocator::Deleter, NULL); - size_written += block_size; - } - blocks_.clear(); - } - - private: - struct Datablock { - char* data; - size_t size; - Datablock(char* p, size_t s) : data(p), size(s) {} - }; - - static void Deleter(void* arg, const char* bytes, size_t size) { - delete[] bytes; - } - - Sink* dest_; - std::vector blocks_; - - // Note: copying this object is allowed -}; - -size_t UncompressAsMuchAsPossible(Source* compressed, Sink* uncompressed) { - SnappySinkAllocator allocator(uncompressed); - SnappyScatteredWriter writer(allocator); - InternalUncompress(compressed, &writer); - return writer.Produced(); -} - -bool Uncompress(Source* compressed, Sink* uncompressed) { - // Read the uncompressed length from the front of the compressed input - SnappyDecompressor decompressor(compressed); - uint32 uncompressed_len = 0; - if (!decompressor.ReadUncompressedLength(&uncompressed_len)) { - return false; - } - - char c; - size_t allocated_size; - char* buf = uncompressed->GetAppendBufferVariable( - 1, uncompressed_len, &c, 1, &allocated_size); - - const size_t compressed_len = compressed->Available(); - // If we can get a flat buffer, then use it, otherwise do block by block - // uncompression - if (allocated_size >= uncompressed_len) { - SnappyArrayWriter writer(buf); - bool result = InternalUncompressAllTags(&decompressor, &writer, - compressed_len, uncompressed_len); - uncompressed->Append(buf, writer.Produced()); - return result; - } else { - SnappySinkAllocator allocator(uncompressed); - SnappyScatteredWriter writer(allocator); - return InternalUncompressAllTags(&decompressor, &writer, compressed_len, - uncompressed_len); - } -} - -} // end namespace snappy diff --git a/src/snappy/snappy/snappy.h b/src/snappy/snappy/snappy.h deleted file mode 100644 index 4568db890d..0000000000 --- a/src/snappy/snappy/snappy.h +++ /dev/null @@ -1,203 +0,0 @@ -// Copyright 2005 and onwards Google Inc. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// A light-weight compression algorithm. It is designed for speed of -// compression and decompression, rather than for the utmost in space -// savings. -// -// For getting better compression ratios when you are compressing data -// with long repeated sequences or compressing data that is similar to -// other data, while still compressing fast, you might look at first -// using BMDiff and then compressing the output of BMDiff with -// Snappy. - -#ifndef THIRD_PARTY_SNAPPY_SNAPPY_H__ -#define THIRD_PARTY_SNAPPY_SNAPPY_H__ - -#include -#include - -#include "snappy-stubs-public.h" - -namespace snappy { - class Source; - class Sink; - - // ------------------------------------------------------------------------ - // Generic compression/decompression routines. - // ------------------------------------------------------------------------ - - // Compress the bytes read from "*source" and append to "*sink". Return the - // number of bytes written. - size_t Compress(Source* source, Sink* sink); - - // Find the uncompressed length of the given stream, as given by the header. - // Note that the true length could deviate from this; the stream could e.g. - // be truncated. - // - // Also note that this leaves "*source" in a state that is unsuitable for - // further operations, such as RawUncompress(). You will need to rewind - // or recreate the source yourself before attempting any further calls. - bool GetUncompressedLength(Source* source, uint32* result); - - // ------------------------------------------------------------------------ - // Higher-level string based routines (should be sufficient for most users) - // ------------------------------------------------------------------------ - - // Sets "*output" to the compressed version of "input[0,input_length-1]". - // Original contents of *output are lost. - // - // REQUIRES: "input[]" is not an alias of "*output". - size_t Compress(const char* input, size_t input_length, string* output); - - // Decompresses "compressed[0,compressed_length-1]" to "*uncompressed". - // Original contents of "*uncompressed" are lost. - // - // REQUIRES: "compressed[]" is not an alias of "*uncompressed". - // - // returns false if the message is corrupted and could not be decompressed - bool Uncompress(const char* compressed, size_t compressed_length, - string* uncompressed); - - // Decompresses "compressed" to "*uncompressed". - // - // returns false if the message is corrupted and could not be decompressed - bool Uncompress(Source* compressed, Sink* uncompressed); - - // This routine uncompresses as much of the "compressed" as possible - // into sink. It returns the number of valid bytes added to sink - // (extra invalid bytes may have been added due to errors; the caller - // should ignore those). The emitted data typically has length - // GetUncompressedLength(), but may be shorter if an error is - // encountered. - size_t UncompressAsMuchAsPossible(Source* compressed, Sink* uncompressed); - - // ------------------------------------------------------------------------ - // Lower-level character array based routines. May be useful for - // efficiency reasons in certain circumstances. - // ------------------------------------------------------------------------ - - // REQUIRES: "compressed" must point to an area of memory that is at - // least "MaxCompressedLength(input_length)" bytes in length. - // - // Takes the data stored in "input[0..input_length]" and stores - // it in the array pointed to by "compressed". - // - // "*compressed_length" is set to the length of the compressed output. - // - // Example: - // char* output = new char[snappy::MaxCompressedLength(input_length)]; - // size_t output_length; - // RawCompress(input, input_length, output, &output_length); - // ... Process(output, output_length) ... - // delete [] output; - void RawCompress(const char* input, - size_t input_length, - char* compressed, - size_t* compressed_length); - - // Given data in "compressed[0..compressed_length-1]" generated by - // calling the Snappy::Compress routine, this routine - // stores the uncompressed data to - // uncompressed[0..GetUncompressedLength(compressed)-1] - // returns false if the message is corrupted and could not be decrypted - bool RawUncompress(const char* compressed, size_t compressed_length, - char* uncompressed); - - // Given data from the byte source 'compressed' generated by calling - // the Snappy::Compress routine, this routine stores the uncompressed - // data to - // uncompressed[0..GetUncompressedLength(compressed,compressed_length)-1] - // returns false if the message is corrupted and could not be decrypted - bool RawUncompress(Source* compressed, char* uncompressed); - - // Given data in "compressed[0..compressed_length-1]" generated by - // calling the Snappy::Compress routine, this routine - // stores the uncompressed data to the iovec "iov". The number of physical - // buffers in "iov" is given by iov_cnt and their cumulative size - // must be at least GetUncompressedLength(compressed). The individual buffers - // in "iov" must not overlap with each other. - // - // returns false if the message is corrupted and could not be decrypted - bool RawUncompressToIOVec(const char* compressed, size_t compressed_length, - const struct iovec* iov, size_t iov_cnt); - - // Given data from the byte source 'compressed' generated by calling - // the Snappy::Compress routine, this routine stores the uncompressed - // data to the iovec "iov". The number of physical - // buffers in "iov" is given by iov_cnt and their cumulative size - // must be at least GetUncompressedLength(compressed). The individual buffers - // in "iov" must not overlap with each other. - // - // returns false if the message is corrupted and could not be decrypted - bool RawUncompressToIOVec(Source* compressed, const struct iovec* iov, - size_t iov_cnt); - - // Returns the maximal size of the compressed representation of - // input data that is "source_bytes" bytes in length; - size_t MaxCompressedLength(size_t source_bytes); - - // REQUIRES: "compressed[]" was produced by RawCompress() or Compress() - // Returns true and stores the length of the uncompressed data in - // *result normally. Returns false on parsing error. - // This operation takes O(1) time. - bool GetUncompressedLength(const char* compressed, size_t compressed_length, - size_t* result); - - // Returns true iff the contents of "compressed[]" can be uncompressed - // successfully. Does not return the uncompressed data. Takes - // time proportional to compressed_length, but is usually at least - // a factor of four faster than actual decompression. - bool IsValidCompressedBuffer(const char* compressed, - size_t compressed_length); - - // Returns true iff the contents of "compressed" can be uncompressed - // successfully. Does not return the uncompressed data. Takes - // time proportional to *compressed length, but is usually at least - // a factor of four faster than actual decompression. - // On success, consumes all of *compressed. On failure, consumes an - // unspecified prefix of *compressed. - bool IsValidCompressed(Source* compressed); - - // The size of a compression block. Note that many parts of the compression - // code assumes that kBlockSize <= 65536; in particular, the hash table - // can only store 16-bit offsets, and EmitCopy() also assumes the offset - // is 65535 bytes or less. Note also that if you change this, it will - // affect the framing format (see framing_format.txt). - // - // Note that there might be older data around that is compressed with larger - // block sizes, so the decompression code should not rely on the - // non-existence of long backreferences. - static const int kBlockLog = 16; - static const size_t kBlockSize = 1 << kBlockLog; - - static const int kMaxHashTableBits = 14; - static const size_t kMaxHashTableSize = 1 << kMaxHashTableBits; -} // end namespace snappy - -#endif // THIRD_PARTY_SNAPPY_SNAPPY_H__ diff --git a/src/snappy/snappy/snappy_unittest.cc b/src/snappy/snappy/snappy_unittest.cc deleted file mode 100644 index fcb3261d20..0000000000 --- a/src/snappy/snappy/snappy_unittest.cc +++ /dev/null @@ -1,1410 +0,0 @@ -// Copyright 2005 and onwards Google Inc. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#include -#include - - -#include -#include -#include -#include - -#include "snappy.h" -#include "snappy-internal.h" -#include "snappy-test.h" -#include "snappy-sinksource.h" - -DEFINE_int32(start_len, -1, - "Starting prefix size for testing (-1: just full file contents)"); -DEFINE_int32(end_len, -1, - "Starting prefix size for testing (-1: just full file contents)"); -DEFINE_int32(bytes, 10485760, - "How many bytes to compress/uncompress per file for timing"); - -DEFINE_bool(zlib, false, - "Run zlib compression (http://www.zlib.net)"); -DEFINE_bool(lzo, false, - "Run LZO compression (http://www.oberhumer.com/opensource/lzo/)"); -DEFINE_bool(snappy, true, "Run snappy compression"); - -DEFINE_bool(write_compressed, false, - "Write compressed versions of each file to .comp"); -DEFINE_bool(write_uncompressed, false, - "Write uncompressed versions of each file to .uncomp"); - -DEFINE_bool(snappy_dump_decompression_table, false, - "If true, we print the decompression table during tests."); - -namespace snappy { - -#if defined(HAVE_FUNC_MMAP) && defined(HAVE_FUNC_SYSCONF) - -// To test against code that reads beyond its input, this class copies a -// string to a newly allocated group of pages, the last of which -// is made unreadable via mprotect. Note that we need to allocate the -// memory with mmap(), as POSIX allows mprotect() only on memory allocated -// with mmap(), and some malloc/posix_memalign implementations expect to -// be able to read previously allocated memory while doing heap allocations. -class DataEndingAtUnreadablePage { - public: - explicit DataEndingAtUnreadablePage(const string& s) { - const size_t page_size = sysconf(_SC_PAGESIZE); - const size_t size = s.size(); - // Round up space for string to a multiple of page_size. - size_t space_for_string = (size + page_size - 1) & ~(page_size - 1); - alloc_size_ = space_for_string + page_size; - mem_ = mmap(NULL, alloc_size_, - PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); - CHECK_NE(MAP_FAILED, mem_); - protected_page_ = reinterpret_cast(mem_) + space_for_string; - char* dst = protected_page_ - size; - memcpy(dst, s.data(), size); - data_ = dst; - size_ = size; - // Make guard page unreadable. - CHECK_EQ(0, mprotect(protected_page_, page_size, PROT_NONE)); - } - - ~DataEndingAtUnreadablePage() { - const size_t page_size = sysconf(_SC_PAGESIZE); - // Undo the mprotect. - CHECK_EQ(0, mprotect(protected_page_, page_size, PROT_READ|PROT_WRITE)); - CHECK_EQ(0, munmap(mem_, alloc_size_)); - } - - const char* data() const { return data_; } - size_t size() const { return size_; } - - private: - size_t alloc_size_; - void* mem_; - char* protected_page_; - const char* data_; - size_t size_; -}; - -#else // defined(HAVE_FUNC_MMAP) && defined(HAVE_FUNC_SYSCONF) - -// Fallback for systems without mmap. -typedef string DataEndingAtUnreadablePage; - -#endif - -enum CompressorType { - ZLIB, LZO, SNAPPY -}; - -const char* names[] = { - "ZLIB", "LZO", "SNAPPY" -}; - -static size_t MinimumRequiredOutputSpace(size_t input_size, - CompressorType comp) { - switch (comp) { -#ifdef ZLIB_VERSION - case ZLIB: - return ZLib::MinCompressbufSize(input_size); -#endif // ZLIB_VERSION - -#ifdef LZO_VERSION - case LZO: - return input_size + input_size/64 + 16 + 3; -#endif // LZO_VERSION - - case SNAPPY: - return snappy::MaxCompressedLength(input_size); - - default: - LOG(FATAL) << "Unknown compression type number " << comp; - return 0; - } -} - -// Returns true if we successfully compressed, false otherwise. -// -// If compressed_is_preallocated is set, do not resize the compressed buffer. -// This is typically what you want for a benchmark, in order to not spend -// time in the memory allocator. If you do set this flag, however, -// "compressed" must be preinitialized to at least MinCompressbufSize(comp) -// number of bytes, and may contain junk bytes at the end after return. -static bool Compress(const char* input, size_t input_size, CompressorType comp, - string* compressed, bool compressed_is_preallocated) { - if (!compressed_is_preallocated) { - compressed->resize(MinimumRequiredOutputSpace(input_size, comp)); - } - - switch (comp) { -#ifdef ZLIB_VERSION - case ZLIB: { - ZLib zlib; - uLongf destlen = compressed->size(); - int ret = zlib.Compress( - reinterpret_cast(string_as_array(compressed)), - &destlen, - reinterpret_cast(input), - input_size); - CHECK_EQ(Z_OK, ret); - if (!compressed_is_preallocated) { - compressed->resize(destlen); - } - return true; - } -#endif // ZLIB_VERSION - -#ifdef LZO_VERSION - case LZO: { - unsigned char* mem = new unsigned char[LZO1X_1_15_MEM_COMPRESS]; - lzo_uint destlen; - int ret = lzo1x_1_15_compress( - reinterpret_cast(input), - input_size, - reinterpret_cast(string_as_array(compressed)), - &destlen, - mem); - CHECK_EQ(LZO_E_OK, ret); - delete[] mem; - if (!compressed_is_preallocated) { - compressed->resize(destlen); - } - break; - } -#endif // LZO_VERSION - - case SNAPPY: { - size_t destlen; - snappy::RawCompress(input, input_size, - string_as_array(compressed), - &destlen); - CHECK_LE(destlen, snappy::MaxCompressedLength(input_size)); - if (!compressed_is_preallocated) { - compressed->resize(destlen); - } - break; - } - - default: { - return false; // the asked-for library wasn't compiled in - } - } - return true; -} - -static bool Uncompress(const string& compressed, CompressorType comp, - int size, string* output) { - switch (comp) { -#ifdef ZLIB_VERSION - case ZLIB: { - output->resize(size); - ZLib zlib; - uLongf destlen = output->size(); - int ret = zlib.Uncompress( - reinterpret_cast(string_as_array(output)), - &destlen, - reinterpret_cast(compressed.data()), - compressed.size()); - CHECK_EQ(Z_OK, ret); - CHECK_EQ(static_cast(size), destlen); - break; - } -#endif // ZLIB_VERSION - -#ifdef LZO_VERSION - case LZO: { - output->resize(size); - lzo_uint destlen; - int ret = lzo1x_decompress( - reinterpret_cast(compressed.data()), - compressed.size(), - reinterpret_cast(string_as_array(output)), - &destlen, - NULL); - CHECK_EQ(LZO_E_OK, ret); - CHECK_EQ(static_cast(size), destlen); - break; - } -#endif // LZO_VERSION - - case SNAPPY: { - snappy::RawUncompress(compressed.data(), compressed.size(), - string_as_array(output)); - break; - } - - default: { - return false; // the asked-for library wasn't compiled in - } - } - return true; -} - -static void Measure(const char* data, - size_t length, - CompressorType comp, - int repeats, - int block_size) { - // Run tests a few time and pick median running times - static const int kRuns = 5; - double ctime[kRuns]; - double utime[kRuns]; - int compressed_size = 0; - - { - // Chop the input into blocks - int num_blocks = (length + block_size - 1) / block_size; - std::vector input(num_blocks); - std::vector input_length(num_blocks); - std::vector compressed(num_blocks); - std::vector output(num_blocks); - for (int b = 0; b < num_blocks; b++) { - int input_start = b * block_size; - int input_limit = std::min((b+1)*block_size, length); - input[b] = data+input_start; - input_length[b] = input_limit-input_start; - - // Pre-grow the output buffer so we don't measure string append time. - compressed[b].resize(MinimumRequiredOutputSpace(block_size, comp)); - } - - // First, try one trial compression to make sure the code is compiled in - if (!Compress(input[0], input_length[0], comp, &compressed[0], true)) { - LOG(WARNING) << "Skipping " << names[comp] << ": " - << "library not compiled in"; - return; - } - - for (int run = 0; run < kRuns; run++) { - CycleTimer ctimer, utimer; - - for (int b = 0; b < num_blocks; b++) { - // Pre-grow the output buffer so we don't measure string append time. - compressed[b].resize(MinimumRequiredOutputSpace(block_size, comp)); - } - - ctimer.Start(); - for (int b = 0; b < num_blocks; b++) - for (int i = 0; i < repeats; i++) - Compress(input[b], input_length[b], comp, &compressed[b], true); - ctimer.Stop(); - - // Compress once more, with resizing, so we don't leave junk - // at the end that will confuse the decompressor. - for (int b = 0; b < num_blocks; b++) { - Compress(input[b], input_length[b], comp, &compressed[b], false); - } - - for (int b = 0; b < num_blocks; b++) { - output[b].resize(input_length[b]); - } - - utimer.Start(); - for (int i = 0; i < repeats; i++) - for (int b = 0; b < num_blocks; b++) - Uncompress(compressed[b], comp, input_length[b], &output[b]); - utimer.Stop(); - - ctime[run] = ctimer.Get(); - utime[run] = utimer.Get(); - } - - compressed_size = 0; - for (size_t i = 0; i < compressed.size(); i++) { - compressed_size += compressed[i].size(); - } - } - - std::sort(ctime, ctime + kRuns); - std::sort(utime, utime + kRuns); - const int med = kRuns/2; - - float comp_rate = (length / ctime[med]) * repeats / 1048576.0; - float uncomp_rate = (length / utime[med]) * repeats / 1048576.0; - string x = names[comp]; - x += ":"; - string urate = (uncomp_rate >= 0) - ? StringPrintf("%.1f", uncomp_rate) - : string("?"); - printf("%-7s [b %dM] bytes %6d -> %6d %4.1f%% " - "comp %5.1f MB/s uncomp %5s MB/s\n", - x.c_str(), - block_size/(1<<20), - static_cast(length), static_cast(compressed_size), - (compressed_size * 100.0) / std::max(1, length), - comp_rate, - urate.c_str()); -} - -static int VerifyString(const string& input) { - string compressed; - DataEndingAtUnreadablePage i(input); - const size_t written = snappy::Compress(i.data(), i.size(), &compressed); - CHECK_EQ(written, compressed.size()); - CHECK_LE(compressed.size(), - snappy::MaxCompressedLength(input.size())); - CHECK(snappy::IsValidCompressedBuffer(compressed.data(), compressed.size())); - - string uncompressed; - DataEndingAtUnreadablePage c(compressed); - CHECK(snappy::Uncompress(c.data(), c.size(), &uncompressed)); - CHECK_EQ(uncompressed, input); - return uncompressed.size(); -} - -static void VerifyStringSink(const string& input) { - string compressed; - DataEndingAtUnreadablePage i(input); - const size_t written = snappy::Compress(i.data(), i.size(), &compressed); - CHECK_EQ(written, compressed.size()); - CHECK_LE(compressed.size(), - snappy::MaxCompressedLength(input.size())); - CHECK(snappy::IsValidCompressedBuffer(compressed.data(), compressed.size())); - - string uncompressed; - uncompressed.resize(input.size()); - snappy::UncheckedByteArraySink sink(string_as_array(&uncompressed)); - DataEndingAtUnreadablePage c(compressed); - snappy::ByteArraySource source(c.data(), c.size()); - CHECK(snappy::Uncompress(&source, &sink)); - CHECK_EQ(uncompressed, input); -} - -static void VerifyIOVec(const string& input) { - string compressed; - DataEndingAtUnreadablePage i(input); - const size_t written = snappy::Compress(i.data(), i.size(), &compressed); - CHECK_EQ(written, compressed.size()); - CHECK_LE(compressed.size(), - snappy::MaxCompressedLength(input.size())); - CHECK(snappy::IsValidCompressedBuffer(compressed.data(), compressed.size())); - - // Try uncompressing into an iovec containing a random number of entries - // ranging from 1 to 10. - char* buf = new char[input.size()]; - ACMRandom rnd(input.size()); - size_t num = rnd.Next() % 10 + 1; - if (input.size() < num) { - num = input.size(); - } - struct iovec* iov = new iovec[num]; - int used_so_far = 0; - for (size_t i = 0; i < num; ++i) { - iov[i].iov_base = buf + used_so_far; - if (i == num - 1) { - iov[i].iov_len = input.size() - used_so_far; - } else { - // Randomly choose to insert a 0 byte entry. - if (rnd.OneIn(5)) { - iov[i].iov_len = 0; - } else { - iov[i].iov_len = rnd.Uniform(input.size()); - } - } - used_so_far += iov[i].iov_len; - } - CHECK(snappy::RawUncompressToIOVec( - compressed.data(), compressed.size(), iov, num)); - CHECK(!memcmp(buf, input.data(), input.size())); - delete[] iov; - delete[] buf; -} - -// Test that data compressed by a compressor that does not -// obey block sizes is uncompressed properly. -static void VerifyNonBlockedCompression(const string& input) { - if (input.length() > snappy::kBlockSize) { - // We cannot test larger blocks than the maximum block size, obviously. - return; - } - - string prefix; - Varint::Append32(&prefix, input.size()); - - // Setup compression table - snappy::internal::WorkingMemory wmem; - int table_size; - uint16* table = wmem.GetHashTable(input.size(), &table_size); - - // Compress entire input in one shot - string compressed; - compressed += prefix; - compressed.resize(prefix.size()+snappy::MaxCompressedLength(input.size())); - char* dest = string_as_array(&compressed) + prefix.size(); - char* end = snappy::internal::CompressFragment(input.data(), input.size(), - dest, table, table_size); - compressed.resize(end - compressed.data()); - - // Uncompress into string - string uncomp_str; - CHECK(snappy::Uncompress(compressed.data(), compressed.size(), &uncomp_str)); - CHECK_EQ(uncomp_str, input); - - // Uncompress using source/sink - string uncomp_str2; - uncomp_str2.resize(input.size()); - snappy::UncheckedByteArraySink sink(string_as_array(&uncomp_str2)); - snappy::ByteArraySource source(compressed.data(), compressed.size()); - CHECK(snappy::Uncompress(&source, &sink)); - CHECK_EQ(uncomp_str2, input); - - // Uncompress into iovec - { - static const int kNumBlocks = 10; - struct iovec vec[kNumBlocks]; - const int block_size = 1 + input.size() / kNumBlocks; - string iovec_data(block_size * kNumBlocks, 'x'); - for (int i = 0; i < kNumBlocks; i++) { - vec[i].iov_base = string_as_array(&iovec_data) + i * block_size; - vec[i].iov_len = block_size; - } - CHECK(snappy::RawUncompressToIOVec(compressed.data(), compressed.size(), - vec, kNumBlocks)); - CHECK_EQ(string(iovec_data.data(), input.size()), input); - } -} - -// Expand the input so that it is at least K times as big as block size -static string Expand(const string& input) { - static const int K = 3; - string data = input; - while (data.size() < K * snappy::kBlockSize) { - data += input; - } - return data; -} - -static int Verify(const string& input) { - VLOG(1) << "Verifying input of size " << input.size(); - - // Compress using string based routines - const int result = VerifyString(input); - - // Verify using sink based routines - VerifyStringSink(input); - - VerifyNonBlockedCompression(input); - VerifyIOVec(input); - if (!input.empty()) { - const string expanded = Expand(input); - VerifyNonBlockedCompression(expanded); - VerifyIOVec(input); - } - - return result; -} - - -static bool IsValidCompressedBuffer(const string& c) { - return snappy::IsValidCompressedBuffer(c.data(), c.size()); -} -static bool Uncompress(const string& c, string* u) { - return snappy::Uncompress(c.data(), c.size(), u); -} - -// This test checks to ensure that snappy doesn't coredump if it gets -// corrupted data. -TEST(CorruptedTest, VerifyCorrupted) { - string source = "making sure we don't crash with corrupted input"; - VLOG(1) << source; - string dest; - string uncmp; - snappy::Compress(source.data(), source.size(), &dest); - - // Mess around with the data. It's hard to simulate all possible - // corruptions; this is just one example ... - CHECK_GT(dest.size(), 3); - dest[1]--; - dest[3]++; - // this really ought to fail. - CHECK(!IsValidCompressedBuffer(dest)); - CHECK(!Uncompress(dest, &uncmp)); - - // This is testing for a security bug - a buffer that decompresses to 100k - // but we lie in the snappy header and only reserve 0 bytes of memory :) - source.resize(100000); - for (size_t i = 0; i < source.length(); ++i) { - source[i] = 'A'; - } - snappy::Compress(source.data(), source.size(), &dest); - dest[0] = dest[1] = dest[2] = dest[3] = 0; - CHECK(!IsValidCompressedBuffer(dest)); - CHECK(!Uncompress(dest, &uncmp)); - - if (sizeof(void *) == 4) { - // Another security check; check a crazy big length can't DoS us with an - // over-allocation. - // Currently this is done only for 32-bit builds. On 64-bit builds, - // where 3 GB might be an acceptable allocation size, Uncompress() - // attempts to decompress, and sometimes causes the test to run out of - // memory. - dest[0] = dest[1] = dest[2] = dest[3] = '\xff'; - // This decodes to a really large size, i.e., about 3 GB. - dest[4] = 'k'; - CHECK(!IsValidCompressedBuffer(dest)); - CHECK(!Uncompress(dest, &uncmp)); - } else { - LOG(WARNING) << "Crazy decompression lengths not checked on 64-bit build"; - } - - // This decodes to about 2 MB; much smaller, but should still fail. - dest[0] = dest[1] = dest[2] = '\xff'; - dest[3] = 0x00; - CHECK(!IsValidCompressedBuffer(dest)); - CHECK(!Uncompress(dest, &uncmp)); - - // try reading stuff in from a bad file. - for (int i = 1; i <= 3; ++i) { - string data = ReadTestDataFile(StringPrintf("baddata%d.snappy", i).c_str(), - 0); - string uncmp; - // check that we don't return a crazy length - size_t ulen; - CHECK(!snappy::GetUncompressedLength(data.data(), data.size(), &ulen) - || (ulen < (1<<20))); - uint32 ulen2; - snappy::ByteArraySource source(data.data(), data.size()); - CHECK(!snappy::GetUncompressedLength(&source, &ulen2) || - (ulen2 < (1<<20))); - CHECK(!IsValidCompressedBuffer(data)); - CHECK(!Uncompress(data, &uncmp)); - } -} - -// Helper routines to construct arbitrary compressed strings. -// These mirror the compression code in snappy.cc, but are copied -// here so that we can bypass some limitations in the how snappy.cc -// invokes these routines. -static void AppendLiteral(string* dst, const string& literal) { - if (literal.empty()) return; - int n = literal.size() - 1; - if (n < 60) { - // Fit length in tag byte - dst->push_back(0 | (n << 2)); - } else { - // Encode in upcoming bytes - char number[4]; - int count = 0; - while (n > 0) { - number[count++] = n & 0xff; - n >>= 8; - } - dst->push_back(0 | ((59+count) << 2)); - *dst += string(number, count); - } - *dst += literal; -} - -static void AppendCopy(string* dst, int offset, int length) { - while (length > 0) { - // Figure out how much to copy in one shot - int to_copy; - if (length >= 68) { - to_copy = 64; - } else if (length > 64) { - to_copy = 60; - } else { - to_copy = length; - } - length -= to_copy; - - if ((to_copy >= 4) && (to_copy < 12) && (offset < 2048)) { - assert(to_copy-4 < 8); // Must fit in 3 bits - dst->push_back(1 | ((to_copy-4) << 2) | ((offset >> 8) << 5)); - dst->push_back(offset & 0xff); - } else if (offset < 65536) { - dst->push_back(2 | ((to_copy-1) << 2)); - dst->push_back(offset & 0xff); - dst->push_back(offset >> 8); - } else { - dst->push_back(3 | ((to_copy-1) << 2)); - dst->push_back(offset & 0xff); - dst->push_back((offset >> 8) & 0xff); - dst->push_back((offset >> 16) & 0xff); - dst->push_back((offset >> 24) & 0xff); - } - } -} - -TEST(Snappy, SimpleTests) { - Verify(""); - Verify("a"); - Verify("ab"); - Verify("abc"); - - Verify("aaaaaaa" + string(16, 'b') + string("aaaaa") + "abc"); - Verify("aaaaaaa" + string(256, 'b') + string("aaaaa") + "abc"); - Verify("aaaaaaa" + string(2047, 'b') + string("aaaaa") + "abc"); - Verify("aaaaaaa" + string(65536, 'b') + string("aaaaa") + "abc"); - Verify("abcaaaaaaa" + string(65536, 'b') + string("aaaaa") + "abc"); -} - -// Verify max blowup (lots of four-byte copies) -TEST(Snappy, MaxBlowup) { - string input; - for (int i = 0; i < 20000; i++) { - ACMRandom rnd(i); - uint32 bytes = static_cast(rnd.Next()); - input.append(reinterpret_cast(&bytes), sizeof(bytes)); - } - for (int i = 19999; i >= 0; i--) { - ACMRandom rnd(i); - uint32 bytes = static_cast(rnd.Next()); - input.append(reinterpret_cast(&bytes), sizeof(bytes)); - } - Verify(input); -} - -TEST(Snappy, RandomData) { - ACMRandom rnd(FLAGS_test_random_seed); - - const int num_ops = 20000; - for (int i = 0; i < num_ops; i++) { - if ((i % 1000) == 0) { - VLOG(0) << "Random op " << i << " of " << num_ops; - } - - string x; - size_t len = rnd.Uniform(4096); - if (i < 100) { - len = 65536 + rnd.Uniform(65536); - } - while (x.size() < len) { - int run_len = 1; - if (rnd.OneIn(10)) { - run_len = rnd.Skewed(8); - } - char c = (i < 100) ? rnd.Uniform(256) : rnd.Skewed(3); - while (run_len-- > 0 && x.size() < len) { - x += c; - } - } - - Verify(x); - } -} - -TEST(Snappy, FourByteOffset) { - // The new compressor cannot generate four-byte offsets since - // it chops up the input into 32KB pieces. So we hand-emit the - // copy manually. - - // The two fragments that make up the input string. - string fragment1 = "012345689abcdefghijklmnopqrstuvwxyz"; - string fragment2 = "some other string"; - - // How many times each fragment is emitted. - const int n1 = 2; - const int n2 = 100000 / fragment2.size(); - const int length = n1 * fragment1.size() + n2 * fragment2.size(); - - string compressed; - Varint::Append32(&compressed, length); - - AppendLiteral(&compressed, fragment1); - string src = fragment1; - for (int i = 0; i < n2; i++) { - AppendLiteral(&compressed, fragment2); - src += fragment2; - } - AppendCopy(&compressed, src.size(), fragment1.size()); - src += fragment1; - CHECK_EQ(length, src.size()); - - string uncompressed; - CHECK(snappy::IsValidCompressedBuffer(compressed.data(), compressed.size())); - CHECK(snappy::Uncompress(compressed.data(), compressed.size(), - &uncompressed)); - CHECK_EQ(uncompressed, src); -} - -TEST(Snappy, IOVecEdgeCases) { - // Test some tricky edge cases in the iovec output that are not necessarily - // exercised by random tests. - - // Our output blocks look like this initially (the last iovec is bigger - // than depicted): - // [ ] [ ] [ ] [ ] [ ] - static const int kLengths[] = { 2, 1, 4, 8, 128 }; - - struct iovec iov[ARRAYSIZE(kLengths)]; - for (int i = 0; i < ARRAYSIZE(kLengths); ++i) { - iov[i].iov_base = new char[kLengths[i]]; - iov[i].iov_len = kLengths[i]; - } - - string compressed; - Varint::Append32(&compressed, 22); - - // A literal whose output crosses three blocks. - // [ab] [c] [123 ] [ ] [ ] - AppendLiteral(&compressed, "abc123"); - - // A copy whose output crosses two blocks (source and destination - // segments marked). - // [ab] [c] [1231] [23 ] [ ] - // ^--^ -- - AppendCopy(&compressed, 3, 3); - - // A copy where the input is, at first, in the block before the output: - // - // [ab] [c] [1231] [231231 ] [ ] - // ^--- ^--- - // Then during the copy, the pointers move such that the input and - // output pointers are in the same block: - // - // [ab] [c] [1231] [23123123] [ ] - // ^- ^- - // And then they move again, so that the output pointer is no longer - // in the same block as the input pointer: - // [ab] [c] [1231] [23123123] [123 ] - // ^-- ^-- - AppendCopy(&compressed, 6, 9); - - // Finally, a copy where the input is from several blocks back, - // and it also crosses three blocks: - // - // [ab] [c] [1231] [23123123] [123b ] - // ^ ^ - // [ab] [c] [1231] [23123123] [123bc ] - // ^ ^ - // [ab] [c] [1231] [23123123] [123bc12 ] - // ^- ^- - AppendCopy(&compressed, 17, 4); - - CHECK(snappy::RawUncompressToIOVec( - compressed.data(), compressed.size(), iov, ARRAYSIZE(iov))); - CHECK_EQ(0, memcmp(iov[0].iov_base, "ab", 2)); - CHECK_EQ(0, memcmp(iov[1].iov_base, "c", 1)); - CHECK_EQ(0, memcmp(iov[2].iov_base, "1231", 4)); - CHECK_EQ(0, memcmp(iov[3].iov_base, "23123123", 8)); - CHECK_EQ(0, memcmp(iov[4].iov_base, "123bc12", 7)); - - for (int i = 0; i < ARRAYSIZE(kLengths); ++i) { - delete[] reinterpret_cast(iov[i].iov_base); - } -} - -TEST(Snappy, IOVecLiteralOverflow) { - static const int kLengths[] = { 3, 4 }; - - struct iovec iov[ARRAYSIZE(kLengths)]; - for (int i = 0; i < ARRAYSIZE(kLengths); ++i) { - iov[i].iov_base = new char[kLengths[i]]; - iov[i].iov_len = kLengths[i]; - } - - string compressed; - Varint::Append32(&compressed, 8); - - AppendLiteral(&compressed, "12345678"); - - CHECK(!snappy::RawUncompressToIOVec( - compressed.data(), compressed.size(), iov, ARRAYSIZE(iov))); - - for (int i = 0; i < ARRAYSIZE(kLengths); ++i) { - delete[] reinterpret_cast(iov[i].iov_base); - } -} - -TEST(Snappy, IOVecCopyOverflow) { - static const int kLengths[] = { 3, 4 }; - - struct iovec iov[ARRAYSIZE(kLengths)]; - for (int i = 0; i < ARRAYSIZE(kLengths); ++i) { - iov[i].iov_base = new char[kLengths[i]]; - iov[i].iov_len = kLengths[i]; - } - - string compressed; - Varint::Append32(&compressed, 8); - - AppendLiteral(&compressed, "123"); - AppendCopy(&compressed, 3, 5); - - CHECK(!snappy::RawUncompressToIOVec( - compressed.data(), compressed.size(), iov, ARRAYSIZE(iov))); - - for (int i = 0; i < ARRAYSIZE(kLengths); ++i) { - delete[] reinterpret_cast(iov[i].iov_base); - } -} - -static bool CheckUncompressedLength(const string& compressed, - size_t* ulength) { - const bool result1 = snappy::GetUncompressedLength(compressed.data(), - compressed.size(), - ulength); - - snappy::ByteArraySource source(compressed.data(), compressed.size()); - uint32 length; - const bool result2 = snappy::GetUncompressedLength(&source, &length); - CHECK_EQ(result1, result2); - return result1; -} - -TEST(SnappyCorruption, TruncatedVarint) { - string compressed, uncompressed; - size_t ulength; - compressed.push_back('\xf0'); - CHECK(!CheckUncompressedLength(compressed, &ulength)); - CHECK(!snappy::IsValidCompressedBuffer(compressed.data(), compressed.size())); - CHECK(!snappy::Uncompress(compressed.data(), compressed.size(), - &uncompressed)); -} - -TEST(SnappyCorruption, UnterminatedVarint) { - string compressed, uncompressed; - size_t ulength; - compressed.push_back('\x80'); - compressed.push_back('\x80'); - compressed.push_back('\x80'); - compressed.push_back('\x80'); - compressed.push_back('\x80'); - compressed.push_back(10); - CHECK(!CheckUncompressedLength(compressed, &ulength)); - CHECK(!snappy::IsValidCompressedBuffer(compressed.data(), compressed.size())); - CHECK(!snappy::Uncompress(compressed.data(), compressed.size(), - &uncompressed)); -} - -TEST(SnappyCorruption, OverflowingVarint) { - string compressed, uncompressed; - size_t ulength; - compressed.push_back('\xfb'); - compressed.push_back('\xff'); - compressed.push_back('\xff'); - compressed.push_back('\xff'); - compressed.push_back('\x7f'); - CHECK(!CheckUncompressedLength(compressed, &ulength)); - CHECK(!snappy::IsValidCompressedBuffer(compressed.data(), compressed.size())); - CHECK(!snappy::Uncompress(compressed.data(), compressed.size(), - &uncompressed)); -} - -TEST(Snappy, ReadPastEndOfBuffer) { - // Check that we do not read past end of input - - // Make a compressed string that ends with a single-byte literal - string compressed; - Varint::Append32(&compressed, 1); - AppendLiteral(&compressed, "x"); - - string uncompressed; - DataEndingAtUnreadablePage c(compressed); - CHECK(snappy::Uncompress(c.data(), c.size(), &uncompressed)); - CHECK_EQ(uncompressed, string("x")); -} - -// Check for an infinite loop caused by a copy with offset==0 -TEST(Snappy, ZeroOffsetCopy) { - const char* compressed = "\x40\x12\x00\x00"; - // \x40 Length (must be > kMaxIncrementCopyOverflow) - // \x12\x00\x00 Copy with offset==0, length==5 - char uncompressed[100]; - EXPECT_FALSE(snappy::RawUncompress(compressed, 4, uncompressed)); -} - -TEST(Snappy, ZeroOffsetCopyValidation) { - const char* compressed = "\x05\x12\x00\x00"; - // \x05 Length - // \x12\x00\x00 Copy with offset==0, length==5 - EXPECT_FALSE(snappy::IsValidCompressedBuffer(compressed, 4)); -} - -namespace { - -int TestFindMatchLength(const char* s1, const char *s2, unsigned length) { - std::pair p = - snappy::internal::FindMatchLength(s1, s2, s2 + length); - CHECK_EQ(p.first < 8, p.second); - return p.first; -} - -} // namespace - -TEST(Snappy, FindMatchLength) { - // Exercise all different code paths through the function. - // 64-bit version: - - // Hit s1_limit in 64-bit loop, hit s1_limit in single-character loop. - EXPECT_EQ(6, TestFindMatchLength("012345", "012345", 6)); - EXPECT_EQ(11, TestFindMatchLength("01234567abc", "01234567abc", 11)); - - // Hit s1_limit in 64-bit loop, find a non-match in single-character loop. - EXPECT_EQ(9, TestFindMatchLength("01234567abc", "01234567axc", 9)); - - // Same, but edge cases. - EXPECT_EQ(11, TestFindMatchLength("01234567abc!", "01234567abc!", 11)); - EXPECT_EQ(11, TestFindMatchLength("01234567abc!", "01234567abc?", 11)); - - // Find non-match at once in first loop. - EXPECT_EQ(0, TestFindMatchLength("01234567xxxxxxxx", "?1234567xxxxxxxx", 16)); - EXPECT_EQ(1, TestFindMatchLength("01234567xxxxxxxx", "0?234567xxxxxxxx", 16)); - EXPECT_EQ(4, TestFindMatchLength("01234567xxxxxxxx", "01237654xxxxxxxx", 16)); - EXPECT_EQ(7, TestFindMatchLength("01234567xxxxxxxx", "0123456?xxxxxxxx", 16)); - - // Find non-match in first loop after one block. - EXPECT_EQ(8, TestFindMatchLength("abcdefgh01234567xxxxxxxx", - "abcdefgh?1234567xxxxxxxx", 24)); - EXPECT_EQ(9, TestFindMatchLength("abcdefgh01234567xxxxxxxx", - "abcdefgh0?234567xxxxxxxx", 24)); - EXPECT_EQ(12, TestFindMatchLength("abcdefgh01234567xxxxxxxx", - "abcdefgh01237654xxxxxxxx", 24)); - EXPECT_EQ(15, TestFindMatchLength("abcdefgh01234567xxxxxxxx", - "abcdefgh0123456?xxxxxxxx", 24)); - - // 32-bit version: - - // Short matches. - EXPECT_EQ(0, TestFindMatchLength("01234567", "?1234567", 8)); - EXPECT_EQ(1, TestFindMatchLength("01234567", "0?234567", 8)); - EXPECT_EQ(2, TestFindMatchLength("01234567", "01?34567", 8)); - EXPECT_EQ(3, TestFindMatchLength("01234567", "012?4567", 8)); - EXPECT_EQ(4, TestFindMatchLength("01234567", "0123?567", 8)); - EXPECT_EQ(5, TestFindMatchLength("01234567", "01234?67", 8)); - EXPECT_EQ(6, TestFindMatchLength("01234567", "012345?7", 8)); - EXPECT_EQ(7, TestFindMatchLength("01234567", "0123456?", 8)); - EXPECT_EQ(7, TestFindMatchLength("01234567", "0123456?", 7)); - EXPECT_EQ(7, TestFindMatchLength("01234567!", "0123456??", 7)); - - // Hit s1_limit in 32-bit loop, hit s1_limit in single-character loop. - EXPECT_EQ(10, TestFindMatchLength("xxxxxxabcd", "xxxxxxabcd", 10)); - EXPECT_EQ(10, TestFindMatchLength("xxxxxxabcd?", "xxxxxxabcd?", 10)); - EXPECT_EQ(13, TestFindMatchLength("xxxxxxabcdef", "xxxxxxabcdef", 13)); - - // Same, but edge cases. - EXPECT_EQ(12, TestFindMatchLength("xxxxxx0123abc!", "xxxxxx0123abc!", 12)); - EXPECT_EQ(12, TestFindMatchLength("xxxxxx0123abc!", "xxxxxx0123abc?", 12)); - - // Hit s1_limit in 32-bit loop, find a non-match in single-character loop. - EXPECT_EQ(11, TestFindMatchLength("xxxxxx0123abc", "xxxxxx0123axc", 13)); - - // Find non-match at once in first loop. - EXPECT_EQ(6, TestFindMatchLength("xxxxxx0123xxxxxxxx", - "xxxxxx?123xxxxxxxx", 18)); - EXPECT_EQ(7, TestFindMatchLength("xxxxxx0123xxxxxxxx", - "xxxxxx0?23xxxxxxxx", 18)); - EXPECT_EQ(8, TestFindMatchLength("xxxxxx0123xxxxxxxx", - "xxxxxx0132xxxxxxxx", 18)); - EXPECT_EQ(9, TestFindMatchLength("xxxxxx0123xxxxxxxx", - "xxxxxx012?xxxxxxxx", 18)); - - // Same, but edge cases. - EXPECT_EQ(6, TestFindMatchLength("xxxxxx0123", "xxxxxx?123", 10)); - EXPECT_EQ(7, TestFindMatchLength("xxxxxx0123", "xxxxxx0?23", 10)); - EXPECT_EQ(8, TestFindMatchLength("xxxxxx0123", "xxxxxx0132", 10)); - EXPECT_EQ(9, TestFindMatchLength("xxxxxx0123", "xxxxxx012?", 10)); - - // Find non-match in first loop after one block. - EXPECT_EQ(10, TestFindMatchLength("xxxxxxabcd0123xx", - "xxxxxxabcd?123xx", 16)); - EXPECT_EQ(11, TestFindMatchLength("xxxxxxabcd0123xx", - "xxxxxxabcd0?23xx", 16)); - EXPECT_EQ(12, TestFindMatchLength("xxxxxxabcd0123xx", - "xxxxxxabcd0132xx", 16)); - EXPECT_EQ(13, TestFindMatchLength("xxxxxxabcd0123xx", - "xxxxxxabcd012?xx", 16)); - - // Same, but edge cases. - EXPECT_EQ(10, TestFindMatchLength("xxxxxxabcd0123", "xxxxxxabcd?123", 14)); - EXPECT_EQ(11, TestFindMatchLength("xxxxxxabcd0123", "xxxxxxabcd0?23", 14)); - EXPECT_EQ(12, TestFindMatchLength("xxxxxxabcd0123", "xxxxxxabcd0132", 14)); - EXPECT_EQ(13, TestFindMatchLength("xxxxxxabcd0123", "xxxxxxabcd012?", 14)); -} - -TEST(Snappy, FindMatchLengthRandom) { - const int kNumTrials = 10000; - const int kTypicalLength = 10; - ACMRandom rnd(FLAGS_test_random_seed); - - for (int i = 0; i < kNumTrials; i++) { - string s, t; - char a = rnd.Rand8(); - char b = rnd.Rand8(); - while (!rnd.OneIn(kTypicalLength)) { - s.push_back(rnd.OneIn(2) ? a : b); - t.push_back(rnd.OneIn(2) ? a : b); - } - DataEndingAtUnreadablePage u(s); - DataEndingAtUnreadablePage v(t); - int matched = TestFindMatchLength(u.data(), v.data(), t.size()); - if (matched == t.size()) { - EXPECT_EQ(s, t); - } else { - EXPECT_NE(s[matched], t[matched]); - for (int j = 0; j < matched; j++) { - EXPECT_EQ(s[j], t[j]); - } - } - } -} - -static uint16 MakeEntry(unsigned int extra, - unsigned int len, - unsigned int copy_offset) { - // Check that all of the fields fit within the allocated space - assert(extra == (extra & 0x7)); // At most 3 bits - assert(copy_offset == (copy_offset & 0x7)); // At most 3 bits - assert(len == (len & 0x7f)); // At most 7 bits - return len | (copy_offset << 8) | (extra << 11); -} - -// Check that the decompression table is correct, and optionally print out -// the computed one. -TEST(Snappy, VerifyCharTable) { - using snappy::internal::LITERAL; - using snappy::internal::COPY_1_BYTE_OFFSET; - using snappy::internal::COPY_2_BYTE_OFFSET; - using snappy::internal::COPY_4_BYTE_OFFSET; - using snappy::internal::char_table; - - uint16 dst[256]; - - // Place invalid entries in all places to detect missing initialization - int assigned = 0; - for (int i = 0; i < 256; i++) { - dst[i] = 0xffff; - } - - // Small LITERAL entries. We store (len-1) in the top 6 bits. - for (unsigned int len = 1; len <= 60; len++) { - dst[LITERAL | ((len-1) << 2)] = MakeEntry(0, len, 0); - assigned++; - } - - // Large LITERAL entries. We use 60..63 in the high 6 bits to - // encode the number of bytes of length info that follow the opcode. - for (unsigned int extra_bytes = 1; extra_bytes <= 4; extra_bytes++) { - // We set the length field in the lookup table to 1 because extra - // bytes encode len-1. - dst[LITERAL | ((extra_bytes+59) << 2)] = MakeEntry(extra_bytes, 1, 0); - assigned++; - } - - // COPY_1_BYTE_OFFSET. - // - // The tag byte in the compressed data stores len-4 in 3 bits, and - // offset/256 in 5 bits. offset%256 is stored in the next byte. - // - // This format is used for length in range [4..11] and offset in - // range [0..2047] - for (unsigned int len = 4; len < 12; len++) { - for (unsigned int offset = 0; offset < 2048; offset += 256) { - dst[COPY_1_BYTE_OFFSET | ((len-4)<<2) | ((offset>>8)<<5)] = - MakeEntry(1, len, offset>>8); - assigned++; - } - } - - // COPY_2_BYTE_OFFSET. - // Tag contains len-1 in top 6 bits, and offset in next two bytes. - for (unsigned int len = 1; len <= 64; len++) { - dst[COPY_2_BYTE_OFFSET | ((len-1)<<2)] = MakeEntry(2, len, 0); - assigned++; - } - - // COPY_4_BYTE_OFFSET. - // Tag contents len-1 in top 6 bits, and offset in next four bytes. - for (unsigned int len = 1; len <= 64; len++) { - dst[COPY_4_BYTE_OFFSET | ((len-1)<<2)] = MakeEntry(4, len, 0); - assigned++; - } - - // Check that each entry was initialized exactly once. - EXPECT_EQ(256, assigned) << "Assigned only " << assigned << " of 256"; - for (int i = 0; i < 256; i++) { - EXPECT_NE(0xffff, dst[i]) << "Did not assign byte " << i; - } - - if (FLAGS_snappy_dump_decompression_table) { - printf("static const uint16 char_table[256] = {\n "); - for (int i = 0; i < 256; i++) { - printf("0x%04x%s", - dst[i], - ((i == 255) ? "\n" : (((i%8) == 7) ? ",\n " : ", "))); - } - printf("};\n"); - } - - // Check that computed table matched recorded table. - for (int i = 0; i < 256; i++) { - EXPECT_EQ(dst[i], char_table[i]) << "Mismatch in byte " << i; - } -} - -static void CompressFile(const char* fname) { - string fullinput; - CHECK_OK(file::GetContents(fname, &fullinput, file::Defaults())); - - string compressed; - Compress(fullinput.data(), fullinput.size(), SNAPPY, &compressed, false); - - CHECK_OK(file::SetContents(string(fname).append(".comp"), compressed, - file::Defaults())); -} - -static void UncompressFile(const char* fname) { - string fullinput; - CHECK_OK(file::GetContents(fname, &fullinput, file::Defaults())); - - size_t uncompLength; - CHECK(CheckUncompressedLength(fullinput, &uncompLength)); - - string uncompressed; - uncompressed.resize(uncompLength); - CHECK(snappy::Uncompress(fullinput.data(), fullinput.size(), &uncompressed)); - - CHECK_OK(file::SetContents(string(fname).append(".uncomp"), uncompressed, - file::Defaults())); -} - -static void MeasureFile(const char* fname) { - string fullinput; - CHECK_OK(file::GetContents(fname, &fullinput, file::Defaults())); - printf("%-40s :\n", fname); - - int start_len = (FLAGS_start_len < 0) ? fullinput.size() : FLAGS_start_len; - int end_len = fullinput.size(); - if (FLAGS_end_len >= 0) { - end_len = std::min(fullinput.size(), FLAGS_end_len); - } - for (int len = start_len; len <= end_len; len++) { - const char* const input = fullinput.data(); - int repeats = (FLAGS_bytes + len) / (len + 1); - if (FLAGS_zlib) Measure(input, len, ZLIB, repeats, 1024<<10); - if (FLAGS_lzo) Measure(input, len, LZO, repeats, 1024<<10); - if (FLAGS_snappy) Measure(input, len, SNAPPY, repeats, 4096<<10); - - // For block-size based measurements - if (0 && FLAGS_snappy) { - Measure(input, len, SNAPPY, repeats, 8<<10); - Measure(input, len, SNAPPY, repeats, 16<<10); - Measure(input, len, SNAPPY, repeats, 32<<10); - Measure(input, len, SNAPPY, repeats, 64<<10); - Measure(input, len, SNAPPY, repeats, 256<<10); - Measure(input, len, SNAPPY, repeats, 1024<<10); - } - } -} - -static struct { - const char* label; - const char* filename; - size_t size_limit; -} files[] = { - { "html", "html", 0 }, - { "urls", "urls.10K", 0 }, - { "jpg", "fireworks.jpeg", 0 }, - { "jpg_200", "fireworks.jpeg", 200 }, - { "pdf", "paper-100k.pdf", 0 }, - { "html4", "html_x_4", 0 }, - { "txt1", "alice29.txt", 0 }, - { "txt2", "asyoulik.txt", 0 }, - { "txt3", "lcet10.txt", 0 }, - { "txt4", "plrabn12.txt", 0 }, - { "pb", "geo.protodata", 0 }, - { "gaviota", "kppkn.gtb", 0 }, -}; - -static void BM_UFlat(int iters, int arg) { - StopBenchmarkTiming(); - - // Pick file to process based on "arg" - CHECK_GE(arg, 0); - CHECK_LT(arg, ARRAYSIZE(files)); - string contents = ReadTestDataFile(files[arg].filename, - files[arg].size_limit); - - string zcontents; - snappy::Compress(contents.data(), contents.size(), &zcontents); - char* dst = new char[contents.size()]; - - SetBenchmarkBytesProcessed(static_cast(iters) * - static_cast(contents.size())); - SetBenchmarkLabel(files[arg].label); - StartBenchmarkTiming(); - while (iters-- > 0) { - CHECK(snappy::RawUncompress(zcontents.data(), zcontents.size(), dst)); - } - StopBenchmarkTiming(); - - delete[] dst; -} -BENCHMARK(BM_UFlat)->DenseRange(0, ARRAYSIZE(files) - 1); - -static void BM_UValidate(int iters, int arg) { - StopBenchmarkTiming(); - - // Pick file to process based on "arg" - CHECK_GE(arg, 0); - CHECK_LT(arg, ARRAYSIZE(files)); - string contents = ReadTestDataFile(files[arg].filename, - files[arg].size_limit); - - string zcontents; - snappy::Compress(contents.data(), contents.size(), &zcontents); - - SetBenchmarkBytesProcessed(static_cast(iters) * - static_cast(contents.size())); - SetBenchmarkLabel(files[arg].label); - StartBenchmarkTiming(); - while (iters-- > 0) { - CHECK(snappy::IsValidCompressedBuffer(zcontents.data(), zcontents.size())); - } - StopBenchmarkTiming(); -} -BENCHMARK(BM_UValidate)->DenseRange(0, 4); - -static void BM_UIOVec(int iters, int arg) { - StopBenchmarkTiming(); - - // Pick file to process based on "arg" - CHECK_GE(arg, 0); - CHECK_LT(arg, ARRAYSIZE(files)); - string contents = ReadTestDataFile(files[arg].filename, - files[arg].size_limit); - - string zcontents; - snappy::Compress(contents.data(), contents.size(), &zcontents); - - // Uncompress into an iovec containing ten entries. - const int kNumEntries = 10; - struct iovec iov[kNumEntries]; - char *dst = new char[contents.size()]; - int used_so_far = 0; - for (int i = 0; i < kNumEntries; ++i) { - iov[i].iov_base = dst + used_so_far; - if (used_so_far == contents.size()) { - iov[i].iov_len = 0; - continue; - } - - if (i == kNumEntries - 1) { - iov[i].iov_len = contents.size() - used_so_far; - } else { - iov[i].iov_len = contents.size() / kNumEntries; - } - used_so_far += iov[i].iov_len; - } - - SetBenchmarkBytesProcessed(static_cast(iters) * - static_cast(contents.size())); - SetBenchmarkLabel(files[arg].label); - StartBenchmarkTiming(); - while (iters-- > 0) { - CHECK(snappy::RawUncompressToIOVec(zcontents.data(), zcontents.size(), iov, - kNumEntries)); - } - StopBenchmarkTiming(); - - delete[] dst; -} -BENCHMARK(BM_UIOVec)->DenseRange(0, 4); - -static void BM_UFlatSink(int iters, int arg) { - StopBenchmarkTiming(); - - // Pick file to process based on "arg" - CHECK_GE(arg, 0); - CHECK_LT(arg, ARRAYSIZE(files)); - string contents = ReadTestDataFile(files[arg].filename, - files[arg].size_limit); - - string zcontents; - snappy::Compress(contents.data(), contents.size(), &zcontents); - char* dst = new char[contents.size()]; - - SetBenchmarkBytesProcessed(static_cast(iters) * - static_cast(contents.size())); - SetBenchmarkLabel(files[arg].label); - StartBenchmarkTiming(); - while (iters-- > 0) { - snappy::ByteArraySource source(zcontents.data(), zcontents.size()); - snappy::UncheckedByteArraySink sink(dst); - CHECK(snappy::Uncompress(&source, &sink)); - } - StopBenchmarkTiming(); - - string s(dst, contents.size()); - CHECK_EQ(contents, s); - - delete[] dst; -} - -BENCHMARK(BM_UFlatSink)->DenseRange(0, ARRAYSIZE(files) - 1); - -static void BM_ZFlat(int iters, int arg) { - StopBenchmarkTiming(); - - // Pick file to process based on "arg" - CHECK_GE(arg, 0); - CHECK_LT(arg, ARRAYSIZE(files)); - string contents = ReadTestDataFile(files[arg].filename, - files[arg].size_limit); - - char* dst = new char[snappy::MaxCompressedLength(contents.size())]; - - SetBenchmarkBytesProcessed(static_cast(iters) * - static_cast(contents.size())); - StartBenchmarkTiming(); - - size_t zsize = 0; - while (iters-- > 0) { - snappy::RawCompress(contents.data(), contents.size(), dst, &zsize); - } - StopBenchmarkTiming(); - const double compression_ratio = - static_cast(zsize) / std::max(1, contents.size()); - SetBenchmarkLabel(StringPrintf("%s (%.2f %%)", - files[arg].label, 100.0 * compression_ratio)); - VLOG(0) << StringPrintf("compression for %s: %zd -> %zd bytes", - files[arg].label, contents.size(), zsize); - delete[] dst; -} -BENCHMARK(BM_ZFlat)->DenseRange(0, ARRAYSIZE(files) - 1); - -} // namespace snappy - -int main(int argc, char** argv) { - InitGoogle(argv[0], &argc, &argv, true); - RunSpecifiedBenchmarks(); - - if (argc >= 2) { - for (int arg = 1; arg < argc; arg++) { - if (FLAGS_write_compressed) { - snappy::CompressFile(argv[arg]); - } else if (FLAGS_write_uncompressed) { - snappy::UncompressFile(argv[arg]); - } else { - snappy::MeasureFile(argv[arg]); - } - } - return 0; - } - - return RUN_ALL_TESTS(); -} diff --git a/src/snappy/snappy/testdata/alice29.txt b/src/snappy/snappy/testdata/alice29.txt deleted file mode 100644 index 703365523b..0000000000 --- a/src/snappy/snappy/testdata/alice29.txt +++ /dev/null @@ -1,3609 +0,0 @@ - - - - - ALICE'S ADVENTURES IN WONDERLAND - - Lewis Carroll - - THE MILLENNIUM FULCRUM EDITION 2.9 - - - - - CHAPTER I - - Down the Rabbit-Hole - - - Alice was beginning to get very tired of sitting by her sister -on the bank, and of having nothing to do: once or twice she had -peeped into the book her sister was reading, but it had no -pictures or conversations in it, `and what is the use of a book,' -thought Alice `without pictures or conversation?' - - So she was considering in her own mind (as well as she could, -for the hot day made her feel very sleepy and stupid), whether -the pleasure of making a daisy-chain would be worth the trouble -of getting up and picking the daisies, when suddenly a White -Rabbit with pink eyes ran close by her. - - There was nothing so VERY remarkable in that; nor did Alice -think it so VERY much out of the way to hear the Rabbit say to -itself, `Oh dear! Oh dear! I shall be late!' (when she thought -it over afterwards, it occurred to her that she ought to have -wondered at this, but at the time it all seemed quite natural); -but when the Rabbit actually TOOK A WATCH OUT OF ITS WAISTCOAT- -POCKET, and looked at it, and then hurried on, Alice started to -her feet, for it flashed across her mind that she had never -before seen a rabbit with either a waistcoat-pocket, or a watch to -take out of it, and burning with curiosity, she ran across the -field after it, and fortunately was just in time to see it pop -down a large rabbit-hole under the hedge. - - In another moment down went Alice after it, never once -considering how in the world she was to get out again. - - The rabbit-hole went straight on like a tunnel for some way, -and then dipped suddenly down, so suddenly that Alice had not a -moment to think about stopping herself before she found herself -falling down a very deep well. - - Either the well was very deep, or she fell very slowly, for she -had plenty of time as she went down to look about her and to -wonder what was going to happen next. First, she tried to look -down and make out what she was coming to, but it was too dark to -see anything; then she looked at the sides of the well, and -noticed that they were filled with cupboards and book-shelves; -here and there she saw maps and pictures hung upon pegs. She -took down a jar from one of the shelves as she passed; it was -labelled `ORANGE MARMALADE', but to her great disappointment it -was empty: she did not like to drop the jar for fear of killing -somebody, so managed to put it into one of the cupboards as she -fell past it. - - `Well!' thought Alice to herself, `after such a fall as this, I -shall think nothing of tumbling down stairs! How brave they'll -all think me at home! Why, I wouldn't say anything about it, -even if I fell off the top of the house!' (Which was very likely -true.) - - Down, down, down. Would the fall NEVER come to an end! `I -wonder how many miles I've fallen by this time?' she said aloud. -`I must be getting somewhere near the centre of the earth. Let -me see: that would be four thousand miles down, I think--' (for, -you see, Alice had learnt several things of this sort in her -lessons in the schoolroom, and though this was not a VERY good -opportunity for showing off her knowledge, as there was no one to -listen to her, still it was good practice to say it over) `--yes, -that's about the right distance--but then I wonder what Latitude -or Longitude I've got to?' (Alice had no idea what Latitude was, -or Longitude either, but thought they were nice grand words to -say.) - - Presently she began again. `I wonder if I shall fall right -THROUGH the earth! How funny it'll seem to come out among the -people that walk with their heads downward! The Antipathies, I -think--' (she was rather glad there WAS no one listening, this -time, as it didn't sound at all the right word) `--but I shall -have to ask them what the name of the country is, you know. -Please, Ma'am, is this New Zealand or Australia?' (and she tried -to curtsey as she spoke--fancy CURTSEYING as you're falling -through the air! Do you think you could manage it?) `And what -an ignorant little girl she'll think me for asking! No, it'll -never do to ask: perhaps I shall see it written up somewhere.' - - Down, down, down. There was nothing else to do, so Alice soon -began talking again. `Dinah'll miss me very much to-night, I -should think!' (Dinah was the cat.) `I hope they'll remember -her saucer of milk at tea-time. Dinah my dear! I wish you were -down here with me! There are no mice in the air, I'm afraid, but -you might catch a bat, and that's very like a mouse, you know. -But do cats eat bats, I wonder?' And here Alice began to get -rather sleepy, and went on saying to herself, in a dreamy sort of -way, `Do cats eat bats? Do cats eat bats?' and sometimes, `Do -bats eat cats?' for, you see, as she couldn't answer either -question, it didn't much matter which way she put it. She felt -that she was dozing off, and had just begun to dream that she -was walking hand in hand with Dinah, and saying to her very -earnestly, `Now, Dinah, tell me the truth: did you ever eat a -bat?' when suddenly, thump! thump! down she came upon a heap of -sticks and dry leaves, and the fall was over. - - Alice was not a bit hurt, and she jumped up on to her feet in a -moment: she looked up, but it was all dark overhead; before her -was another long passage, and the White Rabbit was still in -sight, hurrying down it. There was not a moment to be lost: -away went Alice like the wind, and was just in time to hear it -say, as it turned a corner, `Oh my ears and whiskers, how late -it's getting!' She was close behind it when she turned the -corner, but the Rabbit was no longer to be seen: she found -herself in a long, low hall, which was lit up by a row of lamps -hanging from the roof. - - There were doors all round the hall, but they were all locked; -and when Alice had been all the way down one side and up the -other, trying every door, she walked sadly down the middle, -wondering how she was ever to get out again. - - Suddenly she came upon a little three-legged table, all made of -solid glass; there was nothing on it except a tiny golden key, -and Alice's first thought was that it might belong to one of the -doors of the hall; but, alas! either the locks were too large, or -the key was too small, but at any rate it would not open any of -them. However, on the second time round, she came upon a low -curtain she had not noticed before, and behind it was a little -door about fifteen inches high: she tried the little golden key -in the lock, and to her great delight it fitted! - - Alice opened the door and found that it led into a small -passage, not much larger than a rat-hole: she knelt down and -looked along the passage into the loveliest garden you ever saw. -How she longed to get out of that dark hall, and wander about -among those beds of bright flowers and those cool fountains, but -she could not even get her head though the doorway; `and even if -my head would go through,' thought poor Alice, `it would be of -very little use without my shoulders. Oh, how I wish -I could shut up like a telescope! I think I could, if I only -know how to begin.' For, you see, so many out-of-the-way things -had happened lately, that Alice had begun to think that very few -things indeed were really impossible. - - There seemed to be no use in waiting by the little door, so she -went back to the table, half hoping she might find another key on -it, or at any rate a book of rules for shutting people up like -telescopes: this time she found a little bottle on it, (`which -certainly was not here before,' said Alice,) and round the neck -of the bottle was a paper label, with the words `DRINK ME' -beautifully printed on it in large letters. - - It was all very well to say `Drink me,' but the wise little -Alice was not going to do THAT in a hurry. `No, I'll look -first,' she said, `and see whether it's marked "poison" or not'; -for she had read several nice little histories about children who -had got burnt, and eaten up by wild beasts and other unpleasant -things, all because they WOULD not remember the simple rules -their friends had taught them: such as, that a red-hot poker -will burn you if you hold it too long; and that if you cut your -finger VERY deeply with a knife, it usually bleeds; and she had -never forgotten that, if you drink much from a bottle marked -`poison,' it is almost certain to disagree with you, sooner or -later. - - However, this bottle was NOT marked `poison,' so Alice ventured -to taste it, and finding it very nice, (it had, in fact, a sort -of mixed flavour of cherry-tart, custard, pine-apple, roast -turkey, toffee, and hot buttered toast,) she very soon finished -it off. - - * * * * * * * - - * * * * * * - - * * * * * * * - - `What a curious feeling!' said Alice; `I must be shutting up -like a telescope.' - - And so it was indeed: she was now only ten inches high, and -her face brightened up at the thought that she was now the right -size for going though the little door into that lovely garden. -First, however, she waited for a few minutes to see if she was -going to shrink any further: she felt a little nervous about -this; `for it might end, you know,' said Alice to herself, `in my -going out altogether, like a candle. I wonder what I should be -like then?' And she tried to fancy what the flame of a candle is -like after the candle is blown out, for she could not remember -ever having seen such a thing. - - After a while, finding that nothing more happened, she decided -on going into the garden at once; but, alas for poor Alice! when -she got to the door, she found he had forgotten the little golden -key, and when she went back to the table for it, she found she -could not possibly reach it: she could see it quite plainly -through the glass, and she tried her best to climb up one of the -legs of the table, but it was too slippery; and when she had -tired herself out with trying, the poor little thing sat down and -cried. - - `Come, there's no use in crying like that!' said Alice to -herself, rather sharply; `I advise you to leave off this minute!' -She generally gave herself very good advice, (though she very -seldom followed it), and sometimes she scolded herself so -severely as to bring tears into her eyes; and once she remembered -trying to box her own ears for having cheated herself in a game -of croquet she was playing against herself, for this curious -child was very fond of pretending to be two people. `But it's no -use now,' thought poor Alice, `to pretend to be two people! Why, -there's hardly enough of me left to make ONE respectable -person!' - - Soon her eye fell on a little glass box that was lying under -the table: she opened it, and found in it a very small cake, on -which the words `EAT ME' were beautifully marked in currants. -`Well, I'll eat it,' said Alice, `and if it makes me grow larger, -I can reach the key; and if it makes me grow smaller, I can creep -under the door; so either way I'll get into the garden, and I -don't care which happens!' - - She ate a little bit, and said anxiously to herself, `Which -way? Which way?', holding her hand on the top of her head to -feel which way it was growing, and she was quite surprised to -find that she remained the same size: to be sure, this generally -happens when one eats cake, but Alice had got so much into the -way of expecting nothing but out-of-the-way things to happen, -that it seemed quite dull and stupid for life to go on in the -common way. - - So she set to work, and very soon finished off the cake. - - * * * * * * * - - * * * * * * - - * * * * * * * - - - - - CHAPTER II - - The Pool of Tears - - - `Curiouser and curiouser!' cried Alice (she was so much -surprised, that for the moment she quite forgot how to speak good -English); `now I'm opening out like the largest telescope that -ever was! Good-bye, feet!' (for when she looked down at her -feet, they seemed to be almost out of sight, they were getting so -far off). `Oh, my poor little feet, I wonder who will put on -your shoes and stockings for you now, dears? I'm sure _I_ shan't -be able! I shall be a great deal too far off to trouble myself -about you: you must manage the best way you can; --but I must be -kind to them,' thought Alice, `or perhaps they won't walk the -way I want to go! Let me see: I'll give them a new pair of -boots every Christmas.' - - And she went on planning to herself how she would manage it. -`They must go by the carrier,' she thought; `and how funny it'll -seem, sending presents to one's own feet! And how odd the -directions will look! - - ALICE'S RIGHT FOOT, ESQ. - HEARTHRUG, - NEAR THE FENDER, - (WITH ALICE'S LOVE). - -Oh dear, what nonsense I'm talking!' - - Just then her head struck against the roof of the hall: in -fact she was now more than nine feet high, and she at once took -up the little golden key and hurried off to the garden door. - - Poor Alice! It was as much as she could do, lying down on one -side, to look through into the garden with one eye; but to get -through was more hopeless than ever: she sat down and began to -cry again. - - `You ought to be ashamed of yourself,' said Alice, `a great -girl like you,' (she might well say this), `to go on crying in -this way! Stop this moment, I tell you!' But she went on all -the same, shedding gallons of tears, until there was a large pool -all round her, about four inches deep and reaching half down the -hall. - - After a time she heard a little pattering of feet in the -distance, and she hastily dried her eyes to see what was coming. -It was the White Rabbit returning, splendidly dressed, with a -pair of white kid gloves in one hand and a large fan in the -other: he came trotting along in a great hurry, muttering to -himself as he came, `Oh! the Duchess, the Duchess! Oh! won't she -be savage if I've kept her waiting!' Alice felt so desperate -that she was ready to ask help of any one; so, when the Rabbit -came near her, she began, in a low, timid voice, `If you please, -sir--' The Rabbit started violently, dropped the white kid -gloves and the fan, and skurried away into the darkness as hard -as he could go. - - Alice took up the fan and gloves, and, as the hall was very -hot, she kept fanning herself all the time she went on talking: -`Dear, dear! How queer everything is to-day! And yesterday -things went on just as usual. I wonder if I've been changed in -the night? Let me think: was I the same when I got up this -morning? I almost think I can remember feeling a little -different. But if I'm not the same, the next question is, Who in -the world am I? Ah, THAT'S the great puzzle!' And she began -thinking over all the children she knew that were of the same age -as herself, to see if she could have been changed for any of -them. - - `I'm sure I'm not Ada,' she said, `for her hair goes in such -long ringlets, and mine doesn't go in ringlets at all; and I'm -sure I can't be Mabel, for I know all sorts of things, and she, -oh! she knows such a very little! Besides, SHE'S she, and I'm I, -and--oh dear, how puzzling it all is! I'll try if I know all the -things I used to know. Let me see: four times five is twelve, -and four times six is thirteen, and four times seven is--oh dear! -I shall never get to twenty at that rate! However, the -Multiplication Table doesn't signify: let's try Geography. -London is the capital of Paris, and Paris is the capital of Rome, -and Rome--no, THAT'S all wrong, I'm certain! I must have been -changed for Mabel! I'll try and say "How doth the little--"' -and she crossed her hands on her lap as if she were saying lessons, -and began to repeat it, but her voice sounded hoarse and -strange, and the words did not come the same as they used to do:-- - - `How doth the little crocodile - Improve his shining tail, - And pour the waters of the Nile - On every golden scale! - - `How cheerfully he seems to grin, - How neatly spread his claws, - And welcome little fishes in - With gently smiling jaws!' - - `I'm sure those are not the right words,' said poor Alice, and -her eyes filled with tears again as she went on, `I must be Mabel -after all, and I shall have to go and live in that poky little -house, and have next to no toys to play with, and oh! ever so -many lessons to learn! No, I've made up my mind about it; if I'm -Mabel, I'll stay down here! It'll be no use their putting their -heads down and saying "Come up again, dear!" I shall only look -up and say "Who am I then? Tell me that first, and then, if I -like being that person, I'll come up: if not, I'll stay down -here till I'm somebody else"--but, oh dear!' cried Alice, with a -sudden burst of tears, `I do wish they WOULD put their heads -down! I am so VERY tired of being all alone here!' - - As she said this she looked down at her hands, and was -surprised to see that she had put on one of the Rabbit's little -white kid gloves while she was talking. `How CAN I have done -that?' she thought. `I must be growing small again.' She got up -and went to the table to measure herself by it, and found that, -as nearly as she could guess, she was now about two feet high, -and was going on shrinking rapidly: she soon found out that the -cause of this was the fan she was holding, and she dropped it -hastily, just in time to avoid shrinking away altogether. - -`That WAS a narrow escape!' said Alice, a good deal frightened at -the sudden change, but very glad to find herself still in -existence; `and now for the garden!' and she ran with all speed -back to the little door: but, alas! the little door was shut -again, and the little golden key was lying on the glass table as -before, `and things are worse than ever,' thought the poor child, -`for I never was so small as this before, never! And I declare -it's too bad, that it is!' - - As she said these words her foot slipped, and in another -moment, splash! she was up to her chin in salt water. He first -idea was that she had somehow fallen into the sea, `and in that -case I can go back by railway,' she said to herself. (Alice had -been to the seaside once in her life, and had come to the general -conclusion, that wherever you go to on the English coast you find -a number of bathing machines in the sea, some children digging in -the sand with wooden spades, then a row of lodging houses, and -behind them a railway station.) However, she soon made out that -she was in the pool of tears which she had wept when she was nine -feet high. - - `I wish I hadn't cried so much!' said Alice, as she swam about, -trying to find her way out. `I shall be punished for it now, I -suppose, by being drowned in my own tears! That WILL be a queer -thing, to be sure! However, everything is queer to-day.' - - Just then she heard something splashing about in the pool a -little way off, and she swam nearer to make out what it was: at -first she thought it must be a walrus or hippopotamus, but then -she remembered how small she was now, and she soon made out that -it was only a mouse that had slipped in like herself. - - `Would it be of any use, now,' thought Alice, `to speak to this -mouse? Everything is so out-of-the-way down here, that I should -think very likely it can talk: at any rate, there's no harm in -trying.' So she began: `O Mouse, do you know the way out of -this pool? I am very tired of swimming about here, O Mouse!' -(Alice thought this must be the right way of speaking to a mouse: -she had never done such a thing before, but she remembered having -seen in her brother's Latin Grammar, `A mouse--of a mouse--to a -mouse--a mouse--O mouse!' The Mouse looked at her rather -inquisitively, and seemed to her to wink with one of its little -eyes, but it said nothing. - - `Perhaps it doesn't understand English,' thought Alice; `I -daresay it's a French mouse, come over with William the -Conqueror.' (For, with all her knowledge of history, Alice had -no very clear notion how long ago anything had happened.) So she -began again: `Ou est ma chatte?' which was the first sentence in -her French lesson-book. The Mouse gave a sudden leap out of the -water, and seemed to quiver all over with fright. `Oh, I beg -your pardon!' cried Alice hastily, afraid that she had hurt the -poor animal's feelings. `I quite forgot you didn't like cats.' - - `Not like cats!' cried the Mouse, in a shrill, passionate -voice. `Would YOU like cats if you were me?' - - `Well, perhaps not,' said Alice in a soothing tone: `don't be -angry about it. And yet I wish I could show you our cat Dinah: -I think you'd take a fancy to cats if you could only see her. -She is such a dear quiet thing,' Alice went on, half to herself, -as she swam lazily about in the pool, `and she sits purring so -nicely by the fire, licking her paws and washing her face--and -she is such a nice soft thing to nurse--and she's such a capital -one for catching mice--oh, I beg your pardon!' cried Alice again, -for this time the Mouse was bristling all over, and she felt -certain it must be really offended. `We won't talk about her any -more if you'd rather not.' - - `We indeed!' cried the Mouse, who was trembling down to the end -of his tail. `As if I would talk on such a subject! Our family -always HATED cats: nasty, low, vulgar things! Don't let me hear -the name again!' - - `I won't indeed!' said Alice, in a great hurry to change the -subject of conversation. `Are you--are you fond--of--of dogs?' -The Mouse did not answer, so Alice went on eagerly: `There is -such a nice little dog near our house I should like to show you! -A little bright-eyed terrier, you know, with oh, such long curly -brown hair! And it'll fetch things when you throw them, and -it'll sit up and beg for its dinner, and all sorts of things--I -can't remember half of them--and it belongs to a farmer, you -know, and he says it's so useful, it's worth a hundred pounds! -He says it kills all the rats and--oh dear!' cried Alice in a -sorrowful tone, `I'm afraid I've offended it again!' For the -Mouse was swimming away from her as hard as it could go, and -making quite a commotion in the pool as it went. - - So she called softly after it, `Mouse dear! Do come back -again, and we won't talk about cats or dogs either, if you don't -like them!' When the Mouse heard this, it turned round and swam -slowly back to her: its face was quite pale (with passion, Alice -thought), and it said in a low trembling voice, `Let us get to -the shore, and then I'll tell you my history, and you'll -understand why it is I hate cats and dogs.' - - It was high time to go, for the pool was getting quite crowded -with the birds and animals that had fallen into it: there were a -Duck and a Dodo, a Lory and an Eaglet, and several other curious -creatures. Alice led the way, and the whole party swam to the -shore. - - - - CHAPTER III - - A Caucus-Race and a Long Tale - - - They were indeed a queer-looking party that assembled on the -bank--the birds with draggled feathers, the animals with their -fur clinging close to them, and all dripping wet, cross, and -uncomfortable. - - The first question of course was, how to get dry again: they -had a consultation about this, and after a few minutes it seemed -quite natural to Alice to find herself talking familiarly with -them, as if she had known them all her life. Indeed, she had -quite a long argument with the Lory, who at last turned sulky, -and would only say, `I am older than you, and must know better'; -and this Alice would not allow without knowing how old it was, -and, as the Lory positively refused to tell its age, there was no -more to be said. - - At last the Mouse, who seemed to be a person of authority among -them, called out, `Sit down, all of you, and listen to me! I'LL -soon make you dry enough!' They all sat down at once, in a large -ring, with the Mouse in the middle. Alice kept her eyes -anxiously fixed on it, for she felt sure she would catch a bad -cold if she did not get dry very soon. - - `Ahem!' said the Mouse with an important air, `are you all ready? -This is the driest thing I know. Silence all round, if you please! -"William the Conqueror, whose cause was favoured by the pope, was -soon submitted to by the English, who wanted leaders, and had been -of late much accustomed to usurpation and conquest. Edwin and -Morcar, the earls of Mercia and Northumbria--"' - - `Ugh!' said the Lory, with a shiver. - - `I beg your pardon!' said the Mouse, frowning, but very -politely: `Did you speak?' - - `Not I!' said the Lory hastily. - - `I thought you did,' said the Mouse. `--I proceed. "Edwin and -Morcar, the earls of Mercia and Northumbria, declared for him: -and even Stigand, the patriotic archbishop of Canterbury, found -it advisable--"' - - `Found WHAT?' said the Duck. - - `Found IT,' the Mouse replied rather crossly: `of course you -know what "it" means.' - - `I know what "it" means well enough, when I find a thing,' said -the Duck: `it's generally a frog or a worm. The question is, -what did the archbishop find?' - - The Mouse did not notice this question, but hurriedly went on, -`"--found it advisable to go with Edgar Atheling to meet William -and offer him the crown. William's conduct at first was -moderate. But the insolence of his Normans--" How are you -getting on now, my dear?' it continued, turning to Alice as it -spoke. - - `As wet as ever,' said Alice in a melancholy tone: `it doesn't -seem to dry me at all.' - - `In that case,' said the Dodo solemnly, rising to its feet, `I -move that the meeting adjourn, for the immediate adoption of more -energetic remedies--' - - `Speak English!' said the Eaglet. `I don't know the meaning of -half those long words, and, what's more, I don't believe you do -either!' And the Eaglet bent down its head to hide a smile: -some of the other birds tittered audibly. - - `What I was going to say,' said the Dodo in an offended tone, -`was, that the best thing to get us dry would be a Caucus-race.' - - `What IS a Caucus-race?' said Alice; not that she wanted much -to know, but the Dodo had paused as if it thought that SOMEBODY -ought to speak, and no one else seemed inclined to say anything. - - `Why,' said the Dodo, `the best way to explain it is to do it.' -(And, as you might like to try the thing yourself, some winter -day, I will tell you how the Dodo managed it.) - - First it marked out a race-course, in a sort of circle, (`the -exact shape doesn't matter,' it said,) and then all the party -were placed along the course, here and there. There was no `One, -two, three, and away,' but they began running when they liked, -and left off when they liked, so that it was not easy to know -when the race was over. However, when they had been running half -an hour or so, and were quite dry again, the Dodo suddenly called -out `The race is over!' and they all crowded round it, panting, -and asking, `But who has won?' - - This question the Dodo could not answer without a great deal of -thought, and it sat for a long time with one finger pressed upon -its forehead (the position in which you usually see Shakespeare, -in the pictures of him), while the rest waited in silence. At -last the Dodo said, `EVERYBODY has won, and all must have -prizes.' - - `But who is to give the prizes?' quite a chorus of voices -asked. - - `Why, SHE, of course,' said the Dodo, pointing to Alice with -one finger; and the whole party at once crowded round her, -calling out in a confused way, `Prizes! Prizes!' - - Alice had no idea what to do, and in despair she put her hand -in her pocket, and pulled out a box of comfits, (luckily the salt -water had not got into it), and handed them round as prizes. -There was exactly one a-piece all round. - - `But she must have a prize herself, you know,' said the Mouse. - - `Of course,' the Dodo replied very gravely. `What else have -you got in your pocket?' he went on, turning to Alice. - - `Only a thimble,' said Alice sadly. - - `Hand it over here,' said the Dodo. - - Then they all crowded round her once more, while the Dodo -solemnly presented the thimble, saying `We beg your acceptance of -this elegant thimble'; and, when it had finished this short -speech, they all cheered. - - Alice thought the whole thing very absurd, but they all looked -so grave that she did not dare to laugh; and, as she could not -think of anything to say, she simply bowed, and took the thimble, -looking as solemn as she could. - - The next thing was to eat the comfits: this caused some noise -and confusion, as the large birds complained that they could not -taste theirs, and the small ones choked and had to be patted on -the back. However, it was over at last, and they sat down again -in a ring, and begged the Mouse to tell them something more. - - `You promised to tell me your history, you know,' said Alice, -`and why it is you hate--C and D,' she added in a whisper, half -afraid that it would be offended again. - - `Mine is a long and a sad tale!' said the Mouse, turning to -Alice, and sighing. - - `It IS a long tail, certainly,' said Alice, looking down with -wonder at the Mouse's tail; `but why do you call it sad?' And -she kept on puzzling about it while the Mouse was speaking, so -that her idea of the tale was something like this:-- - - `Fury said to a - mouse, That he - met in the - house, - "Let us - both go to - law: I will - prosecute - YOU. --Come, - I'll take no - denial; We - must have a - trial: For - really this - morning I've - nothing - to do." - Said the - mouse to the - cur, "Such - a trial, - dear Sir, - With - no jury - or judge, - would be - wasting - our - breath." - "I'll be - judge, I'll - be jury," - Said - cunning - old Fury: - "I'll - try the - whole - cause, - and - condemn - you - to - death."' - - - `You are not attending!' said the Mouse to Alice severely. -`What are you thinking of?' - - `I beg your pardon,' said Alice very humbly: `you had got to -the fifth bend, I think?' - - `I had NOT!' cried the Mouse, sharply and very angrily. - - `A knot!' said Alice, always ready to make herself useful, and -looking anxiously about her. `Oh, do let me help to undo it!' - - `I shall do nothing of the sort,' said the Mouse, getting up -and walking away. `You insult me by talking such nonsense!' - - `I didn't mean it!' pleaded poor Alice. `But you're so easily -offended, you know!' - - The Mouse only growled in reply. - - `Please come back and finish your story!' Alice called after -it; and the others all joined in chorus, `Yes, please do!' but -the Mouse only shook its head impatiently, and walked a little -quicker. - - `What a pity it wouldn't stay!' sighed the Lory, as soon as it -was quite out of sight; and an old Crab took the opportunity of -saying to her daughter `Ah, my dear! Let this be a lesson to you -never to lose YOUR temper!' `Hold your tongue, Ma!' said the -young Crab, a little snappishly. `You're enough to try the -patience of an oyster!' - - `I wish I had our Dinah here, I know I do!' said Alice aloud, -addressing nobody in particular. `She'd soon fetch it back!' - - `And who is Dinah, if I might venture to ask the question?' -said the Lory. - - Alice replied eagerly, for she was always ready to talk about -her pet: `Dinah's our cat. And she's such a capital one for -catching mice you can't think! And oh, I wish you could see her -after the birds! Why, she'll eat a little bird as soon as look -at it!' - - This speech caused a remarkable sensation among the party. -Some of the birds hurried off at once: one the old Magpie began -wrapping itself up very carefully, remarking, `I really must be -getting home; the night-air doesn't suit my throat!' and a Canary -called out in a trembling voice to its children, `Come away, my -dears! It's high time you were all in bed!' On various pretexts -they all moved off, and Alice was soon left alone. - - `I wish I hadn't mentioned Dinah!' she said to herself in a -melancholy tone. `Nobody seems to like her, down here, and I'm -sure she's the best cat in the world! Oh, my dear Dinah! I -wonder if I shall ever see you any more!' And here poor Alice -began to cry again, for she felt very lonely and low-spirited. -In a little while, however, she again heard a little pattering of -footsteps in the distance, and she looked up eagerly, half hoping -that the Mouse had changed his mind, and was coming back to -finish his story. - - - - CHAPTER IV - - The Rabbit Sends in a Little Bill - - - It was the White Rabbit, trotting slowly back again, and -looking anxiously about as it went, as if it had lost something; -and she heard it muttering to itself `The Duchess! The Duchess! -Oh my dear paws! Oh my fur and whiskers! She'll get me -executed, as sure as ferrets are ferrets! Where CAN I have -dropped them, I wonder?' Alice guessed in a moment that it was -looking for the fan and the pair of white kid gloves, and she -very good-naturedly began hunting about for them, but they were -nowhere to be seen--everything seemed to have changed since her -swim in the pool, and the great hall, with the glass table and -the little door, had vanished completely. - - Very soon the Rabbit noticed Alice, as she went hunting about, -and called out to her in an angry tone, `Why, Mary Ann, what ARE -you doing out here? Run home this moment, and fetch me a pair of -gloves and a fan! Quick, now!' And Alice was so much frightened -that she ran off at once in the direction it pointed to, without -trying to explain the mistake it had made. - - `He took me for his housemaid,' she said to herself as she ran. -`How surprised he'll be when he finds out who I am! But I'd -better take him his fan and gloves--that is, if I can find them.' -As she said this, she came upon a neat little house, on the door -of which was a bright brass plate with the name `W. RABBIT' -engraved upon it. She went in without knocking, and hurried -upstairs, in great fear lest she should meet the real Mary Ann, -and be turned out of the house before she had found the fan and -gloves. - - `How queer it seems,' Alice said to herself, `to be going -messages for a rabbit! I suppose Dinah'll be sending me on -messages next!' And she began fancying the sort of thing that -would happen: `"Miss Alice! Come here directly, and get ready -for your walk!" "Coming in a minute, nurse! But I've got to see -that the mouse doesn't get out." Only I don't think,' Alice went -on, `that they'd let Dinah stop in the house if it began ordering -people about like that!' - - By this time she had found her way into a tidy little room with -a table in the window, and on it (as she had hoped) a fan and two -or three pairs of tiny white kid gloves: she took up the fan and -a pair of the gloves, and was just going to leave the room, when -her eye fell upon a little bottle that stood near the looking- -glass. There was no label this time with the words `DRINK ME,' -but nevertheless she uncorked it and put it to her lips. `I know -SOMETHING interesting is sure to happen,' she said to herself, -`whenever I eat or drink anything; so I'll just see what this -bottle does. I do hope it'll make me grow large again, for -really I'm quite tired of being such a tiny little thing!' - - It did so indeed, and much sooner than she had expected: -before she had drunk half the bottle, she found her head pressing -against the ceiling, and had to stoop to save her neck from being -broken. She hastily put down the bottle, saying to herself -`That's quite enough--I hope I shan't grow any more--As it is, I -can't get out at the door--I do wish I hadn't drunk quite so -much!' - - Alas! it was too late to wish that! She went on growing, and -growing, and very soon had to kneel down on the floor: in -another minute there was not even room for this, and she tried -the effect of lying down with one elbow against the door, and the -other arm curled round her head. Still she went on growing, and, -as a last resource, she put one arm out of the window, and one -foot up the chimney, and said to herself `Now I can do no more, -whatever happens. What WILL become of me?' - - Luckily for Alice, the little magic bottle had now had its full -effect, and she grew no larger: still it was very uncomfortable, -and, as there seemed to be no sort of chance of her ever getting -out of the room again, no wonder she felt unhappy. - - `It was much pleasanter at home,' thought poor Alice, `when one -wasn't always growing larger and smaller, and being ordered about -by mice and rabbits. I almost wish I hadn't gone down that -rabbit-hole--and yet--and yet--it's rather curious, you know, -this sort of life! I do wonder what CAN have happened to me! -When I used to read fairy-tales, I fancied that kind of thing -never happened, and now here I am in the middle of one! There -ought to be a book written about me, that there ought! And when -I grow up, I'll write one--but I'm grown up now,' she added in a -sorrowful tone; `at least there's no room to grow up any more -HERE.' - - `But then,' thought Alice, `shall I NEVER get any older than I -am now? That'll be a comfort, one way--never to be an old woman- --but then--always to have lessons to learn! Oh, I shouldn't like -THAT!' - - `Oh, you foolish Alice!' she answered herself. `How can you -learn lessons in here? Why, there's hardly room for YOU, and no -room at all for any lesson-books!' - - And so she went on, taking first one side and then the other, -and making quite a conversation of it altogether; but after a few -minutes she heard a voice outside, and stopped to listen. - - `Mary Ann! Mary Ann!' said the voice. `Fetch me my gloves -this moment!' Then came a little pattering of feet on the -stairs. Alice knew it was the Rabbit coming to look for her, and -she trembled till she shook the house, quite forgetting that she -was now about a thousand times as large as the Rabbit, and had no -reason to be afraid of it. - - Presently the Rabbit came up to the door, and tried to open it; -but, as the door opened inwards, and Alice's elbow was pressed -hard against it, that attempt proved a failure. Alice heard it -say to itself `Then I'll go round and get in at the window.' - - `THAT you won't' thought Alice, and, after waiting till she -fancied she heard the Rabbit just under the window, she suddenly -spread out her hand, and made a snatch in the air. She did not -get hold of anything, but she heard a little shriek and a fall, -and a crash of broken glass, from which she concluded that it was -just possible it had fallen into a cucumber-frame, or something -of the sort. - - Next came an angry voice--the Rabbit's--`Pat! Pat! Where are -you?' And then a voice she had never heard before, `Sure then -I'm here! Digging for apples, yer honour!' - - `Digging for apples, indeed!' said the Rabbit angrily. `Here! -Come and help me out of THIS!' (Sounds of more broken glass.) - - `Now tell me, Pat, what's that in the window?' - - `Sure, it's an arm, yer honour!' (He pronounced it `arrum.') - - `An arm, you goose! Who ever saw one that size? Why, it -fills the whole window!' - - `Sure, it does, yer honour: but it's an arm for all that.' - - `Well, it's got no business there, at any rate: go and take it -away!' - - There was a long silence after this, and Alice could only hear -whispers now and then; such as, `Sure, I don't like it, yer -honour, at all, at all!' `Do as I tell you, you coward!' and at -last she spread out her hand again, and made another snatch in -the air. This time there were TWO little shrieks, and more -sounds of broken glass. `What a number of cucumber-frames there -must be!' thought Alice. `I wonder what they'll do next! As for -pulling me out of the window, I only wish they COULD! I'm sure I -don't want to stay in here any longer!' - - She waited for some time without hearing anything more: at -last came a rumbling of little cartwheels, and the sound of a -good many voice all talking together: she made out the words: -`Where's the other ladder?--Why, I hadn't to bring but one; -Bill's got the other--Bill! fetch it here, lad!--Here, put 'em up -at this corner--No, tie 'em together first--they don't reach half -high enough yet--Oh! they'll do well enough; don't be particular- --Here, Bill! catch hold of this rope--Will the roof bear?--Mind -that loose slate--Oh, it's coming down! Heads below!' (a loud -crash)--`Now, who did that?--It was Bill, I fancy--Who's to go -down the chimney?--Nay, I shan't! YOU do it!--That I won't, -then!--Bill's to go down--Here, Bill! the master says you're to -go down the chimney!' - - `Oh! So Bill's got to come down the chimney, has he?' said -Alice to herself. `Shy, they seem to put everything upon Bill! -I wouldn't be in Bill's place for a good deal: this fireplace is -narrow, to be sure; but I THINK I can kick a little!' - - She drew her foot as far down the chimney as she could, and -waited till she heard a little animal (she couldn't guess of what -sort it was) scratching and scrambling about in the chimney close -above her: then, saying to herself `This is Bill,' she gave one -sharp kick, and waited to see what would happen next. - - The first thing she heard was a general chorus of `There goes -Bill!' then the Rabbit's voice along--`Catch him, you by the -hedge!' then silence, and then another confusion of voices--`Hold -up his head--Brandy now--Don't choke him--How was it, old fellow? -What happened to you? Tell us all about it!' - - Last came a little feeble, squeaking voice, (`That's Bill,' -thought Alice,) `Well, I hardly know--No more, thank ye; I'm -better now--but I'm a deal too flustered to tell you--all I know -is, something comes at me like a Jack-in-the-box, and up I goes -like a sky-rocket!' - - `So you did, old fellow!' said the others. - - `We must burn the house down!' said the Rabbit's voice; and -Alice called out as loud as she could, `If you do. I'll set -Dinah at you!' - - There was a dead silence instantly, and Alice thought to -herself, `I wonder what they WILL do next! If they had any -sense, they'd take the roof off.' After a minute or two, they -began moving about again, and Alice heard the Rabbit say, `A -barrowful will do, to begin with.' - - `A barrowful of WHAT?' thought Alice; but she had not long to -doubt, for the next moment a shower of little pebbles came -rattling in at the window, and some of them hit her in the face. -`I'll put a stop to this,' she said to herself, and shouted out, -`You'd better not do that again!' which produced another dead -silence. - - Alice noticed with some surprise that the pebbles were all -turning into little cakes as they lay on the floor, and a bright -idea came into her head. `If I eat one of these cakes,' she -thought, `it's sure to make SOME change in my size; and as it -can't possibly make me larger, it must make me smaller, I -suppose.' - - So she swallowed one of the cakes, and was delighted to find -that she began shrinking directly. As soon as she was small -enough to get through the door, she ran out of the house, and -found quite a crowd of little animals and birds waiting outside. -The poor little Lizard, Bill, was in the middle, being held up by -two guinea-pigs, who were giving it something out of a bottle. -They all made a rush at Alice the moment she appeared; but she -ran off as hard as she could, and soon found herself safe in a -thick wood. - - `The first thing I've got to do,' said Alice to herself, as she -wandered about in the wood, `is to grow to my right size again; -and the second thing is to find my way into that lovely garden. -I think that will be the best plan.' - - It sounded an excellent plan, no doubt, and very neatly and -simply arranged; the only difficulty was, that she had not the -smallest idea how to set about it; and while she was peering -about anxiously among the trees, a little sharp bark just over -her head made her look up in a great hurry. - - An enormous puppy was looking down at her with large round -eyes, and feebly stretching out one paw, trying to touch her. -`Poor little thing!' said Alice, in a coaxing tone, and she tried -hard to whistle to it; but she was terribly frightened all the -time at the thought that it might be hungry, in which case it -would be very likely to eat her up in spite of all her coaxing. - - Hardly knowing what she did, she picked up a little bit of -stick, and held it out to the puppy; whereupon the puppy jumped -into the air off all its feet at once, with a yelp of delight, -and rushed at the stick, and made believe to worry it; then Alice -dodged behind a great thistle, to keep herself from being run -over; and the moment she appeared on the other side, the puppy -made another rush at the stick, and tumbled head over heels in -its hurry to get hold of it; then Alice, thinking it was very -like having a game of play with a cart-horse, and expecting every -moment to be trampled under its feet, ran round the thistle -again; then the puppy began a series of short charges at the -stick, running a very little way forwards each time and a long -way back, and barking hoarsely all the while, till at last it sat -down a good way off, panting, with its tongue hanging out of its -mouth, and its great eyes half shut. - - This seemed to Alice a good opportunity for making her escape; -so she set off at once, and ran till she was quite tired and out -of breath, and till the puppy's bark sounded quite faint in the -distance. - - `And yet what a dear little puppy it was!' said Alice, as she -leant against a buttercup to rest herself, and fanned herself -with one of the leaves: `I should have liked teaching it tricks -very much, if--if I'd only been the right size to do it! Oh -dear! I'd nearly forgotten that I've got to grow up again! Let -me see--how IS it to be managed? I suppose I ought to eat or -drink something or other; but the great question is, what?' - - The great question certainly was, what? Alice looked all round -her at the flowers and the blades of grass, but she did not see -anything that looked like the right thing to eat or drink under -the circumstances. There was a large mushroom growing near her, -about the same height as herself; and when she had looked under -it, and on both sides of it, and behind it, it occurred to her -that she might as well look and see what was on the top of it. - - She stretched herself up on tiptoe, and peeped over the edge of -the mushroom, and her eyes immediately met those of a large -caterpillar, that was sitting on the top with its arms folded, -quietly smoking a long hookah, and taking not the smallest notice -of her or of anything else. - - - - CHAPTER V - - Advice from a Caterpillar - - - The Caterpillar and Alice looked at each other for some time in -silence: at last the Caterpillar took the hookah out of its -mouth, and addressed her in a languid, sleepy voice. - - `Who are YOU?' said the Caterpillar. - - This was not an encouraging opening for a conversation. Alice -replied, rather shyly, `I--I hardly know, sir, just at present-- -at least I know who I WAS when I got up this morning, but I think -I must have been changed several times since then.' - - `What do you mean by that?' said the Caterpillar sternly. -`Explain yourself!' - - `I can't explain MYSELF, I'm afraid, sir' said Alice, `because -I'm not myself, you see.' - - `I don't see,' said the Caterpillar. - - `I'm afraid I can't put it more clearly,' Alice replied very -politely, `for I can't understand it myself to begin with; and -being so many different sizes in a day is very confusing.' - - `It isn't,' said the Caterpillar. - - `Well, perhaps you haven't found it so yet,' said Alice; `but -when you have to turn into a chrysalis--you will some day, you -know--and then after that into a butterfly, I should think you'll -feel it a little queer, won't you?' - - `Not a bit,' said the Caterpillar. - - `Well, perhaps your feelings may be different,' said Alice; -`all I know is, it would feel very queer to ME.' - - `You!' said the Caterpillar contemptuously. `Who are YOU?' - - Which brought them back again to the beginning of the -conversation. Alice felt a little irritated at the Caterpillar's -making such VERY short remarks, and she drew herself up and said, -very gravely, `I think, you ought to tell me who YOU are, first.' - - `Why?' said the Caterpillar. - - Here was another puzzling question; and as Alice could not -think of any good reason, and as the Caterpillar seemed to be in -a VERY unpleasant state of mind, she turned away. - - `Come back!' the Caterpillar called after her. `I've something -important to say!' - - This sounded promising, certainly: Alice turned and came back -again. - - `Keep your temper,' said the Caterpillar. - - `Is that all?' said Alice, swallowing down her anger as well as -she could. - - `No,' said the Caterpillar. - - Alice thought she might as well wait, as she had nothing else -to do, and perhaps after all it might tell her something worth -hearing. For some minutes it puffed away without speaking, but -at last it unfolded its arms, took the hookah out of its mouth -again, and said, `So you think you're changed, do you?' - - `I'm afraid I am, sir,' said Alice; `I can't remember things as -I used--and I don't keep the same size for ten minutes together!' - - `Can't remember WHAT things?' said the Caterpillar. - - `Well, I've tried to say "HOW DOTH THE LITTLE BUSY BEE," but it -all came different!' Alice replied in a very melancholy voice. - - `Repeat, "YOU ARE OLD, FATHER WILLIAM,"' said the Caterpillar. - - Alice folded her hands, and began:-- - - `You are old, Father William,' the young man said, - `And your hair has become very white; - And yet you incessantly stand on your head-- - Do you think, at your age, it is right?' - - `In my youth,' Father William replied to his son, - `I feared it might injure the brain; - But, now that I'm perfectly sure I have none, - Why, I do it again and again.' - - `You are old,' said the youth, `as I mentioned before, - And have grown most uncommonly fat; - Yet you turned a back-somersault in at the door-- - Pray, what is the reason of that?' - - `In my youth,' said the sage, as he shook his grey locks, - `I kept all my limbs very supple - By the use of this ointment--one shilling the box-- - Allow me to sell you a couple?' - - `You are old,' said the youth, `and your jaws are too weak - For anything tougher than suet; - Yet you finished the goose, with the bones and the beak-- - Pray how did you manage to do it?' - - `In my youth,' said his father, `I took to the law, - And argued each case with my wife; - And the muscular strength, which it gave to my jaw, - Has lasted the rest of my life.' - - `You are old,' said the youth, `one would hardly suppose - That your eye was as steady as ever; - Yet you balanced an eel on the end of your nose-- - What made you so awfully clever?' - - `I have answered three questions, and that is enough,' - Said his father; `don't give yourself airs! - Do you think I can listen all day to such stuff? - Be off, or I'll kick you down stairs!' - - - `That is not said right,' said the Caterpillar. - - `Not QUITE right, I'm afraid,' said Alice, timidly; `some of the -words have got altered.' - - `It is wrong from beginning to end,' said the Caterpillar -decidedly, and there was silence for some minutes. - - The Caterpillar was the first to speak. - - `What size do you want to be?' it asked. - - `Oh, I'm not particular as to size,' Alice hastily replied; -`only one doesn't like changing so often, you know.' - - `I DON'T know,' said the Caterpillar. - - Alice said nothing: she had never been so much contradicted in -her life before, and she felt that she was losing her temper. - - `Are you content now?' said the Caterpillar. - - `Well, I should like to be a LITTLE larger, sir, if you -wouldn't mind,' said Alice: `three inches is such a wretched -height to be.' - - `It is a very good height indeed!' said the Caterpillar -angrily, rearing itself upright as it spoke (it was exactly three -inches high). - - `But I'm not used to it!' pleaded poor Alice in a piteous tone. -And she thought of herself, `I wish the creatures wouldn't be so -easily offended!' - - `You'll get used to it in time,' said the Caterpillar; and it -put the hookah into its mouth and began smoking again. - - This time Alice waited patiently until it chose to speak again. -In a minute or two the Caterpillar took the hookah out of its -mouth and yawned once or twice, and shook itself. Then it got -down off the mushroom, and crawled away in the grass, merely -remarking as it went, `One side will make you grow taller, and -the other side will make you grow shorter.' - - `One side of WHAT? The other side of WHAT?' thought Alice to -herself. - - `Of the mushroom,' said the Caterpillar, just as if she had -asked it aloud; and in another moment it was out of sight. - - Alice remained looking thoughtfully at the mushroom for a -minute, trying to make out which were the two sides of it; and as -it was perfectly round, she found this a very difficult question. -However, at last she stretched her arms round it as far as they -would go, and broke off a bit of the edge with each hand. - - `And now which is which?' she said to herself, and nibbled a -little of the right-hand bit to try the effect: the next moment -she felt a violent blow underneath her chin: it had struck her -foot! - - She was a good deal frightened by this very sudden change, but -she felt that there was no time to be lost, as she was shrinking -rapidly; so she set to work at once to eat some of the other bit. -Her chin was pressed so closely against her foot, that there was -hardly room to open her mouth; but she did it at last, and -managed to swallow a morsel of the lefthand bit. - - - * * * * * * * - - * * * * * * - - * * * * * * * - - `Come, my head's free at last!' said Alice in a tone of -delight, which changed into alarm in another moment, when she -found that her shoulders were nowhere to be found: all she could -see, when she looked down, was an immense length of neck, which -seemed to rise like a stalk out of a sea of green leaves that lay -far below her. - - `What CAN all that green stuff be?' said Alice. `And where -HAVE my shoulders got to? And oh, my poor hands, how is it I -can't see you?' She was moving them about as she spoke, but no -result seemed to follow, except a little shaking among the -distant green leaves. - - As there seemed to be no chance of getting her hands up to her -head, she tried to get her head down to them, and was delighted -to find that her neck would bend about easily in any direction, -like a serpent. She had just succeeded in curving it down into a -graceful zigzag, and was going to dive in among the leaves, which -she found to be nothing but the tops of the trees under which she -had been wandering, when a sharp hiss made her draw back in a -hurry: a large pigeon had flown into her face, and was beating -her violently with its wings. - - `Serpent!' screamed the Pigeon. - - `I'm NOT a serpent!' said Alice indignantly. `Let me alone!' - - `Serpent, I say again!' repeated the Pigeon, but in a more -subdued tone, and added with a kind of sob, `I've tried every -way, and nothing seems to suit them!' - - `I haven't the least idea what you're talking about,' said -Alice. - - `I've tried the roots of trees, and I've tried banks, and I've -tried hedges,' the Pigeon went on, without attending to her; `but -those serpents! There's no pleasing them!' - - Alice was more and more puzzled, but she thought there was no -use in saying anything more till the Pigeon had finished. - - `As if it wasn't trouble enough hatching the eggs,' said the -Pigeon; `but I must be on the look-out for serpents night and -day! Why, I haven't had a wink of sleep these three weeks!' - - `I'm very sorry you've been annoyed,' said Alice, who was -beginning to see its meaning. - - `And just as I'd taken the highest tree in the wood,' continued -the Pigeon, raising its voice to a shriek, `and just as I was -thinking I should be free of them at last, they must needs come -wriggling down from the sky! Ugh, Serpent!' - - `But I'm NOT a serpent, I tell you!' said Alice. `I'm a--I'm -a--' - - `Well! WHAT are you?' said the Pigeon. `I can see you're -trying to invent something!' - - `I--I'm a little girl,' said Alice, rather doubtfully, as she -remembered the number of changes she had gone through that day. - - `A likely story indeed!' said the Pigeon in a tone of the -deepest contempt. `I've seen a good many little girls in my -time, but never ONE with such a neck as that! No, no! You're a -serpent; and there's no use denying it. I suppose you'll be -telling me next that you never tasted an egg!' - - `I HAVE tasted eggs, certainly,' said Alice, who was a very -truthful child; `but little girls eat eggs quite as much as -serpents do, you know.' - - `I don't believe it,' said the Pigeon; `but if they do, why -then they're a kind of serpent, that's all I can say.' - - This was such a new idea to Alice, that she was quite silent -for a minute or two, which gave the Pigeon the opportunity of -adding, `You're looking for eggs, I know THAT well enough; and -what does it matter to me whether you're a little girl or a -serpent?' - - `It matters a good deal to ME,' said Alice hastily; `but I'm -not looking for eggs, as it happens; and if I was, I shouldn't -want YOURS: I don't like them raw.' - - `Well, be off, then!' said the Pigeon in a sulky tone, as it -settled down again into its nest. Alice crouched down among the -trees as well as she could, for her neck kept getting entangled -among the branches, and every now and then she had to stop and -untwist it. After a while she remembered that she still held the -pieces of mushroom in her hands, and she set to work very -carefully, nibbling first at one and then at the other, and -growing sometimes taller and sometimes shorter, until she had -succeeded in bringing herself down to her usual height. - - It was so long since she had been anything near the right size, -that it felt quite strange at first; but she got used to it in a -few minutes, and began talking to herself, as usual. `Come, -there's half my plan done now! How puzzling all these changes -are! I'm never sure what I'm going to be, from one minute to -another! However, I've got back to my right size: the next -thing is, to get into that beautiful garden--how IS that to be -done, I wonder?' As she said this, she came suddenly upon an -open place, with a little house in it about four feet high. -`Whoever lives there,' thought Alice, `it'll never do to come -upon them THIS size: why, I should frighten them out of their -wits!' So she began nibbling at the righthand bit again, and did -not venture to go near the house till she had brought herself -down to nine inches high. - - - - CHAPTER VI - - Pig and Pepper - - - For a minute or two she stood looking at the house, and -wondering what to do next, when suddenly a footman in livery came -running out of the wood--(she considered him to be a footman -because he was in livery: otherwise, judging by his face only, -she would have called him a fish)--and rapped loudly at the door -with his knuckles. It was opened by another footman in livery, -with a round face, and large eyes like a frog; and both footmen, -Alice noticed, had powdered hair that curled all over their -heads. She felt very curious to know what it was all about, and -crept a little way out of the wood to listen. - - The Fish-Footman began by producing from under his arm a great -letter, nearly as large as himself, and this he handed over to -the other, saying, in a solemn tone, `For the Duchess. An -invitation from the Queen to play croquet.' The Frog-Footman -repeated, in the same solemn tone, only changing the order of the -words a little, `From the Queen. An invitation for the Duchess -to play croquet.' - - Then they both bowed low, and their curls got entangled -together. - - Alice laughed so much at this, that she had to run back into -the wood for fear of their hearing her; and when she next peeped -out the Fish-Footman was gone, and the other was sitting on the -ground near the door, staring stupidly up into the sky. - - Alice went timidly up to the door, and knocked. - - `There's no sort of use in knocking,' said the Footman, `and -that for two reasons. First, because I'm on the same side of the -door as you are; secondly, because they're making such a noise -inside, no one could possibly hear you.' And certainly there was -a most extraordinary noise going on within--a constant howling -and sneezing, and every now and then a great crash, as if a dish -or kettle had been broken to pieces. - - `Please, then,' said Alice, `how am I to get in?' - - `There might be some sense in your knocking,' the Footman went -on without attending to her, `if we had the door between us. For -instance, if you were INSIDE, you might knock, and I could let -you out, you know.' He was looking up into the sky all the time -he was speaking, and this Alice thought decidedly uncivil. `But -perhaps he can't help it,' she said to herself; `his eyes are so -VERY nearly at the top of his head. But at any rate he might -answer questions.--How am I to get in?' she repeated, aloud. - - `I shall sit here,' the Footman remarked, `till tomorrow--' - - At this moment the door of the house opened, and a large plate -came skimming out, straight at the Footman's head: it just -grazed his nose, and broke to pieces against one of the trees -behind him. - - `--or next day, maybe,' the Footman continued in the same tone, -exactly as if nothing had happened. - - `How am I to get in?' asked Alice again, in a louder tone. - - `ARE you to get in at all?' said the Footman. `That's the -first question, you know.' - - It was, no doubt: only Alice did not like to be told so. -`It's really dreadful,' she muttered to herself, `the way all the -creatures argue. It's enough to drive one crazy!' - - The Footman seemed to think this a good opportunity for -repeating his remark, with variations. `I shall sit here,' he -said, `on and off, for days and days.' - - `But what am I to do?' said Alice. - - `Anything you like,' said the Footman, and began whistling. - - `Oh, there's no use in talking to him,' said Alice desperately: -`he's perfectly idiotic!' And she opened the door and went in. - - The door led right into a large kitchen, which was full of -smoke from one end to the other: the Duchess was sitting on a -three-legged stool in the middle, nursing a baby; the cook was -leaning over the fire, stirring a large cauldron which seemed to -be full of soup. - - `There's certainly too much pepper in that soup!' Alice said to -herself, as well as she could for sneezing. - - There was certainly too much of it in the air. Even the -Duchess sneezed occasionally; and as for the baby, it was -sneezing and howling alternately without a moment's pause. The -only things in the kitchen that did not sneeze, were the cook, -and a large cat which was sitting on the hearth and grinning from -ear to ear. - - `Please would you tell me,' said Alice, a little timidly, for -she was not quite sure whether it was good manners for her to -speak first, `why your cat grins like that?' - - `It's a Cheshire cat,' said the Duchess, `and that's why. -Pig!' - - She said the last word with such sudden violence that Alice -quite jumped; but she saw in another moment that it was addressed -to the baby, and not to her, so she took courage, and went on -again:-- - - `I didn't know that Cheshire cats always grinned; in fact, I -didn't know that cats COULD grin.' - - `They all can,' said the Duchess; `and most of 'em do.' - - `I don't know of any that do,' Alice said very politely, -feeling quite pleased to have got into a conversation. - - `You don't know much,' said the Duchess; `and that's a fact.' - - Alice did not at all like the tone of this remark, and thought -it would be as well to introduce some other subject of -conversation. While she was trying to fix on one, the cook took -the cauldron of soup off the fire, and at once set to work -throwing everything within her reach at the Duchess and the baby ---the fire-irons came first; then followed a shower of saucepans, -plates, and dishes. The Duchess took no notice of them even when -they hit her; and the baby was howling so much already, that it -was quite impossible to say whether the blows hurt it or not. - - `Oh, PLEASE mind what you're doing!' cried Alice, jumping up -and down in an agony of terror. `Oh, there goes his PRECIOUS -nose'; as an unusually large saucepan flew close by it, and very -nearly carried it off. - - `If everybody minded their own business,' the Duchess said in a -hoarse growl, `the world would go round a deal faster than it -does.' - - `Which would NOT be an advantage,' said Alice, who felt very -glad to get an opportunity of showing off a little of her -knowledge. `Just think of what work it would make with the day -and night! You see the earth takes twenty-four hours to turn -round on its axis--' - - `Talking of axes,' said the Duchess, `chop off her head!' - - Alice glanced rather anxiously at the cook, to see if she meant -to take the hint; but the cook was busily stirring the soup, and -seemed not to be listening, so she went on again: `Twenty-four -hours, I THINK; or is it twelve? I--' - - `Oh, don't bother ME,' said the Duchess; `I never could abide -figures!' And with that she began nursing her child again, -singing a sort of lullaby to it as she did so, and giving it a -violent shake at the end of every line: - - `Speak roughly to your little boy, - And beat him when he sneezes: - He only does it to annoy, - Because he knows it teases.' - - CHORUS. - - (In which the cook and the baby joined):-- - - `Wow! wow! wow!' - - While the Duchess sang the second verse of the song, she kept -tossing the baby violently up and down, and the poor little thing -howled so, that Alice could hardly hear the words:-- - - `I speak severely to my boy, - I beat him when he sneezes; - For he can thoroughly enjoy - The pepper when he pleases!' - - CHORUS. - - `Wow! wow! wow!' - - `Here! you may nurse it a bit, if you like!' the Duchess said -to Alice, flinging the baby at her as she spoke. `I must go and -get ready to play croquet with the Queen,' and she hurried out of -the room. The cook threw a frying-pan after her as she went out, -but it just missed her. - - Alice caught the baby with some difficulty, as it was a queer- -shaped little creature, and held out its arms and legs in all -directions, `just like a star-fish,' thought Alice. The poor -little thing was snorting like a steam-engine when she caught it, -and kept doubling itself up and straightening itself out again, -so that altogether, for the first minute or two, it was as much -as she could do to hold it. - - As soon as she had made out the proper way of nursing it, -(which was to twist it up into a sort of knot, and then keep -tight hold of its right ear and left foot, so as to prevent its -undoing itself,) she carried it out into the open air. `IF I -don't take this child away with me,' thought Alice, `they're sure -to kill it in a day or two: wouldn't it be murder to leave it -behind?' She said the last words out loud, and the little thing -grunted in reply (it had left off sneezing by this time). `Don't -grunt,' said Alice; `that's not at all a proper way of expressing -yourself.' - - The baby grunted again, and Alice looked very anxiously into -its face to see what was the matter with it. There could be no -doubt that it had a VERY turn-up nose, much more like a snout -than a real nose; also its eyes were getting extremely small for -a baby: altogether Alice did not like the look of the thing at -all. `But perhaps it was only sobbing,' she thought, and looked -into its eyes again, to see if there were any tears. - - No, there were no tears. `If you're going to turn into a pig, -my dear,' said Alice, seriously, `I'll have nothing more to do -with you. Mind now!' The poor little thing sobbed again (or -grunted, it was impossible to say which), and they went on for -some while in silence. - - Alice was just beginning to think to herself, `Now, what am I -to do with this creature when I get it home?' when it grunted -again, so violently, that she looked down into its face in some -alarm. This time there could be NO mistake about it: it was -neither more nor less than a pig, and she felt that it would be -quite absurd for her to carry it further. - - So she set the little creature down, and felt quite relieved to -see it trot away quietly into the wood. `If it had grown up,' -she said to herself, `it would have made a dreadfully ugly child: -but it makes rather a handsome pig, I think.' And she began -thinking over other children she knew, who might do very well as -pigs, and was just saying to herself, `if one only knew the right -way to change them--' when she was a little startled by seeing -the Cheshire Cat sitting on a bough of a tree a few yards off. - - The Cat only grinned when it saw Alice. It looked good- -natured, she thought: still it had VERY long claws and a great -many teeth, so she felt that it ought to be treated with respect. - - `Cheshire Puss,' she began, rather timidly, as she did not at -all know whether it would like the name: however, it only -grinned a little wider. `Come, it's pleased so far,' thought -Alice, and she went on. `Would you tell me, please, which way I -ought to go from here?' - - `That depends a good deal on where you want to get to,' said -the Cat. - - `I don't much care where--' said Alice. - - `Then it doesn't matter which way you go,' said the Cat. - - `--so long as I get SOMEWHERE,' Alice added as an explanation. - - `Oh, you're sure to do that,' said the Cat, `if you only walk -long enough.' - - Alice felt that this could not be denied, so she tried another -question. `What sort of people live about here?' - - `In THAT direction,' the Cat said, waving its right paw round, -`lives a Hatter: and in THAT direction,' waving the other paw, -`lives a March Hare. Visit either you like: they're both mad.' - - `But I don't want to go among mad people,' Alice remarked. - - `Oh, you can't help that,' said the Cat: `we're all mad here. -I'm mad. You're mad.' - - `How do you know I'm mad?' said Alice. - - `You must be,' said the Cat, `or you wouldn't have come here.' - - Alice didn't think that proved it at all; however, she went on -`And how do you know that you're mad?' - - `To begin with,' said the Cat, `a dog's not mad. You grant -that?' - - `I suppose so,' said Alice. - - `Well, then,' the Cat went on, `you see, a dog growls when it's -angry, and wags its tail when it's pleased. Now I growl when I'm -pleased, and wag my tail when I'm angry. Therefore I'm mad.' - - `I call it purring, not growling,' said Alice. - - `Call it what you like,' said the Cat. `Do you play croquet -with the Queen to-day?' - - `I should like it very much,' said Alice, `but I haven't been -invited yet.' - - `You'll see me there,' said the Cat, and vanished. - - Alice was not much surprised at this, she was getting so used -to queer things happening. While she was looking at the place -where it had been, it suddenly appeared again. - - `By-the-bye, what became of the baby?' said the Cat. `I'd -nearly forgotten to ask.' - - `It turned into a pig,' Alice quietly said, just as if it had -come back in a natural way. - - `I thought it would,' said the Cat, and vanished again. - - Alice waited a little, half expecting to see it again, but it -did not appear, and after a minute or two she walked on in the -direction in which the March Hare was said to live. `I've seen -hatters before,' she said to herself; `the March Hare will be -much the most interesting, and perhaps as this is May it won't be -raving mad--at least not so mad as it was in March.' As she said -this, she looked up, and there was the Cat again, sitting on a -branch of a tree. - - `Did you say pig, or fig?' said the Cat. - - `I said pig,' replied Alice; `and I wish you wouldn't keep -appearing and vanishing so suddenly: you make one quite giddy.' - - `All right,' said the Cat; and this time it vanished quite -slowly, beginning with the end of the tail, and ending with the -grin, which remained some time after the rest of it had gone. - - `Well! I've often seen a cat without a grin,' thought Alice; -`but a grin without a cat! It's the most curious thing I ever -say in my life!' - - She had not gone much farther before she came in sight of the -house of the March Hare: she thought it must be the right house, -because the chimneys were shaped like ears and the roof was -thatched with fur. It was so large a house, that she did not -like to go nearer till she had nibbled some more of the lefthand -bit of mushroom, and raised herself to about two feet high: even -then she walked up towards it rather timidly, saying to herself -`Suppose it should be raving mad after all! I almost wish I'd -gone to see the Hatter instead!' - - - - CHAPTER VII - - A Mad Tea-Party - - - There was a table set out under a tree in front of the house, -and the March Hare and the Hatter were having tea at it: a -Dormouse was sitting between them, fast asleep, and the other two -were using it as a cushion, resting their elbows on it, and the -talking over its head. `Very uncomfortable for the Dormouse,' -thought Alice; `only, as it's asleep, I suppose it doesn't mind.' - - The table was a large one, but the three were all crowded -together at one corner of it: `No room! No room!' they cried -out when they saw Alice coming. `There's PLENTY of room!' said -Alice indignantly, and she sat down in a large arm-chair at one -end of the table. - - `Have some wine,' the March Hare said in an encouraging tone. - - Alice looked all round the table, but there was nothing on it -but tea. `I don't see any wine,' she remarked. - - `There isn't any,' said the March Hare. - - `Then it wasn't very civil of you to offer it,' said Alice -angrily. - - `It wasn't very civil of you to sit down without being -invited,' said the March Hare. - - `I didn't know it was YOUR table,' said Alice; `it's laid for a -great many more than three.' - - `Your hair wants cutting,' said the Hatter. He had been -looking at Alice for some time with great curiosity, and this was -his first speech. - - `You should learn not to make personal remarks,' Alice said -with some severity; `it's very rude.' - - The Hatter opened his eyes very wide on hearing this; but all -he SAID was, `Why is a raven like a writing-desk?' - - `Come, we shall have some fun now!' thought Alice. `I'm glad -they've begun asking riddles.--I believe I can guess that,' she -added aloud. - - `Do you mean that you think you can find out the answer to it?' -said the March Hare. - - `Exactly so,' said Alice. - - `Then you should say what you mean,' the March Hare went on. - - `I do,' Alice hastily replied; `at least--at least I mean what -I say--that's the same thing, you know.' - - `Not the same thing a bit!' said the Hatter. `You might just -as well say that "I see what I eat" is the same thing as "I eat -what I see"!' - - `You might just as well say,' added the March Hare, `that "I -like what I get" is the same thing as "I get what I like"!' - - `You might just as well say,' added the Dormouse, who seemed to -be talking in his sleep, `that "I breathe when I sleep" is the -same thing as "I sleep when I breathe"!' - - `It IS the same thing with you,' said the Hatter, and here the -conversation dropped, and the party sat silent for a minute, -while Alice thought over all she could remember about ravens and -writing-desks, which wasn't much. - - The Hatter was the first to break the silence. `What day of -the month is it?' he said, turning to Alice: he had taken his -watch out of his pocket, and was looking at it uneasily, shaking -it every now and then, and holding it to his ear. - - Alice considered a little, and then said `The fourth.' - - `Two days wrong!' sighed the Hatter. `I told you butter -wouldn't suit the works!' he added looking angrily at the March -Hare. - - `It was the BEST butter,' the March Hare meekly replied. - - `Yes, but some crumbs must have got in as well,' the Hatter -grumbled: `you shouldn't have put it in with the bread-knife.' - - The March Hare took the watch and looked at it gloomily: then -he dipped it into his cup of tea, and looked at it again: but he -could think of nothing better to say than his first remark, `It -was the BEST butter, you know.' - - Alice had been looking over his shoulder with some curiosity. -`What a funny watch!' she remarked. `It tells the day of the -month, and doesn't tell what o'clock it is!' - - `Why should it?' muttered the Hatter. `Does YOUR watch tell -you what year it is?' - - `Of course not,' Alice replied very readily: `but that's -because it stays the same year for such a long time together.' - - `Which is just the case with MINE,' said the Hatter. - - Alice felt dreadfully puzzled. The Hatter's remark seemed to -have no sort of meaning in it, and yet it was certainly English. -`I don't quite understand you,' she said, as politely as she -could. - - `The Dormouse is asleep again,' said the Hatter, and he poured -a little hot tea upon its nose. - - The Dormouse shook its head impatiently, and said, without -opening its eyes, `Of course, of course; just what I was going to -remark myself.' - - `Have you guessed the riddle yet?' the Hatter said, turning to -Alice again. - - `No, I give it up,' Alice replied: `what's the answer?' - - `I haven't the slightest idea,' said the Hatter. - - `Nor I,' said the March Hare. - - Alice sighed wearily. `I think you might do something better -with the time,' she said, `than waste it in asking riddles that -have no answers.' - - `If you knew Time as well as I do,' said the Hatter, `you -wouldn't talk about wasting IT. It's HIM.' - - `I don't know what you mean,' said Alice. - - `Of course you don't!' the Hatter said, tossing his head -contemptuously. `I dare say you never even spoke to Time!' - - `Perhaps not,' Alice cautiously replied: `but I know I have to -beat time when I learn music.' - - `Ah! that accounts for it,' said the Hatter. `He won't stand -beating. Now, if you only kept on good terms with him, he'd do -almost anything you liked with the clock. For instance, suppose -it were nine o'clock in the morning, just time to begin lessons: -you'd only have to whisper a hint to Time, and round goes the -clock in a twinkling! Half-past one, time for dinner!' - - (`I only wish it was,' the March Hare said to itself in a -whisper.) - - `That would be grand, certainly,' said Alice thoughtfully: -`but then--I shouldn't be hungry for it, you know.' - - `Not at first, perhaps,' said the Hatter: `but you could keep -it to half-past one as long as you liked.' - - `Is that the way YOU manage?' Alice asked. - - The Hatter shook his head mournfully. `Not I!' he replied. -`We quarrelled last March--just before HE went mad, you know--' -(pointing with his tea spoon at the March Hare,) `--it was at the -great concert given by the Queen of Hearts, and I had to sing - - "Twinkle, twinkle, little bat! - How I wonder what you're at!" - -You know the song, perhaps?' - - `I've heard something like it,' said Alice. - - `It goes on, you know,' the Hatter continued, `in this way:-- - - "Up above the world you fly, - Like a tea-tray in the sky. - Twinkle, twinkle--"' - -Here the Dormouse shook itself, and began singing in its sleep -`Twinkle, twinkle, twinkle, twinkle--' and went on so long that -they had to pinch it to make it stop. - - `Well, I'd hardly finished the first verse,' said the Hatter, -`when the Queen jumped up and bawled out, "He's murdering the -time! Off with his head!"' - - `How dreadfully savage!' exclaimed Alice. - - `And ever since that,' the Hatter went on in a mournful tone, -`he won't do a thing I ask! It's always six o'clock now.' - - A bright idea came into Alice's head. `Is that the reason so -many tea-things are put out here?' she asked. - - `Yes, that's it,' said the Hatter with a sigh: `it's always -tea-time, and we've no time to wash the things between whiles.' - - `Then you keep moving round, I suppose?' said Alice. - - `Exactly so,' said the Hatter: `as the things get used up.' - - `But what happens when you come to the beginning again?' Alice -ventured to ask. - - `Suppose we change the subject,' the March Hare interrupted, -yawning. `I'm getting tired of this. I vote the young lady -tells us a story.' - - `I'm afraid I don't know one,' said Alice, rather alarmed at -the proposal. - - `Then the Dormouse shall!' they both cried. `Wake up, -Dormouse!' And they pinched it on both sides at once. - - The Dormouse slowly opened his eyes. `I wasn't asleep,' he -said in a hoarse, feeble voice: `I heard every word you fellows -were saying.' - - `Tell us a story!' said the March Hare. - - `Yes, please do!' pleaded Alice. - - `And be quick about it,' added the Hatter, `or you'll be asleep -again before it's done.' - - `Once upon a time there were three little sisters,' the -Dormouse began in a great hurry; `and their names were Elsie, -Lacie, and Tillie; and they lived at the bottom of a well--' - - `What did they live on?' said Alice, who always took a great -interest in questions of eating and drinking. - - `They lived on treacle,' said the Dormouse, after thinking a -minute or two. - - `They couldn't have done that, you know,' Alice gently -remarked; `they'd have been ill.' - - `So they were,' said the Dormouse; `VERY ill.' - - Alice tried to fancy to herself what such an extraordinary ways -of living would be like, but it puzzled her too much, so she went -on: `But why did they live at the bottom of a well?' - - `Take some more tea,' the March Hare said to Alice, very -earnestly. - - `I've had nothing yet,' Alice replied in an offended tone, `so -I can't take more.' - - `You mean you can't take LESS,' said the Hatter: `it's very -easy to take MORE than nothing.' - - `Nobody asked YOUR opinion,' said Alice. - - `Who's making personal remarks now?' the Hatter asked -triumphantly. - - Alice did not quite know what to say to this: so she helped -herself to some tea and bread-and-butter, and then turned to the -Dormouse, and repeated her question. `Why did they live at the -bottom of a well?' - - The Dormouse again took a minute or two to think about it, and -then said, `It was a treacle-well.' - - `There's no such thing!' Alice was beginning very angrily, but -the Hatter and the March Hare went `Sh! sh!' and the Dormouse -sulkily remarked, `If you can't be civil, you'd better finish the -story for yourself.' - - `No, please go on!' Alice said very humbly; `I won't interrupt -again. I dare say there may be ONE.' - - `One, indeed!' said the Dormouse indignantly. However, he -consented to go on. `And so these three little sisters--they -were learning to draw, you know--' - - `What did they draw?' said Alice, quite forgetting her promise. - - `Treacle,' said the Dormouse, without considering at all this -time. - - `I want a clean cup,' interrupted the Hatter: `let's all move -one place on.' - - He moved on as he spoke, and the Dormouse followed him: the -March Hare moved into the Dormouse's place, and Alice rather -unwillingly took the place of the March Hare. The Hatter was the -only one who got any advantage from the change: and Alice was a -good deal worse off than before, as the March Hare had just upset -the milk-jug into his plate. - - Alice did not wish to offend the Dormouse again, so she began -very cautiously: `But I don't understand. Where did they draw -the treacle from?' - - `You can draw water out of a water-well,' said the Hatter; `so -I should think you could draw treacle out of a treacle-well--eh, -stupid?' - - `But they were IN the well,' Alice said to the Dormouse, not -choosing to notice this last remark. - - `Of course they were', said the Dormouse; `--well in.' - - This answer so confused poor Alice, that she let the Dormouse -go on for some time without interrupting it. - - `They were learning to draw,' the Dormouse went on, yawning and -rubbing its eyes, for it was getting very sleepy; `and they drew -all manner of things--everything that begins with an M--' - - `Why with an M?' said Alice. - - `Why not?' said the March Hare. - - Alice was silent. - - The Dormouse had closed its eyes by this time, and was going -off into a doze; but, on being pinched by the Hatter, it woke up -again with a little shriek, and went on: `--that begins with an -M, such as mouse-traps, and the moon, and memory, and muchness-- -you know you say things are "much of a muchness"--did you ever -see such a thing as a drawing of a muchness?' - - `Really, now you ask me,' said Alice, very much confused, `I -don't think--' - - `Then you shouldn't talk,' said the Hatter. - - This piece of rudeness was more than Alice could bear: she got -up in great disgust, and walked off; the Dormouse fell asleep -instantly, and neither of the others took the least notice of her -going, though she looked back once or twice, half hoping that -they would call after her: the last time she saw them, they were -trying to put the Dormouse into the teapot. - - `At any rate I'll never go THERE again!' said Alice as she -picked her way through the wood. `It's the stupidest tea-party I -ever was at in all my life!' - - Just as she said this, she noticed that one of the trees had a -door leading right into it. `That's very curious!' she thought. -`But everything's curious today. I think I may as well go in at -once.' And in she went. - - Once more she found herself in the long hall, and close to the -little glass table. `Now, I'll manage better this time,' she -said to herself, and began by taking the little golden key, and -unlocking the door that led into the garden. Then she went to -work nibbling at the mushroom (she had kept a piece of it in her -pocked) till she was about a foot high: then she walked down the -little passage: and THEN--she found herself at last in the -beautiful garden, among the bright flower-beds and the cool -fountains. - - - - CHAPTER VIII - - The Queen's Croquet-Ground - - - A large rose-tree stood near the entrance of the garden: the -roses growing on it were white, but there were three gardeners at -it, busily painting them red. Alice thought this a very curious -thing, and she went nearer to watch them, and just as she came up -to them she heard one of them say, `Look out now, Five! Don't go -splashing paint over me like that!' - - `I couldn't help it,' said Five, in a sulky tone; `Seven jogged -my elbow.' - - On which Seven looked up and said, `That's right, Five! Always -lay the blame on others!' - - `YOU'D better not talk!' said Five. `I heard the Queen say only -yesterday you deserved to be beheaded!' - - `What for?' said the one who had spoken first. - - `That's none of YOUR business, Two!' said Seven. - - `Yes, it IS his business!' said Five, `and I'll tell him--it -was for bringing the cook tulip-roots instead of onions.' - - Seven flung down his brush, and had just begun `Well, of all -the unjust things--' when his eye chanced to fall upon Alice, as -she stood watching them, and he checked himself suddenly: the -others looked round also, and all of them bowed low. - - `Would you tell me,' said Alice, a little timidly, `why you are -painting those roses?' - - Five and Seven said nothing, but looked at Two. Two began in a -low voice, `Why the fact is, you see, Miss, this here ought to -have been a RED rose-tree, and we put a white one in by mistake; -and if the Queen was to find it out, we should all have our heads -cut off, you know. So you see, Miss, we're doing our best, afore -she comes, to--' At this moment Five, who had been anxiously -looking across the garden, called out `The Queen! The Queen!' -and the three gardeners instantly threw themselves flat upon -their faces. There was a sound of many footsteps, and Alice -looked round, eager to see the Queen. - - First came ten soldiers carrying clubs; these were all shaped -like the three gardeners, oblong and flat, with their hands and -feet at the corners: next the ten courtiers; these were -ornamented all over with diamonds, and walked two and two, as the -soldiers did. After these came the royal children; there were -ten of them, and the little dears came jumping merrily along hand -in hand, in couples: they were all ornamented with hearts. Next -came the guests, mostly Kings and Queens, and among them Alice -recognised the White Rabbit: it was talking in a hurried nervous -manner, smiling at everything that was said, and went by without -noticing her. Then followed the Knave of Hearts, carrying the -King's crown on a crimson velvet cushion; and, last of all this -grand procession, came THE KING AND QUEEN OF HEARTS. - - Alice was rather doubtful whether she ought not to lie down on -her face like the three gardeners, but she could not remember -every having heard of such a rule at processions; `and besides, -what would be the use of a procession,' thought she, `if people -had all to lie down upon their faces, so that they couldn't see -it?' So she stood still where she was, and waited. - - When the procession came opposite to Alice, they all stopped -and looked at her, and the Queen said severely `Who is this?' -She said it to the Knave of Hearts, who only bowed and smiled in -reply. - - `Idiot!' said the Queen, tossing her head impatiently; and, -turning to Alice, she went on, `What's your name, child?' - - `My name is Alice, so please your Majesty,' said Alice very -politely; but she added, to herself, `Why, they're only a pack of -cards, after all. I needn't be afraid of them!' - - `And who are THESE?' said the Queen, pointing to the three -gardeners who were lying round the rosetree; for, you see, as -they were lying on their faces, and the pattern on their backs -was the same as the rest of the pack, she could not tell whether -they were gardeners, or soldiers, or courtiers, or three of her -own children. - - `How should I know?' said Alice, surprised at her own courage. -`It's no business of MINE.' - - The Queen turned crimson with fury, and, after glaring at her -for a moment like a wild beast, screamed `Off with her head! -Off--' - - `Nonsense!' said Alice, very loudly and decidedly, and the -Queen was silent. - - The King laid his hand upon her arm, and timidly said -`Consider, my dear: she is only a child!' - - The Queen turned angrily away from him, and said to the Knave -`Turn them over!' - - The Knave did so, very carefully, with one foot. - - `Get up!' said the Queen, in a shrill, loud voice, and the -three gardeners instantly jumped up, and began bowing to the -King, the Queen, the royal children, and everybody else. - - `Leave off that!' screamed the Queen. `You make me giddy.' -And then, turning to the rose-tree, she went on, `What HAVE you -been doing here?' - - `May it please your Majesty,' said Two, in a very humble tone, -going down on one knee as he spoke, `we were trying--' - - `I see!' said the Queen, who had meanwhile been examining the -roses. `Off with their heads!' and the procession moved on, -three of the soldiers remaining behind to execute the unfortunate -gardeners, who ran to Alice for protection. - - `You shan't be beheaded!' said Alice, and she put them into a -large flower-pot that stood near. The three soldiers wandered -about for a minute or two, looking for them, and then quietly -marched off after the others. - - `Are their heads off?' shouted the Queen. - - `Their heads are gone, if it please your Majesty!' the soldiers -shouted in reply. - - `That's right!' shouted the Queen. `Can you play croquet?' - - The soldiers were silent, and looked at Alice, as the question -was evidently meant for her. - - `Yes!' shouted Alice. - - `Come on, then!' roared the Queen, and Alice joined the -procession, wondering very much what would happen next. - - `It's--it's a very fine day!' said a timid voice at her side. -She was walking by the White Rabbit, who was peeping anxiously -into her face. - - `Very,' said Alice: `--where's the Duchess?' - - `Hush! Hush!' said the Rabbit in a low, hurried tone. He -looked anxiously over his shoulder as he spoke, and then raised -himself upon tiptoe, put his mouth close to her ear, and -whispered `She's under sentence of execution.' - - `What for?' said Alice. - - `Did you say "What a pity!"?' the Rabbit asked. - - `No, I didn't,' said Alice: `I don't think it's at all a pity. -I said "What for?"' - - `She boxed the Queen's ears--' the Rabbit began. Alice gave a -little scream of laughter. `Oh, hush!' the Rabbit whispered in a -frightened tone. `The Queen will hear you! You see, she came -rather late, and the Queen said--' - - `Get to your places!' shouted the Queen in a voice of thunder, -and people began running about in all directions, tumbling up -against each other; however, they got settled down in a minute or -two, and the game began. Alice thought she had never seen such a -curious croquet-ground in her life; it was all ridges and -furrows; the balls were live hedgehogs, the mallets live -flamingoes, and the soldiers had to double themselves up and to -stand on their hands and feet, to make the arches. - - The chief difficulty Alice found at first was in managing her -flamingo: she succeeded in getting its body tucked away, -comfortably enough, under her arm, with its legs hanging down, -but generally, just as she had got its neck nicely straightened -out, and was going to give the hedgehog a blow with its head, it -WOULD twist itself round and look up in her face, with such a -puzzled expression that she could not help bursting out laughing: -and when she had got its head down, and was going to begin again, -it was very provoking to find that the hedgehog had unrolled -itself, and was in the act of crawling away: besides all this, -there was generally a ridge or furrow in the way wherever she -wanted to send the hedgehog to, and, as the doubled-up soldiers -were always getting up and walking off to other parts of the -ground, Alice soon came to the conclusion that it was a very -difficult game indeed. - - The players all played at once without waiting for turns, -quarrelling all the while, and fighting for the hedgehogs; and in -a very short time the Queen was in a furious passion, and went -stamping about, and shouting `Off with his head!' or `Off with -her head!' about once in a minute. - - Alice began to feel very uneasy: to be sure, she had not as -yet had any dispute with the Queen, but she knew that it might -happen any minute, `and then,' thought she, `what would become of -me? They're dreadfully fond of beheading people here; the great -wonder is, that there's any one left alive!' - - She was looking about for some way of escape, and wondering -whether she could get away without being seen, when she noticed a -curious appearance in the air: it puzzled her very much at -first, but, after watching it a minute or two, she made it out to -be a grin, and she said to herself `It's the Cheshire Cat: now I -shall have somebody to talk to.' - - `How are you getting on?' said the Cat, as soon as there was -mouth enough for it to speak with. - - Alice waited till the eyes appeared, and then nodded. `It's no -use speaking to it,' she thought, `till its ears have come, or at -least one of them.' In another minute the whole head appeared, -and then Alice put down her flamingo, and began an account of the -game, feeling very glad she had someone to listen to her. The -Cat seemed to think that there was enough of it now in sight, and -no more of it appeared. - - `I don't think they play at all fairly,' Alice began, in rather -a complaining tone, `and they all quarrel so dreadfully one can't -hear oneself speak--and they don't seem to have any rules in -particular; at least, if there are, nobody attends to them--and -you've no idea how confusing it is all the things being alive; -for instance, there's the arch I've got to go through next -walking about at the other end of the ground--and I should have -croqueted the Queen's hedgehog just now, only it ran away when it -saw mine coming!' - - `How do you like the Queen?' said the Cat in a low voice. - - `Not at all,' said Alice: `she's so extremely--' Just then -she noticed that the Queen was close behind her, listening: so -she went on, `--likely to win, that it's hardly worth while -finishing the game.' - - The Queen smiled and passed on. - - `Who ARE you talking to?' said the King, going up to Alice, and -looking at the Cat's head with great curiosity. - - `It's a friend of mine--a Cheshire Cat,' said Alice: `allow me -to introduce it.' - - `I don't like the look of it at all,' said the King: `however, -it may kiss my hand if it likes.' - - `I'd rather not,' the Cat remarked. - - `Don't be impertinent,' said the King, `and don't look at me -like that!' He got behind Alice as he spoke. - - `A cat may look at a king,' said Alice. `I've read that in -some book, but I don't remember where.' - - `Well, it must be removed,' said the King very decidedly, and -he called the Queen, who was passing at the moment, `My dear! I -wish you would have this cat removed!' - - The Queen had only one way of settling all difficulties, great -or small. `Off with his head!' she said, without even looking -round. - - `I'll fetch the executioner myself,' said the King eagerly, and -he hurried off. - - Alice thought she might as well go back, and see how the game -was going on, as she heard the Queen's voice in the distance, -screaming with passion. She had already heard her sentence three -of the players to be executed for having missed their turns, and -she did not like the look of things at all, as the game was in -such confusion that she never knew whether it was her turn or -not. So she went in search of her hedgehog. - - The hedgehog was engaged in a fight with another hedgehog, -which seemed to Alice an excellent opportunity for croqueting one -of them with the other: the only difficulty was, that her -flamingo was gone across to the other side of the garden, where -Alice could see it trying in a helpless sort of way to fly up -into a tree. - - By the time she had caught the flamingo and brought it back, -the fight was over, and both the hedgehogs were out of sight: -`but it doesn't matter much,' thought Alice, `as all the arches -are gone from this side of the ground.' So she tucked it away -under her arm, that it might not escape again, and went back for -a little more conversation with her friend. - - When she got back to the Cheshire Cat, she was surprised to -find quite a large crowd collected round it: there was a dispute -going on between the executioner, the King, and the Queen, who -were all talking at once, while all the rest were quite silent, -and looked very uncomfortable. - - The moment Alice appeared, she was appealed to by all three to -settle the question, and they repeated their arguments to her, -though, as they all spoke at once, she found it very hard indeed -to make out exactly what they said. - - The executioner's argument was, that you couldn't cut off a -head unless there was a body to cut it off from: that he had -never had to do such a thing before, and he wasn't going to begin -at HIS time of life. - - The King's argument was, that anything that had a head could be -beheaded, and that you weren't to talk nonsense. - - The Queen's argument was, that if something wasn't done about -it in less than no time she'd have everybody executed, all round. -(It was this last remark that had made the whole party look so -grave and anxious.) - - Alice could think of nothing else to say but `It belongs to the -Duchess: you'd better ask HER about it.' - - `She's in prison,' the Queen said to the executioner: `fetch -her here.' And the executioner went off like an arrow. - - The Cat's head began fading away the moment he was gone, and, -by the time he had come back with the Dutchess, it had entirely -disappeared; so the King and the executioner ran wildly up and -down looking for it, while the rest of the party went back to the game. - - - - CHAPTER IX - - The Mock Turtle's Story - - - `You can't think how glad I am to see you again, you dear old -thing!' said the Duchess, as she tucked her arm affectionately -into Alice's, and they walked off together. - - Alice was very glad to find her in such a pleasant temper, and -thought to herself that perhaps it was only the pepper that had -made her so savage when they met in the kitchen. - - `When I'M a Duchess,' she said to herself, (not in a very -hopeful tone though), `I won't have any pepper in my kitchen AT -ALL. Soup does very well without--Maybe it's always pepper that -makes people hot-tempered,' she went on, very much pleased at -having found out a new kind of rule, `and vinegar that makes them -sour--and camomile that makes them bitter--and--and barley-sugar -and such things that make children sweet-tempered. I only wish -people knew that: then they wouldn't be so stingy about it, you -know--' - - She had quite forgotten the Duchess by this time, and was a -little startled when she heard her voice close to her ear. -`You're thinking about something, my dear, and that makes you -forget to talk. I can't tell you just now what the moral of that -is, but I shall remember it in a bit.' - - `Perhaps it hasn't one,' Alice ventured to remark. - - `Tut, tut, child!' said the Duchess. `Everything's got a -moral, if only you can find it.' And she squeezed herself up -closer to Alice's side as she spoke. - - Alice did not much like keeping so close to her: first, -because the Duchess was VERY ugly; and secondly, because she was -exactly the right height to rest her chin upon Alice's shoulder, -and it was an uncomfortably sharp chin. However, she did not -like to be rude, so she bore it as well as she could. - - `The game's going on rather better now,' she said, by way of -keeping up the conversation a little. - - `'Tis so,' said the Duchess: `and the moral of that is--"Oh, -'tis love, 'tis love, that makes the world go round!"' - - `Somebody said,' Alice whispered, `that it's done by everybody -minding their own business!' - - `Ah, well! It means much the same thing,' said the Duchess, -digging her sharp little chin into Alice's shoulder as she added, -`and the moral of THAT is--"Take care of the sense, and the -sounds will take care of themselves."' - - `How fond she is of finding morals in things!' Alice thought to -herself. - - `I dare say you're wondering why I don't put my arm round your -waist,' the Duchess said after a pause: `the reason is, that I'm -doubtful about the temper of your flamingo. Shall I try the -experiment?' - - `HE might bite,' Alice cautiously replied, not feeling at all -anxious to have the experiment tried. - - `Very true,' said the Duchess: `flamingoes and mustard both -bite. And the moral of that is--"Birds of a feather flock -together."' - - `Only mustard isn't a bird,' Alice remarked. - - `Right, as usual,' said the Duchess: `what a clear way you -have of putting things!' - - `It's a mineral, I THINK,' said Alice. - - `Of course it is,' said the Duchess, who seemed ready to agree -to everything that Alice said; `there's a large mustard-mine near -here. And the moral of that is--"The more there is of mine, the -less there is of yours."' - - `Oh, I know!' exclaimed Alice, who had not attended to this -last remark, `it's a vegetable. It doesn't look like one, but it -is.' - - `I quite agree with you,' said the Duchess; `and the moral of -that is--"Be what you would seem to be"--or if you'd like it put -more simply--"Never imagine yourself not to be otherwise than -what it might appear to others that what you were or might have -been was not otherwise than what you had been would have appeared -to them to be otherwise."' - - `I think I should understand that better,' Alice said very -politely, `if I had it written down: but I can't quite follow it -as you say it.' - - `That's nothing to what I could say if I chose,' the Duchess -replied, in a pleased tone. - - `Pray don't trouble yourself to say it any longer than that,' -said Alice. - - `Oh, don't talk about trouble!' said the Duchess. `I make you -a present of everything I've said as yet.' - - `A cheap sort of present!' thought Alice. `I'm glad they don't -give birthday presents like that!' But she did not venture to -say it out loud. - - `Thinking again?' the Duchess asked, with another dig of her -sharp little chin. - - `I've a right to think,' said Alice sharply, for she was -beginning to feel a little worried. - - `Just about as much right,' said the Duchess, `as pigs have to -fly; and the m--' - - But here, to Alice's great surprise, the Duchess's voice died -away, even in the middle of her favourite word `moral,' and the -arm that was linked into hers began to tremble. Alice looked up, -and there stood the Queen in front of them, with her arms folded, -frowning like a thunderstorm. - - `A fine day, your Majesty!' the Duchess began in a low, weak -voice. - - `Now, I give you fair warning,' shouted the Queen, stamping on -the ground as she spoke; `either you or your head must be off, -and that in about half no time! Take your choice!' - - The Duchess took her choice, and was gone in a moment. - - `Let's go on with the game,' the Queen said to Alice; and Alice -was too much frightened to say a word, but slowly followed her -back to the croquet-ground. - - The other guests had taken advantage of the Queen's absence, -and were resting in the shade: however, the moment they saw her, -they hurried back to the game, the Queen merely remarking that a -moment's delay would cost them their lives. - - All the time they were playing the Queen never left off -quarrelling with the other players, and shouting `Off with his -head!' or `Off with her head!' Those whom she sentenced were -taken into custody by the soldiers, who of course had to leave -off being arches to do this, so that by the end of half an hour -or so there were no arches left, and all the players, except the -King, the Queen, and Alice, were in custody and under sentence of -execution. - - Then the Queen left off, quite out of breath, and said to -Alice, `Have you seen the Mock Turtle yet?' - - `No,' said Alice. `I don't even know what a Mock Turtle is.' - - `It's the thing Mock Turtle Soup is made from,' said the Queen. - - `I never saw one, or heard of one,' said Alice. - - `Come on, then,' said the Queen, `and he shall tell you his -history,' - - As they walked off together, Alice heard the King say in a low -voice, to the company generally, `You are all pardoned.' `Come, -THAT'S a good thing!' she said to herself, for she had felt quite -unhappy at the number of executions the Queen had ordered. - - They very soon came upon a Gryphon, lying fast asleep in the -sun. (IF you don't know what a Gryphon is, look at the picture.) -`Up, lazy thing!' said the Queen, `and take this young lady to -see the Mock Turtle, and to hear his history. I must go back and -see after some executions I have ordered'; and she walked off, -leaving Alice alone with the Gryphon. Alice did not quite like -the look of the creature, but on the whole she thought it would -be quite as safe to stay with it as to go after that savage -Queen: so she waited. - - The Gryphon sat up and rubbed its eyes: then it watched the -Queen till she was out of sight: then it chuckled. `What fun!' -said the Gryphon, half to itself, half to Alice. - - `What IS the fun?' said Alice. - - `Why, SHE,' said the Gryphon. `It's all her fancy, that: they -never executes nobody, you know. Come on!' - - `Everybody says "come on!" here,' thought Alice, as she went -slowly after it: `I never was so ordered about in all my life, -never!' - - They had not gone far before they saw the Mock Turtle in the -distance, sitting sad and lonely on a little ledge of rock, and, -as they came nearer, Alice could hear him sighing as if his heart -would break. She pitied him deeply. `What is his sorrow?' she -asked the Gryphon, and the Gryphon answered, very nearly in the -same words as before, `It's all his fancy, that: he hasn't got -no sorrow, you know. Come on!' - - So they went up to the Mock Turtle, who looked at them with -large eyes full of tears, but said nothing. - - `This here young lady,' said the Gryphon, `she wants for to -know your history, she do.' - - `I'll tell it her,' said the Mock Turtle in a deep, hollow -tone: `sit down, both of you, and don't speak a word till I've -finished.' - - So they sat down, and nobody spoke for some minutes. Alice -thought to herself, `I don't see how he can EVEN finish, if he -doesn't begin.' But she waited patiently. - - `Once,' said the Mock Turtle at last, with a deep sigh, `I was -a real Turtle.' - - These words were followed by a very long silence, broken only -by an occasional exclamation of `Hjckrrh!' from the Gryphon, and -the constant heavy sobbing of the Mock Turtle. Alice was very -nearly getting up and saying, `Thank you, sir, for your -interesting story,' but she could not help thinking there MUST be -more to come, so she sat still and said nothing. - - `When we were little,' the Mock Turtle went on at last, more -calmly, though still sobbing a little now and then, `we went to -school in the sea. The master was an old Turtle--we used to call -him Tortoise--' - - `Why did you call him Tortoise, if he wasn't one?' Alice asked. - - `We called him Tortoise because he taught us,' said the Mock -Turtle angrily: `really you are very dull!' - - `You ought to be ashamed of yourself for asking such a simple -question,' added the Gryphon; and then they both sat silent and -looked at poor Alice, who felt ready to sink into the earth. At -last the Gryphon said to the Mock Turtle, `Drive on, old fellow! -Don't be all day about it!' and he went on in these words: - - `Yes, we went to school in the sea, though you mayn't believe -it--' - - `I never said I didn't!' interrupted Alice. - - `You did,' said the Mock Turtle. - - `Hold your tongue!' added the Gryphon, before Alice could speak -again. The Mock Turtle went on. - - `We had the best of educations--in fact, we went to school -every day--' - - `I'VE been to a day-school, too,' said Alice; `you needn't be -so proud as all that.' - - `With extras?' asked the Mock Turtle a little anxiously. - - `Yes,' said Alice, `we learned French and music.' - - `And washing?' said the Mock Turtle. - - `Certainly not!' said Alice indignantly. - - `Ah! then yours wasn't a really good school,' said the Mock -Turtle in a tone of great relief. `Now at OURS they had at the -end of the bill, "French, music, AND WASHING--extra."' - - `You couldn't have wanted it much,' said Alice; `living at the -bottom of the sea.' - - `I couldn't afford to learn it.' said the Mock Turtle with a -sigh. `I only took the regular course.' - - `What was that?' inquired Alice. - - `Reeling and Writhing, of course, to begin with,' the Mock -Turtle replied; `and then the different branches of Arithmetic-- -Ambition, Distraction, Uglification, and Derision.' - - `I never heard of "Uglification,"' Alice ventured to say. `What -is it?' - - The Gryphon lifted up both its paws in surprise. `What! Never -heard of uglifying!' it exclaimed. `You know what to beautify -is, I suppose?' - - `Yes,' said Alice doubtfully: `it means--to--make--anything-- -prettier.' - - `Well, then,' the Gryphon went on, `if you don't know what to -uglify is, you ARE a simpleton.' - - Alice did not feel encouraged to ask any more questions about -it, so she turned to the Mock Turtle, and said `What else had you -to learn?' - - `Well, there was Mystery,' the Mock Turtle replied, counting -off the subjects on his flappers, `--Mystery, ancient and modern, -with Seaography: then Drawling--the Drawling-master was an old -conger-eel, that used to come once a week: HE taught us -Drawling, Stretching, and Fainting in Coils.' - - `What was THAT like?' said Alice. - - `Well, I can't show it you myself,' the Mock Turtle said: `I'm -too stiff. And the Gryphon never learnt it.' - - `Hadn't time,' said the Gryphon: `I went to the Classics -master, though. He was an old crab, HE was.' - - `I never went to him,' the Mock Turtle said with a sigh: `he -taught Laughing and Grief, they used to say.' - - `So he did, so he did,' said the Gryphon, sighing in his turn; -and both creatures hid their faces in their paws. - - `And how many hours a day did you do lessons?' said Alice, in a -hurry to change the subject. - - `Ten hours the first day,' said the Mock Turtle: `nine the -next, and so on.' - - `What a curious plan!' exclaimed Alice. - - `That's the reason they're called lessons,' the Gryphon -remarked: `because they lessen from day to day.' - - This was quite a new idea to Alice, and she thought it over a -little before she made her next remark. `Then the eleventh day -must have been a holiday?' - - `Of course it was,' said the Mock Turtle. - - `And how did you manage on the twelfth?' Alice went on eagerly. - - `That's enough about lessons,' the Gryphon interrupted in a -very decided tone: `tell her something about the games now.' - - - - CHAPTER X - - The Lobster Quadrille - - - The Mock Turtle sighed deeply, and drew the back of one flapper -across his eyes. He looked at Alice, and tried to speak, but for -a minute or two sobs choked his voice. `Same as if he had a bone -in his throat,' said the Gryphon: and it set to work shaking him -and punching him in the back. At last the Mock Turtle recovered -his voice, and, with tears running down his cheeks, he went on -again:-- - - `You may not have lived much under the sea--' (`I haven't,' -said Alice)--`and perhaps you were never even introduced to a lobster--' -(Alice began to say `I once tasted--' but checked herself hastily, -and said `No, never') `--so you can have no idea what a delightful -thing a Lobster Quadrille is!' - - `No, indeed,' said Alice. `What sort of a dance is it?' - - `Why,' said the Gryphon, `you first form into a line along the -sea-shore--' - - `Two lines!' cried the Mock Turtle. `Seals, turtles, salmon, -and so on; then, when you've cleared all the jelly-fish out of -the way--' - - `THAT generally takes some time,' interrupted the Gryphon. - - `--you advance twice--' - - `Each with a lobster as a partner!' cried the Gryphon. - - `Of course,' the Mock Turtle said: `advance twice, set to -partners--' - - `--change lobsters, and retire in same order,' continued the -Gryphon. - - `Then, you know,' the Mock Turtle went on, `you throw the--' - - `The lobsters!' shouted the Gryphon, with a bound into the air. - - `--as far out to sea as you can--' - - `Swim after them!' screamed the Gryphon. - - `Turn a somersault in the sea!' cried the Mock Turtle, -capering wildly about. - - `Back to land again, and that's all the first figure,' said the -Mock Turtle, suddenly dropping his voice; and the two creatures, -who had been jumping about like mad things all this time, sat -down again very sadly and quietly, and looked at Alice. - - `It must be a very pretty dance,' said Alice timidly. - - `Would you like to see a little of it?' said the Mock Turtle. - - `Very much indeed,' said Alice. - - `Come, let's try the first figure!' said the Mock Turtle to the -Gryphon. `We can do without lobsters, you know. Which shall -sing?' - - `Oh, YOU sing,' said the Gryphon. `I've forgotten the words.' - - So they began solemnly dancing round and round Alice, every now -and then treading on her toes when they passed too close, and -waving their forepaws to mark the time, while the Mock Turtle -sang this, very slowly and sadly:-- - - -`"Will you walk a little faster?" said a whiting to a snail. -"There's a porpoise close behind us, and he's treading on my - tail. -See how eagerly the lobsters and the turtles all advance! -They are waiting on the shingle--will you come and join the -dance? - -Will you, won't you, will you, won't you, will you join the -dance? -Will you, won't you, will you, won't you, won't you join the -dance? - - -"You can really have no notion how delightful it will be -When they take us up and throw us, with the lobsters, out to - sea!" -But the snail replied "Too far, too far!" and gave a look - askance-- -Said he thanked the whiting kindly, but he would not join the - dance. - Would not, could not, would not, could not, would not join - the dance. - Would not, could not, would not, could not, could not join - the dance. - -`"What matters it how far we go?" his scaly friend replied. -"There is another shore, you know, upon the other side. -The further off from England the nearer is to France-- -Then turn not pale, beloved snail, but come and join the dance. - - Will you, won't you, will you, won't you, will you join the - dance? - Will you, won't you, will you, won't you, won't you join the - dance?"' - - - - `Thank you, it's a very interesting dance to watch,' said -Alice, feeling very glad that it was over at last: `and I do so -like that curious song about the whiting!' - - `Oh, as to the whiting,' said the Mock Turtle, `they--you've -seen them, of course?' - - `Yes,' said Alice, `I've often seen them at dinn--' she -checked herself hastily. - - `I don't know where Dinn may be,' said the Mock Turtle, `but -if you've seen them so often, of course you know what they're -like.' - - `I believe so,' Alice replied thoughtfully. `They have their -tails in their mouths--and they're all over crumbs.' - - `You're wrong about the crumbs,' said the Mock Turtle: -`crumbs would all wash off in the sea. But they HAVE their tails -in their mouths; and the reason is--' here the Mock Turtle -yawned and shut his eyes.--`Tell her about the reason and all -that,' he said to the Gryphon. - - `The reason is,' said the Gryphon, `that they WOULD go with -the lobsters to the dance. So they got thrown out to sea. So -they had to fall a long way. So they got their tails fast in -their mouths. So they couldn't get them out again. That's all.' - - `Thank you,' said Alice, `it's very interesting. I never knew -so much about a whiting before.' - - `I can tell you more than that, if you like,' said the -Gryphon. `Do you know why it's called a whiting?' - - `I never thought about it,' said Alice. `Why?' - - `IT DOES THE BOOTS AND SHOES.' the Gryphon replied very -solemnly. - - Alice was thoroughly puzzled. `Does the boots and shoes!' she -repeated in a wondering tone. - - `Why, what are YOUR shoes done with?' said the Gryphon. `I -mean, what makes them so shiny?' - - Alice looked down at them, and considered a little before she -gave her answer. `They're done with blacking, I believe.' - - `Boots and shoes under the sea,' the Gryphon went on in a deep -voice, `are done with a whiting. Now you know.' - - `And what are they made of?' Alice asked in a tone of great -curiosity. - - `Soles and eels, of course,' the Gryphon replied rather -impatiently: `any shrimp could have told you that.' - - `If I'd been the whiting,' said Alice, whose thoughts were -still running on the song, `I'd have said to the porpoise, "Keep -back, please: we don't want YOU with us!"' - - `They were obliged to have him with them,' the Mock Turtle -said: `no wise fish would go anywhere without a porpoise.' - - `Wouldn't it really?' said Alice in a tone of great surprise. - - `Of course not,' said the Mock Turtle: `why, if a fish came -to ME, and told me he was going a journey, I should say "With -what porpoise?"' - - `Don't you mean "purpose"?' said Alice. - - `I mean what I say,' the Mock Turtle replied in an offended -tone. And the Gryphon added `Come, let's hear some of YOUR -adventures.' - - `I could tell you my adventures--beginning from this morning,' -said Alice a little timidly: `but it's no use going back to -yesterday, because I was a different person then.' - - `Explain all that,' said the Mock Turtle. - - `No, no! The adventures first,' said the Gryphon in an -impatient tone: `explanations take such a dreadful time.' - - So Alice began telling them her adventures from the time when -she first saw the White Rabbit. She was a little nervous about -it just at first, the two creatures got so close to her, one on -each side, and opened their eyes and mouths so VERY wide, but she -gained courage as she went on. Her listeners were perfectly -quiet till she got to the part about her repeating `YOU ARE OLD, -FATHER WILLIAM,' to the Caterpillar, and the words all coming -different, and then the Mock Turtle drew a long breath, and said -`That's very curious.' - - `It's all about as curious as it can be,' said the Gryphon. - - `It all came different!' the Mock Turtle repeated -thoughtfully. `I should like to hear her try and repeat -something now. Tell her to begin.' He looked at the Gryphon as -if he thought it had some kind of authority over Alice. - - `Stand up and repeat "'TIS THE VOICE OF THE SLUGGARD,"' said -the Gryphon. - - `How the creatures order one about, and make one repeat -lessons!' thought Alice; `I might as well be at school at once.' -However, she got up, and began to repeat it, but her head was so -full of the Lobster Quadrille, that she hardly knew what she was -saying, and the words came very queer indeed:-- - - `'Tis the voice of the Lobster; I heard him declare, - "You have baked me too brown, I must sugar my hair." - As a duck with its eyelids, so he with his nose - Trims his belt and his buttons, and turns out his toes.' - - [later editions continued as follows - When the sands are all dry, he is gay as a lark, - And will talk in contemptuous tones of the Shark, - But, when the tide rises and sharks are around, - His voice has a timid and tremulous sound.] - - `That's different from what I used to say when I was a child,' -said the Gryphon. - - `Well, I never heard it before,' said the Mock Turtle; `but it -sounds uncommon nonsense.' - - Alice said nothing; she had sat down with her face in her -hands, wondering if anything would EVER happen in a natural way -again. - - `I should like to have it explained,' said the Mock Turtle. - - `She can't explain it,' said the Gryphon hastily. `Go on with -the next verse.' - - `But about his toes?' the Mock Turtle persisted. `How COULD -he turn them out with his nose, you know?' - - `It's the first position in dancing.' Alice said; but was -dreadfully puzzled by the whole thing, and longed to change the -subject. - - `Go on with the next verse,' the Gryphon repeated impatiently: -`it begins "I passed by his garden."' - - Alice did not dare to disobey, though she felt sure it would -all come wrong, and she went on in a trembling voice:-- - - `I passed by his garden, and marked, with one eye, - How the Owl and the Panther were sharing a pie--' - - [later editions continued as follows - The Panther took pie-crust, and gravy, and meat, - While the Owl had the dish as its share of the treat. - When the pie was all finished, the Owl, as a boon, - Was kindly permitted to pocket the spoon: - While the Panther received knife and fork with a growl, - And concluded the banquet--] - - `What IS the use of repeating all that stuff,' the Mock Turtle -interrupted, `if you don't explain it as you go on? It's by far -the most confusing thing I ever heard!' - - `Yes, I think you'd better leave off,' said the Gryphon: and -Alice was only too glad to do so. - - `Shall we try another figure of the Lobster Quadrille?' the -Gryphon went on. `Or would you like the Mock Turtle to sing you -a song?' - - `Oh, a song, please, if the Mock Turtle would be so kind,' -Alice replied, so eagerly that the Gryphon said, in a rather -offended tone, `Hm! No accounting for tastes! Sing her "Turtle -Soup," will you, old fellow?' - - The Mock Turtle sighed deeply, and began, in a voice sometimes -choked with sobs, to sing this:-- - - - `Beautiful Soup, so rich and green, - Waiting in a hot tureen! - Who for such dainties would not stoop? - Soup of the evening, beautiful Soup! - Soup of the evening, beautiful Soup! - Beau--ootiful Soo--oop! - Beau--ootiful Soo--oop! - Soo--oop of the e--e--evening, - Beautiful, beautiful Soup! - - `Beautiful Soup! Who cares for fish, - Game, or any other dish? - Who would not give all else for two p - ennyworth only of beautiful Soup? - Pennyworth only of beautiful Soup? - Beau--ootiful Soo--oop! - Beau--ootiful Soo--oop! - Soo--oop of the e--e--evening, - Beautiful, beauti--FUL SOUP!' - - `Chorus again!' cried the Gryphon, and the Mock Turtle had -just begun to repeat it, when a cry of `The trial's beginning!' -was heard in the distance. - - `Come on!' cried the Gryphon, and, taking Alice by the hand, -it hurried off, without waiting for the end of the song. - - `What trial is it?' Alice panted as she ran; but the Gryphon -only answered `Come on!' and ran the faster, while more and more -faintly came, carried on the breeze that followed them, the -melancholy words:-- - - `Soo--oop of the e--e--evening, - Beautiful, beautiful Soup!' - - - - CHAPTER XI - - Who Stole the Tarts? - - - The King and Queen of Hearts were seated on their throne when -they arrived, with a great crowd assembled about them--all sorts -of little birds and beasts, as well as the whole pack of cards: -the Knave was standing before them, in chains, with a soldier on -each side to guard him; and near the King was the White Rabbit, -with a trumpet in one hand, and a scroll of parchment in the -other. In the very middle of the court was a table, with a large -dish of tarts upon it: they looked so good, that it made Alice -quite hungry to look at them--`I wish they'd get the trial done,' -she thought, `and hand round the refreshments!' But there seemed -to be no chance of this, so she began looking at everything about -her, to pass away the time. - - Alice had never been in a court of justice before, but she had -read about them in books, and she was quite pleased to find that -she knew the name of nearly everything there. `That's the -judge,' she said to herself, `because of his great wig.' - - The judge, by the way, was the King; and as he wore his crown -over the wig, (look at the frontispiece if you want to see how he -did it,) he did not look at all comfortable, and it was certainly -not becoming. - - `And that's the jury-box,' thought Alice, `and those twelve -creatures,' (she was obliged to say `creatures,' you see, because -some of them were animals, and some were birds,) `I suppose they -are the jurors.' She said this last word two or three times over -to herself, being rather proud of it: for she thought, and -rightly too, that very few little girls of her age knew the -meaning of it at all. However, `jury-men' would have done just -as well. - - The twelve jurors were all writing very busily on slates. -`What are they doing?' Alice whispered to the Gryphon. `They -can't have anything to put down yet, before the trial's begun.' - - `They're putting down their names,' the Gryphon whispered in -reply, `for fear they should forget them before the end of the -trial.' - - `Stupid things!' Alice began in a loud, indignant voice, but -she stopped hastily, for the White Rabbit cried out, `Silence in -the court!' and the King put on his spectacles and looked -anxiously round, to make out who was talking. - - Alice could see, as well as if she were looking over their -shoulders, that all the jurors were writing down `stupid things!' -on their slates, and she could even make out that one of them -didn't know how to spell `stupid,' and that he had to ask his -neighbour to tell him. `A nice muddle their slates'll be in -before the trial's over!' thought Alice. - - One of the jurors had a pencil that squeaked. This of course, -Alice could not stand, and she went round the court and got -behind him, and very soon found an opportunity of taking it -away. She did it so quickly that the poor little juror (it was -Bill, the Lizard) could not make out at all what had become of -it; so, after hunting all about for it, he was obliged to write -with one finger for the rest of the day; and this was of very -little use, as it left no mark on the slate. - - `Herald, read the accusation!' said the King. - - On this the White Rabbit blew three blasts on the trumpet, and -then unrolled the parchment scroll, and read as follows:-- - - `The Queen of Hearts, she made some tarts, - All on a summer day: - The Knave of Hearts, he stole those tarts, - And took them quite away!' - - `Consider your verdict,' the King said to the jury. - - `Not yet, not yet!' the Rabbit hastily interrupted. `There's -a great deal to come before that!' - - `Call the first witness,' said the King; and the White Rabbit -blew three blasts on the trumpet, and called out, `First -witness!' - - The first witness was the Hatter. He came in with a teacup in -one hand and a piece of bread-and-butter in the other. `I beg -pardon, your Majesty,' he began, `for bringing these in: but I -hadn't quite finished my tea when I was sent for.' - - `You ought to have finished,' said the King. `When did you -begin?' - - The Hatter looked at the March Hare, who had followed him into -the court, arm-in-arm with the Dormouse. `Fourteenth of March, I -think it was,' he said. - - `Fifteenth,' said the March Hare. - - `Sixteenth,' added the Dormouse. - - `Write that down,' the King said to the jury, and the jury -eagerly wrote down all three dates on their slates, and then -added them up, and reduced the answer to shillings and pence. - - `Take off your hat,' the King said to the Hatter. - - `It isn't mine,' said the Hatter. - - `Stolen!' the King exclaimed, turning to the jury, who -instantly made a memorandum of the fact. - - `I keep them to sell,' the Hatter added as an explanation; -`I've none of my own. I'm a hatter.' - - Here the Queen put on her spectacles, and began staring at the -Hatter, who turned pale and fidgeted. - - `Give your evidence,' said the King; `and don't be nervous, or -I'll have you executed on the spot.' - - This did not seem to encourage the witness at all: he kept -shifting from one foot to the other, looking uneasily at the -Queen, and in his confusion he bit a large piece out of his -teacup instead of the bread-and-butter. - - Just at this moment Alice felt a very curious sensation, which -puzzled her a good deal until she made out what it was: she was -beginning to grow larger again, and she thought at first she -would get up and leave the court; but on second thoughts she -decided to remain where she was as long as there was room for -her. - - `I wish you wouldn't squeeze so.' said the Dormouse, who was -sitting next to her. `I can hardly breathe.' - - `I can't help it,' said Alice very meekly: `I'm growing.' - - `You've no right to grow here,' said the Dormouse. - - `Don't talk nonsense,' said Alice more boldly: `you know -you're growing too.' - - `Yes, but I grow at a reasonable pace,' said the Dormouse: -`not in that ridiculous fashion.' And he got up very sulkily -and crossed over to the other side of the court. - - All this time the Queen had never left off staring at the -Hatter, and, just as the Dormouse crossed the court, she said to -one of the officers of the court, `Bring me the list of the -singers in the last concert!' on which the wretched Hatter -trembled so, that he shook both his shoes off. - - `Give your evidence,' the King repeated angrily, `or I'll have -you executed, whether you're nervous or not.' - - `I'm a poor man, your Majesty,' the Hatter began, in a -trembling voice, `--and I hadn't begun my tea--not above a week -or so--and what with the bread-and-butter getting so thin--and -the twinkling of the tea--' - - `The twinkling of the what?' said the King. - - `It began with the tea,' the Hatter replied. - - `Of course twinkling begins with a T!' said the King sharply. -`Do you take me for a dunce? Go on!' - - `I'm a poor man,' the Hatter went on, `and most things -twinkled after that--only the March Hare said--' - - `I didn't!' the March Hare interrupted in a great hurry. - - `You did!' said the Hatter. - - `I deny it!' said the March Hare. - - `He denies it,' said the King: `leave out that part.' - - `Well, at any rate, the Dormouse said--' the Hatter went on, -looking anxiously round to see if he would deny it too: but the -Dormouse denied nothing, being fast asleep. - - `After that,' continued the Hatter, `I cut some more bread- -and-butter--' - - `But what did the Dormouse say?' one of the jury asked. - - `That I can't remember,' said the Hatter. - - `You MUST remember,' remarked the King, `or I'll have you -executed.' - - The miserable Hatter dropped his teacup and bread-and-butter, -and went down on one knee. `I'm a poor man, your Majesty,' he -began. - - `You're a very poor speaker,' said the King. - - Here one of the guinea-pigs cheered, and was immediately -suppressed by the officers of the court. (As that is rather a -hard word, I will just explain to you how it was done. They had -a large canvas bag, which tied up at the mouth with strings: -into this they slipped the guinea-pig, head first, and then sat -upon it.) - - `I'm glad I've seen that done,' thought Alice. `I've so often -read in the newspapers, at the end of trials, "There was some -attempts at applause, which was immediately suppressed by the -officers of the court," and I never understood what it meant -till now.' - - `If that's all you know about it, you may stand down,' -continued the King. - - `I can't go no lower,' said the Hatter: `I'm on the floor, as -it is.' - - `Then you may SIT down,' the King replied. - - Here the other guinea-pig cheered, and was suppressed. - - `Come, that finished the guinea-pigs!' thought Alice. `Now we -shall get on better.' - - `I'd rather finish my tea,' said the Hatter, with an anxious -look at the Queen, who was reading the list of singers. - - `You may go,' said the King, and the Hatter hurriedly left the -court, without even waiting to put his shoes on. - - `--and just take his head off outside,' the Queen added to one -of the officers: but the Hatter was out of sight before the -officer could get to the door. - - `Call the next witness!' said the King. - - The next witness was the Duchess's cook. She carried the -pepper-box in her hand, and Alice guessed who it was, even before -she got into the court, by the way the people near the door began -sneezing all at once. - - `Give your evidence,' said the King. - - `Shan't,' said the cook. - - The King looked anxiously at the White Rabbit, who said in a -low voice, `Your Majesty must cross-examine THIS witness.' - - `Well, if I must, I must,' the King said, with a melancholy -air, and, after folding his arms and frowning at the cook till -his eyes were nearly out of sight, he said in a deep voice, `What -are tarts made of?' - - `Pepper, mostly,' said the cook. - - `Treacle,' said a sleepy voice behind her. - - `Collar that Dormouse,' the Queen shrieked out. `Behead that -Dormouse! Turn that Dormouse out of court! Suppress him! Pinch -him! Off with his whiskers!' - - For some minutes the whole court was in confusion, getting the -Dormouse turned out, and, by the time they had settled down -again, the cook had disappeared. - - `Never mind!' said the King, with an air of great relief. -`Call the next witness.' And he added in an undertone to the -Queen, `Really, my dear, YOU must cross-examine the next witness. -It quite makes my forehead ache!' - - Alice watched the White Rabbit as he fumbled over the list, -feeling very curious to see what the next witness would be like, -`--for they haven't got much evidence YET,' she said to herself. -Imagine her surprise, when the White Rabbit read out, at the top -of his shrill little voice, the name `Alice!' - - - - CHAPTER XII - - Alice's Evidence - - - `Here!' cried Alice, quite forgetting in the flurry of the -moment how large she had grown in the last few minutes, and she -jumped up in such a hurry that she tipped over the jury-box with -the edge of her skirt, upsetting all the jurymen on to the heads -of the crowd below, and there they lay sprawling about, reminding -her very much of a globe of goldfish she had accidentally upset -the week before. - - `Oh, I BEG your pardon!' she exclaimed in a tone of great -dismay, and began picking them up again as quickly as she could, -for the accident of the goldfish kept running in her head, and -she had a vague sort of idea that they must be collected at once -and put back into the jury-box, or they would die. - - `The trial cannot proceed,' said the King in a very grave -voice, `until all the jurymen are back in their proper places-- -ALL,' he repeated with great emphasis, looking hard at Alice as -he said do. - - Alice looked at the jury-box, and saw that, in her haste, she -had put the Lizard in head downwards, and the poor little thing -was waving its tail about in a melancholy way, being quite unable -to move. She soon got it out again, and put it right; `not that -it signifies much,' she said to herself; `I should think it -would be QUITE as much use in the trial one way up as the other.' - - As soon as the jury had a little recovered from the shock of -being upset, and their slates and pencils had been found and -handed back to them, they set to work very diligently to write -out a history of the accident, all except the Lizard, who seemed -too much overcome to do anything but sit with its mouth open, -gazing up into the roof of the court. - - `What do you know about this business?' the King said to -Alice. - - `Nothing,' said Alice. - - `Nothing WHATEVER?' persisted the King. - - `Nothing whatever,' said Alice. - - `That's very important,' the King said, turning to the jury. -They were just beginning to write this down on their slates, when -the White Rabbit interrupted: `UNimportant, your Majesty means, -of course,' he said in a very respectful tone, but frowning and -making faces at him as he spoke. - - `UNimportant, of course, I meant,' the King hastily said, and -went on to himself in an undertone, `important--unimportant-- -unimportant--important--' as if he were trying which word -sounded best. - - Some of the jury wrote it down `important,' and some -`unimportant.' Alice could see this, as she was near enough to -look over their slates; `but it doesn't matter a bit,' she -thought to herself. - - At this moment the King, who had been for some time busily -writing in his note-book, cackled out `Silence!' and read out -from his book, `Rule Forty-two. ALL PERSONS MORE THAN A MILE -HIGH TO LEAVE THE COURT.' - - Everybody looked at Alice. - - `I'M not a mile high,' said Alice. - - `You are,' said the King. - - `Nearly two miles high,' added the Queen. - - `Well, I shan't go, at any rate,' said Alice: `besides, -that's not a regular rule: you invented it just now.' - - `It's the oldest rule in the book,' said the King. - - `Then it ought to be Number One,' said Alice. - - The King turned pale, and shut his note-book hastily. -`Consider your verdict,' he said to the jury, in a low, trembling -voice. - - `There's more evidence to come yet, please your Majesty,' said -the White Rabbit, jumping up in a great hurry; `this paper has -just been picked up.' - - `What's in it?' said the Queen. - - `I haven't opened it yet,' said the White Rabbit, `but it seems -to be a letter, written by the prisoner to--to somebody.' - - `It must have been that,' said the King, `unless it was -written to nobody, which isn't usual, you know.' - - `Who is it directed to?' said one of the jurymen. - - `It isn't directed at all,' said the White Rabbit; `in fact, -there's nothing written on the OUTSIDE.' He unfolded the paper -as he spoke, and added `It isn't a letter, after all: it's a set -of verses.' - - `Are they in the prisoner's handwriting?' asked another of -they jurymen. - - `No, they're not,' said the White Rabbit, `and that's the -queerest thing about it.' (The jury all looked puzzled.) - - `He must have imitated somebody else's hand,' said the King. -(The jury all brightened up again.) - - `Please your Majesty,' said the Knave, `I didn't write it, and -they can't prove I did: there's no name signed at the end.' - - `If you didn't sign it,' said the King, `that only makes the -matter worse. You MUST have meant some mischief, or else you'd -have signed your name like an honest man.' - - There was a general clapping of hands at this: it was the -first really clever thing the King had said that day. - - `That PROVES his guilt,' said the Queen. - - `It proves nothing of the sort!' said Alice. `Why, you don't -even know what they're about!' - - `Read them,' said the King. - - The White Rabbit put on his spectacles. `Where shall I begin, -please your Majesty?' he asked. - - `Begin at the beginning,' the King said gravely, `and go on -till you come to the end: then stop.' - - These were the verses the White Rabbit read:-- - - `They told me you had been to her, - And mentioned me to him: - She gave me a good character, - But said I could not swim. - - He sent them word I had not gone - (We know it to be true): - If she should push the matter on, - What would become of you? - - I gave her one, they gave him two, - You gave us three or more; - They all returned from him to you, - Though they were mine before. - - If I or she should chance to be - Involved in this affair, - He trusts to you to set them free, - Exactly as we were. - - My notion was that you had been - (Before she had this fit) - An obstacle that came between - Him, and ourselves, and it. - - Don't let him know she liked them best, - For this must ever be - A secret, kept from all the rest, - Between yourself and me.' - - `That's the most important piece of evidence we've heard yet,' -said the King, rubbing his hands; `so now let the jury--' - - `If any one of them can explain it,' said Alice, (she had -grown so large in the last few minutes that she wasn't a bit -afraid of interrupting him,) `I'll give him sixpence. _I_ don't -believe there's an atom of meaning in it.' - - The jury all wrote down on their slates, `SHE doesn't believe -there's an atom of meaning in it,' but none of them attempted to -explain the paper. - - `If there's no meaning in it,' said the King, `that saves a -world of trouble, you know, as we needn't try to find any. And -yet I don't know,' he went on, spreading out the verses on his -knee, and looking at them with one eye; `I seem to see some -meaning in them, after all. "--SAID I COULD NOT SWIM--" you -can't swim, can you?' he added, turning to the Knave. - - The Knave shook his head sadly. `Do I look like it?' he said. -(Which he certainly did NOT, being made entirely of cardboard.) - - `All right, so far,' said the King, and he went on muttering -over the verses to himself: `"WE KNOW IT TO BE TRUE--" that's -the jury, of course-- "I GAVE HER ONE, THEY GAVE HIM TWO--" why, -that must be what he did with the tarts, you know--' - - `But, it goes on "THEY ALL RETURNED FROM HIM TO YOU,"' said -Alice. - - `Why, there they are!' said the King triumphantly, pointing to -the tarts on the table. `Nothing can be clearer than THAT. -Then again--"BEFORE SHE HAD THIS FIT--" you never had fits, my -dear, I think?' he said to the Queen. - - `Never!' said the Queen furiously, throwing an inkstand at the -Lizard as she spoke. (The unfortunate little Bill had left off -writing on his slate with one finger, as he found it made no -mark; but he now hastily began again, using the ink, that was -trickling down his face, as long as it lasted.) - - `Then the words don't FIT you,' said the King, looking round -the court with a smile. There was a dead silence. - - `It's a pun!' the King added in an offended tone, and -everybody laughed, `Let the jury consider their verdict,' the -King said, for about the twentieth time that day. - - `No, no!' said the Queen. `Sentence first--verdict afterwards.' - - `Stuff and nonsense!' said Alice loudly. `The idea of having -the sentence first!' - - `Hold your tongue!' said the Queen, turning purple. - - `I won't!' said Alice. - - `Off with her head!' the Queen shouted at the top of her voice. -Nobody moved. - - `Who cares for you?' said Alice, (she had grown to her full -size by this time.) `You're nothing but a pack of cards!' - - At this the whole pack rose up into the air, and came flying -down upon her: she gave a little scream, half of fright and half -of anger, and tried to beat them off, and found herself lying on -the bank, with her head in the lap of her sister, who was gently -brushing away some dead leaves that had fluttered down from the -trees upon her face. - - `Wake up, Alice dear!' said her sister; `Why, what a long -sleep you've had!' - - `Oh, I've had such a curious dream!' said Alice, and she told -her sister, as well as she could remember them, all these strange -Adventures of hers that you have just been reading about; and -when she had finished, her sister kissed her, and said, `It WAS a -curious dream, dear, certainly: but now run in to your tea; it's -getting late.' So Alice got up and ran off, thinking while she -ran, as well she might, what a wonderful dream it had been. - - But her sister sat still just as she left her, leaning her -head on her hand, watching the setting sun, and thinking of -little Alice and all her wonderful Adventures, till she too began -dreaming after a fashion, and this was her dream:-- - - First, she dreamed of little Alice herself, and once again the -tiny hands were clasped upon her knee, and the bright eager eyes -were looking up into hers--she could hear the very tones of her -voice, and see that queer little toss of her head to keep back -the wandering hair that WOULD always get into her eyes--and -still as she listened, or seemed to listen, the whole place -around her became alive the strange creatures of her little -sister's dream. - - The long grass rustled at her feet as the White Rabbit hurried -by--the frightened Mouse splashed his way through the -neighbouring pool--she could hear the rattle of the teacups as -the March Hare and his friends shared their never-ending meal, -and the shrill voice of the Queen ordering off her unfortunate -guests to execution--once more the pig-baby was sneezing on the -Duchess's knee, while plates and dishes crashed around it--once -more the shriek of the Gryphon, the squeaking of the Lizard's -slate-pencil, and the choking of the suppressed guinea-pigs, -filled the air, mixed up with the distant sobs of the miserable -Mock Turtle. - - So she sat on, with closed eyes, and half believed herself in -Wonderland, though she knew she had but to open them again, and -all would change to dull reality--the grass would be only -rustling in the wind, and the pool rippling to the waving of the -reeds--the rattling teacups would change to tinkling sheep- -bells, and the Queen's shrill cries to the voice of the shepherd -boy--and the sneeze of the baby, the shriek of the Gryphon, and -all thy other queer noises, would change (she knew) to the -confused clamour of the busy farm-yard--while the lowing of the -cattle in the distance would take the place of the Mock Turtle's -heavy sobs. - - Lastly, she pictured to herself how this same little sister of -hers would, in the after-time, be herself a grown woman; and how -she would keep, through all her riper years, the simple and -loving heart of her childhood: and how she would gather about -her other little children, and make THEIR eyes bright and eager -with many a strange tale, perhaps even with the dream of -Wonderland of long ago: and how she would feel with all their -simple sorrows, and find a pleasure in all their simple joys, -remembering her own child-life, and the happy summer days. - - THE END - \ No newline at end of file diff --git a/src/snappy/snappy/testdata/asyoulik.txt b/src/snappy/snappy/testdata/asyoulik.txt deleted file mode 100644 index 88dc7b60fe..0000000000 --- a/src/snappy/snappy/testdata/asyoulik.txt +++ /dev/null @@ -1,4122 +0,0 @@ - AS YOU LIKE IT - - - DRAMATIS PERSONAE - - -DUKE SENIOR living in banishment. - -DUKE FREDERICK his brother, an usurper of his dominions. - - -AMIENS | - | lords attending on the banished duke. -JAQUES | - - -LE BEAU a courtier attending upon Frederick. - -CHARLES wrestler to Frederick. - - -OLIVER | - | -JAQUES (JAQUES DE BOYS:) | sons of Sir Rowland de Boys. - | -ORLANDO | - - -ADAM | - | servants to Oliver. -DENNIS | - - -TOUCHSTONE a clown. - -SIR OLIVER MARTEXT a vicar. - - -CORIN | - | shepherds. -SILVIUS | - - -WILLIAM a country fellow in love with Audrey. - - A person representing HYMEN. (HYMEN:) - -ROSALIND daughter to the banished duke. - -CELIA daughter to Frederick. - -PHEBE a shepherdess. - -AUDREY a country wench. - - Lords, pages, and attendants, &c. - (Forester:) - (A Lord:) - (First Lord:) - (Second Lord:) - (First Page:) - (Second Page:) - - -SCENE Oliver's house; Duke Frederick's court; and the - Forest of Arden. - - - - - AS YOU LIKE IT - - -ACT I - - - -SCENE I Orchard of Oliver's house. - - - [Enter ORLANDO and ADAM] - -ORLANDO As I remember, Adam, it was upon this fashion - bequeathed me by will but poor a thousand crowns, - and, as thou sayest, charged my brother, on his - blessing, to breed me well: and there begins my - sadness. My brother Jaques he keeps at school, and - report speaks goldenly of his profit: for my part, - he keeps me rustically at home, or, to speak more - properly, stays me here at home unkept; for call you - that keeping for a gentleman of my birth, that - differs not from the stalling of an ox? His horses - are bred better; for, besides that they are fair - with their feeding, they are taught their manage, - and to that end riders dearly hired: but I, his - brother, gain nothing under him but growth; for the - which his animals on his dunghills are as much - bound to him as I. Besides this nothing that he so - plentifully gives me, the something that nature gave - me his countenance seems to take from me: he lets - me feed with his hinds, bars me the place of a - brother, and, as much as in him lies, mines my - gentility with my education. This is it, Adam, that - grieves me; and the spirit of my father, which I - think is within me, begins to mutiny against this - servitude: I will no longer endure it, though yet I - know no wise remedy how to avoid it. - -ADAM Yonder comes my master, your brother. - -ORLANDO Go apart, Adam, and thou shalt hear how he will - shake me up. - - [Enter OLIVER] - -OLIVER Now, sir! what make you here? - -ORLANDO Nothing: I am not taught to make any thing. - -OLIVER What mar you then, sir? - -ORLANDO Marry, sir, I am helping you to mar that which God - made, a poor unworthy brother of yours, with idleness. - -OLIVER Marry, sir, be better employed, and be naught awhile. - -ORLANDO Shall I keep your hogs and eat husks with them? - What prodigal portion have I spent, that I should - come to such penury? - -OLIVER Know you where your are, sir? - -ORLANDO O, sir, very well; here in your orchard. - -OLIVER Know you before whom, sir? - -ORLANDO Ay, better than him I am before knows me. I know - you are my eldest brother; and, in the gentle - condition of blood, you should so know me. The - courtesy of nations allows you my better, in that - you are the first-born; but the same tradition - takes not away my blood, were there twenty brothers - betwixt us: I have as much of my father in me as - you; albeit, I confess, your coming before me is - nearer to his reverence. - -OLIVER What, boy! - -ORLANDO Come, come, elder brother, you are too young in this. - -OLIVER Wilt thou lay hands on me, villain? - -ORLANDO I am no villain; I am the youngest son of Sir - Rowland de Boys; he was my father, and he is thrice - a villain that says such a father begot villains. - Wert thou not my brother, I would not take this hand - from thy throat till this other had pulled out thy - tongue for saying so: thou hast railed on thyself. - -ADAM Sweet masters, be patient: for your father's - remembrance, be at accord. - -OLIVER Let me go, I say. - -ORLANDO I will not, till I please: you shall hear me. My - father charged you in his will to give me good - education: you have trained me like a peasant, - obscuring and hiding from me all gentleman-like - qualities. The spirit of my father grows strong in - me, and I will no longer endure it: therefore allow - me such exercises as may become a gentleman, or - give me the poor allottery my father left me by - testament; with that I will go buy my fortunes. - -OLIVER And what wilt thou do? beg, when that is spent? - Well, sir, get you in: I will not long be troubled - with you; you shall have some part of your will: I - pray you, leave me. - -ORLANDO I will no further offend you than becomes me for my good. - -OLIVER Get you with him, you old dog. - -ADAM Is 'old dog' my reward? Most true, I have lost my - teeth in your service. God be with my old master! - he would not have spoke such a word. - - [Exeunt ORLANDO and ADAM] - -OLIVER Is it even so? begin you to grow upon me? I will - physic your rankness, and yet give no thousand - crowns neither. Holla, Dennis! - - [Enter DENNIS] - -DENNIS Calls your worship? - -OLIVER Was not Charles, the duke's wrestler, here to speak with me? - -DENNIS So please you, he is here at the door and importunes - access to you. - -OLIVER Call him in. - - [Exit DENNIS] - - 'Twill be a good way; and to-morrow the wrestling is. - - [Enter CHARLES] - -CHARLES Good morrow to your worship. - -OLIVER Good Monsieur Charles, what's the new news at the - new court? - -CHARLES There's no news at the court, sir, but the old news: - that is, the old duke is banished by his younger - brother the new duke; and three or four loving lords - have put themselves into voluntary exile with him, - whose lands and revenues enrich the new duke; - therefore he gives them good leave to wander. - -OLIVER Can you tell if Rosalind, the duke's daughter, be - banished with her father? - -CHARLES O, no; for the duke's daughter, her cousin, so loves - her, being ever from their cradles bred together, - that she would have followed her exile, or have died - to stay behind her. She is at the court, and no - less beloved of her uncle than his own daughter; and - never two ladies loved as they do. - -OLIVER Where will the old duke live? - -CHARLES They say he is already in the forest of Arden, and - a many merry men with him; and there they live like - the old Robin Hood of England: they say many young - gentlemen flock to him every day, and fleet the time - carelessly, as they did in the golden world. - -OLIVER What, you wrestle to-morrow before the new duke? - -CHARLES Marry, do I, sir; and I came to acquaint you with a - matter. I am given, sir, secretly to understand - that your younger brother Orlando hath a disposition - to come in disguised against me to try a fall. - To-morrow, sir, I wrestle for my credit; and he that - escapes me without some broken limb shall acquit him - well. Your brother is but young and tender; and, - for your love, I would be loath to foil him, as I - must, for my own honour, if he come in: therefore, - out of my love to you, I came hither to acquaint you - withal, that either you might stay him from his - intendment or brook such disgrace well as he shall - run into, in that it is a thing of his own search - and altogether against my will. - -OLIVER Charles, I thank thee for thy love to me, which - thou shalt find I will most kindly requite. I had - myself notice of my brother's purpose herein and - have by underhand means laboured to dissuade him from - it, but he is resolute. I'll tell thee, Charles: - it is the stubbornest young fellow of France, full - of ambition, an envious emulator of every man's - good parts, a secret and villanous contriver against - me his natural brother: therefore use thy - discretion; I had as lief thou didst break his neck - as his finger. And thou wert best look to't; for if - thou dost him any slight disgrace or if he do not - mightily grace himself on thee, he will practise - against thee by poison, entrap thee by some - treacherous device and never leave thee till he - hath ta'en thy life by some indirect means or other; - for, I assure thee, and almost with tears I speak - it, there is not one so young and so villanous this - day living. I speak but brotherly of him; but - should I anatomize him to thee as he is, I must - blush and weep and thou must look pale and wonder. - -CHARLES I am heartily glad I came hither to you. If he come - to-morrow, I'll give him his payment: if ever he go - alone again, I'll never wrestle for prize more: and - so God keep your worship! - -OLIVER Farewell, good Charles. - - [Exit CHARLES] - - Now will I stir this gamester: I hope I shall see - an end of him; for my soul, yet I know not why, - hates nothing more than he. Yet he's gentle, never - schooled and yet learned, full of noble device, of - all sorts enchantingly beloved, and indeed so much - in the heart of the world, and especially of my own - people, who best know him, that I am altogether - misprised: but it shall not be so long; this - wrestler shall clear all: nothing remains but that - I kindle the boy thither; which now I'll go about. - - [Exit] - - - - - AS YOU LIKE IT - - -ACT I - - - -SCENE II Lawn before the Duke's palace. - - - [Enter CELIA and ROSALIND] - -CELIA I pray thee, Rosalind, sweet my coz, be merry. - -ROSALIND Dear Celia, I show more mirth than I am mistress of; - and would you yet I were merrier? Unless you could - teach me to forget a banished father, you must not - learn me how to remember any extraordinary pleasure. - -CELIA Herein I see thou lovest me not with the full weight - that I love thee. If my uncle, thy banished father, - had banished thy uncle, the duke my father, so thou - hadst been still with me, I could have taught my - love to take thy father for mine: so wouldst thou, - if the truth of thy love to me were so righteously - tempered as mine is to thee. - -ROSALIND Well, I will forget the condition of my estate, to - rejoice in yours. - -CELIA You know my father hath no child but I, nor none is - like to have: and, truly, when he dies, thou shalt - be his heir, for what he hath taken away from thy - father perforce, I will render thee again in - affection; by mine honour, I will; and when I break - that oath, let me turn monster: therefore, my - sweet Rose, my dear Rose, be merry. - -ROSALIND From henceforth I will, coz, and devise sports. Let - me see; what think you of falling in love? - -CELIA Marry, I prithee, do, to make sport withal: but - love no man in good earnest; nor no further in sport - neither than with safety of a pure blush thou mayst - in honour come off again. - -ROSALIND What shall be our sport, then? - -CELIA Let us sit and mock the good housewife Fortune from - her wheel, that her gifts may henceforth be bestowed equally. - -ROSALIND I would we could do so, for her benefits are - mightily misplaced, and the bountiful blind woman - doth most mistake in her gifts to women. - -CELIA 'Tis true; for those that she makes fair she scarce - makes honest, and those that she makes honest she - makes very ill-favouredly. - -ROSALIND Nay, now thou goest from Fortune's office to - Nature's: Fortune reigns in gifts of the world, - not in the lineaments of Nature. - - [Enter TOUCHSTONE] - -CELIA No? when Nature hath made a fair creature, may she - not by Fortune fall into the fire? Though Nature - hath given us wit to flout at Fortune, hath not - Fortune sent in this fool to cut off the argument? - -ROSALIND Indeed, there is Fortune too hard for Nature, when - Fortune makes Nature's natural the cutter-off of - Nature's wit. - -CELIA Peradventure this is not Fortune's work neither, but - Nature's; who perceiveth our natural wits too dull - to reason of such goddesses and hath sent this - natural for our whetstone; for always the dulness of - the fool is the whetstone of the wits. How now, - wit! whither wander you? - -TOUCHSTONE Mistress, you must come away to your father. - -CELIA Were you made the messenger? - -TOUCHSTONE No, by mine honour, but I was bid to come for you. - -ROSALIND Where learned you that oath, fool? - -TOUCHSTONE Of a certain knight that swore by his honour they - were good pancakes and swore by his honour the - mustard was naught: now I'll stand to it, the - pancakes were naught and the mustard was good, and - yet was not the knight forsworn. - -CELIA How prove you that, in the great heap of your - knowledge? - -ROSALIND Ay, marry, now unmuzzle your wisdom. - -TOUCHSTONE Stand you both forth now: stroke your chins, and - swear by your beards that I am a knave. - -CELIA By our beards, if we had them, thou art. - -TOUCHSTONE By my knavery, if I had it, then I were; but if you - swear by that that is not, you are not forsworn: no - more was this knight swearing by his honour, for he - never had any; or if he had, he had sworn it away - before ever he saw those pancakes or that mustard. - -CELIA Prithee, who is't that thou meanest? - -TOUCHSTONE One that old Frederick, your father, loves. - -CELIA My father's love is enough to honour him: enough! - speak no more of him; you'll be whipped for taxation - one of these days. - -TOUCHSTONE The more pity, that fools may not speak wisely what - wise men do foolishly. - -CELIA By my troth, thou sayest true; for since the little - wit that fools have was silenced, the little foolery - that wise men have makes a great show. Here comes - Monsieur Le Beau. - -ROSALIND With his mouth full of news. - -CELIA Which he will put on us, as pigeons feed their young. - -ROSALIND Then shall we be news-crammed. - -CELIA All the better; we shall be the more marketable. - - [Enter LE BEAU] - - Bon jour, Monsieur Le Beau: what's the news? - -LE BEAU Fair princess, you have lost much good sport. - -CELIA Sport! of what colour? - -LE BEAU What colour, madam! how shall I answer you? - -ROSALIND As wit and fortune will. - -TOUCHSTONE Or as the Destinies decree. - -CELIA Well said: that was laid on with a trowel. - -TOUCHSTONE Nay, if I keep not my rank,-- - -ROSALIND Thou losest thy old smell. - -LE BEAU You amaze me, ladies: I would have told you of good - wrestling, which you have lost the sight of. - -ROSALIND You tell us the manner of the wrestling. - -LE BEAU I will tell you the beginning; and, if it please - your ladyships, you may see the end; for the best is - yet to do; and here, where you are, they are coming - to perform it. - -CELIA Well, the beginning, that is dead and buried. - -LE BEAU There comes an old man and his three sons,-- - -CELIA I could match this beginning with an old tale. - -LE BEAU Three proper young men, of excellent growth and presence. - -ROSALIND With bills on their necks, 'Be it known unto all men - by these presents.' - -LE BEAU The eldest of the three wrestled with Charles, the - duke's wrestler; which Charles in a moment threw him - and broke three of his ribs, that there is little - hope of life in him: so he served the second, and - so the third. Yonder they lie; the poor old man, - their father, making such pitiful dole over them - that all the beholders take his part with weeping. - -ROSALIND Alas! - -TOUCHSTONE But what is the sport, monsieur, that the ladies - have lost? - -LE BEAU Why, this that I speak of. - -TOUCHSTONE Thus men may grow wiser every day: it is the first - time that ever I heard breaking of ribs was sport - for ladies. - -CELIA Or I, I promise thee. - -ROSALIND But is there any else longs to see this broken music - in his sides? is there yet another dotes upon - rib-breaking? Shall we see this wrestling, cousin? - -LE BEAU You must, if you stay here; for here is the place - appointed for the wrestling, and they are ready to - perform it. - -CELIA Yonder, sure, they are coming: let us now stay and see it. - - [Flourish. Enter DUKE FREDERICK, Lords, ORLANDO, - CHARLES, and Attendants] - -DUKE FREDERICK Come on: since the youth will not be entreated, his - own peril on his forwardness. - -ROSALIND Is yonder the man? - -LE BEAU Even he, madam. - -CELIA Alas, he is too young! yet he looks successfully. - -DUKE FREDERICK How now, daughter and cousin! are you crept hither - to see the wrestling? - -ROSALIND Ay, my liege, so please you give us leave. - -DUKE FREDERICK You will take little delight in it, I can tell you; - there is such odds in the man. In pity of the - challenger's youth I would fain dissuade him, but he - will not be entreated. Speak to him, ladies; see if - you can move him. - -CELIA Call him hither, good Monsieur Le Beau. - -DUKE FREDERICK Do so: I'll not be by. - -LE BEAU Monsieur the challenger, the princesses call for you. - -ORLANDO I attend them with all respect and duty. - -ROSALIND Young man, have you challenged Charles the wrestler? - -ORLANDO No, fair princess; he is the general challenger: I - come but in, as others do, to try with him the - strength of my youth. - -CELIA Young gentleman, your spirits are too bold for your - years. You have seen cruel proof of this man's - strength: if you saw yourself with your eyes or - knew yourself with your judgment, the fear of your - adventure would counsel you to a more equal - enterprise. We pray you, for your own sake, to - embrace your own safety and give over this attempt. - -ROSALIND Do, young sir; your reputation shall not therefore - be misprised: we will make it our suit to the duke - that the wrestling might not go forward. - -ORLANDO I beseech you, punish me not with your hard - thoughts; wherein I confess me much guilty, to deny - so fair and excellent ladies any thing. But let - your fair eyes and gentle wishes go with me to my - trial: wherein if I be foiled, there is but one - shamed that was never gracious; if killed, but one - dead that was willing to be so: I shall do my - friends no wrong, for I have none to lament me, the - world no injury, for in it I have nothing; only in - the world I fill up a place, which may be better - supplied when I have made it empty. - -ROSALIND The little strength that I have, I would it were with you. - -CELIA And mine, to eke out hers. - -ROSALIND Fare you well: pray heaven I be deceived in you! - -CELIA Your heart's desires be with you! - -CHARLES Come, where is this young gallant that is so - desirous to lie with his mother earth? - -ORLANDO Ready, sir; but his will hath in it a more modest working. - -DUKE FREDERICK You shall try but one fall. - -CHARLES No, I warrant your grace, you shall not entreat him - to a second, that have so mightily persuaded him - from a first. - -ORLANDO An you mean to mock me after, you should not have - mocked me before: but come your ways. - -ROSALIND Now Hercules be thy speed, young man! - -CELIA I would I were invisible, to catch the strong - fellow by the leg. - - [They wrestle] - -ROSALIND O excellent young man! - -CELIA If I had a thunderbolt in mine eye, I can tell who - should down. - - [Shout. CHARLES is thrown] - -DUKE FREDERICK No more, no more. - -ORLANDO Yes, I beseech your grace: I am not yet well breathed. - -DUKE FREDERICK How dost thou, Charles? - -LE BEAU He cannot speak, my lord. - -DUKE FREDERICK Bear him away. What is thy name, young man? - -ORLANDO Orlando, my liege; the youngest son of Sir Rowland de Boys. - -DUKE FREDERICK I would thou hadst been son to some man else: - The world esteem'd thy father honourable, - But I did find him still mine enemy: - Thou shouldst have better pleased me with this deed, - Hadst thou descended from another house. - But fare thee well; thou art a gallant youth: - I would thou hadst told me of another father. - - [Exeunt DUKE FREDERICK, train, and LE BEAU] - -CELIA Were I my father, coz, would I do this? - -ORLANDO I am more proud to be Sir Rowland's son, - His youngest son; and would not change that calling, - To be adopted heir to Frederick. - -ROSALIND My father loved Sir Rowland as his soul, - And all the world was of my father's mind: - Had I before known this young man his son, - I should have given him tears unto entreaties, - Ere he should thus have ventured. - -CELIA Gentle cousin, - Let us go thank him and encourage him: - My father's rough and envious disposition - Sticks me at heart. Sir, you have well deserved: - If you do keep your promises in love - But justly, as you have exceeded all promise, - Your mistress shall be happy. - -ROSALIND Gentleman, - - [Giving him a chain from her neck] - - Wear this for me, one out of suits with fortune, - That could give more, but that her hand lacks means. - Shall we go, coz? - -CELIA Ay. Fare you well, fair gentleman. - -ORLANDO Can I not say, I thank you? My better parts - Are all thrown down, and that which here stands up - Is but a quintain, a mere lifeless block. - -ROSALIND He calls us back: my pride fell with my fortunes; - I'll ask him what he would. Did you call, sir? - Sir, you have wrestled well and overthrown - More than your enemies. - -CELIA Will you go, coz? - -ROSALIND Have with you. Fare you well. - - [Exeunt ROSALIND and CELIA] - -ORLANDO What passion hangs these weights upon my tongue? - I cannot speak to her, yet she urged conference. - O poor Orlando, thou art overthrown! - Or Charles or something weaker masters thee. - - [Re-enter LE BEAU] - -LE BEAU Good sir, I do in friendship counsel you - To leave this place. Albeit you have deserved - High commendation, true applause and love, - Yet such is now the duke's condition - That he misconstrues all that you have done. - The duke is humorous; what he is indeed, - More suits you to conceive than I to speak of. - -ORLANDO I thank you, sir: and, pray you, tell me this: - Which of the two was daughter of the duke - That here was at the wrestling? - -LE BEAU Neither his daughter, if we judge by manners; - But yet indeed the lesser is his daughter - The other is daughter to the banish'd duke, - And here detain'd by her usurping uncle, - To keep his daughter company; whose loves - Are dearer than the natural bond of sisters. - But I can tell you that of late this duke - Hath ta'en displeasure 'gainst his gentle niece, - Grounded upon no other argument - But that the people praise her for her virtues - And pity her for her good father's sake; - And, on my life, his malice 'gainst the lady - Will suddenly break forth. Sir, fare you well: - Hereafter, in a better world than this, - I shall desire more love and knowledge of you. - -ORLANDO I rest much bounden to you: fare you well. - - [Exit LE BEAU] - - Thus must I from the smoke into the smother; - From tyrant duke unto a tyrant brother: - But heavenly Rosalind! - - [Exit] - - - - - AS YOU LIKE IT - - -ACT I - - - -SCENE III A room in the palace. - - - [Enter CELIA and ROSALIND] - -CELIA Why, cousin! why, Rosalind! Cupid have mercy! not a word? - -ROSALIND Not one to throw at a dog. - -CELIA No, thy words are too precious to be cast away upon - curs; throw some of them at me; come, lame me with reasons. - -ROSALIND Then there were two cousins laid up; when the one - should be lamed with reasons and the other mad - without any. - -CELIA But is all this for your father? - -ROSALIND No, some of it is for my child's father. O, how - full of briers is this working-day world! - -CELIA They are but burs, cousin, thrown upon thee in - holiday foolery: if we walk not in the trodden - paths our very petticoats will catch them. - -ROSALIND I could shake them off my coat: these burs are in my heart. - -CELIA Hem them away. - -ROSALIND I would try, if I could cry 'hem' and have him. - -CELIA Come, come, wrestle with thy affections. - -ROSALIND O, they take the part of a better wrestler than myself! - -CELIA O, a good wish upon you! you will try in time, in - despite of a fall. But, turning these jests out of - service, let us talk in good earnest: is it - possible, on such a sudden, you should fall into so - strong a liking with old Sir Rowland's youngest son? - -ROSALIND The duke my father loved his father dearly. - -CELIA Doth it therefore ensue that you should love his son - dearly? By this kind of chase, I should hate him, - for my father hated his father dearly; yet I hate - not Orlando. - -ROSALIND No, faith, hate him not, for my sake. - -CELIA Why should I not? doth he not deserve well? - -ROSALIND Let me love him for that, and do you love him - because I do. Look, here comes the duke. - -CELIA With his eyes full of anger. - - [Enter DUKE FREDERICK, with Lords] - -DUKE FREDERICK Mistress, dispatch you with your safest haste - And get you from our court. - -ROSALIND Me, uncle? - -DUKE FREDERICK You, cousin - Within these ten days if that thou be'st found - So near our public court as twenty miles, - Thou diest for it. - -ROSALIND I do beseech your grace, - Let me the knowledge of my fault bear with me: - If with myself I hold intelligence - Or have acquaintance with mine own desires, - If that I do not dream or be not frantic,-- - As I do trust I am not--then, dear uncle, - Never so much as in a thought unborn - Did I offend your highness. - -DUKE FREDERICK Thus do all traitors: - If their purgation did consist in words, - They are as innocent as grace itself: - Let it suffice thee that I trust thee not. - -ROSALIND Yet your mistrust cannot make me a traitor: - Tell me whereon the likelihood depends. - -DUKE FREDERICK Thou art thy father's daughter; there's enough. - -ROSALIND So was I when your highness took his dukedom; - So was I when your highness banish'd him: - Treason is not inherited, my lord; - Or, if we did derive it from our friends, - What's that to me? my father was no traitor: - Then, good my liege, mistake me not so much - To think my poverty is treacherous. - -CELIA Dear sovereign, hear me speak. - -DUKE FREDERICK Ay, Celia; we stay'd her for your sake, - Else had she with her father ranged along. - -CELIA I did not then entreat to have her stay; - It was your pleasure and your own remorse: - I was too young that time to value her; - But now I know her: if she be a traitor, - Why so am I; we still have slept together, - Rose at an instant, learn'd, play'd, eat together, - And wheresoever we went, like Juno's swans, - Still we went coupled and inseparable. - -DUKE FREDERICK She is too subtle for thee; and her smoothness, - Her very silence and her patience - Speak to the people, and they pity her. - Thou art a fool: she robs thee of thy name; - And thou wilt show more bright and seem more virtuous - When she is gone. Then open not thy lips: - Firm and irrevocable is my doom - Which I have pass'd upon her; she is banish'd. - -CELIA Pronounce that sentence then on me, my liege: - I cannot live out of her company. - -DUKE FREDERICK You are a fool. You, niece, provide yourself: - If you outstay the time, upon mine honour, - And in the greatness of my word, you die. - - [Exeunt DUKE FREDERICK and Lords] - -CELIA O my poor Rosalind, whither wilt thou go? - Wilt thou change fathers? I will give thee mine. - I charge thee, be not thou more grieved than I am. - -ROSALIND I have more cause. - -CELIA Thou hast not, cousin; - Prithee be cheerful: know'st thou not, the duke - Hath banish'd me, his daughter? - -ROSALIND That he hath not. - -CELIA No, hath not? Rosalind lacks then the love - Which teacheth thee that thou and I am one: - Shall we be sunder'd? shall we part, sweet girl? - No: let my father seek another heir. - Therefore devise with me how we may fly, - Whither to go and what to bear with us; - And do not seek to take your change upon you, - To bear your griefs yourself and leave me out; - For, by this heaven, now at our sorrows pale, - Say what thou canst, I'll go along with thee. - -ROSALIND Why, whither shall we go? - -CELIA To seek my uncle in the forest of Arden. - -ROSALIND Alas, what danger will it be to us, - Maids as we are, to travel forth so far! - Beauty provoketh thieves sooner than gold. - -CELIA I'll put myself in poor and mean attire - And with a kind of umber smirch my face; - The like do you: so shall we pass along - And never stir assailants. - -ROSALIND Were it not better, - Because that I am more than common tall, - That I did suit me all points like a man? - A gallant curtle-axe upon my thigh, - A boar-spear in my hand; and--in my heart - Lie there what hidden woman's fear there will-- - We'll have a swashing and a martial outside, - As many other mannish cowards have - That do outface it with their semblances. - -CELIA What shall I call thee when thou art a man? - -ROSALIND I'll have no worse a name than Jove's own page; - And therefore look you call me Ganymede. - But what will you be call'd? - -CELIA Something that hath a reference to my state - No longer Celia, but Aliena. - -ROSALIND But, cousin, what if we assay'd to steal - The clownish fool out of your father's court? - Would he not be a comfort to our travel? - -CELIA He'll go along o'er the wide world with me; - Leave me alone to woo him. Let's away, - And get our jewels and our wealth together, - Devise the fittest time and safest way - To hide us from pursuit that will be made - After my flight. Now go we in content - To liberty and not to banishment. - - [Exeunt] - - - - - AS YOU LIKE IT - - -ACT II - - - -SCENE I The Forest of Arden. - - - [Enter DUKE SENIOR, AMIENS, and two or three Lords, - like foresters] - -DUKE SENIOR Now, my co-mates and brothers in exile, - Hath not old custom made this life more sweet - Than that of painted pomp? Are not these woods - More free from peril than the envious court? - Here feel we but the penalty of Adam, - The seasons' difference, as the icy fang - And churlish chiding of the winter's wind, - Which, when it bites and blows upon my body, - Even till I shrink with cold, I smile and say - 'This is no flattery: these are counsellors - That feelingly persuade me what I am.' - Sweet are the uses of adversity, - Which, like the toad, ugly and venomous, - Wears yet a precious jewel in his head; - And this our life exempt from public haunt - Finds tongues in trees, books in the running brooks, - Sermons in stones and good in every thing. - I would not change it. - -AMIENS Happy is your grace, - That can translate the stubbornness of fortune - Into so quiet and so sweet a style. - -DUKE SENIOR Come, shall we go and kill us venison? - And yet it irks me the poor dappled fools, - Being native burghers of this desert city, - Should in their own confines with forked heads - Have their round haunches gored. - -First Lord Indeed, my lord, - The melancholy Jaques grieves at that, - And, in that kind, swears you do more usurp - Than doth your brother that hath banish'd you. - To-day my Lord of Amiens and myself - Did steal behind him as he lay along - Under an oak whose antique root peeps out - Upon the brook that brawls along this wood: - To the which place a poor sequester'd stag, - That from the hunter's aim had ta'en a hurt, - Did come to languish, and indeed, my lord, - The wretched animal heaved forth such groans - That their discharge did stretch his leathern coat - Almost to bursting, and the big round tears - Coursed one another down his innocent nose - In piteous chase; and thus the hairy fool - Much marked of the melancholy Jaques, - Stood on the extremest verge of the swift brook, - Augmenting it with tears. - -DUKE SENIOR But what said Jaques? - Did he not moralize this spectacle? - -First Lord O, yes, into a thousand similes. - First, for his weeping into the needless stream; - 'Poor deer,' quoth he, 'thou makest a testament - As worldlings do, giving thy sum of more - To that which had too much:' then, being there alone, - Left and abandon'd of his velvet friends, - ''Tis right:' quoth he; 'thus misery doth part - The flux of company:' anon a careless herd, - Full of the pasture, jumps along by him - And never stays to greet him; 'Ay' quoth Jaques, - 'Sweep on, you fat and greasy citizens; - 'Tis just the fashion: wherefore do you look - Upon that poor and broken bankrupt there?' - Thus most invectively he pierceth through - The body of the country, city, court, - Yea, and of this our life, swearing that we - Are mere usurpers, tyrants and what's worse, - To fright the animals and to kill them up - In their assign'd and native dwelling-place. - -DUKE SENIOR And did you leave him in this contemplation? - -Second Lord We did, my lord, weeping and commenting - Upon the sobbing deer. - -DUKE SENIOR Show me the place: - I love to cope him in these sullen fits, - For then he's full of matter. - -First Lord I'll bring you to him straight. - - [Exeunt] - - - - - AS YOU LIKE IT - - -ACT II - - - -SCENE II A room in the palace. - - - [Enter DUKE FREDERICK, with Lords] - -DUKE FREDERICK Can it be possible that no man saw them? - It cannot be: some villains of my court - Are of consent and sufferance in this. - -First Lord I cannot hear of any that did see her. - The ladies, her attendants of her chamber, - Saw her abed, and in the morning early - They found the bed untreasured of their mistress. - -Second Lord My lord, the roynish clown, at whom so oft - Your grace was wont to laugh, is also missing. - Hisperia, the princess' gentlewoman, - Confesses that she secretly o'erheard - Your daughter and her cousin much commend - The parts and graces of the wrestler - That did but lately foil the sinewy Charles; - And she believes, wherever they are gone, - That youth is surely in their company. - -DUKE FREDERICK Send to his brother; fetch that gallant hither; - If he be absent, bring his brother to me; - I'll make him find him: do this suddenly, - And let not search and inquisition quail - To bring again these foolish runaways. - - [Exeunt] - - - - - AS YOU LIKE IT - - -ACT II - - - -SCENE III Before OLIVER'S house. - - - [Enter ORLANDO and ADAM, meeting] - -ORLANDO Who's there? - -ADAM What, my young master? O, my gentle master! - O my sweet master! O you memory - Of old Sir Rowland! why, what make you here? - Why are you virtuous? why do people love you? - And wherefore are you gentle, strong and valiant? - Why would you be so fond to overcome - The bonny priser of the humorous duke? - Your praise is come too swiftly home before you. - Know you not, master, to some kind of men - Their graces serve them but as enemies? - No more do yours: your virtues, gentle master, - Are sanctified and holy traitors to you. - O, what a world is this, when what is comely - Envenoms him that bears it! - -ORLANDO Why, what's the matter? - -ADAM O unhappy youth! - Come not within these doors; within this roof - The enemy of all your graces lives: - Your brother--no, no brother; yet the son-- - Yet not the son, I will not call him son - Of him I was about to call his father-- - Hath heard your praises, and this night he means - To burn the lodging where you use to lie - And you within it: if he fail of that, - He will have other means to cut you off. - I overheard him and his practises. - This is no place; this house is but a butchery: - Abhor it, fear it, do not enter it. - -ORLANDO Why, whither, Adam, wouldst thou have me go? - -ADAM No matter whither, so you come not here. - -ORLANDO What, wouldst thou have me go and beg my food? - Or with a base and boisterous sword enforce - A thievish living on the common road? - This I must do, or know not what to do: - Yet this I will not do, do how I can; - I rather will subject me to the malice - Of a diverted blood and bloody brother. - -ADAM But do not so. I have five hundred crowns, - The thrifty hire I saved under your father, - Which I did store to be my foster-nurse - When service should in my old limbs lie lame - And unregarded age in corners thrown: - Take that, and He that doth the ravens feed, - Yea, providently caters for the sparrow, - Be comfort to my age! Here is the gold; - And all this I give you. Let me be your servant: - Though I look old, yet I am strong and lusty; - For in my youth I never did apply - Hot and rebellious liquors in my blood, - Nor did not with unbashful forehead woo - The means of weakness and debility; - Therefore my age is as a lusty winter, - Frosty, but kindly: let me go with you; - I'll do the service of a younger man - In all your business and necessities. - -ORLANDO O good old man, how well in thee appears - The constant service of the antique world, - When service sweat for duty, not for meed! - Thou art not for the fashion of these times, - Where none will sweat but for promotion, - And having that, do choke their service up - Even with the having: it is not so with thee. - But, poor old man, thou prunest a rotten tree, - That cannot so much as a blossom yield - In lieu of all thy pains and husbandry - But come thy ways; well go along together, - And ere we have thy youthful wages spent, - We'll light upon some settled low content. - -ADAM Master, go on, and I will follow thee, - To the last gasp, with truth and loyalty. - From seventeen years till now almost fourscore - Here lived I, but now live here no more. - At seventeen years many their fortunes seek; - But at fourscore it is too late a week: - Yet fortune cannot recompense me better - Than to die well and not my master's debtor. - - [Exeunt] - - - - - AS YOU LIKE IT - - -ACT II - - - -SCENE IV The Forest of Arden. - - - [Enter ROSALIND for Ganymede, CELIA for Aliena, - and TOUCHSTONE] - -ROSALIND O Jupiter, how weary are my spirits! - -TOUCHSTONE I care not for my spirits, if my legs were not weary. - -ROSALIND I could find in my heart to disgrace my man's - apparel and to cry like a woman; but I must comfort - the weaker vessel, as doublet and hose ought to show - itself courageous to petticoat: therefore courage, - good Aliena! - -CELIA I pray you, bear with me; I cannot go no further. - -TOUCHSTONE For my part, I had rather bear with you than bear - you; yet I should bear no cross if I did bear you, - for I think you have no money in your purse. - -ROSALIND Well, this is the forest of Arden. - -TOUCHSTONE Ay, now am I in Arden; the more fool I; when I was - at home, I was in a better place: but travellers - must be content. - -ROSALIND Ay, be so, good Touchstone. - - [Enter CORIN and SILVIUS] - - Look you, who comes here; a young man and an old in - solemn talk. - -CORIN That is the way to make her scorn you still. - -SILVIUS O Corin, that thou knew'st how I do love her! - -CORIN I partly guess; for I have loved ere now. - -SILVIUS No, Corin, being old, thou canst not guess, - Though in thy youth thou wast as true a lover - As ever sigh'd upon a midnight pillow: - But if thy love were ever like to mine-- - As sure I think did never man love so-- - How many actions most ridiculous - Hast thou been drawn to by thy fantasy? - -CORIN Into a thousand that I have forgotten. - -SILVIUS O, thou didst then ne'er love so heartily! - If thou remember'st not the slightest folly - That ever love did make thee run into, - Thou hast not loved: - Or if thou hast not sat as I do now, - Wearying thy hearer in thy mistress' praise, - Thou hast not loved: - Or if thou hast not broke from company - Abruptly, as my passion now makes me, - Thou hast not loved. - O Phebe, Phebe, Phebe! - - [Exit] - -ROSALIND Alas, poor shepherd! searching of thy wound, - I have by hard adventure found mine own. - -TOUCHSTONE And I mine. I remember, when I was in love I broke - my sword upon a stone and bid him take that for - coming a-night to Jane Smile; and I remember the - kissing of her batlet and the cow's dugs that her - pretty chopt hands had milked; and I remember the - wooing of a peascod instead of her, from whom I took - two cods and, giving her them again, said with - weeping tears 'Wear these for my sake.' We that are - true lovers run into strange capers; but as all is - mortal in nature, so is all nature in love mortal in folly. - -ROSALIND Thou speakest wiser than thou art ware of. - -TOUCHSTONE Nay, I shall ne'er be ware of mine own wit till I - break my shins against it. - -ROSALIND Jove, Jove! this shepherd's passion - Is much upon my fashion. - -TOUCHSTONE And mine; but it grows something stale with me. - -CELIA I pray you, one of you question yond man - If he for gold will give us any food: - I faint almost to death. - -TOUCHSTONE Holla, you clown! - -ROSALIND Peace, fool: he's not thy kinsman. - -CORIN Who calls? - -TOUCHSTONE Your betters, sir. - -CORIN Else are they very wretched. - -ROSALIND Peace, I say. Good even to you, friend. - -CORIN And to you, gentle sir, and to you all. - -ROSALIND I prithee, shepherd, if that love or gold - Can in this desert place buy entertainment, - Bring us where we may rest ourselves and feed: - Here's a young maid with travel much oppress'd - And faints for succor. - -CORIN Fair sir, I pity her - And wish, for her sake more than for mine own, - My fortunes were more able to relieve her; - But I am shepherd to another man - And do not shear the fleeces that I graze: - My master is of churlish disposition - And little recks to find the way to heaven - By doing deeds of hospitality: - Besides, his cote, his flocks and bounds of feed - Are now on sale, and at our sheepcote now, - By reason of his absence, there is nothing - That you will feed on; but what is, come see. - And in my voice most welcome shall you be. - -ROSALIND What is he that shall buy his flock and pasture? - -CORIN That young swain that you saw here but erewhile, - That little cares for buying any thing. - -ROSALIND I pray thee, if it stand with honesty, - Buy thou the cottage, pasture and the flock, - And thou shalt have to pay for it of us. - -CELIA And we will mend thy wages. I like this place. - And willingly could waste my time in it. - -CORIN Assuredly the thing is to be sold: - Go with me: if you like upon report - The soil, the profit and this kind of life, - I will your very faithful feeder be - And buy it with your gold right suddenly. - - [Exeunt] - - - - - AS YOU LIKE IT - - -ACT II - - - -SCENE V The Forest. - - - [Enter AMIENS, JAQUES, and others] - - SONG. -AMIENS Under the greenwood tree - Who loves to lie with me, - And turn his merry note - Unto the sweet bird's throat, - Come hither, come hither, come hither: - Here shall he see No enemy - But winter and rough weather. - -JAQUES More, more, I prithee, more. - -AMIENS It will make you melancholy, Monsieur Jaques. - -JAQUES I thank it. More, I prithee, more. I can suck - melancholy out of a song, as a weasel sucks eggs. - More, I prithee, more. - -AMIENS My voice is ragged: I know I cannot please you. - -JAQUES I do not desire you to please me; I do desire you to - sing. Come, more; another stanzo: call you 'em stanzos? - -AMIENS What you will, Monsieur Jaques. - -JAQUES Nay, I care not for their names; they owe me - nothing. Will you sing? - -AMIENS More at your request than to please myself. - -JAQUES Well then, if ever I thank any man, I'll thank you; - but that they call compliment is like the encounter - of two dog-apes, and when a man thanks me heartily, - methinks I have given him a penny and he renders me - the beggarly thanks. Come, sing; and you that will - not, hold your tongues. - -AMIENS Well, I'll end the song. Sirs, cover the while; the - duke will drink under this tree. He hath been all - this day to look you. - -JAQUES And I have been all this day to avoid him. He is - too disputable for my company: I think of as many - matters as he, but I give heaven thanks and make no - boast of them. Come, warble, come. - - SONG. - Who doth ambition shun - - [All together here] - - And loves to live i' the sun, - Seeking the food he eats - And pleased with what he gets, - Come hither, come hither, come hither: - Here shall he see No enemy - But winter and rough weather. - -JAQUES I'll give you a verse to this note that I made - yesterday in despite of my invention. - -AMIENS And I'll sing it. - -JAQUES Thus it goes:-- - - If it do come to pass - That any man turn ass, - Leaving his wealth and ease, - A stubborn will to please, - Ducdame, ducdame, ducdame: - Here shall he see - Gross fools as he, - An if he will come to me. - -AMIENS What's that 'ducdame'? - -JAQUES 'Tis a Greek invocation, to call fools into a - circle. I'll go sleep, if I can; if I cannot, I'll - rail against all the first-born of Egypt. - -AMIENS And I'll go seek the duke: his banquet is prepared. - - [Exeunt severally] - - - - - AS YOU LIKE IT - - -ACT II - - - -SCENE VI The forest. - - - [Enter ORLANDO and ADAM] - -ADAM Dear master, I can go no further. O, I die for food! - Here lie I down, and measure out my grave. Farewell, - kind master. - -ORLANDO Why, how now, Adam! no greater heart in thee? Live - a little; comfort a little; cheer thyself a little. - If this uncouth forest yield any thing savage, I - will either be food for it or bring it for food to - thee. Thy conceit is nearer death than thy powers. - For my sake be comfortable; hold death awhile at - the arm's end: I will here be with thee presently; - and if I bring thee not something to eat, I will - give thee leave to die: but if thou diest before I - come, thou art a mocker of my labour. Well said! - thou lookest cheerly, and I'll be with thee quickly. - Yet thou liest in the bleak air: come, I will bear - thee to some shelter; and thou shalt not die for - lack of a dinner, if there live any thing in this - desert. Cheerly, good Adam! - - [Exeunt] - - - - - AS YOU LIKE IT - - -ACT II - - - -SCENE VII The forest. - - - [A table set out. Enter DUKE SENIOR, AMIENS, and - Lords like outlaws] - -DUKE SENIOR I think he be transform'd into a beast; - For I can no where find him like a man. - -First Lord My lord, he is but even now gone hence: - Here was he merry, hearing of a song. - -DUKE SENIOR If he, compact of jars, grow musical, - We shall have shortly discord in the spheres. - Go, seek him: tell him I would speak with him. - - [Enter JAQUES] - -First Lord He saves my labour by his own approach. - -DUKE SENIOR Why, how now, monsieur! what a life is this, - That your poor friends must woo your company? - What, you look merrily! - -JAQUES A fool, a fool! I met a fool i' the forest, - A motley fool; a miserable world! - As I do live by food, I met a fool - Who laid him down and bask'd him in the sun, - And rail'd on Lady Fortune in good terms, - In good set terms and yet a motley fool. - 'Good morrow, fool,' quoth I. 'No, sir,' quoth he, - 'Call me not fool till heaven hath sent me fortune:' - And then he drew a dial from his poke, - And, looking on it with lack-lustre eye, - Says very wisely, 'It is ten o'clock: - Thus we may see,' quoth he, 'how the world wags: - 'Tis but an hour ago since it was nine, - And after one hour more 'twill be eleven; - And so, from hour to hour, we ripe and ripe, - And then, from hour to hour, we rot and rot; - And thereby hangs a tale.' When I did hear - The motley fool thus moral on the time, - My lungs began to crow like chanticleer, - That fools should be so deep-contemplative, - And I did laugh sans intermission - An hour by his dial. O noble fool! - A worthy fool! Motley's the only wear. - -DUKE SENIOR What fool is this? - -JAQUES O worthy fool! One that hath been a courtier, - And says, if ladies be but young and fair, - They have the gift to know it: and in his brain, - Which is as dry as the remainder biscuit - After a voyage, he hath strange places cramm'd - With observation, the which he vents - In mangled forms. O that I were a fool! - I am ambitious for a motley coat. - -DUKE SENIOR Thou shalt have one. - -JAQUES It is my only suit; - Provided that you weed your better judgments - Of all opinion that grows rank in them - That I am wise. I must have liberty - Withal, as large a charter as the wind, - To blow on whom I please; for so fools have; - And they that are most galled with my folly, - They most must laugh. And why, sir, must they so? - The 'why' is plain as way to parish church: - He that a fool doth very wisely hit - Doth very foolishly, although he smart, - Not to seem senseless of the bob: if not, - The wise man's folly is anatomized - Even by the squandering glances of the fool. - Invest me in my motley; give me leave - To speak my mind, and I will through and through - Cleanse the foul body of the infected world, - If they will patiently receive my medicine. - -DUKE SENIOR Fie on thee! I can tell what thou wouldst do. - -JAQUES What, for a counter, would I do but good? - -DUKE SENIOR Most mischievous foul sin, in chiding sin: - For thou thyself hast been a libertine, - As sensual as the brutish sting itself; - And all the embossed sores and headed evils, - That thou with licence of free foot hast caught, - Wouldst thou disgorge into the general world. - -JAQUES Why, who cries out on pride, - That can therein tax any private party? - Doth it not flow as hugely as the sea, - Till that the weary very means do ebb? - What woman in the city do I name, - When that I say the city-woman bears - The cost of princes on unworthy shoulders? - Who can come in and say that I mean her, - When such a one as she such is her neighbour? - Or what is he of basest function - That says his bravery is not of my cost, - Thinking that I mean him, but therein suits - His folly to the mettle of my speech? - There then; how then? what then? Let me see wherein - My tongue hath wrong'd him: if it do him right, - Then he hath wrong'd himself; if he be free, - Why then my taxing like a wild-goose flies, - Unclaim'd of any man. But who comes here? - - [Enter ORLANDO, with his sword drawn] - -ORLANDO Forbear, and eat no more. - -JAQUES Why, I have eat none yet. - -ORLANDO Nor shalt not, till necessity be served. - -JAQUES Of what kind should this cock come of? - -DUKE SENIOR Art thou thus bolden'd, man, by thy distress, - Or else a rude despiser of good manners, - That in civility thou seem'st so empty? - -ORLANDO You touch'd my vein at first: the thorny point - Of bare distress hath ta'en from me the show - Of smooth civility: yet am I inland bred - And know some nurture. But forbear, I say: - He dies that touches any of this fruit - Till I and my affairs are answered. - -JAQUES An you will not be answered with reason, I must die. - -DUKE SENIOR What would you have? Your gentleness shall force - More than your force move us to gentleness. - -ORLANDO I almost die for food; and let me have it. - -DUKE SENIOR Sit down and feed, and welcome to our table. - -ORLANDO Speak you so gently? Pardon me, I pray you: - I thought that all things had been savage here; - And therefore put I on the countenance - Of stern commandment. But whate'er you are - That in this desert inaccessible, - Under the shade of melancholy boughs, - Lose and neglect the creeping hours of time - If ever you have look'd on better days, - If ever been where bells have knoll'd to church, - If ever sat at any good man's feast, - If ever from your eyelids wiped a tear - And know what 'tis to pity and be pitied, - Let gentleness my strong enforcement be: - In the which hope I blush, and hide my sword. - -DUKE SENIOR True is it that we have seen better days, - And have with holy bell been knoll'd to church - And sat at good men's feasts and wiped our eyes - Of drops that sacred pity hath engender'd: - And therefore sit you down in gentleness - And take upon command what help we have - That to your wanting may be minister'd. - -ORLANDO Then but forbear your food a little while, - Whiles, like a doe, I go to find my fawn - And give it food. There is an old poor man, - Who after me hath many a weary step - Limp'd in pure love: till he be first sufficed, - Oppress'd with two weak evils, age and hunger, - I will not touch a bit. - -DUKE SENIOR Go find him out, - And we will nothing waste till you return. - -ORLANDO I thank ye; and be blest for your good comfort! - - [Exit] - -DUKE SENIOR Thou seest we are not all alone unhappy: - This wide and universal theatre - Presents more woeful pageants than the scene - Wherein we play in. - -JAQUES All the world's a stage, - And all the men and women merely players: - They have their exits and their entrances; - And one man in his time plays many parts, - His acts being seven ages. At first the infant, - Mewling and puking in the nurse's arms. - And then the whining school-boy, with his satchel - And shining morning face, creeping like snail - Unwillingly to school. And then the lover, - Sighing like furnace, with a woeful ballad - Made to his mistress' eyebrow. Then a soldier, - Full of strange oaths and bearded like the pard, - Jealous in honour, sudden and quick in quarrel, - Seeking the bubble reputation - Even in the cannon's mouth. And then the justice, - In fair round belly with good capon lined, - With eyes severe and beard of formal cut, - Full of wise saws and modern instances; - And so he plays his part. The sixth age shifts - Into the lean and slipper'd pantaloon, - With spectacles on nose and pouch on side, - His youthful hose, well saved, a world too wide - For his shrunk shank; and his big manly voice, - Turning again toward childish treble, pipes - And whistles in his sound. Last scene of all, - That ends this strange eventful history, - Is second childishness and mere oblivion, - Sans teeth, sans eyes, sans taste, sans everything. - - [Re-enter ORLANDO, with ADAM] - -DUKE SENIOR Welcome. Set down your venerable burthen, - And let him feed. - -ORLANDO I thank you most for him. - -ADAM So had you need: - I scarce can speak to thank you for myself. - -DUKE SENIOR Welcome; fall to: I will not trouble you - As yet, to question you about your fortunes. - Give us some music; and, good cousin, sing. - - SONG. -AMIENS Blow, blow, thou winter wind. - Thou art not so unkind - As man's ingratitude; - Thy tooth is not so keen, - Because thou art not seen, - Although thy breath be rude. - Heigh-ho! sing, heigh-ho! unto the green holly: - Most friendship is feigning, most loving mere folly: - Then, heigh-ho, the holly! - This life is most jolly. - Freeze, freeze, thou bitter sky, - That dost not bite so nigh - As benefits forgot: - Though thou the waters warp, - Thy sting is not so sharp - As friend remember'd not. - Heigh-ho! sing, &c. - -DUKE SENIOR If that you were the good Sir Rowland's son, - As you have whisper'd faithfully you were, - And as mine eye doth his effigies witness - Most truly limn'd and living in your face, - Be truly welcome hither: I am the duke - That loved your father: the residue of your fortune, - Go to my cave and tell me. Good old man, - Thou art right welcome as thy master is. - Support him by the arm. Give me your hand, - And let me all your fortunes understand. - - [Exeunt] - - - - - AS YOU LIKE IT - - -ACT III - - - -SCENE I A room in the palace. - - - [Enter DUKE FREDERICK, Lords, and OLIVER] - -DUKE FREDERICK Not see him since? Sir, sir, that cannot be: - But were I not the better part made mercy, - I should not seek an absent argument - Of my revenge, thou present. But look to it: - Find out thy brother, wheresoe'er he is; - Seek him with candle; bring him dead or living - Within this twelvemonth, or turn thou no more - To seek a living in our territory. - Thy lands and all things that thou dost call thine - Worth seizure do we seize into our hands, - Till thou canst quit thee by thy brothers mouth - Of what we think against thee. - -OLIVER O that your highness knew my heart in this! - I never loved my brother in my life. - -DUKE FREDERICK More villain thou. Well, push him out of doors; - And let my officers of such a nature - Make an extent upon his house and lands: - Do this expediently and turn him going. - - [Exeunt] - - - - - AS YOU LIKE IT - - -ACT III - - - -SCENE II The forest. - - - [Enter ORLANDO, with a paper] - -ORLANDO Hang there, my verse, in witness of my love: - And thou, thrice-crowned queen of night, survey - With thy chaste eye, from thy pale sphere above, - Thy huntress' name that my full life doth sway. - O Rosalind! these trees shall be my books - And in their barks my thoughts I'll character; - That every eye which in this forest looks - Shall see thy virtue witness'd every where. - Run, run, Orlando; carve on every tree - The fair, the chaste and unexpressive she. - - [Exit] - - [Enter CORIN and TOUCHSTONE] - -CORIN And how like you this shepherd's life, Master Touchstone? - -TOUCHSTONE Truly, shepherd, in respect of itself, it is a good - life, but in respect that it is a shepherd's life, - it is naught. In respect that it is solitary, I - like it very well; but in respect that it is - private, it is a very vile life. Now, in respect it - is in the fields, it pleaseth me well; but in - respect it is not in the court, it is tedious. As - is it a spare life, look you, it fits my humour well; - but as there is no more plenty in it, it goes much - against my stomach. Hast any philosophy in thee, shepherd? - -CORIN No more but that I know the more one sickens the - worse at ease he is; and that he that wants money, - means and content is without three good friends; - that the property of rain is to wet and fire to - burn; that good pasture makes fat sheep, and that a - great cause of the night is lack of the sun; that - he that hath learned no wit by nature nor art may - complain of good breeding or comes of a very dull kindred. - -TOUCHSTONE Such a one is a natural philosopher. Wast ever in - court, shepherd? - -CORIN No, truly. - -TOUCHSTONE Then thou art damned. - -CORIN Nay, I hope. - -TOUCHSTONE Truly, thou art damned like an ill-roasted egg, all - on one side. - -CORIN For not being at court? Your reason. - -TOUCHSTONE Why, if thou never wast at court, thou never sawest - good manners; if thou never sawest good manners, - then thy manners must be wicked; and wickedness is - sin, and sin is damnation. Thou art in a parlous - state, shepherd. - -CORIN Not a whit, Touchstone: those that are good manners - at the court are as ridiculous in the country as the - behavior of the country is most mockable at the - court. You told me you salute not at the court, but - you kiss your hands: that courtesy would be - uncleanly, if courtiers were shepherds. - -TOUCHSTONE Instance, briefly; come, instance. - -CORIN Why, we are still handling our ewes, and their - fells, you know, are greasy. - -TOUCHSTONE Why, do not your courtier's hands sweat? and is not - the grease of a mutton as wholesome as the sweat of - a man? Shallow, shallow. A better instance, I say; come. - -CORIN Besides, our hands are hard. - -TOUCHSTONE Your lips will feel them the sooner. Shallow again. - A more sounder instance, come. - -CORIN And they are often tarred over with the surgery of - our sheep: and would you have us kiss tar? The - courtier's hands are perfumed with civet. - -TOUCHSTONE Most shallow man! thou worms-meat, in respect of a - good piece of flesh indeed! Learn of the wise, and - perpend: civet is of a baser birth than tar, the - very uncleanly flux of a cat. Mend the instance, shepherd. - -CORIN You have too courtly a wit for me: I'll rest. - -TOUCHSTONE Wilt thou rest damned? God help thee, shallow man! - God make incision in thee! thou art raw. - -CORIN Sir, I am a true labourer: I earn that I eat, get - that I wear, owe no man hate, envy no man's - happiness, glad of other men's good, content with my - harm, and the greatest of my pride is to see my ewes - graze and my lambs suck. - -TOUCHSTONE That is another simple sin in you, to bring the ewes - and the rams together and to offer to get your - living by the copulation of cattle; to be bawd to a - bell-wether, and to betray a she-lamb of a - twelvemonth to a crooked-pated, old, cuckoldly ram, - out of all reasonable match. If thou beest not - damned for this, the devil himself will have no - shepherds; I cannot see else how thou shouldst - 'scape. - -CORIN Here comes young Master Ganymede, my new mistress's brother. - - [Enter ROSALIND, with a paper, reading] - -ROSALIND From the east to western Ind, - No jewel is like Rosalind. - Her worth, being mounted on the wind, - Through all the world bears Rosalind. - All the pictures fairest lined - Are but black to Rosalind. - Let no fair be kept in mind - But the fair of Rosalind. - -TOUCHSTONE I'll rhyme you so eight years together, dinners and - suppers and sleeping-hours excepted: it is the - right butter-women's rank to market. - -ROSALIND Out, fool! - -TOUCHSTONE For a taste: - If a hart do lack a hind, - Let him seek out Rosalind. - If the cat will after kind, - So be sure will Rosalind. - Winter garments must be lined, - So must slender Rosalind. - They that reap must sheaf and bind; - Then to cart with Rosalind. - Sweetest nut hath sourest rind, - Such a nut is Rosalind. - He that sweetest rose will find - Must find love's prick and Rosalind. - This is the very false gallop of verses: why do you - infect yourself with them? - -ROSALIND Peace, you dull fool! I found them on a tree. - -TOUCHSTONE Truly, the tree yields bad fruit. - -ROSALIND I'll graff it with you, and then I shall graff it - with a medlar: then it will be the earliest fruit - i' the country; for you'll be rotten ere you be half - ripe, and that's the right virtue of the medlar. - -TOUCHSTONE You have said; but whether wisely or no, let the - forest judge. - - [Enter CELIA, with a writing] - -ROSALIND Peace! Here comes my sister, reading: stand aside. - -CELIA [Reads] - - Why should this a desert be? - For it is unpeopled? No: - Tongues I'll hang on every tree, - That shall civil sayings show: - Some, how brief the life of man - Runs his erring pilgrimage, - That the stretching of a span - Buckles in his sum of age; - Some, of violated vows - 'Twixt the souls of friend and friend: - But upon the fairest boughs, - Or at every sentence end, - Will I Rosalinda write, - Teaching all that read to know - The quintessence of every sprite - Heaven would in little show. - Therefore Heaven Nature charged - That one body should be fill'd - With all graces wide-enlarged: - Nature presently distill'd - Helen's cheek, but not her heart, - Cleopatra's majesty, - Atalanta's better part, - Sad Lucretia's modesty. - Thus Rosalind of many parts - By heavenly synod was devised, - Of many faces, eyes and hearts, - To have the touches dearest prized. - Heaven would that she these gifts should have, - And I to live and die her slave. - -ROSALIND O most gentle pulpiter! what tedious homily of love - have you wearied your parishioners withal, and never - cried 'Have patience, good people!' - -CELIA How now! back, friends! Shepherd, go off a little. - Go with him, sirrah. - -TOUCHSTONE Come, shepherd, let us make an honourable retreat; - though not with bag and baggage, yet with scrip and scrippage. - - [Exeunt CORIN and TOUCHSTONE] - -CELIA Didst thou hear these verses? - -ROSALIND O, yes, I heard them all, and more too; for some of - them had in them more feet than the verses would bear. - -CELIA That's no matter: the feet might bear the verses. - -ROSALIND Ay, but the feet were lame and could not bear - themselves without the verse and therefore stood - lamely in the verse. - -CELIA But didst thou hear without wondering how thy name - should be hanged and carved upon these trees? - -ROSALIND I was seven of the nine days out of the wonder - before you came; for look here what I found on a - palm-tree. I was never so be-rhymed since - Pythagoras' time, that I was an Irish rat, which I - can hardly remember. - -CELIA Trow you who hath done this? - -ROSALIND Is it a man? - -CELIA And a chain, that you once wore, about his neck. - Change you colour? - -ROSALIND I prithee, who? - -CELIA O Lord, Lord! it is a hard matter for friends to - meet; but mountains may be removed with earthquakes - and so encounter. - -ROSALIND Nay, but who is it? - -CELIA Is it possible? - -ROSALIND Nay, I prithee now with most petitionary vehemence, - tell me who it is. - -CELIA O wonderful, wonderful, and most wonderful - wonderful! and yet again wonderful, and after that, - out of all hooping! - -ROSALIND Good my complexion! dost thou think, though I am - caparisoned like a man, I have a doublet and hose in - my disposition? One inch of delay more is a - South-sea of discovery; I prithee, tell me who is it - quickly, and speak apace. I would thou couldst - stammer, that thou mightst pour this concealed man - out of thy mouth, as wine comes out of a narrow- - mouthed bottle, either too much at once, or none at - all. I prithee, take the cork out of thy mouth that - may drink thy tidings. - -CELIA So you may put a man in your belly. - -ROSALIND Is he of God's making? What manner of man? Is his - head worth a hat, or his chin worth a beard? - -CELIA Nay, he hath but a little beard. - -ROSALIND Why, God will send more, if the man will be - thankful: let me stay the growth of his beard, if - thou delay me not the knowledge of his chin. - -CELIA It is young Orlando, that tripped up the wrestler's - heels and your heart both in an instant. - -ROSALIND Nay, but the devil take mocking: speak, sad brow and - true maid. - -CELIA I' faith, coz, 'tis he. - -ROSALIND Orlando? - -CELIA Orlando. - -ROSALIND Alas the day! what shall I do with my doublet and - hose? What did he when thou sawest him? What said - he? How looked he? Wherein went he? What makes - him here? Did he ask for me? Where remains he? - How parted he with thee? and when shalt thou see - him again? Answer me in one word. - -CELIA You must borrow me Gargantua's mouth first: 'tis a - word too great for any mouth of this age's size. To - say ay and no to these particulars is more than to - answer in a catechism. - -ROSALIND But doth he know that I am in this forest and in - man's apparel? Looks he as freshly as he did the - day he wrestled? - -CELIA It is as easy to count atomies as to resolve the - propositions of a lover; but take a taste of my - finding him, and relish it with good observance. - I found him under a tree, like a dropped acorn. - -ROSALIND It may well be called Jove's tree, when it drops - forth such fruit. - -CELIA Give me audience, good madam. - -ROSALIND Proceed. - -CELIA There lay he, stretched along, like a wounded knight. - -ROSALIND Though it be pity to see such a sight, it well - becomes the ground. - -CELIA Cry 'holla' to thy tongue, I prithee; it curvets - unseasonably. He was furnished like a hunter. - -ROSALIND O, ominous! he comes to kill my heart. - -CELIA I would sing my song without a burden: thou bringest - me out of tune. - -ROSALIND Do you not know I am a woman? when I think, I must - speak. Sweet, say on. - -CELIA You bring me out. Soft! comes he not here? - - [Enter ORLANDO and JAQUES] - -ROSALIND 'Tis he: slink by, and note him. - -JAQUES I thank you for your company; but, good faith, I had - as lief have been myself alone. - -ORLANDO And so had I; but yet, for fashion sake, I thank you - too for your society. - -JAQUES God be wi' you: let's meet as little as we can. - -ORLANDO I do desire we may be better strangers. - -JAQUES I pray you, mar no more trees with writing - love-songs in their barks. - -ORLANDO I pray you, mar no more of my verses with reading - them ill-favouredly. - -JAQUES Rosalind is your love's name? - -ORLANDO Yes, just. - -JAQUES I do not like her name. - -ORLANDO There was no thought of pleasing you when she was - christened. - -JAQUES What stature is she of? - -ORLANDO Just as high as my heart. - -JAQUES You are full of pretty answers. Have you not been - acquainted with goldsmiths' wives, and conned them - out of rings? - -ORLANDO Not so; but I answer you right painted cloth, from - whence you have studied your questions. - -JAQUES You have a nimble wit: I think 'twas made of - Atalanta's heels. Will you sit down with me? and - we two will rail against our mistress the world and - all our misery. - -ORLANDO I will chide no breather in the world but myself, - against whom I know most faults. - -JAQUES The worst fault you have is to be in love. - -ORLANDO 'Tis a fault I will not change for your best virtue. - I am weary of you. - -JAQUES By my troth, I was seeking for a fool when I found - you. - -ORLANDO He is drowned in the brook: look but in, and you - shall see him. - -JAQUES There I shall see mine own figure. - -ORLANDO Which I take to be either a fool or a cipher. - -JAQUES I'll tarry no longer with you: farewell, good - Signior Love. - -ORLANDO I am glad of your departure: adieu, good Monsieur - Melancholy. - - [Exit JAQUES] - -ROSALIND [Aside to CELIA] I will speak to him, like a saucy - lackey and under that habit play the knave with him. - Do you hear, forester? - -ORLANDO Very well: what would you? - -ROSALIND I pray you, what is't o'clock? - -ORLANDO You should ask me what time o' day: there's no clock - in the forest. - -ROSALIND Then there is no true lover in the forest; else - sighing every minute and groaning every hour would - detect the lazy foot of Time as well as a clock. - -ORLANDO And why not the swift foot of Time? had not that - been as proper? - -ROSALIND By no means, sir: Time travels in divers paces with - divers persons. I'll tell you who Time ambles - withal, who Time trots withal, who Time gallops - withal and who he stands still withal. - -ORLANDO I prithee, who doth he trot withal? - -ROSALIND Marry, he trots hard with a young maid between the - contract of her marriage and the day it is - solemnized: if the interim be but a se'nnight, - Time's pace is so hard that it seems the length of - seven year. - -ORLANDO Who ambles Time withal? - -ROSALIND With a priest that lacks Latin and a rich man that - hath not the gout, for the one sleeps easily because - he cannot study, and the other lives merrily because - he feels no pain, the one lacking the burden of lean - and wasteful learning, the other knowing no burden - of heavy tedious penury; these Time ambles withal. - -ORLANDO Who doth he gallop withal? - -ROSALIND With a thief to the gallows, for though he go as - softly as foot can fall, he thinks himself too soon there. - -ORLANDO Who stays it still withal? - -ROSALIND With lawyers in the vacation, for they sleep between - term and term and then they perceive not how Time moves. - -ORLANDO Where dwell you, pretty youth? - -ROSALIND With this shepherdess, my sister; here in the - skirts of the forest, like fringe upon a petticoat. - -ORLANDO Are you native of this place? - -ROSALIND As the cony that you see dwell where she is kindled. - -ORLANDO Your accent is something finer than you could - purchase in so removed a dwelling. - -ROSALIND I have been told so of many: but indeed an old - religious uncle of mine taught me to speak, who was - in his youth an inland man; one that knew courtship - too well, for there he fell in love. I have heard - him read many lectures against it, and I thank God - I am not a woman, to be touched with so many - giddy offences as he hath generally taxed their - whole sex withal. - -ORLANDO Can you remember any of the principal evils that he - laid to the charge of women? - -ROSALIND There were none principal; they were all like one - another as half-pence are, every one fault seeming - monstrous till his fellow fault came to match it. - -ORLANDO I prithee, recount some of them. - -ROSALIND No, I will not cast away my physic but on those that - are sick. There is a man haunts the forest, that - abuses our young plants with carving 'Rosalind' on - their barks; hangs odes upon hawthorns and elegies - on brambles, all, forsooth, deifying the name of - Rosalind: if I could meet that fancy-monger I would - give him some good counsel, for he seems to have the - quotidian of love upon him. - -ORLANDO I am he that is so love-shaked: I pray you tell me - your remedy. - -ROSALIND There is none of my uncle's marks upon you: he - taught me how to know a man in love; in which cage - of rushes I am sure you are not prisoner. - -ORLANDO What were his marks? - -ROSALIND A lean cheek, which you have not, a blue eye and - sunken, which you have not, an unquestionable - spirit, which you have not, a beard neglected, - which you have not; but I pardon you for that, for - simply your having in beard is a younger brother's - revenue: then your hose should be ungartered, your - bonnet unbanded, your sleeve unbuttoned, your shoe - untied and every thing about you demonstrating a - careless desolation; but you are no such man; you - are rather point-device in your accoutrements as - loving yourself than seeming the lover of any other. - -ORLANDO Fair youth, I would I could make thee believe I love. - -ROSALIND Me believe it! you may as soon make her that you - love believe it; which, I warrant, she is apter to - do than to confess she does: that is one of the - points in the which women still give the lie to - their consciences. But, in good sooth, are you he - that hangs the verses on the trees, wherein Rosalind - is so admired? - -ORLANDO I swear to thee, youth, by the white hand of - Rosalind, I am that he, that unfortunate he. - -ROSALIND But are you so much in love as your rhymes speak? - -ORLANDO Neither rhyme nor reason can express how much. - -ROSALIND Love is merely a madness, and, I tell you, deserves - as well a dark house and a whip as madmen do: and - the reason why they are not so punished and cured - is, that the lunacy is so ordinary that the whippers - are in love too. Yet I profess curing it by counsel. - -ORLANDO Did you ever cure any so? - -ROSALIND Yes, one, and in this manner. He was to imagine me - his love, his mistress; and I set him every day to - woo me: at which time would I, being but a moonish - youth, grieve, be effeminate, changeable, longing - and liking, proud, fantastical, apish, shallow, - inconstant, full of tears, full of smiles, for every - passion something and for no passion truly any - thing, as boys and women are for the most part - cattle of this colour; would now like him, now loathe - him; then entertain him, then forswear him; now weep - for him, then spit at him; that I drave my suitor - from his mad humour of love to a living humour of - madness; which was, to forswear the full stream of - the world, and to live in a nook merely monastic. - And thus I cured him; and this way will I take upon - me to wash your liver as clean as a sound sheep's - heart, that there shall not be one spot of love in't. - -ORLANDO I would not be cured, youth. - -ROSALIND I would cure you, if you would but call me Rosalind - and come every day to my cote and woo me. - -ORLANDO Now, by the faith of my love, I will: tell me - where it is. - -ROSALIND Go with me to it and I'll show it you and by the way - you shall tell me where in the forest you live. - Will you go? - -ORLANDO With all my heart, good youth. - -ROSALIND Nay you must call me Rosalind. Come, sister, will you go? - - [Exeunt] - - - - - AS YOU LIKE IT - - -ACT III - - - -SCENE III The forest. - - - [Enter TOUCHSTONE and AUDREY; JAQUES behind] - -TOUCHSTONE Come apace, good Audrey: I will fetch up your - goats, Audrey. And how, Audrey? am I the man yet? - doth my simple feature content you? - -AUDREY Your features! Lord warrant us! what features! - -TOUCHSTONE I am here with thee and thy goats, as the most - capricious poet, honest Ovid, was among the Goths. - -JAQUES [Aside] O knowledge ill-inhabited, worse than Jove - in a thatched house! - -TOUCHSTONE When a man's verses cannot be understood, nor a - man's good wit seconded with the forward child - Understanding, it strikes a man more dead than a - great reckoning in a little room. Truly, I would - the gods had made thee poetical. - -AUDREY I do not know what 'poetical' is: is it honest in - deed and word? is it a true thing? - -TOUCHSTONE No, truly; for the truest poetry is the most - feigning; and lovers are given to poetry, and what - they swear in poetry may be said as lovers they do feign. - -AUDREY Do you wish then that the gods had made me poetical? - -TOUCHSTONE I do, truly; for thou swearest to me thou art - honest: now, if thou wert a poet, I might have some - hope thou didst feign. - -AUDREY Would you not have me honest? - -TOUCHSTONE No, truly, unless thou wert hard-favoured; for - honesty coupled to beauty is to have honey a sauce to sugar. - -JAQUES [Aside] A material fool! - -AUDREY Well, I am not fair; and therefore I pray the gods - make me honest. - -TOUCHSTONE Truly, and to cast away honesty upon a foul slut - were to put good meat into an unclean dish. - -AUDREY I am not a slut, though I thank the gods I am foul. - -TOUCHSTONE Well, praised be the gods for thy foulness! - sluttishness may come hereafter. But be it as it may - be, I will marry thee, and to that end I have been - with Sir Oliver Martext, the vicar of the next - village, who hath promised to meet me in this place - of the forest and to couple us. - -JAQUES [Aside] I would fain see this meeting. - -AUDREY Well, the gods give us joy! - -TOUCHSTONE Amen. A man may, if he were of a fearful heart, - stagger in this attempt; for here we have no temple - but the wood, no assembly but horn-beasts. But what - though? Courage! As horns are odious, they are - necessary. It is said, 'many a man knows no end of - his goods:' right; many a man has good horns, and - knows no end of them. Well, that is the dowry of - his wife; 'tis none of his own getting. Horns? - Even so. Poor men alone? No, no; the noblest deer - hath them as huge as the rascal. Is the single man - therefore blessed? No: as a walled town is more - worthier than a village, so is the forehead of a - married man more honourable than the bare brow of a - bachelor; and by how much defence is better than no - skill, by so much is a horn more precious than to - want. Here comes Sir Oliver. - - [Enter SIR OLIVER MARTEXT] - - Sir Oliver Martext, you are well met: will you - dispatch us here under this tree, or shall we go - with you to your chapel? - -SIR OLIVER MARTEXT Is there none here to give the woman? - -TOUCHSTONE I will not take her on gift of any man. - -SIR OLIVER MARTEXT Truly, she must be given, or the marriage is not lawful. - -JAQUES [Advancing] - - Proceed, proceed I'll give her. - -TOUCHSTONE Good even, good Master What-ye-call't: how do you, - sir? You are very well met: God 'ild you for your - last company: I am very glad to see you: even a - toy in hand here, sir: nay, pray be covered. - -JAQUES Will you be married, motley? - -TOUCHSTONE As the ox hath his bow, sir, the horse his curb and - the falcon her bells, so man hath his desires; and - as pigeons bill, so wedlock would be nibbling. - -JAQUES And will you, being a man of your breeding, be - married under a bush like a beggar? Get you to - church, and have a good priest that can tell you - what marriage is: this fellow will but join you - together as they join wainscot; then one of you will - prove a shrunk panel and, like green timber, warp, warp. - -TOUCHSTONE [Aside] I am not in the mind but I were better to be - married of him than of another: for he is not like - to marry me well; and not being well married, it - will be a good excuse for me hereafter to leave my wife. - -JAQUES Go thou with me, and let me counsel thee. - -TOUCHSTONE 'Come, sweet Audrey: - We must be married, or we must live in bawdry. - Farewell, good Master Oliver: not,-- - O sweet Oliver, - O brave Oliver, - Leave me not behind thee: but,-- - Wind away, - Begone, I say, - I will not to wedding with thee. - - [Exeunt JAQUES, TOUCHSTONE and AUDREY] - -SIR OLIVER MARTEXT 'Tis no matter: ne'er a fantastical knave of them - all shall flout me out of my calling. - - [Exit] - - - - - AS YOU LIKE IT - - -ACT III - - - -SCENE IV The forest. - - - [Enter ROSALIND and CELIA] - -ROSALIND Never talk to me; I will weep. - -CELIA Do, I prithee; but yet have the grace to consider - that tears do not become a man. - -ROSALIND But have I not cause to weep? - -CELIA As good cause as one would desire; therefore weep. - -ROSALIND His very hair is of the dissembling colour. - -CELIA Something browner than Judas's marry, his kisses are - Judas's own children. - -ROSALIND I' faith, his hair is of a good colour. - -CELIA An excellent colour: your chestnut was ever the only colour. - -ROSALIND And his kissing is as full of sanctity as the touch - of holy bread. - -CELIA He hath bought a pair of cast lips of Diana: a nun - of winter's sisterhood kisses not more religiously; - the very ice of chastity is in them. - -ROSALIND But why did he swear he would come this morning, and - comes not? - -CELIA Nay, certainly, there is no truth in him. - -ROSALIND Do you think so? - -CELIA Yes; I think he is not a pick-purse nor a - horse-stealer, but for his verity in love, I do - think him as concave as a covered goblet or a - worm-eaten nut. - -ROSALIND Not true in love? - -CELIA Yes, when he is in; but I think he is not in. - -ROSALIND You have heard him swear downright he was. - -CELIA 'Was' is not 'is:' besides, the oath of a lover is - no stronger than the word of a tapster; they are - both the confirmer of false reckonings. He attends - here in the forest on the duke your father. - -ROSALIND I met the duke yesterday and had much question with - him: he asked me of what parentage I was; I told - him, of as good as he; so he laughed and let me go. - But what talk we of fathers, when there is such a - man as Orlando? - -CELIA O, that's a brave man! he writes brave verses, - speaks brave words, swears brave oaths and breaks - them bravely, quite traverse, athwart the heart of - his lover; as a puisny tilter, that spurs his horse - but on one side, breaks his staff like a noble - goose: but all's brave that youth mounts and folly - guides. Who comes here? - - [Enter CORIN] - -CORIN Mistress and master, you have oft inquired - After the shepherd that complain'd of love, - Who you saw sitting by me on the turf, - Praising the proud disdainful shepherdess - That was his mistress. - -CELIA Well, and what of him? - -CORIN If you will see a pageant truly play'd, - Between the pale complexion of true love - And the red glow of scorn and proud disdain, - Go hence a little and I shall conduct you, - If you will mark it. - -ROSALIND O, come, let us remove: - The sight of lovers feedeth those in love. - Bring us to this sight, and you shall say - I'll prove a busy actor in their play. - - [Exeunt] - - - - - AS YOU LIKE IT - - -ACT III - - - -SCENE V Another part of the forest. - - - [Enter SILVIUS and PHEBE] - -SILVIUS Sweet Phebe, do not scorn me; do not, Phebe; - Say that you love me not, but say not so - In bitterness. The common executioner, - Whose heart the accustom'd sight of death makes hard, - Falls not the axe upon the humbled neck - But first begs pardon: will you sterner be - Than he that dies and lives by bloody drops? - - [Enter ROSALIND, CELIA, and CORIN, behind] - -PHEBE I would not be thy executioner: - I fly thee, for I would not injure thee. - Thou tell'st me there is murder in mine eye: - 'Tis pretty, sure, and very probable, - That eyes, that are the frail'st and softest things, - Who shut their coward gates on atomies, - Should be call'd tyrants, butchers, murderers! - Now I do frown on thee with all my heart; - And if mine eyes can wound, now let them kill thee: - Now counterfeit to swoon; why now fall down; - Or if thou canst not, O, for shame, for shame, - Lie not, to say mine eyes are murderers! - Now show the wound mine eye hath made in thee: - Scratch thee but with a pin, and there remains - Some scar of it; lean but upon a rush, - The cicatrice and capable impressure - Thy palm some moment keeps; but now mine eyes, - Which I have darted at thee, hurt thee not, - Nor, I am sure, there is no force in eyes - That can do hurt. - -SILVIUS O dear Phebe, - If ever,--as that ever may be near,-- - You meet in some fresh cheek the power of fancy, - Then shall you know the wounds invisible - That love's keen arrows make. - -PHEBE But till that time - Come not thou near me: and when that time comes, - Afflict me with thy mocks, pity me not; - As till that time I shall not pity thee. - -ROSALIND And why, I pray you? Who might be your mother, - That you insult, exult, and all at once, - Over the wretched? What though you have no beauty,-- - As, by my faith, I see no more in you - Than without candle may go dark to bed-- - Must you be therefore proud and pitiless? - Why, what means this? Why do you look on me? - I see no more in you than in the ordinary - Of nature's sale-work. 'Od's my little life, - I think she means to tangle my eyes too! - No, faith, proud mistress, hope not after it: - 'Tis not your inky brows, your black silk hair, - Your bugle eyeballs, nor your cheek of cream, - That can entame my spirits to your worship. - You foolish shepherd, wherefore do you follow her, - Like foggy south puffing with wind and rain? - You are a thousand times a properer man - Than she a woman: 'tis such fools as you - That makes the world full of ill-favour'd children: - 'Tis not her glass, but you, that flatters her; - And out of you she sees herself more proper - Than any of her lineaments can show her. - But, mistress, know yourself: down on your knees, - And thank heaven, fasting, for a good man's love: - For I must tell you friendly in your ear, - Sell when you can: you are not for all markets: - Cry the man mercy; love him; take his offer: - Foul is most foul, being foul to be a scoffer. - So take her to thee, shepherd: fare you well. - -PHEBE Sweet youth, I pray you, chide a year together: - I had rather hear you chide than this man woo. - -ROSALIND He's fallen in love with your foulness and she'll - fall in love with my anger. If it be so, as fast as - she answers thee with frowning looks, I'll sauce her - with bitter words. Why look you so upon me? - -PHEBE For no ill will I bear you. - -ROSALIND I pray you, do not fall in love with me, - For I am falser than vows made in wine: - Besides, I like you not. If you will know my house, - 'Tis at the tuft of olives here hard by. - Will you go, sister? Shepherd, ply her hard. - Come, sister. Shepherdess, look on him better, - And be not proud: though all the world could see, - None could be so abused in sight as he. - Come, to our flock. - - [Exeunt ROSALIND, CELIA and CORIN] - -PHEBE Dead Shepherd, now I find thy saw of might, - 'Who ever loved that loved not at first sight?' - -SILVIUS Sweet Phebe,-- - -PHEBE Ha, what say'st thou, Silvius? - -SILVIUS Sweet Phebe, pity me. - -PHEBE Why, I am sorry for thee, gentle Silvius. - -SILVIUS Wherever sorrow is, relief would be: - If you do sorrow at my grief in love, - By giving love your sorrow and my grief - Were both extermined. - -PHEBE Thou hast my love: is not that neighbourly? - -SILVIUS I would have you. - -PHEBE Why, that were covetousness. - Silvius, the time was that I hated thee, - And yet it is not that I bear thee love; - But since that thou canst talk of love so well, - Thy company, which erst was irksome to me, - I will endure, and I'll employ thee too: - But do not look for further recompense - Than thine own gladness that thou art employ'd. - -SILVIUS So holy and so perfect is my love, - And I in such a poverty of grace, - That I shall think it a most plenteous crop - To glean the broken ears after the man - That the main harvest reaps: loose now and then - A scatter'd smile, and that I'll live upon. - -PHEBE Know'st now the youth that spoke to me erewhile? - -SILVIUS Not very well, but I have met him oft; - And he hath bought the cottage and the bounds - That the old carlot once was master of. - -PHEBE Think not I love him, though I ask for him: - 'Tis but a peevish boy; yet he talks well; - But what care I for words? yet words do well - When he that speaks them pleases those that hear. - It is a pretty youth: not very pretty: - But, sure, he's proud, and yet his pride becomes him: - He'll make a proper man: the best thing in him - Is his complexion; and faster than his tongue - Did make offence his eye did heal it up. - He is not very tall; yet for his years he's tall: - His leg is but so so; and yet 'tis well: - There was a pretty redness in his lip, - A little riper and more lusty red - Than that mix'd in his cheek; 'twas just the difference - Between the constant red and mingled damask. - There be some women, Silvius, had they mark'd him - In parcels as I did, would have gone near - To fall in love with him; but, for my part, - I love him not nor hate him not; and yet - I have more cause to hate him than to love him: - For what had he to do to chide at me? - He said mine eyes were black and my hair black: - And, now I am remember'd, scorn'd at me: - I marvel why I answer'd not again: - But that's all one; omittance is no quittance. - I'll write to him a very taunting letter, - And thou shalt bear it: wilt thou, Silvius? - -SILVIUS Phebe, with all my heart. - -PHEBE I'll write it straight; - The matter's in my head and in my heart: - I will be bitter with him and passing short. - Go with me, Silvius. - - [Exeunt] - - - - - AS YOU LIKE IT - - -ACT IV - - - -SCENE I The forest. - - - [Enter ROSALIND, CELIA, and JAQUES] - -JAQUES I prithee, pretty youth, let me be better acquainted - with thee. - -ROSALIND They say you are a melancholy fellow. - -JAQUES I am so; I do love it better than laughing. - -ROSALIND Those that are in extremity of either are abominable - fellows and betray themselves to every modern - censure worse than drunkards. - -JAQUES Why, 'tis good to be sad and say nothing. - -ROSALIND Why then, 'tis good to be a post. - -JAQUES I have neither the scholar's melancholy, which is - emulation, nor the musician's, which is fantastical, - nor the courtier's, which is proud, nor the - soldier's, which is ambitious, nor the lawyer's, - which is politic, nor the lady's, which is nice, nor - the lover's, which is all these: but it is a - melancholy of mine own, compounded of many simples, - extracted from many objects, and indeed the sundry's - contemplation of my travels, in which my often - rumination wraps me m a most humorous sadness. - -ROSALIND A traveller! By my faith, you have great reason to - be sad: I fear you have sold your own lands to see - other men's; then, to have seen much and to have - nothing, is to have rich eyes and poor hands. - -JAQUES Yes, I have gained my experience. - -ROSALIND And your experience makes you sad: I had rather have - a fool to make me merry than experience to make me - sad; and to travel for it too! - - [Enter ORLANDO] - -ORLANDO Good day and happiness, dear Rosalind! - -JAQUES Nay, then, God be wi' you, an you talk in blank verse. - - [Exit] - -ROSALIND Farewell, Monsieur Traveller: look you lisp and - wear strange suits, disable all the benefits of your - own country, be out of love with your nativity and - almost chide God for making you that countenance you - are, or I will scarce think you have swam in a - gondola. Why, how now, Orlando! where have you been - all this while? You a lover! An you serve me such - another trick, never come in my sight more. - -ORLANDO My fair Rosalind, I come within an hour of my promise. - -ROSALIND Break an hour's promise in love! He that will - divide a minute into a thousand parts and break but - a part of the thousandth part of a minute in the - affairs of love, it may be said of him that Cupid - hath clapped him o' the shoulder, but I'll warrant - him heart-whole. - -ORLANDO Pardon me, dear Rosalind. - -ROSALIND Nay, an you be so tardy, come no more in my sight: I - had as lief be wooed of a snail. - -ORLANDO Of a snail? - -ROSALIND Ay, of a snail; for though he comes slowly, he - carries his house on his head; a better jointure, - I think, than you make a woman: besides he brings - his destiny with him. - -ORLANDO What's that? - -ROSALIND Why, horns, which such as you are fain to be - beholding to your wives for: but he comes armed in - his fortune and prevents the slander of his wife. - -ORLANDO Virtue is no horn-maker; and my Rosalind is virtuous. - -ROSALIND And I am your Rosalind. - -CELIA It pleases him to call you so; but he hath a - Rosalind of a better leer than you. - -ROSALIND Come, woo me, woo me, for now I am in a holiday - humour and like enough to consent. What would you - say to me now, an I were your very very Rosalind? - -ORLANDO I would kiss before I spoke. - -ROSALIND Nay, you were better speak first, and when you were - gravelled for lack of matter, you might take - occasion to kiss. Very good orators, when they are - out, they will spit; and for lovers lacking--God - warn us!--matter, the cleanliest shift is to kiss. - -ORLANDO How if the kiss be denied? - -ROSALIND Then she puts you to entreaty, and there begins new matter. - -ORLANDO Who could be out, being before his beloved mistress? - -ROSALIND Marry, that should you, if I were your mistress, or - I should think my honesty ranker than my wit. - -ORLANDO What, of my suit? - -ROSALIND Not out of your apparel, and yet out of your suit. - Am not I your Rosalind? - -ORLANDO I take some joy to say you are, because I would be - talking of her. - -ROSALIND Well in her person I say I will not have you. - -ORLANDO Then in mine own person I die. - -ROSALIND No, faith, die by attorney. The poor world is - almost six thousand years old, and in all this time - there was not any man died in his own person, - videlicit, in a love-cause. Troilus had his brains - dashed out with a Grecian club; yet he did what he - could to die before, and he is one of the patterns - of love. Leander, he would have lived many a fair - year, though Hero had turned nun, if it had not been - for a hot midsummer night; for, good youth, he went - but forth to wash him in the Hellespont and being - taken with the cramp was drowned and the foolish - coroners of that age found it was 'Hero of Sestos.' - But these are all lies: men have died from time to - time and worms have eaten them, but not for love. - -ORLANDO I would not have my right Rosalind of this mind, - for, I protest, her frown might kill me. - -ROSALIND By this hand, it will not kill a fly. But come, now - I will be your Rosalind in a more coming-on - disposition, and ask me what you will. I will grant - it. - -ORLANDO Then love me, Rosalind. - -ROSALIND Yes, faith, will I, Fridays and Saturdays and all. - -ORLANDO And wilt thou have me? - -ROSALIND Ay, and twenty such. - -ORLANDO What sayest thou? - -ROSALIND Are you not good? - -ORLANDO I hope so. - -ROSALIND Why then, can one desire too much of a good thing? - Come, sister, you shall be the priest and marry us. - Give me your hand, Orlando. What do you say, sister? - -ORLANDO Pray thee, marry us. - -CELIA I cannot say the words. - -ROSALIND You must begin, 'Will you, Orlando--' - -CELIA Go to. Will you, Orlando, have to wife this Rosalind? - -ORLANDO I will. - -ROSALIND Ay, but when? - -ORLANDO Why now; as fast as she can marry us. - -ROSALIND Then you must say 'I take thee, Rosalind, for wife.' - -ORLANDO I take thee, Rosalind, for wife. - -ROSALIND I might ask you for your commission; but I do take - thee, Orlando, for my husband: there's a girl goes - before the priest; and certainly a woman's thought - runs before her actions. - -ORLANDO So do all thoughts; they are winged. - -ROSALIND Now tell me how long you would have her after you - have possessed her. - -ORLANDO For ever and a day. - -ROSALIND Say 'a day,' without the 'ever.' No, no, Orlando; - men are April when they woo, December when they wed: - maids are May when they are maids, but the sky - changes when they are wives. I will be more jealous - of thee than a Barbary cock-pigeon over his hen, - more clamorous than a parrot against rain, more - new-fangled than an ape, more giddy in my desires - than a monkey: I will weep for nothing, like Diana - in the fountain, and I will do that when you are - disposed to be merry; I will laugh like a hyen, and - that when thou art inclined to sleep. - -ORLANDO But will my Rosalind do so? - -ROSALIND By my life, she will do as I do. - -ORLANDO O, but she is wise. - -ROSALIND Or else she could not have the wit to do this: the - wiser, the waywarder: make the doors upon a woman's - wit and it will out at the casement; shut that and - 'twill out at the key-hole; stop that, 'twill fly - with the smoke out at the chimney. - -ORLANDO A man that had a wife with such a wit, he might say - 'Wit, whither wilt?' - -ROSALIND Nay, you might keep that cheque for it till you met - your wife's wit going to your neighbour's bed. - -ORLANDO And what wit could wit have to excuse that? - -ROSALIND Marry, to say she came to seek you there. You shall - never take her without her answer, unless you take - her without her tongue. O, that woman that cannot - make her fault her husband's occasion, let her - never nurse her child herself, for she will breed - it like a fool! - -ORLANDO For these two hours, Rosalind, I will leave thee. - -ROSALIND Alas! dear love, I cannot lack thee two hours. - -ORLANDO I must attend the duke at dinner: by two o'clock I - will be with thee again. - -ROSALIND Ay, go your ways, go your ways; I knew what you - would prove: my friends told me as much, and I - thought no less: that flattering tongue of yours - won me: 'tis but one cast away, and so, come, - death! Two o'clock is your hour? - -ORLANDO Ay, sweet Rosalind. - -ROSALIND By my troth, and in good earnest, and so God mend - me, and by all pretty oaths that are not dangerous, - if you break one jot of your promise or come one - minute behind your hour, I will think you the most - pathetical break-promise and the most hollow lover - and the most unworthy of her you call Rosalind that - may be chosen out of the gross band of the - unfaithful: therefore beware my censure and keep - your promise. - -ORLANDO With no less religion than if thou wert indeed my - Rosalind: so adieu. - -ROSALIND Well, Time is the old justice that examines all such - offenders, and let Time try: adieu. - - [Exit ORLANDO] - -CELIA You have simply misused our sex in your love-prate: - we must have your doublet and hose plucked over your - head, and show the world what the bird hath done to - her own nest. - -ROSALIND O coz, coz, coz, my pretty little coz, that thou - didst know how many fathom deep I am in love! But - it cannot be sounded: my affection hath an unknown - bottom, like the bay of Portugal. - -CELIA Or rather, bottomless, that as fast as you pour - affection in, it runs out. - -ROSALIND No, that same wicked bastard of Venus that was begot - of thought, conceived of spleen and born of madness, - that blind rascally boy that abuses every one's eyes - because his own are out, let him be judge how deep I - am in love. I'll tell thee, Aliena, I cannot be out - of the sight of Orlando: I'll go find a shadow and - sigh till he come. - -CELIA And I'll sleep. - - [Exeunt] - - - - - AS YOU LIKE IT - - -ACT IV - - - -SCENE II The forest. - - - [Enter JAQUES, Lords, and Foresters] - -JAQUES Which is he that killed the deer? - -A Lord Sir, it was I. - -JAQUES Let's present him to the duke, like a Roman - conqueror; and it would do well to set the deer's - horns upon his head, for a branch of victory. Have - you no song, forester, for this purpose? - -Forester Yes, sir. - -JAQUES Sing it: 'tis no matter how it be in tune, so it - make noise enough. - - SONG. -Forester What shall he have that kill'd the deer? - His leather skin and horns to wear. - Then sing him home; - - [The rest shall bear this burden] - - Take thou no scorn to wear the horn; - It was a crest ere thou wast born: - Thy father's father wore it, - And thy father bore it: - The horn, the horn, the lusty horn - Is not a thing to laugh to scorn. - - [Exeunt] - - - - - AS YOU LIKE IT - - -ACT IV - - - -SCENE III The forest. - - - [Enter ROSALIND and CELIA] - -ROSALIND How say you now? Is it not past two o'clock? and - here much Orlando! - -CELIA I warrant you, with pure love and troubled brain, he - hath ta'en his bow and arrows and is gone forth to - sleep. Look, who comes here. - - [Enter SILVIUS] - -SILVIUS My errand is to you, fair youth; - My gentle Phebe bid me give you this: - I know not the contents; but, as I guess - By the stern brow and waspish action - Which she did use as she was writing of it, - It bears an angry tenor: pardon me: - I am but as a guiltless messenger. - -ROSALIND Patience herself would startle at this letter - And play the swaggerer; bear this, bear all: - She says I am not fair, that I lack manners; - She calls me proud, and that she could not love me, - Were man as rare as phoenix. 'Od's my will! - Her love is not the hare that I do hunt: - Why writes she so to me? Well, shepherd, well, - This is a letter of your own device. - -SILVIUS No, I protest, I know not the contents: - Phebe did write it. - -ROSALIND Come, come, you are a fool - And turn'd into the extremity of love. - I saw her hand: she has a leathern hand. - A freestone-colour'd hand; I verily did think - That her old gloves were on, but 'twas her hands: - She has a huswife's hand; but that's no matter: - I say she never did invent this letter; - This is a man's invention and his hand. - -SILVIUS Sure, it is hers. - -ROSALIND Why, 'tis a boisterous and a cruel style. - A style for-challengers; why, she defies me, - Like Turk to Christian: women's gentle brain - Could not drop forth such giant-rude invention - Such Ethiope words, blacker in their effect - Than in their countenance. Will you hear the letter? - -SILVIUS So please you, for I never heard it yet; - Yet heard too much of Phebe's cruelty. - -ROSALIND She Phebes me: mark how the tyrant writes. - - [Reads] - - Art thou god to shepherd turn'd, - That a maiden's heart hath burn'd? - Can a woman rail thus? - -SILVIUS Call you this railing? - -ROSALIND [Reads] - - Why, thy godhead laid apart, - Warr'st thou with a woman's heart? - Did you ever hear such railing? - Whiles the eye of man did woo me, - That could do no vengeance to me. - Meaning me a beast. - If the scorn of your bright eyne - Have power to raise such love in mine, - Alack, in me what strange effect - Would they work in mild aspect! - Whiles you chid me, I did love; - How then might your prayers move! - He that brings this love to thee - Little knows this love in me: - And by him seal up thy mind; - Whether that thy youth and kind - Will the faithful offer take - Of me and all that I can make; - Or else by him my love deny, - And then I'll study how to die. - -SILVIUS Call you this chiding? - -CELIA Alas, poor shepherd! - -ROSALIND Do you pity him? no, he deserves no pity. Wilt - thou love such a woman? What, to make thee an - instrument and play false strains upon thee! not to - be endured! Well, go your way to her, for I see - love hath made thee a tame snake, and say this to - her: that if she love me, I charge her to love - thee; if she will not, I will never have her unless - thou entreat for her. If you be a true lover, - hence, and not a word; for here comes more company. - - [Exit SILVIUS] - - [Enter OLIVER] - -OLIVER Good morrow, fair ones: pray you, if you know, - Where in the purlieus of this forest stands - A sheep-cote fenced about with olive trees? - -CELIA West of this place, down in the neighbour bottom: - The rank of osiers by the murmuring stream - Left on your right hand brings you to the place. - But at this hour the house doth keep itself; - There's none within. - -OLIVER If that an eye may profit by a tongue, - Then should I know you by description; - Such garments and such years: 'The boy is fair, - Of female favour, and bestows himself - Like a ripe sister: the woman low - And browner than her brother.' Are not you - The owner of the house I did inquire for? - -CELIA It is no boast, being ask'd, to say we are. - -OLIVER Orlando doth commend him to you both, - And to that youth he calls his Rosalind - He sends this bloody napkin. Are you he? - -ROSALIND I am: what must we understand by this? - -OLIVER Some of my shame; if you will know of me - What man I am, and how, and why, and where - This handkercher was stain'd. - -CELIA I pray you, tell it. - -OLIVER When last the young Orlando parted from you - He left a promise to return again - Within an hour, and pacing through the forest, - Chewing the food of sweet and bitter fancy, - Lo, what befell! he threw his eye aside, - And mark what object did present itself: - Under an oak, whose boughs were moss'd with age - And high top bald with dry antiquity, - A wretched ragged man, o'ergrown with hair, - Lay sleeping on his back: about his neck - A green and gilded snake had wreathed itself, - Who with her head nimble in threats approach'd - The opening of his mouth; but suddenly, - Seeing Orlando, it unlink'd itself, - And with indented glides did slip away - Into a bush: under which bush's shade - A lioness, with udders all drawn dry, - Lay couching, head on ground, with catlike watch, - When that the sleeping man should stir; for 'tis - The royal disposition of that beast - To prey on nothing that doth seem as dead: - This seen, Orlando did approach the man - And found it was his brother, his elder brother. - -CELIA O, I have heard him speak of that same brother; - And he did render him the most unnatural - That lived amongst men. - -OLIVER And well he might so do, - For well I know he was unnatural. - -ROSALIND But, to Orlando: did he leave him there, - Food to the suck'd and hungry lioness? - -OLIVER Twice did he turn his back and purposed so; - But kindness, nobler ever than revenge, - And nature, stronger than his just occasion, - Made him give battle to the lioness, - Who quickly fell before him: in which hurtling - From miserable slumber I awaked. - -CELIA Are you his brother? - -ROSALIND Wast you he rescued? - -CELIA Was't you that did so oft contrive to kill him? - -OLIVER 'Twas I; but 'tis not I I do not shame - To tell you what I was, since my conversion - So sweetly tastes, being the thing I am. - -ROSALIND But, for the bloody napkin? - -OLIVER By and by. - When from the first to last betwixt us two - Tears our recountments had most kindly bathed, - As how I came into that desert place:-- - In brief, he led me to the gentle duke, - Who gave me fresh array and entertainment, - Committing me unto my brother's love; - Who led me instantly unto his cave, - There stripp'd himself, and here upon his arm - The lioness had torn some flesh away, - Which all this while had bled; and now he fainted - And cried, in fainting, upon Rosalind. - Brief, I recover'd him, bound up his wound; - And, after some small space, being strong at heart, - He sent me hither, stranger as I am, - To tell this story, that you might excuse - His broken promise, and to give this napkin - Dyed in his blood unto the shepherd youth - That he in sport doth call his Rosalind. - - [ROSALIND swoons] - -CELIA Why, how now, Ganymede! sweet Ganymede! - -OLIVER Many will swoon when they do look on blood. - -CELIA There is more in it. Cousin Ganymede! - -OLIVER Look, he recovers. - -ROSALIND I would I were at home. - -CELIA We'll lead you thither. - I pray you, will you take him by the arm? - -OLIVER Be of good cheer, youth: you a man! you lack a - man's heart. - -ROSALIND I do so, I confess it. Ah, sirrah, a body would - think this was well counterfeited! I pray you, tell - your brother how well I counterfeited. Heigh-ho! - -OLIVER This was not counterfeit: there is too great - testimony in your complexion that it was a passion - of earnest. - -ROSALIND Counterfeit, I assure you. - -OLIVER Well then, take a good heart and counterfeit to be a man. - -ROSALIND So I do: but, i' faith, I should have been a woman by right. - -CELIA Come, you look paler and paler: pray you, draw - homewards. Good sir, go with us. - -OLIVER That will I, for I must bear answer back - How you excuse my brother, Rosalind. - -ROSALIND I shall devise something: but, I pray you, commend - my counterfeiting to him. Will you go? - - [Exeunt] - - - - - AS YOU LIKE IT - - -ACT V - - - -SCENE I The forest. - - - [Enter TOUCHSTONE and AUDREY] - -TOUCHSTONE We shall find a time, Audrey; patience, gentle Audrey. - -AUDREY Faith, the priest was good enough, for all the old - gentleman's saying. - -TOUCHSTONE A most wicked Sir Oliver, Audrey, a most vile - Martext. But, Audrey, there is a youth here in the - forest lays claim to you. - -AUDREY Ay, I know who 'tis; he hath no interest in me in - the world: here comes the man you mean. - -TOUCHSTONE It is meat and drink to me to see a clown: by my - troth, we that have good wits have much to answer - for; we shall be flouting; we cannot hold. - - [Enter WILLIAM] - -WILLIAM Good even, Audrey. - -AUDREY God ye good even, William. - -WILLIAM And good even to you, sir. - -TOUCHSTONE Good even, gentle friend. Cover thy head, cover thy - head; nay, prithee, be covered. How old are you, friend? - -WILLIAM Five and twenty, sir. - -TOUCHSTONE A ripe age. Is thy name William? - -WILLIAM William, sir. - -TOUCHSTONE A fair name. Wast born i' the forest here? - -WILLIAM Ay, sir, I thank God. - -TOUCHSTONE 'Thank God;' a good answer. Art rich? - -WILLIAM Faith, sir, so so. - -TOUCHSTONE 'So so' is good, very good, very excellent good; and - yet it is not; it is but so so. Art thou wise? - -WILLIAM Ay, sir, I have a pretty wit. - -TOUCHSTONE Why, thou sayest well. I do now remember a saying, - 'The fool doth think he is wise, but the wise man - knows himself to be a fool.' The heathen - philosopher, when he had a desire to eat a grape, - would open his lips when he put it into his mouth; - meaning thereby that grapes were made to eat and - lips to open. You do love this maid? - -WILLIAM I do, sir. - -TOUCHSTONE Give me your hand. Art thou learned? - -WILLIAM No, sir. - -TOUCHSTONE Then learn this of me: to have, is to have; for it - is a figure in rhetoric that drink, being poured out - of a cup into a glass, by filling the one doth empty - the other; for all your writers do consent that ipse - is he: now, you are not ipse, for I am he. - -WILLIAM Which he, sir? - -TOUCHSTONE He, sir, that must marry this woman. Therefore, you - clown, abandon,--which is in the vulgar leave,--the - society,--which in the boorish is company,--of this - female,--which in the common is woman; which - together is, abandon the society of this female, or, - clown, thou perishest; or, to thy better - understanding, diest; or, to wit I kill thee, make - thee away, translate thy life into death, thy - liberty into bondage: I will deal in poison with - thee, or in bastinado, or in steel; I will bandy - with thee in faction; I will o'errun thee with - policy; I will kill thee a hundred and fifty ways: - therefore tremble and depart. - -AUDREY Do, good William. - -WILLIAM God rest you merry, sir. - - [Exit] - - [Enter CORIN] - -CORIN Our master and mistress seeks you; come, away, away! - -TOUCHSTONE Trip, Audrey! trip, Audrey! I attend, I attend. - - [Exeunt] - - - - - AS YOU LIKE IT - - -ACT V - - - -SCENE II The forest. - - - [Enter ORLANDO and OLIVER] - -ORLANDO Is't possible that on so little acquaintance you - should like her? that but seeing you should love - her? and loving woo? and, wooing, she should - grant? and will you persever to enjoy her? - -OLIVER Neither call the giddiness of it in question, the - poverty of her, the small acquaintance, my sudden - wooing, nor her sudden consenting; but say with me, - I love Aliena; say with her that she loves me; - consent with both that we may enjoy each other: it - shall be to your good; for my father's house and all - the revenue that was old Sir Rowland's will I - estate upon you, and here live and die a shepherd. - -ORLANDO You have my consent. Let your wedding be to-morrow: - thither will I invite the duke and all's contented - followers. Go you and prepare Aliena; for look - you, here comes my Rosalind. - - [Enter ROSALIND] - -ROSALIND God save you, brother. - -OLIVER And you, fair sister. - - [Exit] - -ROSALIND O, my dear Orlando, how it grieves me to see thee - wear thy heart in a scarf! - -ORLANDO It is my arm. - -ROSALIND I thought thy heart had been wounded with the claws - of a lion. - -ORLANDO Wounded it is, but with the eyes of a lady. - -ROSALIND Did your brother tell you how I counterfeited to - swoon when he showed me your handkerchief? - -ORLANDO Ay, and greater wonders than that. - -ROSALIND O, I know where you are: nay, 'tis true: there was - never any thing so sudden but the fight of two rams - and Caesar's thrasonical brag of 'I came, saw, and - overcame:' for your brother and my sister no sooner - met but they looked, no sooner looked but they - loved, no sooner loved but they sighed, no sooner - sighed but they asked one another the reason, no - sooner knew the reason but they sought the remedy; - and in these degrees have they made a pair of stairs - to marriage which they will climb incontinent, or - else be incontinent before marriage: they are in - the very wrath of love and they will together; clubs - cannot part them. - -ORLANDO They shall be married to-morrow, and I will bid the - duke to the nuptial. But, O, how bitter a thing it - is to look into happiness through another man's - eyes! By so much the more shall I to-morrow be at - the height of heart-heaviness, by how much I shall - think my brother happy in having what he wishes for. - -ROSALIND Why then, to-morrow I cannot serve your turn for Rosalind? - -ORLANDO I can live no longer by thinking. - -ROSALIND I will weary you then no longer with idle talking. - Know of me then, for now I speak to some purpose, - that I know you are a gentleman of good conceit: I - speak not this that you should bear a good opinion - of my knowledge, insomuch I say I know you are; - neither do I labour for a greater esteem than may in - some little measure draw a belief from you, to do - yourself good and not to grace me. Believe then, if - you please, that I can do strange things: I have, - since I was three year old, conversed with a - magician, most profound in his art and yet not - damnable. If you do love Rosalind so near the heart - as your gesture cries it out, when your brother - marries Aliena, shall you marry her: I know into - what straits of fortune she is driven; and it is - not impossible to me, if it appear not inconvenient - to you, to set her before your eyes tomorrow human - as she is and without any danger. - -ORLANDO Speakest thou in sober meanings? - -ROSALIND By my life, I do; which I tender dearly, though I - say I am a magician. Therefore, put you in your - best array: bid your friends; for if you will be - married to-morrow, you shall, and to Rosalind, if you will. - - [Enter SILVIUS and PHEBE] - - Look, here comes a lover of mine and a lover of hers. - -PHEBE Youth, you have done me much ungentleness, - To show the letter that I writ to you. - -ROSALIND I care not if I have: it is my study - To seem despiteful and ungentle to you: - You are there followed by a faithful shepherd; - Look upon him, love him; he worships you. - -PHEBE Good shepherd, tell this youth what 'tis to love. - -SILVIUS It is to be all made of sighs and tears; - And so am I for Phebe. - -PHEBE And I for Ganymede. - -ORLANDO And I for Rosalind. - -ROSALIND And I for no woman. - -SILVIUS It is to be all made of faith and service; - And so am I for Phebe. - -PHEBE And I for Ganymede. - -ORLANDO And I for Rosalind. - -ROSALIND And I for no woman. - -SILVIUS It is to be all made of fantasy, - All made of passion and all made of wishes, - All adoration, duty, and observance, - All humbleness, all patience and impatience, - All purity, all trial, all observance; - And so am I for Phebe. - -PHEBE And so am I for Ganymede. - -ORLANDO And so am I for Rosalind. - -ROSALIND And so am I for no woman. - -PHEBE If this be so, why blame you me to love you? - -SILVIUS If this be so, why blame you me to love you? - -ORLANDO If this be so, why blame you me to love you? - -ROSALIND Who do you speak to, 'Why blame you me to love you?' - -ORLANDO To her that is not here, nor doth not hear. - -ROSALIND Pray you, no more of this; 'tis like the howling - of Irish wolves against the moon. - - [To SILVIUS] - - I will help you, if I can: - - [To PHEBE] - - I would love you, if I could. To-morrow meet me all together. - - [To PHEBE] - - I will marry you, if ever I marry woman, and I'll be - married to-morrow: - - [To ORLANDO] - - I will satisfy you, if ever I satisfied man, and you - shall be married to-morrow: - - [To SILVIUS] - - I will content you, if what pleases you contents - you, and you shall be married to-morrow. - - [To ORLANDO] - - As you love Rosalind, meet: - - [To SILVIUS] - - as you love Phebe, meet: and as I love no woman, - I'll meet. So fare you well: I have left you commands. - -SILVIUS I'll not fail, if I live. - -PHEBE Nor I. - -ORLANDO Nor I. - - [Exeunt] - - - - - AS YOU LIKE IT - - -ACT V - - - -SCENE III The forest. - - - [Enter TOUCHSTONE and AUDREY] - -TOUCHSTONE To-morrow is the joyful day, Audrey; to-morrow will - we be married. - -AUDREY I do desire it with all my heart; and I hope it is - no dishonest desire to desire to be a woman of the - world. Here comes two of the banished duke's pages. - - [Enter two Pages] - -First Page Well met, honest gentleman. - -TOUCHSTONE By my troth, well met. Come, sit, sit, and a song. - -Second Page We are for you: sit i' the middle. - -First Page Shall we clap into't roundly, without hawking or - spitting or saying we are hoarse, which are the only - prologues to a bad voice? - -Second Page I'faith, i'faith; and both in a tune, like two - gipsies on a horse. - - SONG. - It was a lover and his lass, - With a hey, and a ho, and a hey nonino, - That o'er the green corn-field did pass - In the spring time, the only pretty ring time, - When birds do sing, hey ding a ding, ding: - Sweet lovers love the spring. - - Between the acres of the rye, - With a hey, and a ho, and a hey nonino - These pretty country folks would lie, - In spring time, &c. - - This carol they began that hour, - With a hey, and a ho, and a hey nonino, - How that a life was but a flower - In spring time, &c. - - And therefore take the present time, - With a hey, and a ho, and a hey nonino; - For love is crowned with the prime - In spring time, &c. - -TOUCHSTONE Truly, young gentlemen, though there was no great - matter in the ditty, yet the note was very - untuneable. - -First Page You are deceived, sir: we kept time, we lost not our time. - -TOUCHSTONE By my troth, yes; I count it but time lost to hear - such a foolish song. God be wi' you; and God mend - your voices! Come, Audrey. - - [Exeunt] - - - - - AS YOU LIKE IT - - -ACT V - - - -SCENE IV The forest. - - - [Enter DUKE SENIOR, AMIENS, JAQUES, ORLANDO, OLIVER, - and CELIA] - -DUKE SENIOR Dost thou believe, Orlando, that the boy - Can do all this that he hath promised? - -ORLANDO I sometimes do believe, and sometimes do not; - As those that fear they hope, and know they fear. - - [Enter ROSALIND, SILVIUS, and PHEBE] - -ROSALIND Patience once more, whiles our compact is urged: - You say, if I bring in your Rosalind, - You will bestow her on Orlando here? - -DUKE SENIOR That would I, had I kingdoms to give with her. - -ROSALIND And you say, you will have her, when I bring her? - -ORLANDO That would I, were I of all kingdoms king. - -ROSALIND You say, you'll marry me, if I be willing? - -PHEBE That will I, should I die the hour after. - -ROSALIND But if you do refuse to marry me, - You'll give yourself to this most faithful shepherd? - -PHEBE So is the bargain. - -ROSALIND You say, that you'll have Phebe, if she will? - -SILVIUS Though to have her and death were both one thing. - -ROSALIND I have promised to make all this matter even. - Keep you your word, O duke, to give your daughter; - You yours, Orlando, to receive his daughter: - Keep your word, Phebe, that you'll marry me, - Or else refusing me, to wed this shepherd: - Keep your word, Silvius, that you'll marry her. - If she refuse me: and from hence I go, - To make these doubts all even. - - [Exeunt ROSALIND and CELIA] - -DUKE SENIOR I do remember in this shepherd boy - Some lively touches of my daughter's favour. - -ORLANDO My lord, the first time that I ever saw him - Methought he was a brother to your daughter: - But, my good lord, this boy is forest-born, - And hath been tutor'd in the rudiments - Of many desperate studies by his uncle, - Whom he reports to be a great magician, - Obscured in the circle of this forest. - - [Enter TOUCHSTONE and AUDREY] - -JAQUES There is, sure, another flood toward, and these - couples are coming to the ark. Here comes a pair of - very strange beasts, which in all tongues are called fools. - -TOUCHSTONE Salutation and greeting to you all! - -JAQUES Good my lord, bid him welcome: this is the - motley-minded gentleman that I have so often met in - the forest: he hath been a courtier, he swears. - -TOUCHSTONE If any man doubt that, let him put me to my - purgation. I have trod a measure; I have flattered - a lady; I have been politic with my friend, smooth - with mine enemy; I have undone three tailors; I have - had four quarrels, and like to have fought one. - -JAQUES And how was that ta'en up? - -TOUCHSTONE Faith, we met, and found the quarrel was upon the - seventh cause. - -JAQUES How seventh cause? Good my lord, like this fellow. - -DUKE SENIOR I like him very well. - -TOUCHSTONE God 'ild you, sir; I desire you of the like. I - press in here, sir, amongst the rest of the country - copulatives, to swear and to forswear: according as - marriage binds and blood breaks: a poor virgin, - sir, an ill-favoured thing, sir, but mine own; a poor - humour of mine, sir, to take that that no man else - will: rich honesty dwells like a miser, sir, in a - poor house; as your pearl in your foul oyster. - -DUKE SENIOR By my faith, he is very swift and sententious. - -TOUCHSTONE According to the fool's bolt, sir, and such dulcet diseases. - -JAQUES But, for the seventh cause; how did you find the - quarrel on the seventh cause? - -TOUCHSTONE Upon a lie seven times removed:--bear your body more - seeming, Audrey:--as thus, sir. I did dislike the - cut of a certain courtier's beard: he sent me word, - if I said his beard was not cut well, he was in the - mind it was: this is called the Retort Courteous. - If I sent him word again 'it was not well cut,' he - would send me word, he cut it to please himself: - this is called the Quip Modest. If again 'it was - not well cut,' he disabled my judgment: this is - called the Reply Churlish. If again 'it was not - well cut,' he would answer, I spake not true: this - is called the Reproof Valiant. If again 'it was not - well cut,' he would say I lied: this is called the - Counter-cheque Quarrelsome: and so to the Lie - Circumstantial and the Lie Direct. - -JAQUES And how oft did you say his beard was not well cut? - -TOUCHSTONE I durst go no further than the Lie Circumstantial, - nor he durst not give me the Lie Direct; and so we - measured swords and parted. - -JAQUES Can you nominate in order now the degrees of the lie? - -TOUCHSTONE O sir, we quarrel in print, by the book; as you have - books for good manners: I will name you the degrees. - The first, the Retort Courteous; the second, the - Quip Modest; the third, the Reply Churlish; the - fourth, the Reproof Valiant; the fifth, the - Countercheque Quarrelsome; the sixth, the Lie with - Circumstance; the seventh, the Lie Direct. All - these you may avoid but the Lie Direct; and you may - avoid that too, with an If. I knew when seven - justices could not take up a quarrel, but when the - parties were met themselves, one of them thought but - of an If, as, 'If you said so, then I said so;' and - they shook hands and swore brothers. Your If is the - only peacemaker; much virtue in If. - -JAQUES Is not this a rare fellow, my lord? he's as good at - any thing and yet a fool. - -DUKE SENIOR He uses his folly like a stalking-horse and under - the presentation of that he shoots his wit. - - [Enter HYMEN, ROSALIND, and CELIA] - - [Still Music] - -HYMEN Then is there mirth in heaven, - When earthly things made even - Atone together. - Good duke, receive thy daughter - Hymen from heaven brought her, - Yea, brought her hither, - That thou mightst join her hand with his - Whose heart within his bosom is. - -ROSALIND [To DUKE SENIOR] To you I give myself, for I am yours. - - [To ORLANDO] - - To you I give myself, for I am yours. - -DUKE SENIOR If there be truth in sight, you are my daughter. - -ORLANDO If there be truth in sight, you are my Rosalind. - -PHEBE If sight and shape be true, - Why then, my love adieu! - -ROSALIND I'll have no father, if you be not he: - I'll have no husband, if you be not he: - Nor ne'er wed woman, if you be not she. - -HYMEN Peace, ho! I bar confusion: - 'Tis I must make conclusion - Of these most strange events: - Here's eight that must take hands - To join in Hymen's bands, - If truth holds true contents. - You and you no cross shall part: - You and you are heart in heart - You to his love must accord, - Or have a woman to your lord: - You and you are sure together, - As the winter to foul weather. - Whiles a wedlock-hymn we sing, - Feed yourselves with questioning; - That reason wonder may diminish, - How thus we met, and these things finish. - - SONG. - Wedding is great Juno's crown: - O blessed bond of board and bed! - 'Tis Hymen peoples every town; - High wedlock then be honoured: - Honour, high honour and renown, - To Hymen, god of every town! - -DUKE SENIOR O my dear niece, welcome thou art to me! - Even daughter, welcome, in no less degree. - -PHEBE I will not eat my word, now thou art mine; - Thy faith my fancy to thee doth combine. - - [Enter JAQUES DE BOYS] - -JAQUES DE BOYS Let me have audience for a word or two: - I am the second son of old Sir Rowland, - That bring these tidings to this fair assembly. - Duke Frederick, hearing how that every day - Men of great worth resorted to this forest, - Address'd a mighty power; which were on foot, - In his own conduct, purposely to take - His brother here and put him to the sword: - And to the skirts of this wild wood he came; - Where meeting with an old religious man, - After some question with him, was converted - Both from his enterprise and from the world, - His crown bequeathing to his banish'd brother, - And all their lands restored to them again - That were with him exiled. This to be true, - I do engage my life. - -DUKE SENIOR Welcome, young man; - Thou offer'st fairly to thy brothers' wedding: - To one his lands withheld, and to the other - A land itself at large, a potent dukedom. - First, in this forest, let us do those ends - That here were well begun and well begot: - And after, every of this happy number - That have endured shrewd days and nights with us - Shall share the good of our returned fortune, - According to the measure of their states. - Meantime, forget this new-fall'n dignity - And fall into our rustic revelry. - Play, music! And you, brides and bridegrooms all, - With measure heap'd in joy, to the measures fall. - -JAQUES Sir, by your patience. If I heard you rightly, - The duke hath put on a religious life - And thrown into neglect the pompous court? - -JAQUES DE BOYS He hath. - -JAQUES To him will I : out of these convertites - There is much matter to be heard and learn'd. - - [To DUKE SENIOR] - - You to your former honour I bequeath; - Your patience and your virtue well deserves it: - - [To ORLANDO] - - You to a love that your true faith doth merit: - - [To OLIVER] - - You to your land and love and great allies: - - [To SILVIUS] - - You to a long and well-deserved bed: - - [To TOUCHSTONE] - - And you to wrangling; for thy loving voyage - Is but for two months victuall'd. So, to your pleasures: - I am for other than for dancing measures. - -DUKE SENIOR Stay, Jaques, stay. - -JAQUES To see no pastime I what you would have - I'll stay to know at your abandon'd cave. - - [Exit] - -DUKE SENIOR Proceed, proceed: we will begin these rites, - As we do trust they'll end, in true delights. - - [A dance] - - - - - AS YOU LIKE IT - - EPILOGUE - - -ROSALIND It is not the fashion to see the lady the epilogue; - but it is no more unhandsome than to see the lord - the prologue. If it be true that good wine needs - no bush, 'tis true that a good play needs no - epilogue; yet to good wine they do use good bushes, - and good plays prove the better by the help of good - epilogues. What a case am I in then, that am - neither a good epilogue nor cannot insinuate with - you in the behalf of a good play! I am not - furnished like a beggar, therefore to beg will not - become me: my way is to conjure you; and I'll begin - with the women. I charge you, O women, for the love - you bear to men, to like as much of this play as - please you: and I charge you, O men, for the love - you bear to women--as I perceive by your simpering, - none of you hates them--that between you and the - women the play may please. If I were a woman I - would kiss as many of you as had beards that pleased - me, complexions that liked me and breaths that I - defied not: and, I am sure, as many as have good - beards or good faces or sweet breaths will, for my - kind offer, when I make curtsy, bid me farewell. - - [Exeunt] diff --git a/src/snappy/snappy/testdata/baddata1.snappy b/src/snappy/snappy/testdata/baddata1.snappy deleted file mode 100644 index 99d970fb4b29ebdb3d00a1a26d8ae1fc07da013a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 27512 zcmb5Wd3;mV_BXtCa(0`v$ss3ALQkN923ksKlO}CLTcJpyg%*0C0Rj}-kfceQ(hOuc z(1=m0qN1XpRK+VQ3MyU(5fMzBs>1v2qXDW?7*yAfhPtx=4l+7$7R&Qz8QL;_ zM@h^dkMxNaUnCr$H*-F zF+f?M6UgqCS!B=-JG!7e4+FK`(gk3&KZDE2GL95AL1|z#IA@Uc6=1m(puBe(kcV2D z$>vJf6@YRc19hb(0FK!NDlKKCWj4XZwQe?XWePZW;;6t91G9k5`;< zHMEl3|7a)#r$Df4mdoJw-e#OxIdAMTI{6p&dFvhl%7Wd znL?9CHQBI`IFH0KV*v5kWmyn!_%{?tV{q|zjpqw0>HNo8T<^}dKYMfWcMX}|%=xo7 z5N~QFX{l{|fNfE#lJS`JT&vF4<4Gi9#;cW_p6QG0^$cg_^txz&SHx%6KAyuUS{jCf zVXG3f1;bT|o=BLpHsyn|0yO#x)|9L0_J@m}0|Pavu!NPfF!pj~3uJ5GQZg}X18x%Q z)M>Nk(aB(PO@@)yna%U&&v7n}jfMQ#&C?o%d5v_e=eQ6Ah0wTA3_||gNGuTychg2F zXul3L&c>3S4p)47q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ZBWp;Texj2^85Q+&?P*ud0Uh!yn!2iyZ~pFpppZ&;xDlT-Uny=q?zR)i35JrNJ#?{%m;dHyUTGx1G6GiGgf)p#@b!8DlF3GXt6{ zyg^GALR(l)%9(PtiLx8c3JwPjW7$On<2rPUCQ>)Cj@nYtv%=}>a8)-LV7O)t#7xKd zq28HIt!#n416Qi^(+C;+tNuRRdTTM;a$kcK4gA{!ps9=v^Nj3x~Fne7(bPX?B4#843jj zv)(Xm0E+;+S=hLb3X>cr524nSMqPOCcN)Av!xVCdU!jUfE(?Gnid7dvI*IgCoVt*X zCZD>ZX3=zJznWFW2U1jp`tyPT_|f8oo7dabHdSIMM%mQsf#x2M7cEkOL@0~;AQ@&f z>hUG{1rpt&mg?(3g}P2On-&4;yN?@RNefzrW1r3kK?Z~pMzEXmFkJ3J)jyCp4X-vc zN6tQAveT>9Y}#_RrpQ>5n!8_>FX7(`+9Fol?iv^hFoFi_ zMT&B&1#SqZuOu!#Pl8WfAA2q*U%gL@Y2!{(2KYD$XFt;PNBZOJR%6RG zh-18^T{^}}P`Np+ajY~xD*VH{hkNuns<^=N`4*?Q-Q^OpJGnV3%xiPilO_N2`T>jH6aIhz diff --git a/src/snappy/snappy/testdata/baddata2.snappy b/src/snappy/snappy/testdata/baddata2.snappy deleted file mode 100644 index 8f5cb13ee23b2a6067d6396093f69a8d3af0e030..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 27483 zcmb5Wd3;mV_BXtCa(0`v$!SiSgeK6G23ksKlO}CLTcJpyg%*0C0Rj}-kfceQ(hOuc z(1=m0qM~vIr7B)gQBY9^5fP9XaTWpPDmYzm#Ce|Y^;swAy}$Q)p7-;4-#>cxIwyM` z*ZQvS?$e)S_GPOwTR4j^?zK#vF>5wIv9-}0?(0%yt7wan4q4=lhC^m+bubX>>$kY0 zk)`gqx5pfDN9jn&r6a4l!{P2epC#mrFAYZ*Q#~lDJ}(gRhs(PH@-oPg=ME2h<9+6s zTkz2mP*Ls3zA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4FBrEs`JSa}Sk)04{H;?{YxAfO)N3^?*zFvx%Y;&RqWqc8xUjY6E$YQuX7tV%S zyqFZz#VR9Z(~ULR?Z`B=iSYXBe^K~$t{z)Wtv2}QJDly#@){k)1V%?pl#RIHoZhFa zoxqrp1Iw%k2be5XMG=s0>*KM7!RWmW*KtL!sxX9np4bDyIGeVYG1{INAKDV^p31&q zU<@`L4waqJFry_|+!XFrn++%6p>p3+rr7p{SP#^XCEOo#l4c~X8UXrxkSWVaDxwK) z0x?o!DTNx+YGtk&YGuZm^9h}+hOp;gjKn~Vgom&ZUZrAUEmO`QZGs~SXMo10I!J7R z8x+aLPrZRCSLs|r_(ge~(cMHeJqYEGRqjI7_>dD`LEdO6(H9=z?#&4T^TJf#%=|iM zMs=2~ajux6hF$1UgayVidV>N`bi8WP{Vh5AoLFN(=?(Z8gfbQ0ODWjW0wjPcJX5zc zhrOsL14l}bvd6~$pFtze5(vBV17$dvY{>h_qlk6|he&pgUAKLf!I20C1H36mSKmhz zJO-J!mHabb;pqZ)Ge?F#6o9jx*!AlJ~C68gs1f{wZG7$;I&+~ z23vzK$mERW(E=bT_8=2m3RpjEr$K||=qzV{q0AOBo_S3kqiJ*Y4ftqYjr}4?IaEA5 zfW$)ai!YPFb2mo-Ke5N#135evAH4dQC~vwFln%ap{HZ^w!=Z4D8PebS0g@YMZWB|* z@k$q~(T@}-NQr-V_Mkr}LmA^4F5B#Iw>h1BdIvj0iDhjnd#3RB@9j}K119~q=zSg! zP<}OW)ETa|yhz=zy!OSuClm%!aOC=5A;`6&3b0~gO{ooP$@d#F9-&fQ{;K7 u@^$L6;smvg{)!^ksO3*xP%W1oI&$vlPl^q))3-mplJS)6<0po8DE=S5+vYz2 diff --git a/src/snappy/snappy/testdata/fireworks.jpeg b/src/snappy/snappy/testdata/fireworks.jpeg deleted file mode 100644 index 078cf1755dc0853e97ad30fc7af4d6af0b67047e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 123093 zcmb5V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6Y_X~H&vP-vKKdqMBMi25Rn?j;y$-Xah$Xo%|5Ni{Rlgojd#3-gRlYAcDFj9i+EKYuoG z&k@QvOp4l+%JOHH1uF!D+(((C@oXBYIAi9H{>4AC)}R}_Rzi~NyTpim#yp*^-Udf| zfmRv}MqNN>k^9u!nr=Sv#hTn&Mx^{PG7&Gv?nhDxOnUg;gD1-u2F(8J0*rbv4ju(kX zBFMS&eupy3<&EQ$+nV)1E=@}5<|1^Zu2k6y3QE$V6qN$tgUE)Cio_j+Bvu!I8C}5V5EHNh5naTW z8?(eFc>@tqp>*=JKxDJC##$0*Oe93uM96~!5f|}xhRAMh-XbDH@9zLu3#3FeKr=V? zih_t-JV>?>Ue5?!0Wb4_QzmzaNEhi4SnBk<_Jl!SXb8zJe@GiMW`R0MHncmDDfKiK zDUc4Pg$)5=->f!6(`&>OL(-Rh;s6S>n1!Mqp%93)MtXrw;AqiYmg@-+y0 zh>`^zkIEt)UYE2&Any<|3>&;Gfhj*o3WsQf9GHkri*ks7rstRu0FPHY#8iL(+4)gF AYXATM diff --git a/src/snappy/snappy/testdata/geo.protodata b/src/snappy/snappy/testdata/geo.protodata deleted file mode 100644 index c4e3e0d8aeb1732a6e773f3382e8a3d0f9c668e8..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 118588 zcmeHQ2Ygdi7tc#eX+sON0+vw-Ad3AMNxBlCw9r8dEu)kT)-4@3eIcQp-b*KlvD{~x7k+i#=)3hx9BI`7#n zAZ}>dc$0FhCa!RN|G43~Bl8ow1;mdX9+A^Ou}@)4*3gN4GmMi*_LX`^moUs#hTOGS zDk+hYt#`c`CHg<)BQI&Z@*^*gc%|lmm(LL|52Zp`?$zjkm-i8ThHT=)=sem!=T-j* zx)HWQ(ALd>TV;V!)9=gilc4`1C6c13XeJqNkM;9DTfgbo4O&NaV0X{gZ~Ba1GVK0d zziD2i40ivj-xOa*FaDdqdx5iC#CZ4~U>bOT`q{yom*$u6C}O5d2O?KQ9U%x;VB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FpTcVha%WHwh zkFHo{;nGg^l}OBn^P_)!(tHBRTh{GN8Nrt)KA5=T3hx9zCt|9XDd3)>*E#L3Sjom(W zG8=ZqVzxOPM$}8KPX4XfRy==m6SQ^<(cI~v0JW~ z{q%Ed=WRgO4eIjyW8~f`7xRzI_~nc*irvBh7=LY=YU7}z&(mCK*{uHma0duIZ)bq8 zNv}!`kh?u8!KtSc$(3$e&rN#i^{Ku3r-x1IqZ~nUrR1!m@j!C1K*y^qS87#5ORf~u IhT`V`0gKK@!2kdN diff --git a/src/snappy/snappy/testdata/html b/src/snappy/snappy/testdata/html deleted file mode 100644 index ef768ccde9..0000000000 --- a/src/snappy/snappy/testdata/html +++ /dev/null @@ -1 +0,0 @@ - content: @ 1099872000000000: 'HTTP/1.1 200 OK\r\nX-Google-Crawl-Date: Mon, 08 Nov 2004 17:22:09 GMT\r\nContent-Type: text/html\r\nConnection: close\r\nX-Powered-By: PHP/4.3.8\r\nServer: Apache/1.3.31 (Unix) mod_gzip/1.3.19.1a PHP/4.3.8\r\nDate: Mon, 08 Nov 2004 17:19:07 GMT\r\n\r\n \r\n\r\n\r\n\r\n\r\n\nMicro Achat : Ordinateurs, PDA - Toute l\'informatique avec 01Informatique, L\'Ordinateur Individuel, Micro Hebdo, D\351cision Informatique et 01R\351seaux\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n

Derni\350re mise \340 jour de cette page : lundi 8 novembre 2004  |  16:45
\r\n \r\n\r\n\r\n\r\n\t\r\n\r\n\t\t\r\n\r\n\t\r\n\r\n\t\r\n\t\t\r\n\r\n\r\n\t\t\r\n\r\n\t\t\r\n\t\r\n\t\r\n\t\t\t

\r\n\r\n\r\n\r\n


\r\n\r\n\r\n\r\n
\n\t\t\t\t\t\n\t\t\t\t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\t\t\r\n

\r\n\t\t\t

\r\n\t\t\t

\r\n\t\t\t
\r\n\t\t\t
\r\n\r\n\r\n \r\n \r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t

CD et DVD bient\364t insensibles aux rayures
OpenOffice gagne son service
La messagerie en cinq minutes selon Ipswitch
> toutes les news


\r\n\t\t
\r\n \r\n\r\n\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t

Recevez chaque jour l\'actualit\351 des produits et des promos
\r\n\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t


\r\n\t\t\t
\r\n\t\t\t\t
\r\n\t\t
\r\n\r\n\r\n\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t \r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t

Entreprise
\r\n\t\t\t\tQuand le billet papier s\'envole vers la d\351mat\351rialisation


Trucs et astuces
\r\n\t\t\t\tD\351pannez Windows XP


Conso
\r\n\t\t\t\tVos photos sur papier imprimante ou labo ?


Produits & Tests
\r\n\t\t\t\t5 programmes d\222encodage vid\351o gratuits


\r\n\t\t
\r\n\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n
\r\n
\r\n\t\t\r\n\t\t

\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n
\r\n\r\n\r\n\t\r\n\t\t\r\n\t\r\n
\r\n\t
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n
\r\n\r\n\r\n\t\r\n\r\n\r\n\r\n\t\t\t\r\n\r\n\r\n\r\n\t\t\t\t\r\n
\r\n
\r\nPortable
\r\nUn nouvel ultra portable r\351alis\351 par Nec
\r\n\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t
\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \t\r\nLe Versa S940 a un format r\351duit, mais ses performances sont \340 la hauteur.
\r\n\340 partir de 1663 \200\r\n
\r\n
\r\nPortable
\r\nAsus pr\351sente trois petits nouveaux dans la gamme A3N
\r\n\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t
\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \t\r\nCes trois portables Centrino int\350grent, entre autres, une webcam et un contr\364leur Wi-Fi.
\r\n\340 partir de 1346 \200\r\n
\r\n
\r\n\t\r\n\t\r\n\t\r\n \t\r\n\t\r\n\t\r\n \t\r\n\t\r\n\t
\r\n\t\r\n\r\n
\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
BON PLAN
\r\n
\r\n
\r\nLes derni\350res technologies INTEL dans un nouveau design pour ce shuttle haut de gamme, pour un prix abordable.
\r\n

\r\n
\r\n\340 partir de
\r\n
415 \200
\r\n
\r\n
\r\n
publicit\351
\r\n
\r\n\t\r\n\r\n
\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t

\r\n\t\t\t\t\t\t\t\t\t\t\t\t
\r\n\t\t\t\tDesktops
\r\n\t\t\t\tPortables
\r\n\t\t\t\tMini-PC
\r\n\t\t\t\tPda / Tablets-PC
\r\n\t\t\t\tApple
\r\n\t\t\t\tGPS
\r\n\t\t\t\t
\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t


\r\n\t\t\t\t\t\t
\r\n\t\t\t\t
\r\n\t\t
\r\n
\r\n
\r\n\t\t\r\n\t\t\r\n\r\n\r\n \r\n\r\n\r\n \r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n
\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n

\r\n\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\t\t\r\n\t\r\n\t\r\n\t\t\t\t\r\n\t\r\n\t\r\n\t\t\t\t\r\n\t\r\n\t\r\n\t\t\t\t\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t
\r\n\tPortable Toshiba consacre deux gammes de machines au multim\351dia
\r\n\tEquipement haut de gamme et Windows Media Center sont au menu de ces portables \340 vocation multim\351dia.

\r\n\tOrdinateur Arriv\351e d\'un Power Mac G5 d\'entr\351e de gamme
\r\n\tLa firme \340 la pomme propose une station de travail \351volutive et relativement abordable.

\r\n\tPC Alienware propose deux machines au look \351trange
\r\n\tAurora et Area 51 sont deux gammes d\'ordinateurs enti\350rement configurables.

\r\n\tPortable Trois nouveaux iBook G4 chez Apple
\r\n\tChez Apple, les portables gagnent en vitesse et communiquent sans fil en standard.

\r\n\t\t\t\t> toutes les news\r\n\t\t\t
\r\n
\r\n
\r\n
\r\n\r\n\r\n\r\n\r\n

\r\n\r\n\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \tAsus A3N15-C Pro
\r\n Voici un portable autonome et puissant gr\342ce \340 la technologie Intel Centrino.
\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t
\r\n\t1170 \200
\r\n
\r\n\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \tSoltek EQ3702A Miroir
\r\n Ce mini PC est une solution int\351ressante pour les utilisateurs poss\351dant d\351j\340 un \351cran.
\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t
\r\n\t559 \200
\r\n
\r\n\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \tIBM ThinkPad R51
\r\n Voici un portable complet et pourtant relativement l\351ger.
\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t
\r\n\t1299 \200
\r\n
\r\n\t\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\t\t> toutes les promos\r\n\t\t
\r\n
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n

\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\r\n

\r\n
\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t
\r\n\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t
\r\n\t\t\t\r\n\t\t\t\t\r\n\r\n\r\n\r\n \r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\r\n
\r\n\t\t
\r\n\t\r\n\r\n
\r\n\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \t\r\n
\r\n
\r\nLes graveurs de DVD
\r\nQuel graveur choisir ? Quel type de format ? Quelle vitesse ? Double couche ou simple couche ? Voici tout ce qu\'il faut savoir pour faire le bon choix.
\r\n\t\t\t\t\t\t
\r\n\t\t
\r\n
\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\r\n
\r\n\t\t
\r\n
\r\n\r\n\r\n\t\r\n\t\t\r\n\r\n\r\n \t\r\n
\r\n\t\t
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t
\r\n\t\t\t\t

\r\n\t\t\t\tChoisir une r\351gion
\r\n\r\n
Un d\351partement
\r\n\r\n
\r\n
Un arrondissement
\r\n\r\n
\r\n
\r\n\t\t\t\tRecherche directe
\r\n\t\t\t\trechercher une ville
et/ou une boutique
\r\n\t\t\t\t

\r\n\t\t\t\t \r\n\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t
Recherche avanc\351e
\r\n\t\t\t\t
\r\n\t\t\t\t
\r\n\t\t\t\t
\r\n\t\t
\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t
Bureautique
\r\n\t\t\t\tTraducteur, organiseur...

\r\n\t\t\t\t

Multim\351dia
\r\n\t\t\t\tPhoto, audio, vid\351o...

\r\n\t\t\t\t

Utilitaires
\r\n\t\t\t\tAntivirus, pilotes, gravure...

\r\n\t\t\t\t

Personnaliser son PC
\r\n\t\t\t\tEcrans de veille, th\350mes...

\r\n\t\t\t\t

D\351veloppement
\r\n\t\t\t\tCr\351ation de logiciels, BDD...

\r\n\t\t\t\t

Jeux
\r\n\t\t\t\tAction, simulation...

\r\n\t\t\t\t

Internet
\r\n\t\t\t\tUtilitaires, email, FTP...

\r\n\t\t\t\t

Loisirs
\r\n\t\t\t\tHumour, culture...

\r\n\t\t\t\t
\r\n\t\t
\r\n
\r\n
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n\t\t
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\r\n\t\t\t
\r\n\t\t\t
\r\n\r\n\t\t

\r\n\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n
\r\n
\r\n
\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\nMicro Achat : Ordinateurs, PDA - Toute l\'informatique avec 01Informatique, L\'Ordinateur Individuel, Micro Hebdo, D\351cision Informatique et 01R\351seaux\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n

Derni\350re mise \340 jour de cette page : lundi 8 novembre 2004  |  16:45
\r\n \r\n\r\n\r\n\r\n\t\r\n\r\n\t\t\r\n\r\n\t\r\n\r\n\t\r\n\t\t\r\n\r\n\r\n\t\t\r\n\r\n\t\t\r\n\t\r\n\t\r\n\t\t\t

\r\n\r\n\r\n\r\n


\r\n\r\n\r\n\r\n
\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t
\"\"
Imagerie 
\"\"\n\t\t\t\t\t\t\t\tLG L1720B\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\340 partir de\n\t\t\t\t\t\t\t\t\t
332.89 €
\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t
Ordinateurs 
\"\"\n\t\t\t\t\t\t\t\tAcer Veriton 7600G\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\340 partir de\n\t\t\t\t\t\t\t\t\t
705 €
\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t
Ordinateurs 
\"\"\n\t\t\t\t\t\t\t\tShuttle SN95G5\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\340 partir de\n\t\t\t\t\t\t\t\t\t
375 €
\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t
Composants 
\"\"\n\t\t\t\t\t\t\t\tAsus A7N8X-E Deluxe\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\340 partir de\n\t\t\t\t\t\t\t\t\t
91.99 €
\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t
Composants 
\"\"\n\t\t\t\t\t\t\t\tThermalright SP-94\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\340 partir de\n\t\t\t\t\t\t\t\t\t
49 €
\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t
\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t
\"\"
1 \">\"PC Look
2 \">\"Atelier Informatique
3 \">\"Zanax Multim\351dia
4 \">\"MISTEROOPS
5 \">\"168 Golden Avenue
6 \">\"microchoix
7 \">\"e-Soph
8 \">\"PC Price Club
9 \">\"PC 77
10 \">\"Web In Informatique
\n\t\t\t\t
\n\t\t\t\t
\r\n \r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t
\n\n\n\n\n\n\n\n\n\n\n\n\n
\n\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\r\n\r\n\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n

\r\n\t\t\t

\r\n\t\t\t

\r\n\t\t\t
\r\n\t\t\t
\r\n\r\n\r\n \r\n \r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t

CD et DVD bient\364t insensibles aux rayures
OpenOffice gagne son service
La messagerie en cinq minutes selon Ipswitch
> toutes les news


\r\n\t\t
\r\n \r\n\r\n\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t

Recevez chaque jour l\'actualit\351 des produits et des promos
\r\n\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t


\r\n\t\t\t
\r\n\t\t\t\t
\r\n\t\t
\r\n\r\n\r\n\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t \r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t

Entreprise
\r\n\t\t\t\tQuand le billet papier s\'envole vers la d\351mat\351rialisation


Trucs et astuces
\r\n\t\t\t\tD\351pannez Windows XP


Conso
\r\n\t\t\t\tVos photos sur papier imprimante ou labo ?


Produits & Tests
\r\n\t\t\t\t5 programmes d\222encodage vid\351o gratuits


\r\n\t\t
\r\n\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n
\r\n
\r\n\t\t\r\n\t\t

\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n
\r\n\r\n\r\n\t\r\n\t\t\r\n\t\r\n
\r\n\t
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n
\r\n\r\n\r\n\t\r\n\r\n\r\n\r\n\t\t\t\r\n\r\n\r\n\r\n\t\t\t\t\r\n
\r\n
\r\nPortable
\r\nUn nouvel ultra portable r\351alis\351 par Nec
\r\n\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t
\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \t\r\nLe Versa S940 a un format r\351duit, mais ses performances sont \340 la hauteur.
\r\n\340 partir de 1663 \200\r\n
\r\n
\r\nPortable
\r\nAsus pr\351sente trois petits nouveaux dans la gamme A3N
\r\n\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t
\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \t\r\nCes trois portables Centrino int\350grent, entre autres, une webcam et un contr\364leur Wi-Fi.
\r\n\340 partir de 1346 \200\r\n
\r\n
\r\n\t\r\n\t\r\n\t\r\n \t\r\n\t\r\n\t\r\n \t\r\n\t\r\n\t
\r\n\t\r\n\r\n
\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
BON PLAN
\r\n
\r\n
\r\nLes derni\350res technologies INTEL dans un nouveau design pour ce shuttle haut de gamme, pour un prix abordable.
\r\n

\r\n
\r\n\340 partir de
\r\n
415 \200
\r\n
\r\n
\r\n
publicit\351
\r\n
\r\n\t\r\n\r\n
\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t

\r\n\t\t\t\t\t\t\t\t\t\t\t\t
\r\n\t\t\t\tDesktops
\r\n\t\t\t\tPortables
\r\n\t\t\t\tMini-PC
\r\n\t\t\t\tPda / Tablets-PC
\r\n\t\t\t\tApple
\r\n\t\t\t\tGPS
\r\n\t\t\t\t
\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t


\r\n\t\t\t\t\t\t
\r\n\t\t\t\t
\r\n\t\t
\r\n
\r\n
\r\n\t\t\r\n\t\t\r\n\r\n\r\n \r\n\r\n\r\n \r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n
\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n

\r\n\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\t\t\r\n\t\r\n\t\r\n\t\t\t\t\r\n\t\r\n\t\r\n\t\t\t\t\r\n\t\r\n\t\r\n\t\t\t\t\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t
\r\n\tPortable Toshiba consacre deux gammes de machines au multim\351dia
\r\n\tEquipement haut de gamme et Windows Media Center sont au menu de ces portables \340 vocation multim\351dia.

\r\n\tOrdinateur Arriv\351e d\'un Power Mac G5 d\'entr\351e de gamme
\r\n\tLa firme \340 la pomme propose une station de travail \351volutive et relativement abordable.

\r\n\tPC Alienware propose deux machines au look \351trange
\r\n\tAurora et Area 51 sont deux gammes d\'ordinateurs enti\350rement configurables.

\r\n\tPortable Trois nouveaux iBook G4 chez Apple
\r\n\tChez Apple, les portables gagnent en vitesse et communiquent sans fil en standard.

\r\n\t\t\t\t> toutes les news\r\n\t\t\t
\r\n
\r\n
\r\n
\r\n\r\n\r\n\r\n\r\n

\r\n\r\n\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \tAsus A3N15-C Pro
\r\n Voici un portable autonome et puissant gr\342ce \340 la technologie Intel Centrino.
\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t
\r\n\t1170 \200
\r\n
\r\n\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \tSoltek EQ3702A Miroir
\r\n Ce mini PC est une solution int\351ressante pour les utilisateurs poss\351dant d\351j\340 un \351cran.
\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t
\r\n\t559 \200
\r\n
\r\n\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \tIBM ThinkPad R51
\r\n Voici un portable complet et pourtant relativement l\351ger.
\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t
\r\n\t1299 \200
\r\n
\r\n\t\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\t\t> toutes les promos\r\n\t\t
\r\n
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n

\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\r\n

\r\n
\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t
\r\n\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t
\r\n\t\t\t\r\n\t\t\t\t\r\n\r\n\r\n\r\n \r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\r\n
\r\n\t\t
\r\n\t\r\n\r\n
\r\n\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \t\r\n
\r\n
\r\nLes graveurs de DVD
\r\nQuel graveur choisir ? Quel type de format ? Quelle vitesse ? Double couche ou simple couche ? Voici tout ce qu\'il faut savoir pour faire le bon choix.
\r\n\t\t\t\t\t\t
\r\n\t\t
\r\n
\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\r\n
\r\n\t\t
\r\n
\r\n\r\n\r\n\t\r\n\t\t\r\n\r\n\r\n \t\r\n
\r\n\t\t
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t
\r\n\t\t\t\t

\r\n\t\t\t\tChoisir une r\351gion
\r\n\r\n
Un d\351partement
\r\n\r\n
\r\n
Un arrondissement
\r\n\r\n
\r\n
\r\n\t\t\t\tRecherche directe
\r\n\t\t\t\trechercher une ville
et/ou une boutique
\r\n\t\t\t\t

\r\n\t\t\t\t \r\n\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t
Recherche avanc\351e
\r\n\t\t\t\t
\r\n\t\t\t\t
\r\n\t\t\t\t
\r\n\t\t
\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t
Bureautique
\r\n\t\t\t\tTraducteur, organiseur...

\r\n\t\t\t\t

Multim\351dia
\r\n\t\t\t\tPhoto, audio, vid\351o...

\r\n\t\t\t\t

Utilitaires
\r\n\t\t\t\tAntivirus, pilotes, gravure...

\r\n\t\t\t\t

Personnaliser son PC
\r\n\t\t\t\tEcrans de veille, th\350mes...

\r\n\t\t\t\t

D\351veloppement
\r\n\t\t\t\tCr\351ation de logiciels, BDD...

\r\n\t\t\t\t

Jeux
\r\n\t\t\t\tAction, simulation...

\r\n\t\t\t\t

Internet
\r\n\t\t\t\tUtilitaires, email, FTP...

\r\n\t\t\t\t

Loisirs
\r\n\t\t\t\tHumour, culture...

\r\n\t\t\t\t
\r\n\t\t
\r\n
\r\n
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n\t\t
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\r\n\t\t\t
\r\n\t\t\t
\r\n\r\n\t\t

\r\n\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n
\r\n
\r\n
\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\nMicro Achat : Ordinateurs, PDA - Toute l\'informatique avec 01Informatique, L\'Ordinateur Individuel, Micro Hebdo, D\351cision Informatique et 01R\351seaux\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n

Derni\350re mise \340 jour de cette page : lundi 8 novembre 2004  |  16:45
\r\n \r\n\r\n\r\n\r\n\t\r\n\r\n\t\t\r\n\r\n\t\r\n\r\n\t\r\n\t\t\r\n\r\n\r\n\t\t\r\n\r\n\t\t\r\n\t\r\n\t\r\n\t\t\t

\r\n\r\n\r\n\r\n


\r\n\r\n\r\n\r\n
\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t
\"\"
Imagerie 
\"\"\n\t\t\t\t\t\t\t\tLG L1720B\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\340 partir de\n\t\t\t\t\t\t\t\t\t
332.89 €
\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t
Ordinateurs 
\"\"\n\t\t\t\t\t\t\t\tAcer Veriton 7600G\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\340 partir de\n\t\t\t\t\t\t\t\t\t
705 €
\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t
Ordinateurs 
\"\"\n\t\t\t\t\t\t\t\tShuttle SN95G5\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\340 partir de\n\t\t\t\t\t\t\t\t\t
375 €
\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t
Composants 
\"\"\n\t\t\t\t\t\t\t\tAsus A7N8X-E Deluxe\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\340 partir de\n\t\t\t\t\t\t\t\t\t
91.99 €
\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t
Composants 
\"\"\n\t\t\t\t\t\t\t\tThermalright SP-94\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\340 partir de\n\t\t\t\t\t\t\t\t\t
49 €
\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t
\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t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\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t

CD et DVD bient\364t insensibles aux rayures
OpenOffice gagne son service
La messagerie en cinq minutes selon Ipswitch
> toutes les news


\r\n\t\t
\r\n \r\n\r\n\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t

Recevez chaque jour l\'actualit\351 des produits et des promos
\r\n\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t


\r\n\t\t\t
\r\n\t\t\t\t
\r\n\t\t
\r\n\r\n\r\n\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t \r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t

Entreprise
\r\n\t\t\t\tQuand le billet papier s\'envole vers la d\351mat\351rialisation


Trucs et astuces
\r\n\t\t\t\tD\351pannez Windows XP


Conso
\r\n\t\t\t\tVos photos sur papier imprimante ou labo ?


Produits & Tests
\r\n\t\t\t\t5 programmes d\222encodage vid\351o gratuits


\r\n\t\t
\r\n\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n
\r\n
\r\n\t\t\r\n\t\t

\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n
\r\n\r\n\r\n\t\r\n\t\t\r\n\t\r\n
\r\n\t
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n
\r\n\r\n\r\n\t\r\n\r\n\r\n\r\n\t\t\t\r\n\r\n\r\n\r\n\t\t\t\t\r\n
\r\n
\r\nPortable
\r\nUn nouvel ultra portable r\351alis\351 par Nec
\r\n\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t
\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \t\r\nLe Versa S940 a un format r\351duit, mais ses performances sont \340 la hauteur.
\r\n\340 partir de 1663 \200\r\n
\r\n
\r\nPortable
\r\nAsus pr\351sente trois petits nouveaux dans la gamme A3N
\r\n\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t
\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \t\r\nCes trois portables Centrino int\350grent, entre autres, une webcam et un contr\364leur Wi-Fi.
\r\n\340 partir de 1346 \200\r\n
\r\n
\r\n\t\r\n\t\r\n\t\r\n \t\r\n\t\r\n\t\r\n \t\r\n\t\r\n\t
\r\n\t\r\n\r\n
\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
BON PLAN
\r\n
\r\n
\r\nLes derni\350res technologies INTEL dans un nouveau design pour ce shuttle haut de gamme, pour un prix abordable.
\r\n

\r\n
\r\n\340 partir de
\r\n
415 \200
\r\n
\r\n
\r\n
publicit\351
\r\n
\r\n\t\r\n\r\n
\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t

\r\n\t\t\t\t\t\t\t\t\t\t\t\t
\r\n\t\t\t\tDesktops
\r\n\t\t\t\tPortables
\r\n\t\t\t\tMini-PC
\r\n\t\t\t\tPda / Tablets-PC
\r\n\t\t\t\tApple
\r\n\t\t\t\tGPS
\r\n\t\t\t\t
\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t


\r\n\t\t\t\t\t\t
\r\n\t\t\t\t
\r\n\t\t
\r\n
\r\n
\r\n\t\t\r\n\t\t\r\n\r\n\r\n \r\n\r\n\r\n \r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n
\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n

\r\n\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\t\t\r\n\t\r\n\t\r\n\t\t\t\t\r\n\t\r\n\t\r\n\t\t\t\t\r\n\t\r\n\t\r\n\t\t\t\t\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t
\r\n\tPortable Toshiba consacre deux gammes de machines au multim\351dia
\r\n\tEquipement haut de gamme et Windows Media Center sont au menu de ces portables \340 vocation multim\351dia.

\r\n\tOrdinateur Arriv\351e d\'un Power Mac G5 d\'entr\351e de gamme
\r\n\tLa firme \340 la pomme propose une station de travail \351volutive et relativement abordable.

\r\n\tPC Alienware propose deux machines au look \351trange
\r\n\tAurora et Area 51 sont deux gammes d\'ordinateurs enti\350rement configurables.

\r\n\tPortable Trois nouveaux iBook G4 chez Apple
\r\n\tChez Apple, les portables gagnent en vitesse et communiquent sans fil en standard.

\r\n\t\t\t\t> toutes les news\r\n\t\t\t
\r\n
\r\n
\r\n
\r\n\r\n\r\n\r\n\r\n

\r\n\r\n\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \tAsus A3N15-C Pro
\r\n Voici un portable autonome et puissant gr\342ce \340 la technologie Intel Centrino.
\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t
\r\n\t1170 \200
\r\n
\r\n\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \tSoltek EQ3702A Miroir
\r\n Ce mini PC est une solution int\351ressante pour les utilisateurs poss\351dant d\351j\340 un \351cran.
\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t
\r\n\t559 \200
\r\n
\r\n\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \tIBM ThinkPad R51
\r\n Voici un portable complet et pourtant relativement l\351ger.
\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t
\r\n\t1299 \200
\r\n
\r\n\t\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\t\t> toutes les promos\r\n\t\t
\r\n
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n

\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\r\n

\r\n
\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t
\r\n\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t
\r\n\t\t\t\r\n\t\t\t\t\r\n\r\n\r\n\r\n \r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\r\n
\r\n\t\t
\r\n\t\r\n\r\n
\r\n\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \t\r\n
\r\n
\r\nLes graveurs de DVD
\r\nQuel graveur choisir ? Quel type de format ? Quelle vitesse ? Double couche ou simple couche ? Voici tout ce qu\'il faut savoir pour faire le bon choix.
\r\n\t\t\t\t\t\t
\r\n\t\t
\r\n
\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\r\n
\r\n\t\t
\r\n
\r\n\r\n\r\n\t\r\n\t\t\r\n\r\n\r\n \t\r\n
\r\n\t\t
\r\n\t\t\r\n\t\t\t\r\n\t\t\t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t\t\t\tTraducteur, organiseur...

\r\n\t\t\t\t

Multim\351dia
\r\n\t\t\t\tPhoto, audio, vid\351o...

\r\n\t\t\t\t

Utilitaires
\r\n\t\t\t\tAntivirus, pilotes, gravure...

\r\n\t\t\t\t

Personnaliser son PC
\r\n\t\t\t\tEcrans de veille, th\350mes...

\r\n\t\t\t\t

D\351veloppement
\r\n\t\t\t\tCr\351ation de logiciels, BDD...

\r\n\t\t\t\t

Jeux
\r\n\t\t\t\tAction, simulation...

\r\n\t\t\t\t

Internet
\r\n\t\t\t\tUtilitaires, email, FTP...

\r\n\t\t\t\t

Loisirs
\r\n\t\t\t\tHumour, culture...

\r\n\t\t\t\t
\r\n\t\t
\r\n
\r\n
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n\t\t
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\r\n\t\t\t
\r\n\t\t\t
\r\n\r\n\t\t

\r\n\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n
\r\n
\r\n
\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\nMicro Achat : Ordinateurs, PDA - Toute l\'informatique avec 01Informatique, L\'Ordinateur Individuel, Micro Hebdo, D\351cision Informatique et 01R\351seaux\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n

Derni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n\t\t\t\t\t\t\t\t\t\340 partir de\n\t\t\t\t\t\t\t\t\t
375 €
\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t
Composants 
\"\"\n\t\t\t\t\t\t\t\tAsus A7N8X-E Deluxe\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\340 partir de\n\t\t\t\t\t\t\t\t\t
91.99 €
\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t
Composants 
\"\"\n\t\t\t\t\t\t\t\tThermalright SP-94\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\340 partir de\n\t\t\t\t\t\t\t\t\t
49 €
\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t
\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t
\"\"
1 \">\"PC Look
2 \">\"Atelier Informatique
3 \">\"Zanax Multim\351dia
4 \">\"MISTEROOPS
5 \">\"168 Golden Avenue
6 \">\"microchoix
7 \">\"e-Soph
8 \">\"PC Price Club
9 \">\"PC 77
10 \">\"Web In Informatique
\n\t\t\t\t
\n\t\t\t\t
\r\n \r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t
\n\n\n\n\n\n\n\n\n\n\n\n\n
\n\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\r\n\r\n\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n

\r\n\t\t\t

\r\n\t\t\t

\r\n\t\t\t
\r\n\t\t\t
\r\n\r\n\r\n \r\n \r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t

CD et DVD bient\364t insensibles aux rayures
OpenOffice gagne son service
La messagerie en cinq minutes selon Ipswitch
> toutes les news


\r\n\t\t
\r\n \r\n\r\n\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t

Recevez chaque jour l\'actualit\351 des produits et des promos
\r\n\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t


\r\n\t\t\t
\r\n\t\t\t\t
\r\n\t\t
\r\n\r\n\r\n\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t \r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t

Entreprise
\r\n\t\t\t\tQuand le billet papier s\'envole vers la d\351mat\351rialisation


Trucs et astuces
\r\n\t\t\t\tD\351pannez Windows XP


Conso
\r\n\t\t\t\tVos photos sur papier imprimante ou labo ?


Produits & Tests
\r\n\t\t\t\t5 programmes d\222encodage vid\351o gratuits


\r\n\t\t
\r\n\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n
\r\n
\r\n\t\t\r\n\t\t

\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n
\r\n\r\n\r\n\t\r\n\t\t\r\n\t\r\n
\r\n\t
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n
\r\n\r\n\r\n\t\r\n\r\n\r\n\r\n\t\t\t\r\n\r\n\r\n\r\n\t\t\t\t\r\n
\r\n
\r\nPortable
\r\nUn nouvel ultra portable r\351alis\351 par Nec
\r\n\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t
\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \t\r\nLe Versa S940 a un format r\351duit, mais ses performances sont \340 la hauteur.
\r\n\340 partir de 1663 \200\r\n
\r\n
\r\nPortable
\r\nAsus pr\351sente trois petits nouveaux dans la gamme A3N
\r\n\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t
\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \t\r\nCes trois portables Centrino int\350grent, entre autres, une webcam et un contr\364leur Wi-Fi.
\r\n\340 partir de 1346 \200\r\n
\r\n
\r\n\t\r\n\t\r\n\t\r\n \t\r\n\t\r\n\t\r\n \t\r\n\t\r\n\t
\r\n\t\r\n\r\n
\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
BON PLAN
\r\n
\r\n
\r\nLes derni\350res technologies INTEL dans un nouveau design pour ce shuttle haut de gamme, pour un prix abordable.
\r\n

\r\n
\r\n\340 partir de
\r\n
415 \200
\r\n
\r\n
\r\n
publicit\351
\r\n
\r\n\t\r\n\r\n
\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t

\r\n\t\t\t\t\t\t\t\t\t\t\t\t
\r\n\t\t\t\tDesktops
\r\n\t\t\t\tPortables
\r\n\t\t\t\tMini-PC
\r\n\t\t\t\tPda / Tablets-PC
\r\n\t\t\t\tApple
\r\n\t\t\t\tGPS
\r\n\t\t\t\t
\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t


\r\n\t\t\t\t\t\t
\r\n\t\t\t\t
\r\n\t\t
\r\n
\r\n
\r\n\t\t\r\n\t\t\r\n\r\n\r\n \r\n\r\n\r\n \r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n
\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n

\r\n\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\t\t\r\n\t\r\n\t\r\n\t\t\t\t\r\n\t\r\n\t\r\n\t\t\t\t\r\n\t\r\n\t\r\n\t\t\t\t\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t
\r\n\tPortable Toshiba consacre deux gammes de machines au multim\351dia
\r\n\tEquipement haut de gamme et Windows Media Center sont au menu de ces portables \340 vocation multim\351dia.

\r\n\tOrdinateur Arriv\351e d\'un Power Mac G5 d\'entr\351e de gamme
\r\n\tLa firme \340 la pomme propose une station de travail \351volutive et relativement abordable.

\r\n\tPC Alienware propose deux machines au look \351trange
\r\n\tAurora et Area 51 sont deux gammes d\'ordinateurs enti\350rement configurables.

\r\n\tPortable Trois nouveaux iBook G4 chez Apple
\r\n\tChez Apple, les portables gagnent en vitesse et communiquent sans fil en standard.

\r\n\t\t\t\t> toutes les news\r\n\t\t\t
\r\n
\r\n
\r\n
\r\n\r\n\r\n\r\n\r\n

\r\n\r\n\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \tAsus A3N15-C Pro
\r\n Voici un portable autonome et puissant gr\342ce \340 la technologie Intel Centrino.
\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t
\r\n\t1170 \200
\r\n
\r\n\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \tSoltek EQ3702A Miroir
\r\n Ce mini PC est une solution int\351ressante pour les utilisateurs poss\351dant d\351j\340 un \351cran.
\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t
\r\n\t559 \200
\r\n
\r\n\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \tIBM ThinkPad R51
\r\n Voici un portable complet et pourtant relativement l\351ger.
\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t
\r\n\t1299 \200
\r\n
\r\n\t\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\t\t> toutes les promos\r\n\t\t
\r\n
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n

\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\r\n

\r\n
\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t
\r\n\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t
\r\n\t\t\t\r\n\t\t\t\t\r\n\r\n\r\n\r\n \r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\r\n
\r\n\t\t
\r\n\t\r\n\r\n
\r\n\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \t\r\n
\r\n
\r\nLes graveurs de DVD
\r\nQuel graveur choisir ? Quel type de format ? Quelle vitesse ? Double couche ou simple couche ? Voici tout ce qu\'il faut savoir pour faire le bon choix.
\r\n\t\t\t\t\t\t
\r\n\t\t
\r\n
\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\r\n
\r\n\t\t
\r\n
\r\n\r\n\r\n\t\r\n\t\t\r\n\r\n\r\n \t\r\n
\r\n\t\t
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t
\r\n\t\t\t\t

\r\n\t\t\t\tChoisir une r\351gion
\r\n\r\n
Un d\351partement
\r\n\r\n
\r\n
Un arrondissement
\r\n\r\n
\r\n
\r\n\t\t\t\tRecherche directe
\r\n\t\t\t\trechercher une ville
et/ou une boutique
\r\n\t\t\t\t

\r\n\t\t\t\t \r\n\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t
Recherche avanc\351e
\r\n\t\t\t\t
\r\n\t\t\t\t
\r\n\t\t\t\t
\r\n\t\t
\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t
Bureautique
\r\n\t\t\t\tTraducteur, organiseur...

\r\n\t\t\t\t

Multim\351dia
\r\n\t\t\t\tPhoto, audio, vid\351o...

\r\n\t\t\t\t

Utilitaires
\r\n\t\t\t\tAntivirus, pilotes, gravure...

\r\n\t\t\t\t

Personnaliser son PC
\r\n\t\t\t\tEcrans de veille, th\350mes...

\r\n\t\t\t\t

D\351veloppement
\r\n\t\t\t\tCr\351ation de logiciels, BDD...

\r\n\t\t\t\t

Jeux
\r\n\t\t\t\tAction, simulation...

\r\n\t\t\t\t

Internet
\r\n\t\t\t\tUtilitaires, email, FTP...

\r\n\t\t\t\t

Loisirs
\r\n\t\t\t\tHumour, culture...

\r\n\t\t\t\t
\r\n\t\t
\r\n
\r\n
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n\t\t
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\r\n\t\t\t
\r\n\t\t\t
\r\n\r\n\t\t

\r\n\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n
\r\n
\r\n
\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\nMicro Achat : Ordinateurs, PDA - Toute l\'informatique avec 01Informatique, L\'Ordinateur Individuel, Micro Hebdo, D\351cision Informatique et 01R\351seaux\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n

Derni\350re mise \340 jour de cette page : lundi 8 novembre 2004  |  16:45
\r\n \r\n\r\n\r\n\r\n\t\r\n\r\n\t\t\r\n\r\n\t\r\n\r\n\t\r\n\t\t\r\n\r\n\r\n\t\t\r\n\r\n\t\t\r\n\t\r\n\t\r\n\t\t\t

\r\n\r\n\r\n\r\n


\r\n\r\n\r\n\r\n
\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t
\"\"
Imagerie 
\"\"\n\t\t\t\t\t\t\t\tLG L1720B\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\340 partir de\n\t\t\t\t\t\t\t\t\t
332.89 €
\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t
Ordinateurs 
\"\"\n\t\t\t\t\t\t\t\tAcer Veriton 7600G\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\340 partir de\n\t\t\t\t\t\t\t\t\t
705 €
\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t
Ordinateurs 
\"\"\n\t\t\t\t\t\t\t\tShuttle SN95G5\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\340 partir de\n\t\t\t\t\t\t\t\t\t
375 €
\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t
Composants 
\"\"\n\t\t\t\t\t\t\t\tAsus A7N8X-E Deluxe\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\340 partir de\n\t\t\t\t\t\t\t\t\t
91.99 €
\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t
Composants 
\"\"\n\t\t\t\t\t\t\t\tThermalright SP-94\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\340 partir de\n\t\t\t\t\t\t\t\t\t
49 €
\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t
\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t
\"\"
1 \">\"PC Look
2 \">\"Atelier Informatique
3 \">\"Zanax Multim\351dia
4 \">\"MISTEROOPS
5 \">\"168 Golden Avenue
6 \">\"microchoix
7 \">\"e-Soph
8 \">\"PC Price Club
9 \">\"PC 77
10 \">\"Web In Informatique
\n\t\t\t\t
\n\t\t\t\t
\r\n \r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t
\n\n\n\n\n\n\n\n\n\n\n\n\n
\n\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\r\n\r\n\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n

\r\n\t\t\t

\r\n\t\t\t

\r\n\t\t\t
\r\n\t\t\t
\r\n\r\n\r\n \r\n \r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t

CD et DVD bient\364t insensibles aux rayures
OpenOffice gagne son service
La messagerie en cinq minutes selon Ipswitch
> toutes les news


\r\n\t\t
\r\n \r\n\r\n\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t

Recevez chaque jour l\'actualit\351 des produits et des promos
\r\n\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t


\r\n\t\t\t
\r\n\t\t\t\t
\r\n\t\t
\r\n\r\n\r\n\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t \r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t

Entreprise
\r\n\t\t\t\tQuand le billet papier s\'envole vers la d\351mat\351rialisation


Trucs et astuces
\r\n\t\t\t\tD\351pannez Windows XP


Conso
\r\n\t\t\t\tVos photos sur papier imprimante ou labo ?


Produits & Tests
\r\n\t\t\t\t5 programmes d\222encodage vid\351o gratuits


\r\n\t\t
\r\n\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n
\r\n
\r\n\t\t\r\n\t\t

\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n
\r\n\r\n\r\n\t\r\n\t\t\r\n\t\r\n
\r\n\t
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n
\r\n\r\n\r\n\t\r\n\r\n\r\n\r\n\t\t\t\r\n\r\n\r\n\r\n\t\t\t\t\r\n
\r\n
\r\nPortable
\r\nUn nouvel ultra portable r\351alis\351 par Nec
\r\n\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t
\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \t\r\nLe Versa S940 a un format r\351duit, mais ses performances sont \340 la hauteur.
\r\n\340 partir de 1663 \200\r\n
\r\n
\r\nPortable
\r\nAsus pr\351sente trois petits nouveaux dans la gamme A3N
\r\n\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t
\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \t\r\nCes trois portables Centrino int\350grent, entre autres, une webcam et un contr\364leur Wi-Fi.
\r\n\340 partir de 1346 \200\r\n
\r\n
\r\n\t\r\n\t\r\n\t\r\n \t\r\n\t\r\n\t\r\n \t\r\n\t\r\n\t
\r\n\t\r\n\r\n
\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
BON PLAN
\r\n
\r\n
\r\nLes derni\350res technologies INTEL dans un nouveau design pour ce shuttle haut de gamme, pour un prix abordable.
\r\n

\r\n
\r\n\340 partir de
\r\n
415 \200
\r\n
\r\n
\r\n
publicit\351
\r\n
\r\n\t\r\n\r\n
\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t

\r\n\t\t\t\t\t\t\t\t\t\t\t\t
\r\n\t\t\t\tDesktops
\r\n\t\t\t\tPortables
\r\n\t\t\t\tMini-PC
\r\n\t\t\t\tPda / Tablets-PC
\r\n\t\t\t\tApple
\r\n\t\t\t\tGPS
\r\n\t\t\t\t
\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t


\r\n\t\t\t\t\t\t
\r\n\t\t\t\t
\r\n\t\t
\r\n
\r\n
\r\n\t\t\r\n\t\t\r\n\r\n\r\n \r\n\r\n\r\n \r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n
\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n

\r\n\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\t\t\r\n\t\r\n\t\r\n\t\t\t\t\r\n\t\r\n\t\r\n\t\t\t\t\r\n\t\r\n\t\r\n\t\t\t\t\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t
\r\n\tPortable Toshiba consacre deux gammes de machines au multim\351dia
\r\n\tEquipement haut de gamme et Windows Media Center sont au menu de ces portables \340 vocation multim\351dia.

\r\n\tOrdinateur Arriv\351e d\'un Power Mac G5 d\'entr\351e de gamme
\r\n\tLa firme \340 la pomme propose une station de travail \351volutive et relativement abordable.

\r\n\tPC Alienware propose deux machines au look \351trange
\r\n\tAurora et Area 51 sont deux gammes d\'ordinateurs enti\350rement configurables.

\r\n\tPortable Trois nouveaux iBook G4 chez Apple
\r\n\tChez Apple, les portables gagnent en vitesse et communiquent sans fil en standard.

\r\n\t\t\t\t> toutes les news\r\n\t\t\t
\r\n
\r\n
\r\n
\r\n\r\n\r\n\r\n\r\n

\r\n\r\n\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \tAsus A3N15-C Pro
\r\n Voici un portable autonome et puissant gr\342ce \340 la technologie Intel Centrino.
\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t
\r\n\t1170 \200
\r\n
\r\n\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \tSoltek EQ3702A Miroir
\r\n Ce mini PC est une solution int\351ressante pour les utilisateurs poss\351dant d\351j\340 un \351cran.
\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t
\r\n\t559 \200
\r\n
\r\n\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \tIBM ThinkPad R51
\r\n Voici un portable complet et pourtant relativement l\351ger.
\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t
\r\n\t1299 \200
\r\n
\r\n\t\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n
\r\n\t\t\t\t> toutes les promos\r\n\t\t
\r\n
\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n

\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\r\n

\r\n
\r\n\t\t\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\r\n\t\t
\r\n\t\t\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t
\r\n\t\t\t\r\n\t\t\t\t\r\n\r\n\r\n\r\n \r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\t\t\r\n\t\t
\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\r\n
\r\n\t\t
\r\n\t\r\n\r\n
\r\n\r\n\t\t\t\t\t \t \t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t \t\r\n
\r\n
\r\nLes graveurs de DVD
\r\nQuel graveur choisir ? Quel type de format ? Quelle vitesse ? Double couche ou simple couche ? Voici tout ce qu\'il faut savoir pour faire le bon choix.
\r\n\t\t\t\t\t\t
\r\n\t\t
\r\n
\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\r\n
\r\n\t\t
\r\n
\r\n\r\n\r\n\t\r\n\t\t\r\n\r\n\r\n \t\r\n
\r\n\t\t
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t
\r\n\t\t\t\t

\r\n\t\t\t\tChoisir une r\351gion
\r\n\r\n
Un d\351partement
\r\n\r\n
\r\n
Un arrondissement
\r\n\r\n
\r\n
\r\n\t\t\t\tRecherche directe
\r\n\t\t\t\trechercher une ville
et/ou une boutique
\r\n\t\t\t\t

\r\n\t\t\t\t \r\n\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t
Recherche avanc\351e
\r\n\t\t\t\t
\r\n\t\t\t\t
\r\n\t\t\t\t
\r\n\t\t
\r\n
\r\n\r\n\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\r\n\t\r\n\t\t\r\n\t\r\n
\r\n\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\t\r\n\t\t\t\r\n\t\t
Bureautique
\r\n\t\t\t\tTraducteur, organiseur...

\r\n\t\t\t\t

Multim\351dia
\r\n\t\t\t\tPhoto, audio, vid\351o...

\r\n\t\t\t\t

Utilitaires
\r\n\t\t\t\tAntivirus, pilotes, gravure...

\r\n\t\t\t\t

Personnaliser son PC
\r\n\t\t\t\tEcrans de veille, th\350mes...

\r\n\t\t\t\t

D\351veloppement
\r\n\t\t\t\tCr\351ation de log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6^!Y}P#`?vkm ze(Oq`pY<8n3B1hTTlY18vgPPJ+350WQ2OKFrsi-1*F>`a!&UG9vs>06{%Ge){ss4S zHUPd8{nhn<8vxkHUIzs diff --git a/src/snappy/snappy/testdata/lcet10.txt b/src/snappy/snappy/testdata/lcet10.txt deleted file mode 100644 index 25dda6b3f1..0000000000 --- a/src/snappy/snappy/testdata/lcet10.txt +++ /dev/null @@ -1,7519 +0,0 @@ - - -The Project Gutenberg Etext of LOC WORKSHOP ON ELECTRONIC TEXTS - - - - - WORKSHOP ON ELECTRONIC TEXTS - - PROCEEDINGS - - - - Edited by James Daly - - - - - - - - 9-10 June 1992 - - - Library of Congress - Washington, D.C. - - - - Supported by a Grant from the David and Lucile Packard Foundation - - - *** *** *** ****** *** *** *** - - - TABLE OF CONTENTS - - -Acknowledgements - -Introduction - -Proceedings - Welcome - Prosser Gifford and Carl Fleischhauer - - Session I. Content in a New Form: Who Will Use It and What Will They Do? - James Daly (Moderator) - Avra Michelson, Overview - Susan H. Veccia, User Evaluation - Joanne Freeman, Beyond the Scholar - Discussion - - Session II. Show and Tell - Jacqueline Hess (Moderator) - Elli Mylonas, Perseus Project - Discussion - Eric M. Calaluca, Patrologia Latina Database - Carl Fleischhauer and Ricky Erway, American Memory - Discussion - Dorothy Twohig, The Papers of George Washington - Discussion - Maria L. Lebron, The Online Journal of Current Clinical Trials - Discussion - Lynne K. Personius, Cornell mathematics books - Discussion - - Session III. Distribution, Networks, and Networking: - Options for Dissemination - Robert G. Zich (Moderator) - Clifford A. Lynch - Discussion - Howard Besser - Discussion - Ronald L. Larsen - Edwin B. Brownrigg - Discussion - - Session IV. Image Capture, Text Capture, Overview of Text and - Image Storage Formats - William L. Hooton (Moderator) - A) Principal Methods for Image Capture of Text: - direct scanning, use of microform - Anne R. Kenney - Pamela Q.J. Andre - Judith A. Zidar - Donald J. Waters - Discussion - B) Special Problems: bound volumes, conservation, - reproducing printed halftones - George Thoma - Carl Fleischhauer - Discussion - C) Image Standards and Implications for Preservation - Jean Baronas - Patricia Battin - Discussion - D) Text Conversion: OCR vs. rekeying, standards of accuracy - and use of imperfect texts, service bureaus - Michael Lesk - Ricky Erway - Judith A. Zidar - Discussion - - Session V. Approaches to Preparing Electronic Texts - Susan Hockey (Moderator) - Stuart Weibel - Discussion - C.M. Sperberg-McQueen - Discussion - Eric M. Calaluca - Discussion - - Session VI. Copyright Issues - Marybeth Peters - - Session VII. Conclusion - Prosser Gifford (Moderator) - General discussion - -Appendix I: Program - -Appendix II: Abstracts - -Appendix III: Directory of Participants - - - *** *** *** ****** *** *** *** - - - Acknowledgements - -I would like to thank Carl Fleischhauer and Prosser Gifford for the -opportunity to learn about areas of human activity unknown to me a scant -ten months ago, and the David and Lucile Packard Foundation for -supporting that opportunity. The help given by others is acknowledged on -a separate page. - - 19 October 1992 - - - *** *** *** ****** *** *** *** - - - INTRODUCTION - -The Workshop on Electronic Texts (1) drew together representatives of -various projects and interest groups to compare ideas, beliefs, -experiences, and, in particular, methods of placing and presenting -historical textual materials in computerized form. Most attendees gained -much in insight and outlook from the event. But the assembly did not -form a new nation, or, to put it another way, the diversity of projects -and interests was too great to draw the representatives into a cohesive, -action-oriented body.(2) - -Everyone attending the Workshop shared an interest in preserving and -providing access to historical texts. But within this broad field the -attendees represented a variety of formal, informal, figurative, and -literal groups, with many individuals belonging to more than one. These -groups may be defined roughly according to the following topics or -activities: - -* Imaging -* Searchable coded texts -* National and international computer networks -* CD-ROM production and dissemination -* Methods and technology for converting older paper materials into -electronic form -* Study of the use of digital materials by scholars and others - -This summary is arranged thematically and does not follow the actual -sequence of presentations. - -NOTES: - (1) In this document, the phrase electronic text is used to mean - any computerized reproduction or version of a document, book, - article, or manuscript (including images), and not merely a machine- - readable or machine-searchable text. - - (2) The Workshop was held at the Library of Congress on 9-10 June - 1992, with funding from the David and Lucile Packard Foundation. - The document that follows represents a summary of the presentations - made at the Workshop and was compiled by James DALY. This - introduction was written by DALY and Carl FLEISCHHAUER. - - -PRESERVATION AND IMAGING - -Preservation, as that term is used by archivists,(3) was most explicitly -discussed in the context of imaging. Anne KENNEY and Lynne PERSONIUS -explained how the concept of a faithful copy and the user-friendliness of -the traditional book have guided their project at Cornell University.(4) -Although interested in computerized dissemination, participants in the -Cornell project are creating digital image sets of older books in the -public domain as a source for a fresh paper facsimile or, in a future -phase, microfilm. The books returned to the library shelves are -high-quality and useful replacements on acid-free paper that should last -a long time. To date, the Cornell project has placed little or no -emphasis on creating searchable texts; one would not be surprised to find -that the project participants view such texts as new editions, and thus -not as faithful reproductions. - -In her talk on preservation, Patricia BATTIN struck an ecumenical and -flexible note as she endorsed the creation and dissemination of a variety -of types of digital copies. Do not be too narrow in defining what counts -as a preservation element, BATTIN counseled; for the present, at least, -digital copies made with preservation in mind cannot be as narrowly -standardized as, say, microfilm copies with the same objective. Setting -standards precipitously can inhibit creativity, but delay can result in -chaos, she advised. - -In part, BATTIN's position reflected the unsettled nature of image-format -standards, and attendees could hear echoes of this unsettledness in the -comments of various speakers. For example, Jean BARONAS reviewed the -status of several formal standards moving through committees of experts; -and Clifford LYNCH encouraged the use of a new guideline for transmitting -document images on Internet. Testimony from participants in the National -Agricultural Library's (NAL) Text Digitization Program and LC's American -Memory project highlighted some of the challenges to the actual creation -or interchange of images, including difficulties in converting -preservation microfilm to digital form. Donald WATERS reported on the -progress of a master plan for a project at Yale University to convert -books on microfilm to digital image sets, Project Open Book (POB). - -The Workshop offered rather less of an imaging practicum than planned, -but "how-to" hints emerge at various points, for example, throughout -KENNEY's presentation and in the discussion of arcana such as -thresholding and dithering offered by George THOMA and FLEISCHHAUER. - -NOTES: - (3) Although there is a sense in which any reproductions of - historical materials preserve the human record, specialists in the - field have developed particular guidelines for the creation of - acceptable preservation copies. - - (4) Titles and affiliations of presenters are given at the - beginning of their respective talks and in the Directory of - Participants (Appendix III). - - -THE MACHINE-READABLE TEXT: MARKUP AND USE - -The sections of the Workshop that dealt with machine-readable text tended -to be more concerned with access and use than with preservation, at least -in the narrow technical sense. Michael SPERBERG-McQUEEN made a forceful -presentation on the Text Encoding Initiative's (TEI) implementation of -the Standard Generalized Markup Language (SGML). His ideas were echoed -by Susan HOCKEY, Elli MYLONAS, and Stuart WEIBEL. While the -presentations made by the TEI advocates contained no practicum, their -discussion focused on the value of the finished product, what the -European Community calls reusability, but what may also be termed -durability. They argued that marking up--that is, coding--a text in a -well-conceived way will permit it to be moved from one computer -environment to another, as well as to be used by various users. Two -kinds of markup were distinguished: 1) procedural markup, which -describes the features of a text (e.g., dots on a page), and 2) -descriptive markup, which describes the structure or elements of a -document (e.g., chapters, paragraphs, and front matter). - -The TEI proponents emphasized the importance of texts to scholarship. -They explained how heavily coded (and thus analyzed and annotated) texts -can underlie research, play a role in scholarly communication, and -facilitate classroom teaching. SPERBERG-McQUEEN reminded listeners that -a written or printed item (e.g., a particular edition of a book) is -merely a representation of the abstraction we call a text. To concern -ourselves with faithfully reproducing a printed instance of the text, -SPERBERG-McQUEEN argued, is to concern ourselves with the representation -of a representation ("images as simulacra for the text"). The TEI proponents' -interest in images tends to focus on corollary materials for use in teaching, -for example, photographs of the Acropolis to accompany a Greek text. - -By the end of the Workshop, SPERBERG-McQUEEN confessed to having been -converted to a limited extent to the view that electronic images -constitute a promising alternative to microfilming; indeed, an -alternative probably superior to microfilming. But he was not convinced -that electronic images constitute a serious attempt to represent text in -electronic form. HOCKEY and MYLONAS also conceded that their experience -at the Pierce Symposium the previous week at Georgetown University and -the present conference at the Library of Congress had compelled them to -reevaluate their perspective on the usefulness of text as images. -Attendees could see that the text and image advocates were in -constructive tension, so to say. - -Three nonTEI presentations described approaches to preparing -machine-readable text that are less rigorous and thus less expensive. In -the case of the Papers of George Washington, Dorothy TWOHIG explained -that the digital version will provide a not-quite-perfect rendering of -the transcribed text--some 135,000 documents, available for research -during the decades while the perfect or print version is completed. -Members of the American Memory team and the staff of NAL's Text -Digitization Program (see below) also outlined a middle ground concerning -searchable texts. In the case of American Memory, contractors produce -texts with about 99-percent accuracy that serve as "browse" or -"reference" versions of written or printed originals. End users who need -faithful copies or perfect renditions must refer to accompanying sets of -digital facsimile images or consult copies of the originals in a nearby -library or archive. American Memory staff argued that the high cost of -producing 100-percent accurate copies would prevent LC from offering -access to large parts of its collections. - - -THE MACHINE-READABLE TEXT: METHODS OF CONVERSION - -Although the Workshop did not include a systematic examination of the -methods for converting texts from paper (or from facsimile images) into -machine-readable form, nevertheless, various speakers touched upon this -matter. For example, WEIBEL reported that OCLC has experimented with a -merging of multiple optical character recognition systems that will -reduce errors from an unacceptable rate of 5 characters out of every -l,000 to an unacceptable rate of 2 characters out of every l,000. - -Pamela ANDRE presented an overview of NAL's Text Digitization Program and -Judith ZIDAR discussed the technical details. ZIDAR explained how NAL -purchased hardware and software capable of performing optical character -recognition (OCR) and text conversion and used its own staff to convert -texts. The process, ZIDAR said, required extensive editing and project -staff found themselves considering alternatives, including rekeying -and/or creating abstracts or summaries of texts. NAL reckoned costs at -$7 per page. By way of contrast, Ricky ERWAY explained that American -Memory had decided from the start to contract out conversion to external -service bureaus. The criteria used to select these contractors were cost -and quality of results, as opposed to methods of conversion. ERWAY noted -that historical documents or books often do not lend themselves to OCR. -Bound materials represent a special problem. In her experience, quality -control--inspecting incoming materials, counting errors in samples--posed -the most time-consuming aspect of contracting out conversion. ERWAY -reckoned American Memory's costs at $4 per page, but cautioned that fewer -cost-elements had been included than in NAL's figure. - - -OPTIONS FOR DISSEMINATION - -The topic of dissemination proper emerged at various points during the -Workshop. At the session devoted to national and international computer -networks, LYNCH, Howard BESSER, Ronald LARSEN, and Edwin BROWNRIGG -highlighted the virtues of Internet today and of the network that will -evolve from Internet. Listeners could discern in these narratives a -vision of an information democracy in which millions of citizens freely -find and use what they need. LYNCH noted that a lack of standards -inhibits disseminating multimedia on the network, a topic also discussed -by BESSER. LARSEN addressed the issues of network scalability and -modularity and commented upon the difficulty of anticipating the effects -of growth in orders of magnitude. BROWNRIGG talked about the ability of -packet radio to provide certain links in a network without the need for -wiring. However, the presenters also called attention to the -shortcomings and incongruities of present-day computer networks. For -example: 1) Network use is growing dramatically, but much network -traffic consists of personal communication (E-mail). 2) Large bodies of -information are available, but a user's ability to search across their -entirety is limited. 3) There are significant resources for science and -technology, but few network sources provide content in the humanities. -4) Machine-readable texts are commonplace, but the capability of the -system to deal with images (let alone other media formats) lags behind. -A glimpse of a multimedia future for networks, however, was provided by -Maria LEBRON in her overview of the Online Journal of Current Clinical -Trials (OJCCT), and the process of scholarly publishing on-line. - -The contrasting form of the CD-ROM disk was never systematically -analyzed, but attendees could glean an impression from several of the -show-and-tell presentations. The Perseus and American Memory examples -demonstrated recently published disks, while the descriptions of the -IBYCUS version of the Papers of George Washington and Chadwyck-Healey's -Patrologia Latina Database (PLD) told of disks to come. According to -Eric CALALUCA, PLD's principal focus has been on converting Jacques-Paul -Migne's definitive collection of Latin texts to machine-readable form. -Although everyone could share the network advocates' enthusiasm for an -on-line future, the possibility of rolling up one's sleeves for a session -with a CD-ROM containing both textual materials and a powerful retrieval -engine made the disk seem an appealing vessel indeed. The overall -discussion suggested that the transition from CD-ROM to on-line networked -access may prove far slower and more difficult than has been anticipated. - - -WHO ARE THE USERS AND WHAT DO THEY DO? - -Although concerned with the technicalities of production, the Workshop -never lost sight of the purposes and uses of electronic versions of -textual materials. As noted above, those interested in imaging discussed -the problematical matter of digital preservation, while the TEI proponents -described how machine-readable texts can be used in research. This latter -topic received thorough treatment in the paper read by Avra MICHELSON. -She placed the phenomenon of electronic texts within the context of -broader trends in information technology and scholarly communication. - -Among other things, MICHELSON described on-line conferences that -represent a vigorous and important intellectual forum for certain -disciplines. Internet now carries more than 700 conferences, with about -80 percent of these devoted to topics in the social sciences and the -humanities. Other scholars use on-line networks for "distance learning." -Meanwhile, there has been a tremendous growth in end-user computing; -professors today are less likely than their predecessors to ask the -campus computer center to process their data. Electronic texts are one -key to these sophisticated applications, MICHELSON reported, and more and -more scholars in the humanities now work in an on-line environment. -Toward the end of the Workshop, Michael LESK presented a corollary to -MICHELSON's talk, reporting the results of an experiment that compared -the work of one group of chemistry students using traditional printed -texts and two groups using electronic sources. The experiment -demonstrated that in the event one does not know what to read, one needs -the electronic systems; the electronic systems hold no advantage at the -moment if one knows what to read, but neither do they impose a penalty. - -DALY provided an anecdotal account of the revolutionizing impact of the -new technology on his previous methods of research in the field of classics. -His account, by extrapolation, served to illustrate in part the arguments -made by MICHELSON concerning the positive effects of the sudden and radical -transformation being wrought in the ways scholars work. - -Susan VECCIA and Joanne FREEMAN delineated the use of electronic -materials outside the university. The most interesting aspect of their -use, FREEMAN said, could be seen as a paradox: teachers in elementary -and secondary schools requested access to primary source materials but, -at the same time, found that "primariness" itself made these materials -difficult for their students to use. - - -OTHER TOPICS - -Marybeth PETERS reviewed copyright law in the United States and offered -advice during a lively discussion of this subject. But uncertainty -remains concerning the price of copyright in a digital medium, because a -solution remains to be worked out concerning management and synthesis of -copyrighted and out-of-copyright pieces of a database. - -As moderator of the final session of the Workshop, Prosser GIFFORD directed -discussion to future courses of action and the potential role of LC in -advancing them. Among the recommendations that emerged were the following: - - * Workshop participants should 1) begin to think about working - with image material, but structure and digitize it in such a - way that at a later stage it can be interpreted into text, and - 2) find a common way to build text and images together so that - they can be used jointly at some stage in the future, with - appropriate network support, because that is how users will want - to access these materials. The Library might encourage attempts - to bring together people who are working on texts and images. - - * A network version of American Memory should be developed or - consideration should be given to making the data in it - available to people interested in doing network multimedia. - Given the current dearth of digital data that is appealing and - unencumbered by extremely complex rights problems, developing a - network version of American Memory could do much to help make - network multimedia a reality. - - * Concerning the thorny issue of electronic deposit, LC should - initiate a catalytic process in terms of distributed - responsibility, that is, bring together the distributed - organizations and set up a study group to look at all the - issues related to electronic deposit and see where we as a - nation should move. For example, LC might attempt to persuade - one major library in each state to deal with its state - equivalent publisher, which might produce a cooperative project - that would be equitably distributed around the country, and one - in which LC would be dealing with a minimal number of publishers - and minimal copyright problems. LC must also deal with the - concept of on-line publishing, determining, among other things, - how serials such as OJCCT might be deposited for copyright. - - * Since a number of projects are planning to carry out - preservation by creating digital images that will end up in - on-line or near-line storage at some institution, LC might play - a helpful role, at least in the near term, by accelerating how - to catalog that information into the Research Library Information - Network (RLIN) and then into OCLC, so that it would be accessible. - This would reduce the possibility of multiple institutions digitizing - the same work. - - -CONCLUSION - -The Workshop was valuable because it brought together partisans from -various groups and provided an occasion to compare goals and methods. -The more committed partisans frequently communicate with others in their -groups, but less often across group boundaries. The Workshop was also -valuable to attendees--including those involved with American Memory--who -came less committed to particular approaches or concepts. These -attendees learned a great deal, and plan to select and employ elements of -imaging, text-coding, and networked distribution that suit their -respective projects and purposes. - -Still, reality rears its ugly head: no breakthrough has been achieved. -On the imaging side, one confronts a proliferation of competing -data-interchange standards and a lack of consensus on the role of digital -facsimiles in preservation. In the realm of machine-readable texts, one -encounters a reasonably mature standard but methodological difficulties -and high costs. These latter problems, of course, represent a special -impediment to the desire, as it is sometimes expressed in the popular -press, "to put the [contents of the] Library of Congress on line." In -the words of one participant, there was "no solution to the economic -problems--the projects that are out there are surviving, but it is going -to be a lot of work to transform the information industry, and so far the -investment to do that is not forthcoming" (LESK, per litteras). - - - *** *** *** ****** *** *** *** - - - PROCEEDINGS - - -WELCOME - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -GIFFORD * Origin of Workshop in current Librarian's desire to make LC's -collections more widely available * Desiderata arising from the prospect -of greater interconnectedness * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -After welcoming participants on behalf of the Library of Congress, -American Memory (AM), and the National Demonstration Lab, Prosser -GIFFORD, director for scholarly programs, Library of Congress, located -the origin of the Workshop on Electronic Texts in a conversation he had -had considerably more than a year ago with Carl FLEISCHHAUER concerning -some of the issues faced by AM. On the assumption that numerous other -people were asking the same questions, the decision was made to bring -together as many of these people as possible to ask the same questions -together. In a deeper sense, GIFFORD said, the origin of the Workshop -lay in the desire of the current Librarian of Congress, James H. -Billington, to make the collections of the Library, especially those -offering unique or unusual testimony on aspects of the American -experience, available to a much wider circle of users than those few -people who can come to Washington to use them. This meant that the -emphasis of AM, from the outset, has been on archival collections of the -basic material, and on making these collections themselves available, -rather than selected or heavily edited products. - -From AM's emphasis followed the questions with which the Workshop began: -who will use these materials, and in what form will they wish to use -them. But an even larger issue deserving mention, in GIFFORD's view, was -the phenomenal growth in Internet connectivity. He expressed the hope -that the prospect of greater interconnectedness than ever before would -lead to: 1) much more cooperative and mutually supportive endeavors; 2) -development of systems of shared and distributed responsibilities to -avoid duplication and to ensure accuracy and preservation of unique -materials; and 3) agreement on the necessary standards and development of -the appropriate directories and indices to make navigation -straightforward among the varied resources that are, and increasingly -will be, available. In this connection, GIFFORD requested that -participants reflect from the outset upon the sorts of outcomes they -thought the Workshop might have. Did those present constitute a group -with sufficient common interests to propose a next step or next steps, -and if so, what might those be? They would return to these questions the -following afternoon. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -FLEISCHHAUER * Core of Workshop concerns preparation and production of -materials * Special challenge in conversion of textual materials * -Quality versus quantity * Do the several groups represented share common -interests? * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Carl FLEISCHHAUER, coordinator, American Memory, Library of Congress, -emphasized that he would attempt to represent the people who perform some -of the work of converting or preparing materials and that the core of -the Workshop had to do with preparation and production. FLEISCHHAUER -then drew a distinction between the long term, when many things would be -available and connected in the ways that GIFFORD described, and the short -term, in which AM not only has wrestled with the issue of what is the -best course to pursue but also has faced a variety of technical -challenges. - -FLEISCHHAUER remarked AM's endeavors to deal with a wide range of library -formats, such as motion picture collections, sound-recording collections, -and pictorial collections of various sorts, especially collections of -photographs. In the course of these efforts, AM kept coming back to -textual materials--manuscripts or rare printed matter, bound materials, -etc. Text posed the greatest conversion challenge of all. Thus, the -genesis of the Workshop, which reflects the problems faced by AM. These -problems include physical problems. For example, those in the library -and archive business deal with collections made up of fragile and rare -manuscript items, bound materials, especially the notoriously brittle -bound materials of the late nineteenth century. These are precious -cultural artifacts, however, as well as interesting sources of -information, and LC desires to retain and conserve them. AM needs to -handle things without damaging them. Guillotining a book to run it -through a sheet feeder must be avoided at all costs. - -Beyond physical problems, issues pertaining to quality arose. For -example, the desire to provide users with a searchable text is affected -by the question of acceptable level of accuracy. One hundred percent -accuracy is tremendously expensive. On the other hand, the output of -optical character recognition (OCR) can be tremendously inaccurate. -Although AM has attempted to find a middle ground, uncertainty persists -as to whether or not it has discovered the right solution. - -Questions of quality arose concerning images as well. FLEISCHHAUER -contrasted the extremely high level of quality of the digital images in -the Cornell Xerox Project with AM's efforts to provide a browse-quality -or access-quality image, as opposed to an archival or preservation image. -FLEISCHHAUER therefore welcomed the opportunity to compare notes. - -FLEISCHHAUER observed in passing that conversations he had had about -networks have begun to signal that for various forms of media a -determination may be made that there is a browse-quality item, or a -distribution-and-access-quality item that may coexist in some systems -with a higher quality archival item that would be inconvenient to send -through the network because of its size. FLEISCHHAUER referred, of -course, to images more than to searchable text. - -As AM considered those questions, several conceptual issues arose: ought -AM occasionally to reproduce materials entirely through an image set, at -other times, entirely through a text set, and in some cases, a mix? -There probably would be times when the historical authenticity of an -artifact would require that its image be used. An image might be -desirable as a recourse for users if one could not provide 100-percent -accurate text. Again, AM wondered, as a practical matter, if a -distinction could be drawn between rare printed matter that might exist -in multiple collections--that is, in ten or fifteen libraries. In such -cases, the need for perfect reproduction would be less than for unique -items. Implicit in his remarks, FLEISCHHAUER conceded, was the admission -that AM has been tilting strongly towards quantity and drawing back a -little from perfect quality. That is, it seemed to AM that society would -be better served if more things were distributed by LC--even if they were -not quite perfect--than if fewer things, perfectly represented, were -distributed. This was stated as a proposition to be tested, with -responses to be gathered from users. - -In thinking about issues related to reproduction of materials and seeing -other people engaged in parallel activities, AM deemed it useful to -convene a conference. Hence, the Workshop. FLEISCHHAUER thereupon -surveyed the several groups represented: 1) the world of images (image -users and image makers); 2) the world of text and scholarship and, within -this group, those concerned with language--FLEISCHHAUER confessed to finding -delightful irony in the fact that some of the most advanced thinkers on -computerized texts are those dealing with ancient Greek and Roman materials; -3) the network world; and 4) the general world of library science, which -includes people interested in preservation and cataloging. - -FLEISCHHAUER concluded his remarks with special thanks to the David and -Lucile Packard Foundation for its support of the meeting, the American -Memory group, the Office for Scholarly Programs, the National -Demonstration Lab, and the Office of Special Events. He expressed the -hope that David Woodley Packard might be able to attend, noting that -Packard's work and the work of the foundation had sponsored a number of -projects in the text area. - - ****** - -SESSION I. CONTENT IN A NEW FORM: WHO WILL USE IT AND WHAT WILL THEY DO? - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -DALY * Acknowledgements * A new Latin authors disk * Effects of the new -technology on previous methods of research * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Serving as moderator, James DALY acknowledged the generosity of all the -presenters for giving of their time, counsel, and patience in planning -the Workshop, as well as of members of the American Memory project and -other Library of Congress staff, and the David and Lucile Packard -Foundation and its executive director, Colburn S. Wilbur. - -DALY then recounted his visit in March to the Center for Electronic Texts -in the Humanities (CETH) and the Department of Classics at Rutgers -University, where an old friend, Lowell Edmunds, introduced him to the -department's IBYCUS scholarly personal computer, and, in particular, the -new Latin CD-ROM, containing, among other things, almost all classical -Latin literary texts through A.D. 200. Packard Humanities Institute -(PHI), Los Altos, California, released this disk late in 1991, with a -nominal triennial licensing fee. - -Playing with the disk for an hour or so at Rutgers brought home to DALY -at once the revolutionizing impact of the new technology on his previous -methods of research. Had this disk been available two or three years -earlier, DALY contended, when he was engaged in preparing a commentary on -Book 10 of Virgil's Aeneid for Cambridge University Press, he would not -have required a forty-eight-square-foot table on which to spread the -numerous, most frequently consulted items, including some ten or twelve -concordances to key Latin authors, an almost equal number of lexica to -authors who lacked concordances, and where either lexica or concordances -were lacking, numerous editions of authors antedating and postdating Virgil. - -Nor, when checking each of the average six to seven words contained in -the Virgilian hexameter for its usage elsewhere in Virgil's works or -other Latin authors, would DALY have had to maintain the laborious -mechanical process of flipping through these concordances, lexica, and -editions each time. Nor would he have had to frequent as often the -Milton S. Eisenhower Library at the Johns Hopkins University to consult -the Thesaurus Linguae Latinae. Instead of devoting countless hours, or -the bulk of his research time, to gathering data concerning Virgil's use -of words, DALY--now freed by PHI's Latin authors disk from the -tyrannical, yet in some ways paradoxically happy scholarly drudgery-- -would have been able to devote that same bulk of time to analyzing and -interpreting Virgilian verbal usage. - -Citing Theodore Brunner, Gregory Crane, Elli MYLONAS, and Avra MICHELSON, -DALY argued that this reversal in his style of work, made possible by the -new technology, would perhaps have resulted in better, more productive -research. Indeed, even in the course of his browsing the Latin authors -disk at Rutgers, its powerful search, retrieval, and highlighting -capabilities suggested to him several new avenues of research into -Virgil's use of sound effects. This anecdotal account, DALY maintained, -may serve to illustrate in part the sudden and radical transformation -being wrought in the ways scholars work. - - ****** - -++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -MICHELSON * Elements related to scholarship and technology * Electronic -texts within the context of broader trends within information technology -and scholarly communication * Evaluation of the prospects for the use of -electronic texts * Relationship of electronic texts to processes of -scholarly communication in humanities research * New exchange formats -created by scholars * Projects initiated to increase scholarly access to -converted text * Trend toward making electronic resources available -through research and education networks * Changes taking place in -scholarly communication among humanities scholars * Network-mediated -scholarship transforming traditional scholarly practices * Key -information technology trends affecting the conduct of scholarly -communication over the next decade * The trend toward end-user computing -* The trend toward greater connectivity * Effects of these trends * Key -transformations taking place * Summary of principal arguments * -++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Avra MICHELSON, Archival Research and Evaluation Staff, National Archives -and Records Administration (NARA), argued that establishing who will use -electronic texts and what they will use them for involves a consideration -of both information technology and scholarship trends. This -consideration includes several elements related to scholarship and -technology: 1) the key trends in information technology that are most -relevant to scholarship; 2) the key trends in the use of currently -available technology by scholars in the nonscientific community; and 3) -the relationship between these two very distinct but interrelated trends. -The investment in understanding this relationship being made by -information providers, technologists, and public policy developers, as -well as by scholars themselves, seems to be pervasive and growing, -MICHELSON contended. She drew on collaborative work with Jeff Rothenberg -on the scholarly use of technology. - -MICHELSON sought to place the phenomenon of electronic texts within the -context of broader trends within information technology and scholarly -communication. She argued that electronic texts are of most use to -researchers to the extent that the researchers' working context (i.e., -their relevant bibliographic sources, collegial feedback, analytic tools, -notes, drafts, etc.), along with their field's primary and secondary -sources, also is accessible in electronic form and can be integrated in -ways that are unique to the on-line environment. - -Evaluation of the prospects for the use of electronic texts includes two -elements: 1) an examination of the ways in which researchers currently -are using electronic texts along with other electronic resources, and 2) -an analysis of key information technology trends that are affecting the -long-term conduct of scholarly communication. MICHELSON limited her -discussion of the use of electronic texts to the practices of humanists -and noted that the scientific community was outside the panel's overview. - -MICHELSON examined the nature of the current relationship of electronic -texts in particular, and electronic resources in general, to what she -maintained were, essentially, five processes of scholarly communication -in humanities research. Researchers 1) identify sources, 2) communicate -with their colleagues, 3) interpret and analyze data, 4) disseminate -their research findings, and 5) prepare curricula to instruct the next -generation of scholars and students. This examination would produce a -clearer understanding of the synergy among these five processes that -fuels the tendency of the use of electronic resources for one process to -stimulate its use for other processes of scholarly communication. - -For the first process of scholarly communication, the identification of -sources, MICHELSON remarked the opportunity scholars now enjoy to -supplement traditional word-of-mouth searches for sources among their -colleagues with new forms of electronic searching. So, for example, -instead of having to visit the library, researchers are able to explore -descriptions of holdings in their offices. Furthermore, if their own -institutions' holdings prove insufficient, scholars can access more than -200 major American library catalogues over Internet, including the -universities of California, Michigan, Pennsylvania, and Wisconsin. -Direct access to the bibliographic databases offers intellectual -empowerment to scholars by presenting a comprehensive means of browsing -through libraries from their homes and offices at their convenience. - -The second process of communication involves communication among -scholars. Beyond the most common methods of communication, scholars are -using E-mail and a variety of new electronic communications formats -derived from it for further academic interchange. E-mail exchanges are -growing at an astonishing rate, reportedly 15 percent a month. They -currently constitute approximately half the traffic on research and -education networks. Moreover, the global spread of E-mail has been so -rapid that it is now possible for American scholars to use it to -communicate with colleagues in close to 140 other countries. - -Other new exchange formats created by scholars and operating on Internet -include more than 700 conferences, with about 80 percent of these devoted -to topics in the social sciences and humanities. The rate of growth of -these scholarly electronic conferences also is astonishing. From l990 to -l991, 200 new conferences were identified on Internet. From October 1991 -to June 1992, an additional 150 conferences in the social sciences and -humanities were added to this directory of listings. Scholars have -established conferences in virtually every field, within every different -discipline. For example, there are currently close to 600 active social -science and humanities conferences on topics such as art and -architecture, ethnomusicology, folklore, Japanese culture, medical -education, and gifted and talented education. The appeal to scholars of -communicating through these conferences is that, unlike any other medium, -electronic conferences today provide a forum for global communication -with peers at the front end of the research process. - -Interpretation and analysis of sources constitutes the third process of -scholarly communication that MICHELSON discussed in terms of texts and -textual resources. The methods used to analyze sources fall somewhere on -a continuum from quantitative analysis to qualitative analysis. -Typically, evidence is culled and evaluated using methods drawn from both -ends of this continuum. At one end, quantitative analysis involves the -use of mathematical processes such as a count of frequencies and -distributions of occurrences or, on a higher level, regression analysis. -At the other end of the continuum, qualitative analysis typically -involves nonmathematical processes oriented toward language -interpretation or the building of theory. Aspects of this work involve -the processing--either manual or computational--of large and sometimes -massive amounts of textual sources, although the use of nontextual -sources as evidence, such as photographs, sound recordings, film footage, -and artifacts, is significant as well. - -Scholars have discovered that many of the methods of interpretation and -analysis that are related to both quantitative and qualitative methods -are processes that can be performed by computers. For example, computers -can count. They can count brush strokes used in a Rembrandt painting or -perform regression analysis for understanding cause and effect. By means -of advanced technologies, computers can recognize patterns, analyze text, -and model concepts. Furthermore, computers can complete these processes -faster with more sources and with greater precision than scholars who -must rely on manual interpretation of data. But if scholars are to use -computers for these processes, source materials must be in a form -amenable to computer-assisted analysis. For this reason many scholars, -once they have identified the sources that are key to their research, are -converting them to machine-readable form. Thus, a representative example -of the numerous textual conversion projects organized by scholars around -the world in recent years to support computational text analysis is the -TLG, the Thesaurus Linguae Graecae. This project is devoted to -converting the extant ancient texts of classical Greece. (Editor's note: -according to the TLG Newsletter of May l992, TLG was in use in thirty-two -different countries. This figure updates MICHELSON's previous count by one.) - -The scholars performing these conversions have been asked to recognize -that the electronic sources they are converting for one use possess value -for other research purposes as well. As a result, during the past few -years, humanities scholars have initiated a number of projects to -increase scholarly access to converted text. So, for example, the Text -Encoding Initiative (TEI), about which more is said later in the program, -was established as an effort by scholars to determine standard elements -and methods for encoding machine-readable text for electronic exchange. -In a second effort to facilitate the sharing of converted text, scholars -have created a new institution, the Center for Electronic Texts in the -Humanities (CETH). The center estimates that there are 8,000 series of -source texts in the humanities that have been converted to -machine-readable form worldwide. CETH is undertaking an international -search for converted text in the humanities, compiling it into an -electronic library, and preparing bibliographic descriptions of the -sources for the Research Libraries Information Network's (RLIN) -machine-readable data file. The library profession has begun to initiate -large conversion projects as well, such as American Memory. - -While scholars have been making converted text available to one another, -typically on disk or on CD-ROM, the clear trend is toward making these -resources available through research and education networks. Thus, the -American and French Research on the Treasury of the French Language -(ARTFL) and the Dante Project are already available on Internet. -MICHELSON summarized this section on interpretation and analysis by -noting that: 1) increasing numbers of humanities scholars in the library -community are recognizing the importance to the advancement of -scholarship of retrospective conversion of source materials in the arts -and humanities; and 2) there is a growing realization that making the -sources available on research and education networks maximizes their -usefulness for the analysis performed by humanities scholars. - -The fourth process of scholarly communication is dissemination of -research findings, that is, publication. Scholars are using existing -research and education networks to engineer a new type of publication: -scholarly-controlled journals that are electronically produced and -disseminated. Although such journals are still emerging as a -communication format, their number has grown, from approximately twelve -to thirty-six during the past year (July 1991 to June 1992). Most of -these electronic scholarly journals are devoted to topics in the -humanities. As with network conferences, scholarly enthusiasm for these -electronic journals stems from the medium's unique ability to advance -scholarship in a way that no other medium can do by supporting global -feedback and interchange, practically in real time, early in the research -process. Beyond scholarly journals, MICHELSON remarked the delivery of -commercial full-text products, such as articles in professional journals, -newsletters, magazines, wire services, and reference sources. These are -being delivered via on-line local library catalogues, especially through -CD-ROMs. Furthermore, according to MICHELSON, there is general optimism -that the copyright and fees issues impeding the delivery of full text on -existing research and education networks soon will be resolved. - -The final process of scholarly communication is curriculum development -and instruction, and this involves the use of computer information -technologies in two areas. The first is the development of -computer-oriented instructional tools, which includes simulations, -multimedia applications, and computer tools that are used to assist in -the analysis of sources in the classroom, etc. The Perseus Project, a -database that provides a multimedia curriculum on classical Greek -civilization, is a good example of the way in which entire curricula are -being recast using information technologies. It is anticipated that the -current difficulty in exchanging electronically computer-based -instructional software, which in turn makes it difficult for one scholar -to build upon the work of others, will be resolved before too long. -Stand-alone curricular applications that involve electronic text will be -sharable through networks, reinforcing their significance as intellectual -products as well as instructional tools. - -The second aspect of electronic learning involves the use of research and -education networks for distance education programs. Such programs -interactively link teachers with students in geographically scattered -locations and rely on the availability of electronic instructional -resources. Distance education programs are gaining wide appeal among -state departments of education because of their demonstrated capacity to -bring advanced specialized course work and an array of experts to many -classrooms. A recent report found that at least 32 states operated at -least one statewide network for education in 1991, with networks under -development in many of the remaining states. - -MICHELSON summarized this section by noting two striking changes taking -place in scholarly communication among humanities scholars. First is the -extent to which electronic text in particular, and electronic resources -in general, are being infused into each of the five processes described -above. As mentioned earlier, there is a certain synergy at work here. -The use of electronic resources for one process tends to stimulate its -use for other processes, because the chief course of movement is toward a -comprehensive on-line working context for humanities scholars that -includes on-line availability of key bibliographies, scholarly feedback, -sources, analytical tools, and publications. MICHELSON noted further -that the movement toward a comprehensive on-line working context for -humanities scholars is not new. In fact, it has been underway for more -than forty years in the humanities, since Father Roberto Busa began -developing an electronic concordance of the works of Saint Thomas Aquinas -in 1949. What we are witnessing today, MICHELSON contended, is not the -beginning of this on-line transition but, for at least some humanities -scholars, the turning point in the transition from a print to an -electronic working context. Coinciding with the on-line transition, the -second striking change is the extent to which research and education -networks are becoming the new medium of scholarly communication. The -existing Internet and the pending National Education and Research Network -(NREN) represent the new meeting ground where scholars are going for -bibliographic information, scholarly dialogue and feedback, the most -current publications in their field, and high-level educational -offerings. Traditional scholarly practices are undergoing tremendous -transformations as a result of the emergence and growing prominence of -what is called network-mediated scholarship. - -MICHELSON next turned to the second element of the framework she proposed -at the outset of her talk for evaluating the prospects for electronic -text, namely the key information technology trends affecting the conduct -of scholarly communication over the next decade: 1) end-user computing -and 2) connectivity. - -End-user computing means that the person touching the keyboard, or -performing computations, is the same as the person who initiates or -consumes the computation. The emergence of personal computers, along -with a host of other forces, such as ubiquitous computing, advances in -interface design, and the on-line transition, is prompting the consumers -of computation to do their own computing, and is thus rendering obsolete -the traditional distinction between end users and ultimate users. - -The trend toward end-user computing is significant to consideration of -the prospects for electronic texts because it means that researchers are -becoming more adept at doing their own computations and, thus, more -competent in the use of electronic media. By avoiding programmer -intermediaries, computation is becoming central to the researcher's -thought process. This direct involvement in computing is changing the -researcher's perspective on the nature of research itself, that is, the -kinds of questions that can be posed, the analytical methodologies that -can be used, the types and amount of sources that are appropriate for -analyses, and the form in which findings are presented. The trend toward -end-user computing means that, increasingly, electronic media and -computation are being infused into all processes of humanities -scholarship, inspiring remarkable transformations in scholarly -communication. - -The trend toward greater connectivity suggests that researchers are using -computation increasingly in network environments. Connectivity is -important to scholarship because it erases the distance that separates -students from teachers and scholars from their colleagues, while allowing -users to access remote databases, share information in many different -media, connect to their working context wherever they are, and -collaborate in all phases of research. - -The combination of the trend toward end-user computing and the trend -toward connectivity suggests that the scholarly use of electronic -resources, already evident among some researchers, will soon become an -established feature of scholarship. The effects of these trends, along -with ongoing changes in scholarly practices, point to a future in which -humanities researchers will use computation and electronic communication -to help them formulate ideas, access sources, perform research, -collaborate with colleagues, seek peer review, publish and disseminate -results, and engage in many other professional and educational activities. - -In summary, MICHELSON emphasized four points: 1) A portion of humanities -scholars already consider electronic texts the preferred format for -analysis and dissemination. 2) Scholars are using these electronic -texts, in conjunction with other electronic resources, in all the -processes of scholarly communication. 3) The humanities scholars' -working context is in the process of changing from print technology to -electronic technology, in many ways mirroring transformations that have -occurred or are occurring within the scientific community. 4) These -changes are occurring in conjunction with the development of a new -communication medium: research and education networks that are -characterized by their capacity to advance scholarship in a wholly unique -way. - -MICHELSON also reiterated her three principal arguments: l) Electronic -texts are best understood in terms of the relationship to other -electronic resources and the growing prominence of network-mediated -scholarship. 2) The prospects for electronic texts lie in their capacity -to be integrated into the on-line network of electronic resources that -comprise the new working context for scholars. 3) Retrospective conversion -of portions of the scholarly record should be a key strategy as information -providers respond to changes in scholarly communication practices. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -VECCIA * AM's evaluation project and public users of electronic resources -* AM and its design * Site selection and evaluating the Macintosh -implementation of AM * Characteristics of the six public libraries -selected * Characteristics of AM's users in these libraries * Principal -ways AM is being used * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Susan VECCIA, team leader, and Joanne FREEMAN, associate coordinator, -American Memory, Library of Congress, gave a joint presentation. First, -by way of introduction, VECCIA explained her and FREEMAN's roles in -American Memory (AM). Serving principally as an observer, VECCIA has -assisted with the evaluation project of AM, placing AM collections in a -variety of different sites around the country and helping to organize and -implement that project. FREEMAN has been an associate coordinator of AM -and has been involved principally with the interpretative materials, -preparing some of the electronic exhibits and printed historical -information that accompanies AM and that is requested by users. VECCIA -and FREEMAN shared anecdotal observations concerning AM with public users -of electronic resources. Notwithstanding a fairly structured evaluation -in progress, both VECCIA and FREEMAN chose not to report on specifics in -terms of numbers, etc., because they felt it was too early in the -evaluation project to do so. - -AM is an electronic archive of primary source materials from the Library -of Congress, selected collections representing a variety of formats-- -photographs, graphic arts, recorded sound, motion pictures, broadsides, -and soon, pamphlets and books. In terms of the design of this system, -the interpretative exhibits have been kept separate from the primary -resources, with good reason. Accompanying this collection are printed -documentation and user guides, as well as guides that FREEMAN prepared for -teachers so that they may begin using the content of the system at once. - -VECCIA described the evaluation project before talking about the public -users of AM, limiting her remarks to public libraries, because FREEMAN -would talk more specifically about schools from kindergarten to twelfth -grade (K-12). Having started in spring 1991, the evaluation currently -involves testing of the Macintosh implementation of AM. Since the -primary goal of this evaluation is to determine the most appropriate -audience or audiences for AM, very different sites were selected. This -makes evaluation difficult because of the varying degrees of technology -literacy among the sites. AM is situated in forty-four locations, of -which six are public libraries and sixteen are schools. Represented -among the schools are elementary, junior high, and high schools. -District offices also are involved in the evaluation, which will -conclude in summer 1993. - -VECCIA focused the remainder of her talk on the six public libraries, one -of which doubles as a state library. They represent a range of -geographic areas and a range of demographic characteristics. For -example, three are located in urban settings, two in rural settings, and -one in a suburban setting. A range of technical expertise is to be found -among these facilities as well. For example, one is an "Apple library of -the future," while two others are rural one-room libraries--in one, AM -sits at the front desk next to a tractor manual. - -All public libraries have been extremely enthusiastic, supportive, and -appreciative of the work that AM has been doing. VECCIA characterized -various users: Most users in public libraries describe themselves as -general readers; of the students who use AM in the public libraries, -those in fourth grade and above seem most interested. Public libraries -in rural sites tend to attract retired people, who have been highly -receptive to AM. Users tend to fall into two additional categories: -people interested in the content and historical connotations of these -primary resources, and those fascinated by the technology. The format -receiving the most comments has been motion pictures. The adult users in -public libraries are more comfortable with IBM computers, whereas young -people seem comfortable with either IBM or Macintosh, although most of -them seem to come from a Macintosh background. This same tendency is -found in the schools. - -What kinds of things do users do with AM? In a public library there are -two main goals or ways that AM is being used: as an individual learning -tool, and as a leisure activity. Adult learning was one area that VECCIA -would highlight as a possible application for a tool such as AM. She -described a patron of a rural public library who comes in every day on -his lunch hour and literally reads AM, methodically going through the -collection image by image. At the end of his hour he makes an electronic -bookmark, puts it in his pocket, and returns to work. The next day he -comes in and resumes where he left off. Interestingly, this man had -never been in the library before he used AM. In another small, rural -library, the coordinator reports that AM is a popular activity for some -of the older, retired people in the community, who ordinarily would not -use "those things,"--computers. Another example of adult learning in -public libraries is book groups, one of which, in particular, is using AM -as part of its reading on industrialization, integration, and urbanization -in the early 1900s. - -One library reports that a family is using AM to help educate their -children. In another instance, individuals from a local museum came in -to use AM to prepare an exhibit on toys of the past. These two examples -emphasize the mission of the public library as a cultural institution, -reaching out to people who do not have the same resources available to -those who live in a metropolitan area or have access to a major library. -One rural library reports that junior high school students in large -numbers came in one afternoon to use AM for entertainment. A number of -public libraries reported great interest among postcard collectors in the -Detroit collection, which was essentially a collection of images used on -postcards around the turn of the century. Train buffs are similarly -interested because that was a time of great interest in railroading. -People, it was found, relate to things that they know of firsthand. For -example, in both rural public libraries where AM was made available, -observers reported that the older people with personal remembrances of -the turn of the century were gravitating to the Detroit collection. -These examples served to underscore MICHELSON's observation re the -integration of electronic tools and ideas--that people learn best when -the material relates to something they know. - -VECCIA made the final point that in many cases AM serves as a -public-relations tool for the public libraries that are testing it. In -one case, AM is being used as a vehicle to secure additional funding for -the library. In another case, AM has served as an inspiration to the -staff of a major local public library in the South to think about ways to -make its own collection of photographs more accessible to the public. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -FREEMAN * AM and archival electronic resources in a school environment * -Questions concerning context * Questions concerning the electronic format -itself * Computer anxiety * Access and availability of the system * -Hardware * Strengths gained through the use of archival resources in -schools * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Reiterating an observation made by VECCIA, that AM is an archival -resource made up of primary materials with very little interpretation, -FREEMAN stated that the project has attempted to bridge the gap between -these bare primary materials and a school environment, and in that cause -has created guided introductions to AM collections. Loud demand from the -educational community, chiefly from teachers working with the upper -grades of elementary school through high school, greeted the announcement -that AM would be tested around the country. - -FREEMAN reported not only on what was learned about AM in a school -environment, but also on several universal questions that were raised -concerning archival electronic resources in schools. She discussed -several strengths of this type of material in a school environment as -opposed to a highly structured resource that offers a limited number of -paths to follow. - -FREEMAN first raised several questions about using AM in a school -environment. There is often some difficulty in developing a sense of -what the system contains. Many students sit down at a computer resource -and assume that, because AM comes from the Library of Congress, all of -American history is now at their fingertips. As a result of that sort of -mistaken judgment, some students are known to conclude that AM contains -nothing of use to them when they look for one or two things and do not -find them. It is difficult to discover that middle ground where one has -a sense of what the system contains. Some students grope toward the idea -of an archive, a new idea to them, since they have not previously -experienced what it means to have access to a vast body of somewhat -random information. - -Other questions raised by FREEMAN concerned the electronic format itself. -For instance, in a school environment it is often difficult both for -teachers and students to gain a sense of what it is they are viewing. -They understand that it is a visual image, but they do not necessarily -know that it is a postcard from the turn of the century, a panoramic -photograph, or even machine-readable text of an eighteenth-century -broadside, a twentieth-century printed book, or a nineteenth-century -diary. That distinction is often difficult for people in a school -environment to grasp. Because of that, it occasionally becomes difficult -to draw conclusions from what one is viewing. - -FREEMAN also noted the obvious fear of the computer, which constitutes a -difficulty in using an electronic resource. Though students in general -did not suffer from this anxiety, several older students feared that they -were computer-illiterate, an assumption that became self-fulfilling when -they searched for something but failed to find it. FREEMAN said she -believed that some teachers also fear computer resources, because they -believe they lack complete control. FREEMAN related the example of -teachers shooing away students because it was not their time to use the -system. This was a case in which the situation had to be extremely -structured so that the teachers would not feel that they had lost their -grasp on what the system contained. - -A final question raised by FREEMAN concerned access and availability of -the system. She noted the occasional existence of a gap in communication -between school librarians and teachers. Often AM sits in a school -library and the librarian is the person responsible for monitoring the -system. Teachers do not always take into their world new library -resources about which the librarian is excited. Indeed, at the sites -where AM had been used most effectively within a library, the librarian -was required to go to specific teachers and instruct them in its use. As -a result, several AM sites will have in-service sessions over a summer, -in the hope that perhaps, with a more individualized link, teachers will -be more likely to use the resource. - -A related issue in the school context concerned the number of -workstations available at any one location. Centralization of equipment -at the district level, with teachers invited to download things and walk -away with them, proved unsuccessful because the hours these offices were -open were also school hours. - -Another issue was hardware. As VECCIA observed, a range of sites exists, -some technologically advanced and others essentially acquiring their -first computer for the primary purpose of using it in conjunction with -AM's testing. Users at technologically sophisticated sites want even -more sophisticated hardware, so that they can perform even more -sophisticated tasks with the materials in AM. But once they acquire a -newer piece of hardware, they must learn how to use that also; at an -unsophisticated site it takes an extremely long time simply to become -accustomed to the computer, not to mention the program offered with the -computer. All of these small issues raise one large question, namely, -are systems like AM truly rewarding in a school environment, or do they -simply act as innovative toys that do little more than spark interest? - -FREEMAN contended that the evaluation project has revealed several strengths -that were gained through the use of archival resources in schools, including: - - * Psychic rewards from using AM as a vast, rich database, with - teachers assigning various projects to students--oral presentations, - written reports, a documentary, a turn-of-the-century newspaper-- - projects that start with the materials in AM but are completed using - other resources; AM thus is used as a research tool in conjunction - with other electronic resources, as well as with books and items in - the library where the system is set up. - - * Students are acquiring computer literacy in a humanities context. - - * This sort of system is overcoming the isolation between disciplines - that often exists in schools. For example, many English teachers are - requiring their students to write papers on historical topics - represented in AM. Numerous teachers have reported that their - students are learning critical thinking skills using the system. - - * On a broader level, AM is introducing primary materials, not only - to students but also to teachers, in an environment where often - simply none exist--an exciting thing for the students because it - helps them learn to conduct research, to interpret, and to draw - their own conclusions. In learning to conduct research and what it - means, students are motivated to seek knowledge. That relates to - another positive outcome--a high level of personal involvement of - students with the materials in this system and greater motivation to - conduct their own research and draw their own conclusions. - - * Perhaps the most ironic strength of these kinds of archival - electronic resources is that many of the teachers AM interviewed - were desperate, it is no exaggeration to say, not only for primary - materials but for unstructured primary materials. These would, they - thought, foster personally motivated research, exploration, and - excitement in their students. Indeed, these materials have done - just that. Ironically, however, this lack of structure produces - some of the confusion to which the newness of these kinds of - resources may also contribute. The key to effective use of archival - products in a school environment is a clear, effective introduction - to the system and to what it contains. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -DISCUSSION * Nothing known, quantitatively, about the number of -humanities scholars who must see the original versus those who would -settle for an edited transcript, or about the ways in which humanities -scholars are using information technology * Firm conclusions concerning -the manner and extent of the use of supporting materials in print -provided by AM to await completion of evaluative study * A listener's -reflections on additional applications of electronic texts * Role of -electronic resources in teaching elementary research skills to students * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -During the discussion that followed the presentations by MICHELSON, -VECCIA, and FREEMAN, additional points emerged. - -LESK asked if MICHELSON could give any quantitative estimate of the -number of humanities scholars who must see or want to see the original, -or the best possible version of the material, versus those who typically -would settle for an edited transcript. While unable to provide a figure, -she offered her impressions as an archivist who has done some reference -work and has discussed this issue with other archivists who perform -reference, that those who use archives and those who use primary sources -for what would be considered very high-level scholarly research, as -opposed to, say, undergraduate papers, were few in number, especially -given the public interest in using primary sources to conduct -genealogical or avocational research and the kind of professional -research done by people in private industry or the federal government. -More important in MICHELSON's view was that, quantitatively, nothing is -known about the ways in which, for example, humanities scholars are using -information technology. No studies exist to offer guidance in creating -strategies. The most recent study was conducted in 1985 by the American -Council of Learned Societies (ACLS), and what it showed was that 50 -percent of humanities scholars at that time were using computers. That -constitutes the extent of our knowledge. - -Concerning AM's strategy for orienting people toward the scope of -electronic resources, FREEMAN could offer no hard conclusions at this -point, because she and her colleagues were still waiting to see, -particularly in the schools, what has been made of their efforts. Within -the system, however, AM has provided what are called electronic exhibits- --such as introductions to time periods and materials--and these are -intended to offer a student user a sense of what a broadside is and what -it might tell her or him. But FREEMAN conceded that the project staff -would have to talk with students next year, after teachers have had a -summer to use the materials, and attempt to discover what the students -were learning from the materials. In addition, FREEMAN described -supporting materials in print provided by AM at the request of local -teachers during a meeting held at LC. These included time lines, -bibliographies, and other materials that could be reproduced on a -photocopier in a classroom. Teachers could walk away with and use these, -and in this way gain a better understanding of the contents. But again, -reaching firm conclusions concerning the manner and extent of their use -would have to wait until next year. - -As to the changes she saw occurring at the National Archives and Records -Administration (NARA) as a result of the increasing emphasis on -technology in scholarly research, MICHELSON stated that NARA at this -point was absorbing the report by her and Jeff Rothenberg addressing -strategies for the archival profession in general, although not for the -National Archives specifically. NARA is just beginning to establish its -role and what it can do. In terms of changes and initiatives that NARA -can take, no clear response could be given at this time. - -GREENFIELD remarked two trends mentioned in the session. Reflecting on -DALY's opening comments on how he could have used a Latin collection of -text in an electronic form, he said that at first he thought most scholars -would be unwilling to do that. But as he thought of that in terms of the -original meaning of research--that is, having already mastered these texts, -researching them for critical and comparative purposes--for the first time, -the electronic format made a lot of sense. GREENFIELD could envision -growing numbers of scholars learning the new technologies for that very -aspect of their scholarship and for convenience's sake. - -Listening to VECCIA and FREEMAN, GREENFIELD thought of an additional -application of electronic texts. He realized that AM could be used as a -guide to lead someone to original sources. Students cannot be expected -to have mastered these sources, things they have never known about -before. Thus, AM is leading them, in theory, to a vast body of -information and giving them a superficial overview of it, enabling them -to select parts of it. GREENFIELD asked if any evidence exists that this -resource will indeed teach the new user, the K-12 students, how to do -research. Scholars already know how to do research and are applying -these new tools. But he wondered why students would go beyond picking -out things that were most exciting to them. - -FREEMAN conceded the correctness of GREENFIELD's observation as applied -to a school environment. The risk is that a student would sit down at a -system, play with it, find some things of interest, and then walk away. -But in the relatively controlled situation of a school library, much will -depend on the instructions a teacher or a librarian gives a student. She -viewed the situation not as one of fine-tuning research skills but of -involving students at a personal level in understanding and researching -things. Given the guidance one can receive at school, it then becomes -possible to teach elementary research skills to students, which in fact -one particular librarian said she was teaching her fifth graders. -FREEMAN concluded that introducing the idea of following one's own path -of inquiry, which is essentially what research entails, involves more -than teaching specific skills. To these comments VECCIA added the -observation that the individual teacher and the use of a creative -resource, rather than AM itself, seemed to make the key difference. -Some schools and some teachers are making excellent use of the nature -of critical thinking and teaching skills, she said. - -Concurring with these remarks, DALY closed the session with the thought that -the more that producers produced for teachers and for scholars to use with -their students, the more successful their electronic products would prove. - - ****** - -SESSION II. SHOW AND TELL - -Jacqueline HESS, director, National Demonstration Laboratory, served as -moderator of the "show-and-tell" session. She noted that a -question-and-answer period would follow each presentation. - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -MYLONAS * Overview and content of Perseus * Perseus' primary materials -exist in a system-independent, archival form * A concession * Textual -aspects of Perseus * Tools to use with the Greek text * Prepared indices -and full-text searches in Perseus * English-Greek word search leads to -close study of words and concepts * Navigating Perseus by tracing down -indices * Using the iconography to perform research * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Elli MYLONAS, managing editor, Perseus Project, Harvard University, first -gave an overview of Perseus, a large, collaborative effort based at -Harvard University but with contributors and collaborators located at -numerous universities and colleges in the United States (e.g., Bowdoin, -Maryland, Pomona, Chicago, Virginia). Funded primarily by the -Annenberg/CPB Project, with additional funding from Apple, Harvard, and -the Packard Humanities Institute, among others, Perseus is a multimedia, -hypertextual database for teaching and research on classical Greek -civilization, which was released in February 1992 in version 1.0 and -distributed by Yale University Press. - -Consisting entirely of primary materials, Perseus includes ancient Greek -texts and translations of those texts; catalog entries--that is, museum -catalog entries, not library catalog entries--on vases, sites, coins, -sculpture, and archaeological objects; maps; and a dictionary, among -other sources. The number of objects and the objects for which catalog -entries exist are accompanied by thousands of color images, which -constitute a major feature of the database. Perseus contains -approximately 30 megabytes of text, an amount that will double in -subsequent versions. In addition to these primary materials, the Perseus -Project has been building tools for using them, making access and -navigation easier, the goal being to build part of the electronic -environment discussed earlier in the morning in which students or -scholars can work with their sources. - -The demonstration of Perseus will show only a fraction of the real work -that has gone into it, because the project had to face the dilemma of -what to enter when putting something into machine-readable form: should -one aim for very high quality or make concessions in order to get the -material in? Since Perseus decided to opt for very high quality, all of -its primary materials exist in a system-independent--insofar as it is -possible to be system-independent--archival form. Deciding what that -archival form would be and attaining it required much work and thought. -For example, all the texts are marked up in SGML, which will be made -compatible with the guidelines of the Text Encoding Initiative (TEI) when -they are issued. - -Drawings are postscript files, not meeting international standards, but -at least designed to go across platforms. Images, or rather the real -archival forms, consist of the best available slides, which are being -digitized. Much of the catalog material exists in database form--a form -that the average user could use, manipulate, and display on a personal -computer, but only at great cost. Thus, this is where the concession -comes in: All of this rich, well-marked-up information is stripped of -much of its content; the images are converted into bit-maps and the text -into small formatted chunks. All this information can then be imported -into HyperCard and run on a mid-range Macintosh, which is what Perseus -users have. This fact has made it possible for Perseus to attain wide -use fairly rapidly. Without those archival forms the HyperCard version -being demonstrated could not be made easily, and the project could not -have the potential to move to other forms and machines and software as -they appear, none of which information is in Perseus on the CD. - -Of the numerous multimedia aspects of Perseus, MYLONAS focused on the -textual. Part of what makes Perseus such a pleasure to use, MYLONAS -said, is this effort at seamless integration and the ability to move -around both visual and textual material. Perseus also made the decision -not to attempt to interpret its material any more than one interprets by -selecting. But, MYLONAS emphasized, Perseus is not courseware: No -syllabus exists. There is no effort to define how one teaches a topic -using Perseus, although the project may eventually collect papers by -people who have used it to teach. Rather, Perseus aims to provide -primary material in a kind of electronic library, an electronic sandbox, -so to say, in which students and scholars who are working on this -material can explore by themselves. With that, MYLONAS demonstrated -Perseus, beginning with the Perseus gateway, the first thing one sees -upon opening Perseus--an effort in part to solve the contextualizing -problem--which tells the user what the system contains. - -MYLONAS demonstrated only a very small portion, beginning with primary -texts and running off the CD-ROM. Having selected Aeschylus' Prometheus -Bound, which was viewable in Greek and English pretty much in the same -segments together, MYLONAS demonstrated tools to use with the Greek text, -something not possible with a book: looking up the dictionary entry form -of an unfamiliar word in Greek after subjecting it to Perseus' -morphological analysis for all the texts. After finding out about a -word, a user may then decide to see if it is used anywhere else in Greek. -Because vast amounts of indexing support all of the primary material, one -can find out where else all forms of a particular Greek word appear-- -often not a trivial matter because Greek is highly inflected. Further, -since the story of Prometheus has to do with the origins of sacrifice, a -user may wish to study and explore sacrifice in Greek literature; by -typing sacrifice into a small window, a user goes to the English-Greek -word list--something one cannot do without the computer (Perseus has -indexed the definitions of its dictionary)--the string sacrifice appears -in the definitions of these sixty-five words. One may then find out -where any of those words is used in the work(s) of a particular author. -The English definitions are not lemmatized. - -All of the indices driving this kind of usage were originally devised for -speed, MYLONAS observed; in other words, all that kind of information-- -all forms of all words, where they exist, the dictionary form they belong -to--were collected into databases, which will expedite searching. Then -it was discovered that one can do things searching in these databases -that could not be done searching in the full texts. Thus, although there -are full-text searches in Perseus, much of the work is done behind the -scenes, using prepared indices. Re the indexing that is done behind the -scenes, MYLONAS pointed out that without the SGML forms of the text, it -could not be done effectively. Much of this indexing is based on the -structures that are made explicit by the SGML tagging. - -It was found that one of the things many of Perseus' non-Greek-reading -users do is start from the dictionary and then move into the close study -of words and concepts via this kind of English-Greek word search, by which -means they might select a concept. This exercise has been assigned to -students in core courses at Harvard--to study a concept by looking for the -English word in the dictionary, finding the Greek words, and then finding -the words in the Greek but, of course, reading across in the English. -That tells them a great deal about what a translation means as well. - -Should one also wish to see images that have to do with sacrifice, that -person would go to the object key word search, which allows one to -perform a similar kind of index retrieval on the database of -archaeological objects. Without words, pictures are useless; Perseus has -not reached the point where it can do much with images that are not -cataloged. Thus, although it is possible in Perseus with text and images -to navigate by knowing where one wants to end up--for example, a -red-figure vase from the Boston Museum of Fine Arts--one can perform this -kind of navigation very easily by tracing down indices. MYLONAS -illustrated several generic scenes of sacrifice on vases. The features -demonstrated derived from Perseus 1.0; version 2.0 will implement even -better means of retrieval. - -MYLONAS closed by looking at one of the pictures and noting again that -one can do a great deal of research using the iconography as well as the -texts. For instance, students in a core course at Harvard this year were -highly interested in Greek concepts of foreigners and representations of -non-Greeks. So they performed a great deal of research, both with texts -(e.g., Herodotus) and with iconography on vases and coins, on how the -Greeks portrayed non-Greeks. At the same time, art historians who study -iconography were also interested, and were able to use this material. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -DISCUSSION * Indexing and searchability of all English words in Perseus * -Several features of Perseus 1.0 * Several levels of customization -possible * Perseus used for general education * Perseus' effects on -education * Contextual information in Perseus * Main challenge and -emphasis of Perseus * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Several points emerged in the discussion that followed MYLONAS's presentation. - -Although MYLONAS had not demonstrated Perseus' ability to cross-search -documents, she confirmed that all English words in Perseus are indexed -and can be searched. So, for example, sacrifice could have been searched -in all texts, the historical essay, and all the catalogue entries with -their descriptions--in short, in all of Perseus. - -Boolean logic is not in Perseus 1.0 but will be added to the next -version, although an effort is being made not to restrict Perseus to a -database in which one just performs searching, Boolean or otherwise. It -is possible to move laterally through the documents by selecting a word -one is interested in and selecting an area of information one is -interested in and trying to look that word up in that area. - -Since Perseus was developed in HyperCard, several levels of customization -are possible. Simple authoring tools exist that allow one to create -annotated paths through the information, which are useful for note-taking -and for guided tours for teaching purposes and for expository writing. -With a little more ingenuity it is possible to begin to add or substitute -material in Perseus. - -Perseus has not been used so much for classics education as for general -education, where it seemed to have an impact on the students in the core -course at Harvard (a general required course that students must take in -certain areas). Students were able to use primary material much more. - -The Perseus Project has an evaluation team at the University of Maryland -that has been documenting Perseus' effects on education. Perseus is very -popular, and anecdotal evidence indicates that it is having an effect at -places other than Harvard, for example, test sites at Ball State -University, Drury College, and numerous small places where opportunities -to use vast amounts of primary data may not exist. One documented effect -is that archaeological, anthropological, and philological research is -being done by the same person instead of by three different people. - -The contextual information in Perseus includes an overview essay, a -fairly linear historical essay on the fifth century B.C. that provides -links into the primary material (e.g., Herodotus, Thucydides, and -Plutarch), via small gray underscoring (on the screen) of linked -passages. These are handmade links into other material. - -To different extents, most of the production work was done at Harvard, -where the people and the equipment are located. Much of the -collaborative activity involved data collection and structuring, because -the main challenge and the emphasis of Perseus is the gathering of -primary material, that is, building a useful environment for studying -classical Greece, collecting data, and making it useful. -Systems-building is definitely not the main concern. Thus, much of the -work has involved writing essays, collecting information, rewriting it, -and tagging it. That can be done off site. The creative link for the -overview essay as well as for both systems and data was collaborative, -and was forged via E-mail and paper mail with professors at Pomona and -Bowdoin. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -CALALUCA * PLD's principal focus and contribution to scholarship * -Various questions preparatory to beginning the project * Basis for -project * Basic rule in converting PLD * Concerning the images in PLD * -Running PLD under a variety of retrieval softwares * Encoding the -database a hard-fought issue * Various features demonstrated * Importance -of user documentation * Limitations of the CD-ROM version * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Eric CALALUCA, vice president, Chadwyck-Healey, Inc., demonstrated a -software interpretation of the Patrologia Latina Database (PLD). PLD's -principal focus from the beginning of the project about three-and-a-half -years ago was on converting Migne's Latin series, and in the end, -CALALUCA suggested, conversion of the text will be the major contribution -to scholarship. CALALUCA stressed that, as possibly the only private -publishing organization at the Workshop, Chadwyck-Healey had sought no -federal funds or national foundation support before embarking upon the -project, but instead had relied upon a great deal of homework and -marketing to accomplish the task of conversion. - -Ever since the possibilities of computer-searching have emerged, scholars -in the field of late ancient and early medieval studies (philosophers, -theologians, classicists, and those studying the history of natural law -and the history of the legal development of Western civilization) have -been longing for a fully searchable version of Western literature, for -example, all the texts of Augustine and Bernard of Clairvaux and -Boethius, not to mention all the secondary and tertiary authors. - -Various questions arose, CALALUCA said. Should one convert Migne? -Should the database be encoded? Is it necessary to do that? How should -it be delivered? What about CD-ROM? Since this is a transitional -medium, why even bother to create software to run on a CD-ROM? Since -everybody knows people will be networking information, why go to the -trouble--which is far greater with CD-ROM than with the production of -magnetic data? Finally, how does one make the data available? Can many -of the hurdles to using electronic information that some publishers have -imposed upon databases be eliminated? - -The PLD project was based on the principle that computer-searching of -texts is most effective when it is done with a large database. Because -PLD represented a collection that serves so many disciplines across so -many periods, it was irresistible. - -The basic rule in converting PLD was to do no harm, to avoid the sins of -intrusion in such a database: no introduction of newer editions, no -on-the-spot changes, no eradicating of all possible falsehoods from an -edition. Thus, PLD is not the final act in electronic publishing for -this discipline, but simply the beginning. The conversion of PLD has -evoked numerous unanticipated questions: How will information be used? -What about networking? Can the rights of a database be protected? -Should one protect the rights of a database? How can it be made -available? - -Those converting PLD also tried to avoid the sins of omission, that is, -excluding portions of the collections or whole sections. What about the -images? PLD is full of images, some are extremely pious -nineteenth-century representations of the Fathers, while others contain -highly interesting elements. The goal was to cover all the text of Migne -(including notes, in Greek and in Hebrew, the latter of which, in -particular, causes problems in creating a search structure), all the -indices, and even the images, which are being scanned in separately -searchable files. - -Several North American institutions that have placed acquisition requests -for the PLD database have requested it in magnetic form without software, -which means they are already running it without software, without -anything demonstrated at the Workshop. - -What cannot practically be done is go back and reconvert and re-encode -data, a time-consuming and extremely costly enterprise. CALALUCA sees -PLD as a database that can, and should, be run under a variety of -retrieval softwares. This will permit the widest possible searches. -Consequently, the need to produce a CD-ROM of PLD, as well as to develop -software that could handle some 1.3 gigabyte of heavily encoded text, -developed out of conversations with collection development and reference -librarians who wanted software both compassionate enough for the -pedestrian but also capable of incorporating the most detailed -lexicographical studies that a user desires to conduct. In the end, the -encoding and conversion of the data will prove the most enduring -testament to the value of the project. - -The encoding of the database was also a hard-fought issue: Did the -database need to be encoded? Were there normative structures for encoding -humanist texts? Should it be SGML? What about the TEI--will it last, -will it prove useful? CALALUCA expressed some minor doubts as to whether -a data bank can be fully TEI-conformant. Every effort can be made, but -in the end to be TEI-conformant means to accept the need to make some -firm encoding decisions that can, indeed, be disputed. The TEI points -the publisher in a proper direction but does not presume to make all the -decisions for him or her. Essentially, the goal of encoding was to -eliminate, as much as possible, the hindrances to information-networking, -so that if an institution acquires a database, everybody associated with -the institution can have access to it. - -CALALUCA demonstrated a portion of Volume 160, because it had the most -anomalies in it. The software was created by Electronic Book -Technologies of Providence, RI, and is called Dynatext. The software -works only with SGML-coded data. - -Viewing a table of contents on the screen, the audience saw how Dynatext -treats each element as a book and attempts to simplify movement through a -volume. Familiarity with the Patrologia in print (i.e., the text, its -source, and the editions) will make the machine-readable versions highly -useful. (Software with a Windows application was sought for PLD, -CALALUCA said, because this was the main trend for scholarly use.) - -CALALUCA also demonstrated how a user can perform a variety of searches -and quickly move to any part of a volume; the look-up screen provides -some basic, simple word-searching. - -CALALUCA argued that one of the major difficulties is not the software. -Rather, in creating a product that will be used by scholars representing -a broad spectrum of computer sophistication, user documentation proves -to be the most important service one can provide. - -CALALUCA next illustrated a truncated search under mysterium within ten -words of virtus and how one would be able to find its contents throughout -the entire database. He said that the exciting thing about PLD is that -many of the applications in the retrieval software being written for it -will exceed the capabilities of the software employed now for the CD-ROM -version. The CD-ROM faces genuine limitations, in terms of speed and -comprehensiveness, in the creation of a retrieval software to run it. -CALALUCA said he hoped that individual scholars will download the data, -if they wish, to their personal computers, and have ready access to -important texts on a constant basis, which they will be able to use in -their research and from which they might even be able to publish. - -(CALALUCA explained that the blue numbers represented Migne's column numbers, -which are the standard scholarly references. Pulling up a note, he stated -that these texts were heavily edited and the image files would appear simply -as a note as well, so that one could quickly access an image.) - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -FLEISCHHAUER/ERWAY * Several problems with which AM is still wrestling * -Various search and retrieval capabilities * Illustration of automatic -stemming and a truncated search * AM's attempt to find ways to connect -cataloging to the texts * AM's gravitation towards SGML * Striking a -balance between quantity and quality * How AM furnishes users recourse to -images * Conducting a search in a full-text environment * Macintosh and -IBM prototypes of AM * Multimedia aspects of AM * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -A demonstration of American Memory by its coordinator, Carl FLEISCHHAUER, -and Ricky ERWAY, associate coordinator, Library of Congress, concluded -the morning session. Beginning with a collection of broadsides from the -Continental Congress and the Constitutional Convention, the only text -collection in a presentable form at the time of the Workshop, FLEISCHHAUER -highlighted several of the problems with which AM is still wrestling. -(In its final form, the disk will contain two collections, not only the -broadsides but also the full text with illustrations of a set of -approximately 300 African-American pamphlets from the period 1870 to 1910.) - -As FREEMAN had explained earlier, AM has attempted to use a small amount -of interpretation to introduce collections. In the present case, the -contractor, a company named Quick Source, in Silver Spring, MD., used -software called Toolbook and put together a modestly interactive -introduction to the collection. Like the two preceding speakers, -FLEISCHHAUER argued that the real asset was the underlying collection. - -FLEISCHHAUER proceeded to describe various search and retrieval -capabilities while ERWAY worked the computer. In this particular package -the "go to" pull-down allowed the user in effect to jump out of Toolbook, -where the interactive program was located, and enter the third-party -software used by AM for this text collection, which is called Personal -Librarian. This was the Windows version of Personal Librarian, a -software application put together by a company in Rockville, Md. - -Since the broadsides came from the Revolutionary War period, a search was -conducted using the words British or war, with the default operator reset -as or. FLEISCHHAUER demonstrated both automatic stemming (which finds -other forms of the same root) and a truncated search. One of Personal -Librarian's strongest features, the relevance ranking, was represented by -a chart that indicated how often words being sought appeared in -documents, with the one receiving the most "hits" obtaining the highest -score. The "hit list" that is supplied takes the relevance ranking into -account, making the first hit, in effect, the one the software has -selected as the most relevant example. - -While in the text of one of the broadside documents, FLEISCHHAUER -remarked AM's attempt to find ways to connect cataloging to the texts, -which it does in different ways in different manifestations. In the case -shown, the cataloging was pasted on: AM took MARC records that were -written as on-line records right into one of the Library's mainframe -retrieval programs, pulled them out, and handed them off to the contractor, -who massaged them somewhat to display them in the manner shown. One of -AM's questions is, Does the cataloguing normally performed in the mainframe -work in this context, or had AM ought to think through adjustments? - -FLEISCHHAUER made the additional point that, as far as the text goes, AM -has gravitated towards SGML (he pointed to the boldface in the upper part -of the screen). Although extremely limited in its ability to translate -or interpret SGML, Personal Librarian will furnish both bold and italics -on screen; a fairly easy thing to do, but it is one of the ways in which -SGML is useful. - -Striking a balance between quantity and quality has been a major concern -of AM, with accuracy being one of the places where project staff have -felt that less than 100-percent accuracy was not unacceptable. -FLEISCHHAUER cited the example of the standard of the rekeying industry, -namely 99.95 percent; as one service bureau informed him, to go from -99.95 to 100 percent would double the cost. - -FLEISCHHAUER next demonstrated how AM furnishes users recourse to images, -and at the same time recalled LESK's pointed question concerning the -number of people who would look at those images and the number who would -work only with the text. If the implication of LESK's question was -sound, FLEISCHHAUER said, it raised the stakes for text accuracy and -reduced the value of the strategy for images. - -Contending that preservation is always a bugaboo, FLEISCHHAUER -demonstrated several images derived from a scan of a preservation -microfilm that AM had made. He awarded a grade of C at best, perhaps a -C minus or a C plus, for how well it worked out. Indeed, the matter of -learning if other people had better ideas about scanning in general, and, -in particular, scanning from microfilm, was one of the factors that drove -AM to attempt to think through the agenda for the Workshop. Skew, for -example, was one of the issues that AM in its ignorance had not reckoned -would prove so difficult. - -Further, the handling of images of the sort shown, in a desktop computer -environment, involved a considerable amount of zooming and scrolling. -Ultimately, AM staff feel that perhaps the paper copy that is printed out -might be the most useful one, but they remain uncertain as to how much -on-screen reading users will do. - -Returning to the text, FLEISCHHAUER asked viewers to imagine a person who -might be conducting a search in a full-text environment. With this -scenario, he proceeded to illustrate other features of Personal Librarian -that he considered helpful; for example, it provides the ability to -notice words as one reads. Clicking the "include" button on the bottom -of the search window pops the words that have been highlighted into the -search. Thus, a user can refine the search as he or she reads, -re-executing the search and continuing to find things in the quest for -materials. This software not only contains relevance ranking, Boolean -operators, and truncation, it also permits one to perform word algebra, -so to say, where one puts two or three words in parentheses and links -them with one Boolean operator and then a couple of words in another set -of parentheses and asks for things within so many words of others. - -Until they became acquainted recently with some of the work being done in -classics, the AM staff had not realized that a large number of the -projects that involve electronic texts were being done by people with a -profound interest in language and linguistics. Their search strategies -and thinking are oriented to those fields, as is shown in particular by -the Perseus example. As amateur historians, the AM staff were thinking -more of searching for concepts and ideas than for particular words. -Obviously, FLEISCHHAUER conceded, searching for concepts and ideas and -searching for words may be two rather closely related things. - -While displaying several images, FLEISCHHAUER observed that the Macintosh -prototype built by AM contains a greater diversity of formats. Echoing a -previous speaker, he said that it was easier to stitch things together in -the Macintosh, though it tended to be a little more anemic in search and -retrieval. AM, therefore, increasingly has been investigating -sophisticated retrieval engines in the IBM format. - -FLEISCHHAUER demonstrated several additional examples of the prototype -interfaces: One was AM's metaphor for the network future, in which a -kind of reading-room graphic suggests how one would be able to go around -to different materials. AM contains a large number of photographs in -analog video form worked up from a videodisc, which enable users to make -copies to print or incorporate in digital documents. A frame-grabber is -built into the system, making it possible to bring an image into a window -and digitize or print it out. - -FLEISCHHAUER next demonstrated sound recording, which included texts. -Recycled from a previous project, the collection included sixty 78-rpm -phonograph records of political speeches that were made during and -immediately after World War I. These constituted approximately three -hours of audio, as AM has digitized it, which occupy 150 megabytes on a -CD. Thus, they are considerably compressed. From the catalogue card, -FLEISCHHAUER proceeded to a transcript of a speech with the audio -available and with highlighted text following it as it played. -A photograph has been added and a transcription made. - -Considerable value has been added beyond what the Library of Congress -normally would do in cataloguing a sound recording, which raises several -questions for AM concerning where to draw lines about how much value it can -afford to add and at what point, perhaps, this becomes more than AM could -reasonably do or reasonably wish to do. FLEISCHHAUER also demonstrated -a motion picture. As FREEMAN had reported earlier, the motion picture -materials have proved the most popular, not surprisingly. This says more -about the medium, he thought, than about AM's presentation of it. - -Because AM's goal was to bring together things that could be used by -historians or by people who were curious about history, -turn-of-the-century footage seemed to represent the most appropriate -collections from the Library of Congress in motion pictures. These were -the very first films made by Thomas Edison's company and some others at -that time. The particular example illustrated was a Biograph film, -brought in with a frame-grabber into a window. A single videodisc -contains about fifty titles and pieces of film from that period, all of -New York City. Taken together, AM believes, they provide an interesting -documentary resource. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -DISCUSSION * Using the frame-grabber in AM * Volume of material processed -and to be processed * Purpose of AM within LC * Cataloguing and the -nature of AM's material * SGML coding and the question of quality versus -quantity * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -During the question-and-answer period that followed FLEISCHHAUER's -presentation, several clarifications were made. - -AM is bringing in motion pictures from a videodisc. The frame-grabber -devices create a window on a computer screen, which permits users to -digitize a single frame of the movie or one of the photographs. It -produces a crude, rough-and-ready image that high school students can -incorporate into papers, and that has worked very nicely in this way. - -Commenting on FLEISCHHAUER's assertion that AM was looking more at -searching ideas than words, MYLONAS argued that without words an idea -does not exist. FLEISCHHAUER conceded that he ought to have articulated -his point more clearly. MYLONAS stated that they were in fact both -talking about the same thing. By searching for words and by forcing -people to focus on the word, the Perseus Project felt that they would get -them to the idea. The way one reviews results is tailored more to one -kind of user than another. - -Concerning the total volume of material that has been processed in this -way, AM at this point has in retrievable form seven or eight collections, -all of them photographic. In the Macintosh environment, for example, -there probably are 35,000-40,000 photographs. The sound recordings -number sixty items. The broadsides number about 300 items. There are -500 political cartoons in the form of drawings. The motion pictures, as -individual items, number sixty to seventy. - -AM also has a manuscript collection, the life history portion of one of -the federal project series, which will contain 2,900 individual -documents, all first-person narratives. AM has in process about 350 -African-American pamphlets, or about 12,000 printed pages for the period -1870-1910. Also in the works are some 4,000 panoramic photographs. AM -has recycled a fair amount of the work done by LC's Prints and -Photographs Division during the Library's optical disk pilot project in -the 1980s. For example, a special division of LC has tooled up and -thought through all the ramifications of electronic presentation of -photographs. Indeed, they are wheeling them out in great barrel loads. -The purpose of AM within the Library, it is hoped, is to catalyze several -of the other special collection divisions which have no particular -experience with, in some cases, mixed feelings about, an activity such as -AM. Moreover, in many cases the divisions may be characterized as not -only lacking experience in "electronifying" things but also in automated -cataloguing. MARC cataloguing as practiced in the United States is -heavily weighted toward the description of monograph and serial -materials, but is much thinner when one enters the world of manuscripts -and things that are held in the Library's music collection and other -units. In response to a comment by LESK, that AM's material is very -heavily photographic, and is so primarily because individual records have -been made for each photograph, FLEISCHHAUER observed that an item-level -catalog record exists, for example, for each photograph in the Detroit -Publishing collection of 25,000 pictures. In the case of the Federal -Writers Project, for which nearly 3,000 documents exist, representing -information from twenty-six different states, AM with the assistance of -Karen STUART of the Manuscript Division will attempt to find some way not -only to have a collection-level record but perhaps a MARC record for each -state, which will then serve as an umbrella for the 100-200 documents -that come under it. But that drama remains to be enacted. The AM staff -is conservative and clings to cataloguing, though of course visitors tout -artificial intelligence and neural networks in a manner that suggests that -perhaps one need not have cataloguing or that much of it could be put aside. - -The matter of SGML coding, FLEISCHHAUER conceded, returned the discussion -to the earlier treated question of quality versus quantity in the Library -of Congress. Of course, text conversion can be done with 100-percent -accuracy, but it means that when one's holdings are as vast as LC's only -a tiny amount will be exposed, whereas permitting lower levels of -accuracy can lead to exposing or sharing larger amounts, but with the -quality correspondingly impaired. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TWOHIG * A contrary experience concerning electronic options * Volume of -material in the Washington papers and a suggestion of David Packard * -Implications of Packard's suggestion * Transcribing the documents for the -CD-ROM * Accuracy of transcriptions * The CD-ROM edition of the Founding -Fathers documents * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Finding encouragement in a comment of MICHELSON's from the morning -session--that numerous people in the humanities were choosing electronic -options to do their work--Dorothy TWOHIG, editor, The Papers of George -Washington, opened her illustrated talk by noting that her experience -with literary scholars and numerous people in editing was contrary to -MICHELSON's. TWOHIG emphasized literary scholars' complete ignorance of -the technological options available to them or their reluctance or, in -some cases, their downright hostility toward these options. - -After providing an overview of the five Founding Fathers projects -(Jefferson at Princeton, Franklin at Yale, John Adams at the -Massachusetts Historical Society, and Madison down the hall from her at -the University of Virginia), TWOHIG observed that the Washington papers, -like all of the projects, include both sides of the Washington -correspondence and deal with some 135,000 documents to be published with -extensive annotation in eighty to eighty-five volumes, a project that -will not be completed until well into the next century. Thus, it was -with considerable enthusiasm several years ago that the Washington Papers -Project (WPP) greeted David Packard's suggestion that the papers of the -Founding Fathers could be published easily and inexpensively, and to the -great benefit of American scholarship, via CD-ROM. - -In pragmatic terms, funding from the Packard Foundation would expedite -the transcription of thousands of documents waiting to be put on disk in -the WPP offices. Further, since the costs of collecting, editing, and -converting the Founding Fathers documents into letterpress editions were -running into the millions of dollars, and the considerable staffs -involved in all of these projects were devoting their careers to -producing the work, the Packard Foundation's suggestion had a -revolutionary aspect: Transcriptions of the entire corpus of the -Founding Fathers papers would be available on CD-ROM to public and -college libraries, even high schools, at a fraction of the cost-- -$100-$150 for the annual license fee--to produce a limited university -press run of 1,000 of each volume of the published papers at $45-$150 per -printed volume. Given the current budget crunch in educational systems -and the corresponding constraints on librarians in smaller institutions -who wish to add these volumes to their collections, producing the -documents on CD-ROM would likely open a greatly expanded audience for the -papers. TWOHIG stressed, however, that development of the Founding -Fathers CD-ROM is still in its infancy. Serious software problems remain -to be resolved before the material can be put into readable form. - -Funding from the Packard Foundation resulted in a major push to -transcribe the 75,000 or so documents of the Washington papers remaining -to be transcribed onto computer disks. Slides illustrated several of the -problems encountered, for example, the present inability of CD-ROM to -indicate the cross-outs (deleted material) in eighteenth century -documents. TWOHIG next described documents from various periods in the -eighteenth century that have been transcribed in chronological order and -delivered to the Packard offices in California, where they are converted -to the CD-ROM, a process that is expected to consume five years to -complete (that is, reckoning from David Packard's suggestion made several -years ago, until about July 1994). TWOHIG found an encouraging -indication of the project's benefits in the ongoing use made by scholars -of the search functions of the CD-ROM, particularly in reducing the time -spent in manually turning the pages of the Washington papers. - -TWOHIG next furnished details concerning the accuracy of transcriptions. -For instance, the insertion of thousands of documents on the CD-ROM -currently does not permit each document to be verified against the -original manuscript several times as in the case of documents that appear -in the published edition. However, the transcriptions receive a cursory -check for obvious typos, the misspellings of proper names, and other -errors from the WPP CD-ROM editor. Eventually, all documents that appear -in the electronic version will be checked by project editors. Although -this process has met with opposition from some of the editors on the -grounds that imperfect work may leave their offices, the advantages in -making this material available as a research tool outweigh fears about the -misspelling of proper names and other relatively minor editorial matters. - -Completion of all five Founding Fathers projects (i.e., retrievability -and searchability of all of the documents by proper names, alternate -spellings, or varieties of subjects) will provide one of the richest -sources of this size for the history of the United States in the latter -part of the eighteenth century. Further, publication on CD-ROM will -allow editors to include even minutiae, such as laundry lists, not -included in the printed volumes. - -It seems possible that the extensive annotation provided in the printed -volumes eventually will be added to the CD-ROM edition, pending -negotiations with the publishers of the papers. At the moment, the -Founding Fathers CD-ROM is accessible only on the IBYCUS, a computer -developed out of the Thesaurus Linguae Graecae project and designed for -the use of classical scholars. There are perhaps 400 IBYCUS computers in -the country, most of which are in university classics departments. -Ultimately, it is anticipated that the CD-ROM edition of the Founding -Fathers documents will run on any IBM-compatible or Macintosh computer -with a CD-ROM drive. Numerous changes in the software will also occur -before the project is completed. (Editor's note: an IBYCUS was -unavailable to demonstrate the CD-ROM.) - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -DISCUSSION * Several additional features of WPP clarified * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Discussion following TWOHIG's presentation served to clarify several -additional features, including (1) that the project's primary -intellectual product consists in the electronic transcription of the -material; (2) that the text transmitted to the CD-ROM people is not -marked up; (3) that cataloging and subject-indexing of the material -remain to be worked out (though at this point material can be retrieved -by name); and (4) that because all the searching is done in the hardware, -the IBYCUS is designed to read a CD-ROM which contains only sequential -text files. Technically, it then becomes very easy to read the material -off and put it on another device. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -LEBRON * Overview of the history of the joint project between AAAS and -OCLC * Several practices the on-line environment shares with traditional -publishing on hard copy * Several technical and behavioral barriers to -electronic publishing * How AAAS and OCLC arrived at the subject of -clinical trials * Advantages of the electronic format and other features -of OJCCT * An illustrated tour of the journal * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Maria LEBRON, managing editor, The Online Journal of Current Clinical -Trials (OJCCT), presented an illustrated overview of the history of the -joint project between the American Association for the Advancement of -Science (AAAS) and the Online Computer Library Center, Inc. (OCLC). The -joint venture between AAAS and OCLC owes its beginning to a -reorganization launched by the new chief executive officer at OCLC about -three years ago and combines the strengths of these two disparate -organizations. In short, OJCCT represents the process of scholarly -publishing on line. - -LEBRON next discussed several practices the on-line environment shares -with traditional publishing on hard copy--for example, peer review of -manuscripts--that are highly important in the academic world. LEBRON -noted in particular the implications of citation counts for tenure -committees and grants committees. In the traditional hard-copy -environment, citation counts are readily demonstrable, whereas the -on-line environment represents an ethereal medium to most academics. - -LEBRON remarked several technical and behavioral barriers to electronic -publishing, for instance, the problems in transmission created by special -characters or by complex graphics and halftones. In addition, she noted -economic limitations such as the storage costs of maintaining back issues -and market or audience education. - -Manuscripts cannot be uploaded to OJCCT, LEBRON explained, because it is -not a bulletin board or E-mail, forms of electronic transmission of -information that have created an ambience clouding people's understanding -of what the journal is attempting to do. OJCCT, which publishes -peer-reviewed medical articles dealing with the subject of clinical -trials, includes text, tabular material, and graphics, although at this -time it can transmit only line illustrations. - -Next, LEBRON described how AAAS and OCLC arrived at the subject of -clinical trials: It is 1) a highly statistical discipline that 2) does -not require halftones but can satisfy the needs of its audience with line -illustrations and graphic material, and 3) there is a need for the speedy -dissemination of high-quality research results. Clinical trials are -research activities that involve the administration of a test treatment -to some experimental unit in order to test its usefulness before it is -made available to the general population. LEBRON proceeded to give -additional information on OJCCT concerning its editor-in-chief, editorial -board, editorial content, and the types of articles it publishes -(including peer-reviewed research reports and reviews), as well as -features shared by other traditional hard-copy journals. - -Among the advantages of the electronic format are faster dissemination of -information, including raw data, and the absence of space constraints -because pages do not exist. (This latter fact creates an interesting -situation when it comes to citations.) Nor are there any issues. AAAS's -capacity to download materials directly from the journal to a -subscriber's printer, hard drive, or floppy disk helps ensure highly -accurate transcription. Other features of OJCCT include on-screen alerts -that allow linkage of subsequently published documents to the original -documents; on-line searching by subject, author, title, etc.; indexing of -every single word that appears in an article; viewing access to an -article by component (abstract, full text, or graphs); numbered -paragraphs to replace page counts; publication in Science every thirty -days of indexing of all articles published in the journal; -typeset-quality screens; and Hypertext links that enable subscribers to -bring up Medline abstracts directly without leaving the journal. - -After detailing the two primary ways to gain access to the journal, -through the OCLC network and Compuserv if one desires graphics or through -the Internet if just an ASCII file is desired, LEBRON illustrated the -speedy editorial process and the coding of the document using SGML tags -after it has been accepted for publication. She also gave an illustrated -tour of the journal, its search-and-retrieval capabilities in particular, -but also including problems associated with scanning in illustrations, -and the importance of on-screen alerts to the medical profession re -retractions or corrections, or more frequently, editorials, letters to -the editors, or follow-up reports. She closed by inviting the audience -to join AAAS on 1 July, when OJCCT was scheduled to go on-line. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -DISCUSSION * Additional features of OJCCT * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -In the lengthy discussion that followed LEBRON's presentation, these -points emerged: - - * The SGML text can be tailored as users wish. - - * All these articles have a fairly simple document definition. - - * Document-type definitions (DTDs) were developed and given to OJCCT - for coding. - - * No articles will be removed from the journal. (Because there are - no back issues, there are no lost issues either. Once a subscriber - logs onto the journal he or she has access not only to the currently - published materials, but retrospectively to everything that has been - published in it. Thus the table of contents grows bigger. The date - of publication serves to distinguish between currently published - materials and older materials.) - - * The pricing system for the journal resembles that for most medical - journals: for 1992, $95 for a year, plus telecommunications charges - (there are no connect time charges); for 1993, $110 for the - entire year for single users, though the journal can be put on a - local area network (LAN). However, only one person can access the - journal at a time. Site licenses may come in the future. - - * AAAS is working closely with colleagues at OCLC to display - mathematical equations on screen. - - * Without compromising any steps in the editorial process, the - technology has reduced the time lag between when a manuscript is - originally submitted and the time it is accepted; the review process - does not differ greatly from the standard six-to-eight weeks - employed by many of the hard-copy journals. The process still - depends on people. - - * As far as a preservation copy is concerned, articles will be - maintained on the computer permanently and subscribers, as part of - their subscription, will receive a microfiche-quality archival copy - of everything published during that year; in addition, reprints can - be purchased in much the same way as in a hard-copy environment. - Hard copies are prepared but are not the primary medium for the - dissemination of the information. - - * Because OJCCT is not yet on line, it is difficult to know how many - people would simply browse through the journal on the screen as - opposed to downloading the whole thing and printing it out; a mix of - both types of users likely will result. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -PERSONIUS * Developments in technology over the past decade * The CLASS -Project * Advantages for technology and for the CLASS Project * -Developing a network application an underlying assumption of the project -* Details of the scanning process * Print-on-demand copies of books * -Future plans include development of a browsing tool * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Lynne PERSONIUS, assistant director, Cornell Information Technologies for -Scholarly Information Services, Cornell University, first commented on -the tremendous impact that developments in technology over the past ten -years--networking, in particular--have had on the way information is -handled, and how, in her own case, these developments have counterbalanced -Cornell's relative geographical isolation. Other significant technologies -include scanners, which are much more sophisticated than they were ten years -ago; mass storage and the dramatic savings that result from it in terms of -both space and money relative to twenty or thirty years ago; new and -improved printing technologies, which have greatly affected the distribution -of information; and, of course, digital technologies, whose applicability to -library preservation remains at issue. - -Given that context, PERSONIUS described the College Library Access and -Storage System (CLASS) Project, a library preservation project, -primarily, and what has been accomplished. Directly funded by the -Commission on Preservation and Access and by the Xerox Corporation, which -has provided a significant amount of hardware, the CLASS Project has been -working with a development team at Xerox to develop a software -application tailored to library preservation requirements. Within -Cornell, participants in the project have been working jointly with both -library and information technologies. The focus of the project has been -on reformatting and saving books that are in brittle condition. -PERSONIUS showed Workshop participants a brittle book, and described how -such books were the result of developments in papermaking around the -beginning of the Industrial Revolution. The papermaking process was -changed so that a significant amount of acid was introduced into the -actual paper itself, which deteriorates as it sits on library shelves. - -One of the advantages for technology and for the CLASS Project is that -the information in brittle books is mostly out of copyright and thus -offers an opportunity to work with material that requires library -preservation, and to create and work on an infrastructure to save the -material. Acknowledging the familiarity of those working in preservation -with this information, PERSONIUS noted that several things are being -done: the primary preservation technology used today is photocopying of -brittle material. Saving the intellectual content of the material is the -main goal. With microfilm copy, the intellectual content is preserved on -the assumption that in the future the image can be reformatted in any -other way that then exists. - -An underlying assumption of the CLASS Project from the beginning was -that it would develop a network application. Project staff scan books -at a workstation located in the library, near the brittle material. -An image-server filing system is located at a distance from that -workstation, and a printer is located in another building. All of the -materials digitized and stored on the image-filing system are cataloged -in the on-line catalogue. In fact, a record for each of these electronic -books is stored in the RLIN database so that a record exists of what is -in the digital library throughout standard catalogue procedures. In the -future, researchers working from their own workstations in their offices, -or their networks, will have access--wherever they might be--through a -request server being built into the new digital library. A second -assumption is that the preferred means of finding the material will be by -looking through a catalogue. PERSONIUS described the scanning process, -which uses a prototype scanner being developed by Xerox and which scans a -very high resolution image at great speed. Another significant feature, -because this is a preservation application, is the placing of the pages -that fall apart one for one on the platen. Ordinarily, a scanner could -be used with some sort of a document feeder, but because of this -application that is not feasible. Further, because CLASS is a -preservation application, after the paper replacement is made there, a -very careful quality control check is performed. An original book is -compared to the printed copy and verification is made, before proceeding, -that all of the image, all of the information, has been captured. Then, -a new library book is produced: The printed images are rebound by a -commercial binder and a new book is returned to the shelf. -Significantly, the books returned to the library shelves are beautiful -and useful replacements on acid-free paper that should last a long time, -in effect, the equivalent of preservation photocopies. Thus, the project -has a library of digital books. In essence, CLASS is scanning and -storing books as 600 dot-per-inch bit-mapped images, compressed using -Group 4 CCITT (i.e., the French acronym for International Consultative -Committee for Telegraph and Telephone) compression. They are stored as -TIFF files on an optical filing system that is composed of a database -used for searching and locating the books and an optical jukebox that -stores 64 twelve-inch platters. A very-high-resolution printed copy of -these books at 600 dots per inch is created, using a Xerox DocuTech -printer to make the paper replacements on acid-free paper. - -PERSONIUS maintained that the CLASS Project presents an opportunity to -introduce people to books as digital images by using a paper medium. -Books are returned to the shelves while people are also given the ability -to print on demand--to make their own copies of books. (PERSONIUS -distributed copies of an engineering journal published by engineering -students at Cornell around 1900 as an example of what a print-on-demand -copy of material might be like. This very cheap copy would be available -to people to use for their own research purposes and would bridge the gap -between an electronic work and the paper that readers like to have.) -PERSONIUS then attempted to illustrate a very early prototype of -networked access to this digital library. Xerox Corporation has -developed a prototype of a view station that can send images across the -network to be viewed. - -The particular library brought down for demonstration contained two -mathematics books. CLASS is developing and will spend the next year -developing an application that allows people at workstations to browse -the books. Thus, CLASS is developing a browsing tool, on the assumption -that users do not want to read an entire book from a workstation, but -would prefer to be able to look through and decide if they would like to -have a printed copy of it. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -DISCUSSION * Re retrieval software * "Digital file copyright" * Scanning -rate during production * Autosegmentation * Criteria employed in -selecting books for scanning * Compression and decompression of images * -OCR not precluded * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -During the question-and-answer period that followed her presentation, -PERSONIUS made these additional points: - - * Re retrieval software, Cornell is developing a Unix-based server - as well as clients for the server that support multiple platforms - (Macintosh, IBM and Sun workstations), in the hope that people from - any of those platforms will retrieve books; a further operating - assumption is that standard interfaces will be used as much as - possible, where standards can be put in place, because CLASS - considers this retrieval software a library application and would - like to be able to look at material not only at Cornell but at other - institutions. - - * The phrase "digital file copyright by Cornell University" was - added at the advice of Cornell's legal staff with the caveat that it - probably would not hold up in court. Cornell does not want people - to copy its books and sell them but would like to keep them - available for use in a library environment for library purposes. - - * In production the scanner can scan about 300 pages per hour, - capturing 600 dots per inch. - - * The Xerox software has filters to scan halftone material and avoid - the moire patterns that occur when halftone material is scanned. - Xerox has been working on hardware and software that would enable - the scanner itself to recognize this situation and deal with it - appropriately--a kind of autosegmentation that would enable the - scanner to handle halftone material as well as text on a single page. - - * The books subjected to the elaborate process described above were - selected because CLASS is a preservation project, with the first 500 - books selected coming from Cornell's mathematics collection, because - they were still being heavily used and because, although they were - in need of preservation, the mathematics library and the mathematics - faculty were uncomfortable having them microfilmed. (They wanted a - printed copy.) Thus, these books became a logical choice for this - project. Other books were chosen by the project's selection committees - for experiments with the technology, as well as to meet a demand or need. - - * Images will be decompressed before they are sent over the line; at - this time they are compressed and sent to the image filing system - and then sent to the printer as compressed images; they are returned - to the workstation as compressed 600-dpi images and the workstation - decompresses and scales them for display--an inefficient way to - access the material though it works quite well for printing and - other purposes. - - * CLASS is also decompressing on Macintosh and IBM, a slow process - right now. Eventually, compression and decompression will take - place on an image conversion server. Trade-offs will be made, based - on future performance testing, concerning where the file is - compressed and what resolution image is sent. - - * OCR has not been precluded; images are being stored that have been - scanned at a high resolution, which presumably would suit them well - to an OCR process. Because the material being scanned is about 100 - years old and was printed with less-than-ideal technologies, very - early and preliminary tests have not produced good results. But the - project is capturing an image that is of sufficient resolution to be - subjected to OCR in the future. Moreover, the system architecture - and the system plan have a logical place to store an OCR image if it - has been captured. But that is not being done now. - - ****** - -SESSION III. DISTRIBUTION, NETWORKS, AND NETWORKING: OPTIONS FOR -DISSEMINATION - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -ZICH * Issues pertaining to CD-ROMs * Options for publishing in CD-ROM * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Robert ZICH, special assistant to the associate librarian for special -projects, Library of Congress, and moderator of this session, first noted -the blessed but somewhat awkward circumstance of having four very -distinguished people representing networks and networking or at least -leaning in that direction, while lacking anyone to speak from the -strongest possible background in CD-ROMs. ZICH expressed the hope that -members of the audience would join the discussion. He stressed the -subtitle of this particular session, "Options for Dissemination," and, -concerning CD-ROMs, the importance of determining when it would be wise -to consider dissemination in CD-ROM versus networks. A shopping list of -issues pertaining to CD-ROMs included: the grounds for selecting -commercial publishers, and in-house publication where possible versus -nonprofit or government publication. A similar list for networks -included: determining when one should consider dissemination through a -network, identifying the mechanisms or entities that exist to place items -on networks, identifying the pool of existing networks, determining how a -producer would choose between networks, and identifying the elements of -a business arrangement in a network. - -Options for publishing in CD-ROM: an outside publisher versus -self-publication. If an outside publisher is used, it can be nonprofit, -such as the Government Printing Office (GPO) or the National Technical -Information Service (NTIS), in the case of government. The pros and cons -associated with employing an outside publisher are obvious. Among the -pros, there is no trouble getting accepted. One pays the bill and, in -effect, goes one's way. Among the cons, when one pays an outside -publisher to perform the work, that publisher will perform the work it is -obliged to do, but perhaps without the production expertise and skill in -marketing and dissemination that some would seek. There is the body of -commercial publishers that do possess that kind of expertise in -distribution and marketing but that obviously are selective. In -self-publication, one exercises full control, but then one must handle -matters such as distribution and marketing. Such are some of the options -for publishing in the case of CD-ROM. - -In the case of technical and design issues, which are also important, -there are many matters which many at the Workshop already knew a good -deal about: retrieval system requirements and costs, what to do about -images, the various capabilities and platforms, the trade-offs between -cost and performance, concerns about local-area networkability, -interoperability, etc. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -LYNCH * Creating networked information is different from using networks -as an access or dissemination vehicle * Networked multimedia on a large -scale does not yet work * Typical CD-ROM publication model a two-edged -sword * Publishing information on a CD-ROM in the present world of -immature standards * Contrast between CD-ROM and network pricing * -Examples demonstrated earlier in the day as a set of insular information -gems * Paramount need to link databases * Layering to become increasingly -necessary * Project NEEDS and the issues of information reuse and active -versus passive use * X-Windows as a way of differentiating between -network access and networked information * Barriers to the distribution -of networked multimedia information * Need for good, real-time delivery -protocols * The question of presentation integrity in client-server -computing in the academic world * Recommendations for producing multimedia -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Clifford LYNCH, director, Library Automation, University of California, -opened his talk with the general observation that networked information -constituted a difficult and elusive topic because it is something just -starting to develop and not yet fully understood. LYNCH contended that -creating genuinely networked information was different from using -networks as an access or dissemination vehicle and was more sophisticated -and more subtle. He invited the members of the audience to extrapolate, -from what they heard about the preceding demonstration projects, to what -sort of a world of electronics information--scholarly, archival, -cultural, etc.--they wished to end up with ten or fifteen years from now. -LYNCH suggested that to extrapolate directly from these projects would -produce unpleasant results. - -Putting the issue of CD-ROM in perspective before getting into -generalities on networked information, LYNCH observed that those engaged -in multimedia today who wish to ship a product, so to say, probably do -not have much choice except to use CD-ROM: networked multimedia on a -large scale basically does not yet work because the technology does not -exist. For example, anybody who has tried moving images around over the -Internet knows that this is an exciting touch-and-go process, a -fascinating and fertile area for experimentation, research, and -development, but not something that one can become deeply enthusiastic -about committing to production systems at this time. - -This situation will change, LYNCH said. He differentiated CD-ROM from -the practices that have been followed up to now in distributing data on -CD-ROM. For LYNCH the problem with CD-ROM is not its portability or its -slowness but the two-edged sword of having the retrieval application and -the user interface inextricably bound up with the data, which is the -typical CD-ROM publication model. It is not a case of publishing data -but of distributing a typically stand-alone, typically closed system, -all--software, user interface, and data--on a little disk. Hence, all -the between-disk navigational issues as well as the impossibility in most -cases of integrating data on one disk with that on another. Most CD-ROM -retrieval software does not network very gracefully at present. However, -in the present world of immature standards and lack of understanding of -what network information is or what the ground rules are for creating or -using it, publishing information on a CD-ROM does add value in a very -real sense. - -LYNCH drew a contrast between CD-ROM and network pricing and in doing so -highlighted something bizarre in information pricing. A large -institution such as the University of California has vendors who will -offer to sell information on CD-ROM for a price per year in four digits, -but for the same data (e.g., an abstracting and indexing database) on -magnetic tape, regardless of how many people may use it concurrently, -will quote a price in six digits. - -What is packaged with the CD-ROM in one sense adds value--a complete -access system, not just raw, unrefined information--although it is not -generally perceived that way. This is because the access software, -although it adds value, is viewed by some people, particularly in the -university environment where there is a very heavy commitment to -networking, as being developed in the wrong direction. - -Given that context, LYNCH described the examples demonstrated as a set of -insular information gems--Perseus, for example, offers nicely linked -information, but would be very difficult to integrate with other -databases, that is, to link together seamlessly with other source files -from other sources. It resembles an island, and in this respect is -similar to numerous stand-alone projects that are based on videodiscs, -that is, on the single-workstation concept. - -As scholarship evolves in a network environment, the paramount need will -be to link databases. We must link personal databases to public -databases, to group databases, in fairly seamless ways--which is -extremely difficult in the environments under discussion with copies of -databases proliferating all over the place. - -The notion of layering also struck LYNCH as lurking in several of the -projects demonstrated. Several databases in a sense constitute -information archives without a significant amount of navigation built in. -Educators, critics, and others will want a layered structure--one that -defines or links paths through the layers to allow users to reach -specific points. In LYNCH's view, layering will become increasingly -necessary, and not just within a single resource but across resources -(e.g., tracing mythology and cultural themes across several classics -databases as well as a database of Renaissance culture). This ability to -organize resources, to build things out of multiple other things on the -network or select pieces of it, represented for LYNCH one of the key -aspects of network information. - -Contending that information reuse constituted another significant issue, -LYNCH commended to the audience's attention Project NEEDS (i.e., National -Engineering Education Delivery System). This project's objective is to -produce a database of engineering courseware as well as the components -that can be used to develop new courseware. In a number of the existing -applications, LYNCH said, the issue of reuse (how much one can take apart -and reuse in other applications) was not being well considered. He also -raised the issue of active versus passive use, one aspect of which is -how much information will be manipulated locally by users. Most people, -he argued, may do a little browsing and then will wish to print. LYNCH -was uncertain how these resources would be used by the vast majority of -users in the network environment. - -LYNCH next said a few words about X-Windows as a way of differentiating -between network access and networked information. A number of the -applications demonstrated at the Workshop could be rewritten to use X -across the network, so that one could run them from any X-capable device- --a workstation, an X terminal--and transact with a database across the -network. Although this opens up access a little, assuming one has enough -network to handle it, it does not provide an interface to develop a -program that conveniently integrates information from multiple databases. -X is a viewing technology that has limits. In a real sense, it is just a -graphical version of remote log-in across the network. X-type applications -represent only one step in the progression towards real access. - -LYNCH next discussed barriers to the distribution of networked multimedia -information. The heart of the problem is a lack of standards to provide -the ability for computers to talk to each other, retrieve information, -and shuffle it around fairly casually. At the moment, little progress is -being made on standards for networked information; for example, present -standards do not cover images, digital voice, and digital video. A -useful tool kit of exchange formats for basic texts is only now being -assembled. The synchronization of content streams (i.e., synchronizing a -voice track to a video track, establishing temporal relations between -different components in a multimedia object) constitutes another issue -for networked multimedia that is just beginning to receive attention. - -Underlying network protocols also need some work; good, real-time -delivery protocols on the Internet do not yet exist. In LYNCH's view, -highly important in this context is the notion of networked digital -object IDs, the ability of one object on the network to point to another -object (or component thereof) on the network. Serious bandwidth issues -also exist. LYNCH was uncertain if billion-bit-per-second networks would -prove sufficient if numerous people ran video in parallel. - -LYNCH concluded by offering an issue for database creators to consider, -as well as several comments about what might constitute good trial -multimedia experiments. In a networked information world the database -builder or service builder (publisher) does not exercise the same -extensive control over the integrity of the presentation; strange -programs "munge" with one's data before the user sees it. Serious -thought must be given to what guarantees integrity of presentation. Part -of that is related to where one draws the boundaries around a networked -information service. This question of presentation integrity in -client-server computing has not been stressed enough in the academic -world, LYNCH argued, though commercial service providers deal with it -regularly. - -Concerning multimedia, LYNCH observed that good multimedia at the moment -is hideously expensive to produce. He recommended producing multimedia -with either very high sale value, or multimedia with a very long life -span, or multimedia that will have a very broad usage base and whose -costs therefore can be amortized among large numbers of users. In this -connection, historical and humanistically oriented material may be a good -place to start, because it tends to have a longer life span than much of -the scientific material, as well as a wider user base. LYNCH noted, for -example, that American Memory fits many of the criteria outlined. He -remarked the extensive discussion about bringing the Internet or the -National Research and Education Network (NREN) into the K-12 environment -as a way of helping the American educational system. - -LYNCH closed by noting that the kinds of applications demonstrated struck -him as excellent justifications of broad-scale networking for K-12, but -that at this time no "killer" application exists to mobilize the K-12 -community to obtain connectivity. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -DISCUSSION * Dearth of genuinely interesting applications on the network -a slow-changing situation * The issue of the integrity of presentation in -a networked environment * Several reasons why CD-ROM software does not -network * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -During the discussion period that followed LYNCH's presentation, several -additional points were made. - -LYNCH reiterated even more strongly his contention that, historically, -once one goes outside high-end science and the group of those who need -access to supercomputers, there is a great dearth of genuinely -interesting applications on the network. He saw this situation changing -slowly, with some of the scientific databases and scholarly discussion -groups and electronic journals coming on as well as with the availability -of Wide Area Information Servers (WAIS) and some of the databases that -are being mounted there. However, many of those things do not seem to -have piqued great popular interest. For instance, most high school -students of LYNCH's acquaintance would not qualify as devotees of serious -molecular biology. - -Concerning the issue of the integrity of presentation, LYNCH believed -that a couple of information providers have laid down the law at least on -certain things. For example, his recollection was that the National -Library of Medicine feels strongly that one needs to employ the -identifier field if he or she is to mount a database commercially. The -problem with a real networked environment is that one does not know who -is reformatting and reprocessing one's data when one enters a client -server mode. It becomes anybody's guess, for example, if the network -uses a Z39.50 server, or what clients are doing with one's data. A data -provider can say that his contract will only permit clients to have -access to his data after he vets them and their presentation and makes -certain it suits him. But LYNCH held out little expectation that the -network marketplace would evolve in that way, because it required too -much prior negotiation. - -CD-ROM software does not network for a variety of reasons, LYNCH said. -He speculated that CD-ROM publishers are not eager to have their products -really hook into wide area networks, because they fear it will make their -data suppliers nervous. Moreover, until relatively recently, one had to -be rather adroit to run a full TCP/IP stack plus applications on a -PC-size machine, whereas nowadays it is becoming easier as PCs grow -bigger and faster. LYNCH also speculated that software providers had not -heard from their customers until the last year or so, or had not heard -from enough of their customers. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -BESSER * Implications of disseminating images on the network; planning -the distribution of multimedia documents poses two critical -implementation problems * Layered approach represents the way to deal -with users' capabilities * Problems in platform design; file size and its -implications for networking * Transmission of megabyte size images -impractical * Compression and decompression at the user's end * Promising -trends for compression * A disadvantage of using X-Windows * A project at -the Smithsonian that mounts images on several networks * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Howard BESSER, School of Library and Information Science, University of -Pittsburgh, spoke primarily about multimedia, focusing on images and the -broad implications of disseminating them on the network. He argued that -planning the distribution of multimedia documents posed two critical -implementation problems, which he framed in the form of two questions: -1) What platform will one use and what hardware and software will users -have for viewing of the material? and 2) How can one deliver a -sufficiently robust set of information in an accessible format in a -reasonable amount of time? Depending on whether network or CD-ROM is the -medium used, this question raises different issues of storage, -compression, and transmission. - -Concerning the design of platforms (e.g., sound, gray scale, simple -color, etc.) and the various capabilities users may have, BESSER -maintained that a layered approach was the way to deal with users' -capabilities. A result would be that users with less powerful -workstations would simply have less functionality. He urged members of -the audience to advocate standards and accompanying software that handle -layered functionality across a wide variety of platforms. - -BESSER also addressed problems in platform design, namely, deciding how -large a machine to design for situations when the largest number of users -have the lowest level of the machine, and one desires higher -functionality. BESSER then proceeded to the question of file size and -its implications for networking. He discussed still images in the main. -For example, a digital color image that fills the screen of a standard -mega-pel workstation (Sun or Next) will require one megabyte of storage -for an eight-bit image or three megabytes of storage for a true color or -twenty-four-bit image. Lossless compression algorithms (that is, -computational procedures in which no data is lost in the process of -compressing [and decompressing] an image--the exact bit-representation is -maintained) might bring storage down to a third of a megabyte per image, -but not much further than that. The question of size makes it difficult -to fit an appropriately sized set of these images on a single disk or to -transmit them quickly enough on a network. - -With these full screen mega-pel images that constitute a third of a -megabyte, one gets 1,000-3,000 full-screen images on a one-gigabyte disk; -a standard CD-ROM represents approximately 60 percent of that. Storing -images the size of a PC screen (just 8 bit color) increases storage -capacity to 4,000-12,000 images per gigabyte; 60 percent of that gives -one the size of a CD-ROM, which in turn creates a major problem. One -cannot have full-screen, full-color images with lossless compression; one -must compress them or use a lower resolution. For megabyte-size images, -anything slower than a T-1 speed is impractical. For example, on a -fifty-six-kilobaud line, it takes three minutes to transfer a -one-megabyte file, if it is not compressed; and this speed assumes ideal -circumstances (no other user contending for network bandwidth). Thus, -questions of disk access, remote display, and current telephone -connection speed make transmission of megabyte-size images impractical. - -BESSER then discussed ways to deal with these large images, for example, -compression and decompression at the user's end. In this connection, the -issues of how much one is willing to lose in the compression process and -what image quality one needs in the first place are unknown. But what is -known is that compression entails some loss of data. BESSER urged that -more studies be conducted on image quality in different situations, for -example, what kind of images are needed for what kind of disciplines, and -what kind of image quality is needed for a browsing tool, an intermediate -viewing tool, and archiving. - -BESSER remarked two promising trends for compression: from a technical -perspective, algorithms that use what is called subjective redundancy -employ principles from visual psycho-physics to identify and remove -information from the image that the human eye cannot perceive; from an -interchange and interoperability perspective, the JPEG (i.e., Joint -Photographic Experts Group, an ISO standard) compression algorithms also -offer promise. These issues of compression and decompression, BESSER -argued, resembled those raised earlier concerning the design of different -platforms. Gauging the capabilities of potential users constitutes a -primary goal. BESSER advocated layering or separating the images from -the applications that retrieve and display them, to avoid tying them to -particular software. - -BESSER detailed several lessons learned from his work at Berkeley with -Imagequery, especially the advantages and disadvantages of using -X-Windows. In the latter category, for example, retrieval is tied -directly to one's data, an intolerable situation in the long run on a -networked system. Finally, BESSER described a project of Jim Wallace at -the Smithsonian Institution, who is mounting images in a extremely -rudimentary way on the Compuserv and Genie networks and is preparing to -mount them on America On Line. Although the average user takes over -thirty minutes to download these images (assuming a fairly fast modem), -nevertheless, images have been downloaded 25,000 times. - -BESSER concluded his talk with several comments on the business -arrangement between the Smithsonian and Compuserv. He contended that not -enough is known concerning the value of images. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -DISCUSSION * Creating digitized photographic collections nearly -impossible except with large organizations like museums * Need for study -to determine quality of images users will tolerate * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -During the brief exchange between LESK and BESSER that followed, several -clarifications emerged. - -LESK argued that the photographers were far ahead of BESSER: It is -almost impossible to create such digitized photographic collections -except with large organizations like museums, because all the -photographic agencies have been going crazy about this and will not sign -licensing agreements on any sort of reasonable terms. LESK had heard -that National Geographic, for example, had tried to buy the right to use -some image in some kind of educational production for $100 per image, but -the photographers will not touch it. They want accounting and payment -for each use, which cannot be accomplished within the system. BESSER -responded that a consortium of photographers, headed by a former National -Geographic photographer, had started assembling its own collection of -electronic reproductions of images, with the money going back to the -cooperative. - -LESK contended that BESSER was unnecessarily pessimistic about multimedia -images, because people are accustomed to low-quality images, particularly -from video. BESSER urged the launching of a study to determine what -users would tolerate, what they would feel comfortable with, and what -absolutely is the highest quality they would ever need. Conceding that -he had adopted a dire tone in order to arouse people about the issue, -BESSER closed on a sanguine note by saying that he would not be in this -business if he did not think that things could be accomplished. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -LARSEN * Issues of scalability and modularity * Geometric growth of the -Internet and the role played by layering * Basic functions sustaining -this growth * A library's roles and functions in a network environment * -Effects of implementation of the Z39.50 protocol for information -retrieval on the library system * The trade-off between volumes of data -and its potential usage * A snapshot of current trends * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Ronald LARSEN, associate director for information technology, University -of Maryland at College Park, first addressed the issues of scalability -and modularity. He noted the difficulty of anticipating the effects of -orders-of-magnitude growth, reflecting on the twenty years of experience -with the Arpanet and Internet. Recalling the day's demonstrations of -CD-ROM and optical disk material, he went on to ask if the field has yet -learned how to scale new systems to enable delivery and dissemination -across large-scale networks. - -LARSEN focused on the geometric growth of the Internet from its inception -circa 1969 to the present, and the adjustments required to respond to -that rapid growth. To illustrate the issue of scalability, LARSEN -considered computer networks as including three generic components: -computers, network communication nodes, and communication media. Each -component scales (e.g., computers range from PCs to supercomputers; -network nodes scale from interface cards in a PC through sophisticated -routers and gateways; and communication media range from 2,400-baud -dial-up facilities through 4.5-Mbps backbone links, and eventually to -multigigabit-per-second communication lines), and architecturally, the -components are organized to scale hierarchically from local area networks -to international-scale networks. Such growth is made possible by -building layers of communication protocols, as BESSER pointed out. -By layering both physically and logically, a sense of scalability is -maintained from local area networks in offices, across campuses, through -bridges, routers, campus backbones, fiber-optic links, etc., up into -regional networks and ultimately into national and international -networks. - -LARSEN then illustrated the geometric growth over a two-year period-- -through September 1991--of the number of networks that comprise the -Internet. This growth has been sustained largely by the availability of -three basic functions: electronic mail, file transfer (ftp), and remote -log-on (telnet). LARSEN also reviewed the growth in the kind of traffic -that occurs on the network. Network traffic reflects the joint contributions -of a larger population of users and increasing use per user. Today one sees -serious applications involving moving images across the network--a rarity -ten years ago. LARSEN recalled and concurred with BESSER's main point -that the interesting problems occur at the application level. - -LARSEN then illustrated a model of a library's roles and functions in a -network environment. He noted, in particular, the placement of on-line -catalogues onto the network and patrons obtaining access to the library -increasingly through local networks, campus networks, and the Internet. -LARSEN supported LYNCH's earlier suggestion that we need to address -fundamental questions of networked information in order to build -environments that scale in the information sense as well as in the -physical sense. - -LARSEN supported the role of the library system as the access point into -the nation's electronic collections. Implementation of the Z39.50 -protocol for information retrieval would make such access practical and -feasible. For example, this would enable patrons in Maryland to search -California libraries, or other libraries around the world that are -conformant with Z39.50 in a manner that is familiar to University of -Maryland patrons. This client-server model also supports moving beyond -secondary content into primary content. (The notion of how one links -from secondary content to primary content, LARSEN said, represents a -fundamental problem that requires rigorous thought.) After noting -numerous network experiments in accessing full-text materials, including -projects supporting the ordering of materials across the network, LARSEN -revisited the issue of transmitting high-density, high-resolution color -images across the network and the large amounts of bandwidth they -require. He went on to address the bandwidth and synchronization -problems inherent in sending full-motion video across the network. - -LARSEN illustrated the trade-off between volumes of data in bytes or -orders of magnitude and the potential usage of that data. He discussed -transmission rates (particularly, the time it takes to move various forms -of information), and what one could do with a network supporting -multigigabit-per-second transmission. At the moment, the network -environment includes a composite of data-transmission requirements, -volumes and forms, going from steady to bursty (high-volume) and from -very slow to very fast. This aggregate must be considered in the design, -construction, and operation of multigigabyte networks. - -LARSEN's objective is to use the networks and library systems now being -constructed to increase access to resources wherever they exist, and -thus, to evolve toward an on-line electronic virtual library. - -LARSEN concluded by offering a snapshot of current trends: continuing -geometric growth in network capacity and number of users; slower -development of applications; and glacial development and adoption of -standards. The challenge is to design and develop each new application -system with network access and scalability in mind. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -BROWNRIGG * Access to the Internet cannot be taken for granted * Packet -radio and the development of MELVYL in 1980-81 in the Division of Library -Automation at the University of California * Design criteria for packet -radio * A demonstration project in San Diego and future plans * Spread -spectrum * Frequencies at which the radios will run and plans to -reimplement the WAIS server software in the public domain * Need for an -infrastructure of radios that do not move around * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Edwin BROWNRIGG, executive director, Memex Research Institute, first -polled the audience in order to seek out regular users of the Internet as -well as those planning to use it some time in the future. With nearly -everybody in the room falling into one category or the other, BROWNRIGG -made a point re access, namely that numerous individuals, especially those -who use the Internet every day, take for granted their access to it, the -speeds with which they are connected, and how well it all works. -However, as BROWNRIGG discovered between 1987 and 1989 in Australia, -if one wants access to the Internet but cannot afford it or has some -physical boundary that prevents her or him from gaining access, it can -be extremely frustrating. He suggested that because of economics and -physical barriers we were beginning to create a world of haves and have-nots -in the process of scholarly communication, even in the United States. - -BROWNRIGG detailed the development of MELVYL in academic year 1980-81 in -the Division of Library Automation at the University of California, in -order to underscore the issue of access to the system, which at the -outset was extremely limited. In short, the project needed to build a -network, which at that time entailed use of satellite technology, that is, -putting earth stations on campus and also acquiring some terrestrial links -from the State of California's microwave system. The installation of -satellite links, however, did not solve the problem (which actually -formed part of a larger problem involving politics and financial resources). -For while the project team could get a signal onto a campus, it had no means -of distributing the signal throughout the campus. The solution involved -adopting a recent development in wireless communication called packet radio, -which combined the basic notion of packet-switching with radio. The project -used this technology to get the signal from a point on campus where it -came down, an earth station for example, into the libraries, because it -found that wiring the libraries, especially the older marble buildings, -would cost $2,000-$5,000 per terminal. - -BROWNRIGG noted that, ten years ago, the project had neither the public -policy nor the technology that would have allowed it to use packet radio -in any meaningful way. Since then much had changed. He proceeded to -detail research and development of the technology, how it is being -deployed in California, and what direction he thought it would take. -The design criteria are to produce a high-speed, one-time, low-cost, -high-quality, secure, license-free device (packet radio) that one can -plug in and play today, forget about it, and have access to the Internet. -By high speed, BROWNRIGG meant 1 megabyte and 1.5 megabytes. Those units -have been built, he continued, and are in the process of being -type-certified by an independent underwriting laboratory so that they can -be type-licensed by the Federal Communications Commission. As is the -case with citizens band, one will be able to purchase a unit and not have -to worry about applying for a license. - -The basic idea, BROWNRIGG elaborated, is to take high-speed radio data -transmission and create a backbone network that at certain strategic -points in the network will "gateway" into a medium-speed packet radio -(i.e., one that runs at 38.4 kilobytes), so that perhaps by 1994-1995 -people, like those in the audience for the price of a VCR could purchase -a medium-speed radio for the office or home, have full network connectivity -to the Internet, and partake of all its services, with no need for an FCC -license and no regular bill from the local common carrier. BROWNRIGG -presented several details of a demonstration project currently taking -place in San Diego and described plans, pending funding, to install a -full-bore network in the San Francisco area. This network will have 600 -nodes running at backbone speeds, and 100 of these nodes will be libraries, -which in turn will be the gateway ports to the 38.4 kilobyte radios that -will give coverage for the neighborhoods surrounding the libraries. - -BROWNRIGG next explained Part 15.247, a new rule within Title 47 of the -Code of Federal Regulations enacted by the FCC in 1985. This rule -challenged the industry, which has only now risen to the occasion, to -build a radio that would run at no more than one watt of output power and -use a fairly exotic method of modulating the radio wave called spread -spectrum. Spread spectrum in fact permits the building of networks so -that numerous data communications can occur simultaneously, without -interfering with each other, within the same wide radio channel. - -BROWNRIGG explained that the frequencies at which the radios would run -are very short wave signals. They are well above standard microwave and -radar. With a radio wave that small, one watt becomes a tremendous punch -per bit and thus makes transmission at reasonable speed possible. In -order to minimize the potential for congestion, the project is -undertaking to reimplement software which has been available in the -networking business and is taken for granted now, for example, TCP/IP, -routing algorithms, bridges, and gateways. In addition, the project -plans to take the WAIS server software in the public domain and -reimplement it so that one can have a WAIS server on a Mac instead of a -Unix machine. The Memex Research Institute believes that libraries, in -particular, will want to use the WAIS servers with packet radio. This -project, which has a team of about twelve people, will run through 1993 -and will include the 100 libraries already mentioned as well as other -professionals such as those in the medical profession, engineering, and -law. Thus, the need is to create an infrastructure of radios that do not -move around, which, BROWNRIGG hopes, will solve a problem not only for -libraries but for individuals who, by and large today, do not have access -to the Internet from their homes and offices. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -DISCUSSION * Project operating frequencies * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -During a brief discussion period, which also concluded the day's -proceedings, BROWNRIGG stated that the project was operating in four -frequencies. The slow speed is operating at 435 megahertz, and it would -later go up to 920 megahertz. With the high-speed frequency, the -one-megabyte radios will run at 2.4 gigabits, and 1.5 will run at 5.7. -At 5.7, rain can be a factor, but it would have to be tropical rain, -unlike what falls in most parts of the United States. - - ****** - -SESSION IV. IMAGE CAPTURE, TEXT CAPTURE, OVERVIEW OF TEXT AND - IMAGE STORAGE FORMATS - -William HOOTON, vice president of operations, I-NET, moderated this session. - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -KENNEY * Factors influencing development of CXP * Advantages of using -digital technology versus photocopy and microfilm * A primary goal of -CXP; publishing challenges * Characteristics of copies printed * Quality -of samples achieved in image capture * Several factors to be considered -in choosing scanning * Emphasis of CXP on timely and cost-effective -production of black-and-white printed facsimiles * Results of producing -microfilm from digital files * Advantages of creating microfilm * Details -concerning production * Costs * Role of digital technology in library -preservation * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Anne KENNEY, associate director, Department of Preservation and -Conservation, Cornell University, opened her talk by observing that the -Cornell Xerox Project (CXP) has been guided by the assumption that the -ability to produce printed facsimiles or to replace paper with paper -would be important, at least for the present generation of users and -equipment. She described three factors that influenced development of -the project: 1) Because the project has emphasized the preservation of -deteriorating brittle books, the quality of what was produced had to be -sufficiently high to return a paper replacement to the shelf. CXP was -only interested in using: 2) a system that was cost-effective, which -meant that it had to be cost-competitive with the processes currently -available, principally photocopy and microfilm, and 3) new or currently -available product hardware and software. - -KENNEY described the advantages that using digital technology offers over -both photocopy and microfilm: 1) The potential exists to create a higher -quality reproduction of a deteriorating original than conventional -light-lens technology. 2) Because a digital image is an encoded -representation, it can be reproduced again and again with no resulting -loss of quality, as opposed to the situation with light-lens processes, -in which there is discernible difference between a second and a -subsequent generation of an image. 3) A digital image can be manipulated -in a number of ways to improve image capture; for example, Xerox has -developed a windowing application that enables one to capture a page -containing both text and illustrations in a manner that optimizes the -reproduction of both. (With light-lens technology, one must choose which -to optimize, text or the illustration; in preservation microfilming, the -current practice is to shoot an illustrated page twice, once to highlight -the text and the second time to provide the best capture for the -illustration.) 4) A digital image can also be edited, density levels -adjusted to remove underlining and stains, and to increase legibility for -faint documents. 5) On-screen inspection can take place at the time of -initial setup and adjustments made prior to scanning, factors that -substantially reduce the number of retakes required in quality control. - -A primary goal of CXP has been to evaluate the paper output printed on -the Xerox DocuTech, a high-speed printer that produces 600-dpi pages from -scanned images at a rate of 135 pages a minute. KENNEY recounted several -publishing challenges to represent faithful and legible reproductions of -the originals that the 600-dpi copy for the most part successfully -captured. For example, many of the deteriorating volumes in the project -were heavily illustrated with fine line drawings or halftones or came in -languages such as Japanese, in which the buildup of characters comprised -of varying strokes is difficult to reproduce at lower resolutions; a -surprising number of them came with annotations and mathematical -formulas, which it was critical to be able to duplicate exactly. - -KENNEY noted that 1) the copies are being printed on paper that meets the -ANSI standards for performance, 2) the DocuTech printer meets the machine -and toner requirements for proper adhesion of print to page, as described -by the National Archives, and thus 3) paper product is considered to be -the archival equivalent of preservation photocopy. - -KENNEY then discussed several samples of the quality achieved in the -project that had been distributed in a handout, for example, a copy of a -print-on-demand version of the 1911 Reed lecture on the steam turbine, -which contains halftones, line drawings, and illustrations embedded in -text; the first four loose pages in the volume compared the capture -capabilities of scanning to photocopy for a standard test target, the -IEEE standard 167A 1987 test chart. In all instances scanning proved -superior to photocopy, though only slightly more so in one. - -Conceding the simplistic nature of her review of the quality of scanning -to photocopy, KENNEY described it as one representation of the kinds of -settings that could be used with scanning capabilities on the equipment -CXP uses. KENNEY also pointed out that CXP investigated the quality -achieved with binary scanning only, and noted the great promise in gray -scale and color scanning, whose advantages and disadvantages need to be -examined. She argued further that scanning resolutions and file formats -can represent a complex trade-off between the time it takes to capture -material, file size, fidelity to the original, and on-screen display; and -printing and equipment availability. All these factors must be taken -into consideration. - -CXP placed primary emphasis on the production in a timely and -cost-effective manner of printed facsimiles that consisted largely of -black-and-white text. With binary scanning, large files may be -compressed efficiently and in a lossless manner (i.e., no data is lost in -the process of compressing [and decompressing] an image--the exact -bit-representation is maintained) using Group 4 CCITT (i.e., the French -acronym for International Consultative Committee for Telegraph and -Telephone) compression. CXP was getting compression ratios of about -forty to one. Gray-scale compression, which primarily uses JPEG, is much -less economical and can represent a lossy compression (i.e., not -lossless), so that as one compresses and decompresses, the illustration -is subtly changed. While binary files produce a high-quality printed -version, it appears 1) that other combinations of spatial resolution with -gray and/or color hold great promise as well, and 2) that gray scale can -represent a tremendous advantage for on-screen viewing. The quality -associated with binary and gray scale also depends on the equipment used. -For instance, binary scanning produces a much better copy on a binary -printer. - -Among CXP's findings concerning the production of microfilm from digital -files, KENNEY reported that the digital files for the same Reed lecture -were used to produce sample film using an electron beam recorder. The -resulting film was faithful to the image capture of the digital files, -and while CXP felt that the text and image pages represented in the Reed -lecture were superior to that of the light-lens film, the resolution -readings for the 600 dpi were not as high as standard microfilming. -KENNEY argued that the standards defined for light-lens technology are -not totally transferable to a digital environment. Moreover, they are -based on definition of quality for a preservation copy. Although making -this case will prove to be a long, uphill struggle, CXP plans to continue -to investigate the issue over the course of the next year. - -KENNEY concluded this portion of her talk with a discussion of the -advantages of creating film: it can serve as a primary backup and as a -preservation master to the digital file; it could then become the print -or production master and service copies could be paper, film, optical -disks, magnetic media, or on-screen display. - -Finally, KENNEY presented details re production: - - * Development and testing of a moderately-high resolution production - scanning workstation represented a third goal of CXP; to date, 1,000 - volumes have been scanned, or about 300,000 images. - - * The resulting digital files are stored and used to produce - hard-copy replacements for the originals and additional prints on - demand; although the initial costs are high, scanning technology - offers an affordable means for reformatting brittle material. - - * A technician in production mode can scan 300 pages per hour when - performing single-sheet scanning, which is a necessity when working - with truly brittle paper; this figure is expected to increase - significantly with subsequent iterations of the software from Xerox; - a three-month time-and-cost study of scanning found that the average - 300-page book would take about an hour and forty minutes to scan - (this figure included the time for setup, which involves keying in - primary bibliographic data, going into quality control mode to - define page size, establishing front-to-back registration, and - scanning sample pages to identify a default range of settings for - the entire book--functions not dissimilar to those performed by - filmers or those preparing a book for photocopy). - - * The final step in the scanning process involved rescans, which - happily were few and far between, representing well under 1 percent - of the total pages scanned. - -In addition to technician time, CXP costed out equipment, amortized over -four years, the cost of storing and refreshing the digital files every -four years, and the cost of printing and binding, book-cloth binding, a -paper reproduction. The total amounted to a little under $65 per single -300-page volume, with 30 percent overhead included--a figure competitive -with the prices currently charged by photocopy vendors. - -Of course, with scanning, in addition to the paper facsimile, one is left -with a digital file from which subsequent copies of the book can be -produced for a fraction of the cost of photocopy, with readers afforded -choices in the form of these copies. - -KENNEY concluded that digital technology offers an electronic means for a -library preservation effort to pay for itself. If a brittle-book program -included the means of disseminating reprints of books that are in demand -by libraries and researchers alike, the initial investment in capture -could be recovered and used to preserve additional but less popular -books. She disclosed that an economic model for a self-sustaining -program could be developed for CXP's report to the Commission on -Preservation and Access (CPA). - -KENNEY stressed that the focus of CXP has been on obtaining high quality -in a production environment. The use of digital technology is viewed as -an affordable alternative to other reformatting options. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -ANDRE * Overview and history of NATDP * Various agricultural CD-ROM -products created inhouse and by service bureaus * Pilot project on -Internet transmission * Additional products in progress * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Pamela ANDRE, associate director for automation, National Agricultural -Text Digitizing Program (NATDP), National Agricultural Library (NAL), -presented an overview of NATDP, which has been underway at NAL the last -four years, before Judith ZIDAR discussed the technical details. ANDRE -defined agricultural information as a broad range of material going from -basic and applied research in the hard sciences to the one-page pamphlets -that are distributed by the cooperative state extension services on such -things as how to grow blueberries. - -NATDP began in late 1986 with a meeting of representatives from the -land-grant library community to deal with the issue of electronic -information. NAL and forty-five of these libraries banded together to -establish this project--to evaluate the technology for converting what -were then source documents in paper form into electronic form, to provide -access to that digital information, and then to distribute it. -Distributing that material to the community--the university community as -well as the extension service community, potentially down to the county -level--constituted the group's chief concern. - -Since January 1988 (when the microcomputer-based scanning system was -installed at NAL), NATDP has done a variety of things, concerning which -ZIDAR would provide further details. For example, the first technology -considered in the project's discussion phase was digital videodisc, which -indicates how long ago it was conceived. - -Over the four years of this project, four separate CD-ROM products on -four different agricultural topics were created, two at a -scanning-and-OCR station installed at NAL, and two by service bureaus. -Thus, NATDP has gained comparative information in terms of those relative -costs. Each of these products contained the full ASCII text as well as -page images of the material, or between 4,000 and 6,000 pages of material -on these disks. Topics included aquaculture, food, agriculture and -science (i.e., international agriculture and research), acid rain, and -Agent Orange, which was the final product distributed (approximately -eighteen months before the Workshop). - -The third phase of NATDP focused on delivery mechanisms other than -CD-ROM. At the suggestion of Clifford LYNCH, who was a technical -consultant to the project at this point, NATDP became involved with the -Internet and initiated a project with the help of North Carolina State -University, in which fourteen of the land-grant university libraries are -transmitting digital images over the Internet in response to interlibrary -loan requests--a topic for another meeting. At this point, the pilot -project had been completed for about a year and the final report would be -available shortly after the Workshop. In the meantime, the project's -success had led to its extension. (ANDRE noted that one of the first -things done under the program title was to select a retrieval package to -use with subsequent products; Windows Personal Librarian was the package -of choice after a lengthy evaluation.) - -Three additional products had been planned and were in progress: - - 1) An arrangement with the American Society of Agronomy--a - professional society that has published the Agronomy Journal since - about 1908--to scan and create bit-mapped images of its journal. - ASA granted permission first to put and then to distribute this - material in electronic form, to hold it at NAL, and to use these - electronic images as a mechanism to deliver documents or print out - material for patrons, among other uses. Effectively, NAL has the - right to use this material in support of its program. - (Significantly, this arrangement offers a potential cooperative - model for working with other professional societies in agriculture - to try to do the same thing--put the journals of particular interest - to agriculture research into electronic form.) - - 2) An extension of the earlier product on aquaculture. - - 3) The George Washington Carver Papers--a joint project with - Tuskegee University to scan and convert from microfilm some 3,500 - images of Carver's papers, letters, and drawings. - -It was anticipated that all of these products would appear no more than -six months after the Workshop. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -ZIDAR * (A separate arena for scanning) * Steps in creating a database * -Image capture, with and without performing OCR * Keying in tracking data -* Scanning, with electronic and manual tracking * Adjustments during -scanning process * Scanning resolutions * Compression * De-skewing and -filtering * Image capture from microform: the papers and letters of -George Washington Carver * Equipment used for a scanning system * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Judith ZIDAR, coordinator, National Agricultural Text Digitizing Program -(NATDP), National Agricultural Library (NAL), illustrated the technical -details of NATDP, including her primary responsibility, scanning and -creating databases on a topic and putting them on CD-ROM. - -(ZIDAR remarked a separate arena from the CD-ROM projects, although the -processing of the material is nearly identical, in which NATDP is also -scanning material and loading it on a Next microcomputer, which in turn -is linked to NAL's integrated library system. Thus, searches in NAL's -bibliographic database will enable people to pull up actual page images -and text for any documents that have been entered.) - -In accordance with the session's topic, ZIDAR focused her illustrated -talk on image capture, offering a primer on the three main steps in the -process: 1) assemble the printed publications; 2) design the database -(database design occurs in the process of preparing the material for -scanning; this step entails reviewing and organizing the material, -defining the contents--what will constitute a record, what kinds of -fields will be captured in terms of author, title, etc.); 3) perform a -certain amount of markup on the paper publications. NAL performs this -task record by record, preparing work sheets or some other sort of -tracking material and designing descriptors and other enhancements to be -added to the data that will not be captured from the printed publication. -Part of this process also involves determining NATDP's file and directory -structure: NATDP attempts to avoid putting more than approximately 100 -images in a directory, because placing more than that on a CD-ROM would -reduce the access speed. - -This up-front process takes approximately two weeks for a -6,000-7,000-page database. The next step is to capture the page images. -How long this process takes is determined by the decision whether or not -to perform OCR. Not performing OCR speeds the process, whereas text -capture requires greater care because of the quality of the image: it -has to be straighter and allowance must be made for text on a page, not -just for the capture of photographs. - -NATDP keys in tracking data, that is, a standard bibliographic record -including the title of the book and the title of the chapter, which will -later either become the access information or will be attached to the -front of a full-text record so that it is searchable. - -Images are scanned from a bound or unbound publication, chiefly from -bound publications in the case of NATDP, however, because often they are -the only copies and the publications are returned to the shelves. NATDP -usually scans one record at a time, because its database tracking system -tracks the document in that way and does not require further logical -separating of the images. After performing optical character -recognition, NATDP moves the images off the hard disk and maintains a -volume sheet. Though the system tracks electronically, all the -processing steps are also tracked manually with a log sheet. - -ZIDAR next illustrated the kinds of adjustments that one can make when -scanning from paper and microfilm, for example, redoing images that need -special handling, setting for dithering or gray scale, and adjusting for -brightness or for the whole book at one time. - -NATDP is scanning at 300 dots per inch, a standard scanning resolution. -Though adequate for capturing text that is all of a standard size, 300 -dpi is unsuitable for any kind of photographic material or for very small -text. Many scanners allow for different image formats, TIFF, of course, -being a de facto standard. But if one intends to exchange images with -other people, the ability to scan other image formats, even if they are -less common, becomes highly desirable. - -CCITT Group 4 is the standard compression for normal black-and-white -images, JPEG for gray scale or color. ZIDAR recommended 1) using the -standard compressions, particularly if one attempts to make material -available and to allow users to download images and reuse them from -CD-ROMs; and 2) maintaining the ability to output an uncompressed image, -because in image exchange uncompressed images are more likely to be able -to cross platforms. - -ZIDAR emphasized the importance of de-skewing and filtering as -requirements on NATDP's upgraded system. For instance, scanning bound -books, particularly books published by the federal government whose pages -are skewed, and trying to scan them straight if OCR is to be performed, -is extremely time-consuming. The same holds for filtering of -poor-quality or older materials. - -ZIDAR described image capture from microform, using as an example three -reels from a sixty-seven-reel set of the papers and letters of George -Washington Carver that had been produced by Tuskegee University. These -resulted in approximately 3,500 images, which NATDP had had scanned by -its service contractor, Science Applications International Corporation -(SAIC). NATDP also created bibliographic records for access. (NATDP did -not have such specialized equipment as a microfilm scanner. - -Unfortunately, the process of scanning from microfilm was not an -unqualified success, ZIDAR reported: because microfilm frame sizes vary, -occasionally some frames were missed, which without spending much time -and money could not be recaptured. - -OCR could not be performed from the scanned images of the frames. The -bleeding in the text simply output text, when OCR was run, that could not -even be edited. NATDP tested for negative versus positive images, -landscape versus portrait orientation, and single- versus dual-page -microfilm, none of which seemed to affect the quality of the image; but -also on none of them could OCR be performed. - -In selecting the microfilm they would use, therefore, NATDP had other -factors in mind. ZIDAR noted two factors that influenced the quality of -the images: 1) the inherent quality of the original and 2) the amount of -size reduction on the pages. - -The Carver papers were selected because they are informative and visually -interesting, treat a single subject, and are valuable in their own right. -The images were scanned and divided into logical records by SAIC, then -delivered, and loaded onto NATDP's system, where bibliographic -information taken directly from the images was added. Scanning was -completed in summer 1991 and by the end of summer 1992 the disk was -scheduled to be published. - -Problems encountered during processing included the following: Because -the microfilm scanning had to be done in a batch, adjustment for -individual page variations was not possible. The frame size varied on -account of the nature of the material, and therefore some of the frames -were missed while others were just partial frames. The only way to go -back and capture this material was to print out the page with the -microfilm reader from the missing frame and then scan it in from the -page, which was extremely time-consuming. The quality of the images -scanned from the printout of the microfilm compared unfavorably with that -of the original images captured directly from the microfilm. The -inability to perform OCR also was a major disappointment. At the time, -computer output microfilm was unavailable to test. - -The equipment used for a scanning system was the last topic addressed by -ZIDAR. The type of equipment that one would purchase for a scanning -system included: a microcomputer, at least a 386, but preferably a 486; -a large hard disk, 380 megabyte at minimum; a multi-tasking operating -system that allows one to run some things in batch in the background -while scanning or doing text editing, for example, Unix or OS/2 and, -theoretically, Windows; a high-speed scanner and scanning software that -allows one to make the various adjustments mentioned earlier; a -high-resolution monitor (150 dpi ); OCR software and hardware to perform -text recognition; an optical disk subsystem on which to archive all the -images as the processing is done; file management and tracking software. - -ZIDAR opined that the software one purchases was more important than the -hardware and might also cost more than the hardware, but it was likely to -prove critical to the success or failure of one's system. In addition to -a stand-alone scanning workstation for image capture, then, text capture -requires one or two editing stations networked to this scanning station -to perform editing. Editing the text takes two or three times as long as -capturing the images. - -Finally, ZIDAR stressed the importance of buying an open system that allows -for more than one vendor, complies with standards, and can be upgraded. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -WATERS *Yale University Library's master plan to convert microfilm to -digital imagery (POB) * The place of electronic tools in the library of -the future * The uses of images and an image library * Primary input from -preservation microfilm * Features distinguishing POB from CXP and key -hypotheses guiding POB * Use of vendor selection process to facilitate -organizational work * Criteria for selecting vendor * Finalists and -results of process for Yale * Key factor distinguishing vendors * -Components, design principles, and some estimated costs of POB * Role of -preservation materials in developing imaging market * Factors affecting -quality and cost * Factors affecting the usability of complex documents -in image form * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Donald WATERS, head of the Systems Office, Yale University Library, -reported on the progress of a master plan for a project at Yale to -convert microfilm to digital imagery, Project Open Book (POB). Stating -that POB was in an advanced stage of planning, WATERS detailed, in -particular, the process of selecting a vendor partner and several key -issues under discussion as Yale prepares to move into the project itself. -He commented first on the vision that serves as the context of POB and -then described its purpose and scope. - -WATERS sees the library of the future not necessarily as an electronic -library but as a place that generates, preserves, and improves for its -clients ready access to both intellectual and physical recorded -knowledge. Electronic tools must find a place in the library in the -context of this vision. Several roles for electronic tools include -serving as: indirect sources of electronic knowledge or as "finding" -aids (the on-line catalogues, the article-level indices, registers for -documents and archives); direct sources of recorded knowledge; full-text -images; and various kinds of compound sources of recorded knowledge (the -so-called compound documents of Hypertext, mixed text and image, -mixed-text image format, and multimedia). - -POB is looking particularly at images and an image library, the uses to -which images will be put (e.g., storage, printing, browsing, and then use -as input for other processes), OCR as a subsequent process to image -capture, or creating an image library, and also possibly generating -microfilm. - -While input will come from a variety of sources, POB is considering -especially input from preservation microfilm. A possible outcome is that -the film and paper which provide the input for the image library -eventually may go off into remote storage, and that the image library may -be the primary access tool. - -The purpose and scope of POB focus on imaging. Though related to CXP, -POB has two features which distinguish it: 1) scale--conversion of -10,000 volumes into digital image form; and 2) source--conversion from -microfilm. Given these features, several key working hypotheses guide -POB, including: 1) Since POB is using microfilm, it is not concerned with -the image library as a preservation medium. 2) Digital imagery can improve -access to recorded knowledge through printing and network distribution at -a modest incremental cost of microfilm. 3) Capturing and storing documents -in a digital image form is necessary to further improvements in access. -(POB distinguishes between the imaging, digitizing process and OCR, -which at this stage it does not plan to perform.) - -Currently in its first or organizational phase, POB found that it could -use a vendor selection process to facilitate a good deal of the -organizational work (e.g., creating a project team and advisory board, -confirming the validity of the plan, establishing the cost of the project -and a budget, selecting the materials to convert, and then raising the -necessary funds). - -POB developed numerous selection criteria, including: a firm committed -to image-document management, the ability to serve as systems integrator -in a large-scale project over several years, interest in developing the -requisite software as a standard rather than a custom product, and a -willingness to invest substantial resources in the project itself. - -Two vendors, DEC and Xerox, were selected as finalists in October 1991, -and with the support of the Commission on Preservation and Access, each -was commissioned to generate a detailed requirements analysis for the -project and then to submit a formal proposal for the completion of the -project, which included a budget and costs. The terms were that POB would -pay the loser. The results for Yale of involving a vendor included: -broad involvement of Yale staff across the board at a relatively low -cost, which may have long-term significance in carrying out the project -(twenty-five to thirty university people are engaged in POB); better -understanding of the factors that affect corporate response to markets -for imaging products; a competitive proposal; and a more sophisticated -view of the imaging markets. - -The most important factor that distinguished the vendors under -consideration was their identification with the customer. The size and -internal complexity of the company also was an important factor. POB was -looking at large companies that had substantial resources. In the end, -the process generated for Yale two competitive proposals, with Xerox's -the clear winner. WATERS then described the components of the proposal, -the design principles, and some of the costs estimated for the process. - -Components are essentially four: a conversion subsystem, a -network-accessible storage subsystem for 10,000 books (and POB expects -200 to 600 dpi storage), browsing stations distributed on the campus -network, and network access to the image printers. - -Among the design principles, POB wanted conversion at the highest -possible resolution. Assuming TIFF files, TIFF files with Group 4 -compression, TCP/IP, and ethernet network on campus, POB wanted a -client-server approach with image documents distributed to the -workstations and made accessible through native workstation interfaces -such as Windows. POB also insisted on a phased approach to -implementation: 1) a stand-alone, single-user, low-cost entry into the -business with a workstation focused on conversion and allowing POB to -explore user access; 2) movement into a higher-volume conversion with -network-accessible storage and multiple access stations; and 3) a -high-volume conversion, full-capacity storage, and multiple browsing -stations distributed throughout the campus. - -The costs proposed for start-up assumed the existence of the Yale network -and its two DocuTech image printers. Other start-up costs are estimated -at $1 million over the three phases. At the end of the project, the annual -operating costs estimated primarily for the software and hardware proposed -come to about $60,000, but these exclude costs for labor needed in the -conversion process, network and printer usage, and facilities management. - -Finally, the selection process produced for Yale a more sophisticated -view of the imaging markets: the management of complex documents in -image form is not a preservation problem, not a library problem, but a -general problem in a broad, general industry. Preservation materials are -useful for developing that market because of the qualities of the -material. For example, much of it is out of copyright. The resolution -of key issues such as the quality of scanning and image browsing also -will affect development of that market. - -The technology is readily available but changing rapidly. In this -context of rapid change, several factors affect quality and cost, to -which POB intends to pay particular attention, for example, the various -levels of resolution that can be achieved. POB believes it can bring -resolution up to 600 dpi, but an interpolation process from 400 to 600 is -more likely. The variation quality in microfilm will prove to be a -highly important factor. POB may reexamine the standards used to film in -the first place by looking at this process as a follow-on to microfilming. - -Other important factors include: the techniques available to the -operator for handling material, the ways of integrating quality control -into the digitizing work flow, and a work flow that includes indexing and -storage. POB's requirement was to be able to deal with quality control -at the point of scanning. Thus, thanks to Xerox, POB anticipates having -a mechanism which will allow it not only to scan in batch form, but to -review the material as it goes through the scanner and control quality -from the outset. - -The standards for measuring quality and costs depend greatly on the uses -of the material, including subsequent OCR, storage, printing, and -browsing. But especially at issue for POB is the facility for browsing. -This facility, WATERS said, is perhaps the weakest aspect of imaging -technology and the most in need of development. - -A variety of factors affect the usability of complex documents in image -form, among them: 1) the ability of the system to handle the full range -of document types, not just monographs but serials, multi-part -monographs, and manuscripts; 2) the location of the database of record -for bibliographic information about the image document, which POB wants -to enter once and in the most useful place, the on-line catalog; 3) a -document identifier for referencing the bibliographic information in one -place and the images in another; 4) the technique for making the basic -internal structure of the document accessible to the reader; and finally, -5) the physical presentation on the CRT of those documents. POB is ready -to complete this phase now. One last decision involves deciding which -material to scan. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -DISCUSSION * TIFF files constitute de facto standard * NARA's experience -with image conversion software and text conversion * RFC 1314 * -Considerable flux concerning available hardware and software solutions * -NAL through-put rate during scanning * Window management questions * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -In the question-and-answer period that followed WATERS's presentation, -the following points emerged: - - * ZIDAR's statement about using TIFF files as a standard meant de - facto standard. This is what most people use and typically exchange - with other groups, across platforms, or even occasionally across - display software. - - * HOLMES commented on the unsuccessful experience of NARA in - attempting to run image-conversion software or to exchange between - applications: What are supposedly TIFF files go into other software - that is supposed to be able to accept TIFF but cannot recognize the - format and cannot deal with it, and thus renders the exchange - useless. Re text conversion, he noted the different recognition - rates obtained by substituting the make and model of scanners in - NARA's recent test of an "intelligent" character-recognition product - for a new company. In the selection of hardware and software, - HOLMES argued, software no longer constitutes the overriding factor - it did until about a year ago; rather it is perhaps important to - look at both now. - - * Danny Cohen and Alan Katz of the University of Southern California - Information Sciences Institute began circulating as an Internet RFC - (RFC 1314) about a month ago a standard for a TIFF interchange - format for Internet distribution of monochrome bit-mapped images, - which LYNCH said he believed would be used as a de facto standard. - - * FLEISCHHAUER's impression from hearing these reports and thinking - about AM's experience was that there is considerable flux concerning - available hardware and software solutions. HOOTON agreed and - commented at the same time on ZIDAR's statement that the equipment - employed affects the results produced. One cannot draw a complete - conclusion by saying it is difficult or impossible to perform OCR - from scanning microfilm, for example, with that device, that set of - parameters, and system requirements, because numerous other people - are accomplishing just that, using other components, perhaps. - HOOTON opined that both the hardware and the software were highly - important. Most of the problems discussed today have been solved in - numerous different ways by other people. Though it is good to be - cognizant of various experiences, this is not to say that it will - always be thus. - - * At NAL, the through-put rate of the scanning process for paper, - page by page, performing OCR, ranges from 300 to 600 pages per day; - not performing OCR is considerably faster, although how much faster - is not known. This is for scanning from bound books, which is much - slower. - - * WATERS commented on window management questions: DEC proposed an - X-Windows solution which was problematical for two reasons. One was - POB's requirement to be able to manipulate images on the workstation - and bring them down to the workstation itself and the other was - network usage. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -THOMA * Illustration of deficiencies in scanning and storage process * -Image quality in this process * Different costs entailed by better image -quality * Techniques for overcoming various de-ficiencies: fixed -thresholding, dynamic thresholding, dithering, image merge * Page edge -effects * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -George THOMA, chief, Communications Engineering Branch, National Library -of Medicine (NLM), illustrated several of the deficiencies discussed by -the previous speakers. He introduced the topic of special problems by -noting the advantages of electronic imaging. For example, it is regenerable -because it is a coded file, and real-time quality control is possible with -electronic capture, whereas in photographic capture it is not. - -One of the difficulties discussed in the scanning and storage process was -image quality which, without belaboring the obvious, means different -things for maps, medical X-rays, or broadcast television. In the case of -documents, THOMA said, image quality boils down to legibility of the -textual parts, and fidelity in the case of gray or color photo print-type -material. Legibility boils down to scan density, the standard in most -cases being 300 dpi. Increasing the resolution with scanners that -perform 600 or 1200 dpi, however, comes at a cost. - -Better image quality entails at least four different kinds of costs: 1) -equipment costs, because the CCD (i.e., charge-couple device) with -greater number of elements costs more; 2) time costs that translate to -the actual capture costs, because manual labor is involved (the time is -also dependent on the fact that more data has to be moved around in the -machine in the scanning or network devices that perform the scanning as -well as the storage); 3) media costs, because at high resolutions larger -files have to be stored; and 4) transmission costs, because there is just -more data to be transmitted. - -But while resolution takes care of the issue of legibility in image -quality, other deficiencies have to do with contrast and elements on the -page scanned or the image that needed to be removed or clarified. Thus, -THOMA proceeded to illustrate various deficiencies, how they are -manifested, and several techniques to overcome them. - -Fixed thresholding was the first technique described, suitable for -black-and-white text, when the contrast does not vary over the page. One -can have many different threshold levels in scanning devices. Thus, -THOMA offered an example of extremely poor contrast, which resulted from -the fact that the stock was a heavy red. This is the sort of image that -when microfilmed fails to provide any legibility whatsoever. Fixed -thresholding is the way to change the black-to-red contrast to the -desired black-to-white contrast. - -Other examples included material that had been browned or yellowed by -age. This was also a case of contrast deficiency, and correction was -done by fixed thresholding. A final example boils down to the same -thing, slight variability, but it is not significant. Fixed thresholding -solves this problem as well. The microfilm equivalent is certainly legible, -but it comes with dark areas. Though THOMA did not have a slide of the -microfilm in this case, he did show the reproduced electronic image. - -When one has variable contrast over a page or the lighting over the page -area varies, especially in the case where a bound volume has light -shining on it, the image must be processed by a dynamic thresholding -scheme. One scheme, dynamic averaging, allows the threshold level not to -be fixed but to be recomputed for every pixel from the neighboring -characteristics. The neighbors of a pixel determine where the threshold -should be set for that pixel. - -THOMA showed an example of a page that had been made deficient by a -variety of techniques, including a burn mark, coffee stains, and a yellow -marker. Application of a fixed-thresholding scheme, THOMA argued, might -take care of several deficiencies on the page but not all of them. -Performing the calculation for a dynamic threshold setting, however, -removes most of the deficiencies so that at least the text is legible. - -Another problem is representing a gray level with black-and-white pixels -by a process known as dithering or electronic screening. But dithering -does not provide good image quality for pure black-and-white textual -material. THOMA illustrated this point with examples. Although its -suitability for photoprint is the reason for electronic screening or -dithering, it cannot be used for every compound image. In the document -that was distributed by CXP, THOMA noticed that the dithered image of the -IEEE test chart evinced some deterioration in the text. He presented an -extreme example of deterioration in the text in which compounded -documents had to be set right by other techniques. The technique -illustrated by the present example was an image merge in which the page -is scanned twice and the settings go from fixed threshold to the -dithering matrix; the resulting images are merged to give the best -results with each technique. - -THOMA illustrated how dithering is also used in nonphotographic or -nonprint materials with an example of a grayish page from a medical text, -which was reproduced to show all of the gray that appeared in the -original. Dithering provided a reproduction of all the gray in the -original of another example from the same text. - -THOMA finally illustrated the problem of bordering, or page-edge, -effects. Books and bound volumes that are placed on a photocopy machine -or a scanner produce page-edge effects that are undesirable for two -reasons: 1) the aesthetics of the image; after all, if the image is to -be preserved, one does not necessarily want to keep all of its -deficiencies; 2) compression (with the bordering problem THOMA -illustrated, the compression ratio deteriorated tremendously). One way -to eliminate this more serious problem is to have the operator at the -point of scanning window the part of the image that is desirable and -automatically turn all of the pixels out of that picture to white. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -FLEISCHHAUER * AM's experience with scanning bound materials * Dithering -* -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Carl FLEISCHHAUER, coordinator, American Memory, Library of Congress, -reported AM's experience with scanning bound materials, which he likened -to the problems involved in using photocopying machines. Very few -devices in the industry offer book-edge scanning, let alone book cradles. -The problem may be unsolvable, FLEISCHHAUER said, because a large enough -market does not exist for a preservation-quality scanner. AM is using a -Kurzweil scanner, which is a book-edge scanner now sold by Xerox. - -Devoting the remainder of his brief presentation to dithering, -FLEISCHHAUER related AM's experience with a contractor who was using -unsophisticated equipment and software to reduce moire patterns from -printed halftones. AM took the same image and used the dithering -algorithm that forms part of the same Kurzweil Xerox scanner; it -disguised moire patterns much more effectively. - -FLEISCHHAUER also observed that dithering produces a binary file which is -useful for numerous purposes, for example, printing it on a laser printer -without having to "re-halftone" it. But it tends to defeat efficient -compression, because the very thing that dithers to reduce moire patterns -also tends to work against compression schemes. AM thought the -difference in image quality was worth it. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -DISCUSSION * Relative use as a criterion for POB's selection of books to -be converted into digital form * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -During the discussion period, WATERS noted that one of the criteria for -selecting books among the 10,000 to be converted into digital image form -would be how much relative use they would receive--a subject still -requiring evaluation. The challenge will be to understand whether -coherent bodies of material will increase usage or whether POB should -seek material that is being used, scan that, and make it more accessible. -POB might decide to digitize materials that are already heavily used, in -order to make them more accessible and decrease wear on them. Another -approach would be to provide a large body of intellectually coherent -material that may be used more in digital form than it is currently used -in microfilm. POB would seek material that was out of copyright. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -BARONAS * Origin and scope of AIIM * Types of documents produced in -AIIM's standards program * Domain of AIIM's standardization work * AIIM's -structure * TC 171 and MS23 * Electronic image management standards * -Categories of EIM standardization where AIIM standards are being -developed * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Jean BARONAS, senior manager, Department of Standards and Technology, -Association for Information and Image Management (AIIM), described the -not-for-profit association and the national and international programs -for standardization in which AIIM is active. - -Accredited for twenty-five years as the nation's standards development -organization for document image management, AIIM began life in a library -community developing microfilm standards. Today the association -maintains both its library and business-image management standardization -activities--and has moved into electronic image-management -standardization (EIM). - -BARONAS defined the program's scope. AIIM deals with: 1) the -terminology of standards and of the technology it uses; 2) methods of -measurement for the systems, as well as quality; 3) methodologies for -users to evaluate and measure quality; 4) the features of apparatus used -to manage and edit images; and 5) the procedures used to manage images. - -BARONAS noted that three types of documents are produced in the AIIM -standards program: the first two, accredited by the American National -Standards Institute (ANSI), are standards and standard recommended -practices. Recommended practices differ from standards in that they -contain more tutorial information. A technical report is not an ANSI -standard. Because AIIM's policies and procedures for developing -standards are approved by ANSI, its standards are labeled ANSI/AIIM, -followed by the number and title of the standard. - -BARONAS then illustrated the domain of AIIM's standardization work. For -example, AIIM is the administrator of the U.S. Technical Advisory Group -(TAG) to the International Standards Organization's (ISO) technical -committee, TC l7l Micrographics and Optical Memories for Document and -Image Recording, Storage, and Use. AIIM officially works through ANSI in -the international standardization process. - -BARONAS described AIIM's structure, including its board of directors, its -standards board of twelve individuals active in the image-management -industry, its strategic planning and legal admissibility task forces, and -its National Standards Council, which is comprised of the members of a -number of organizations who vote on every AIIM standard before it is -published. BARONAS pointed out that AIIM's liaisons deal with numerous -other standards developers, including the optical disk community, office -and publishing systems, image-codes-and-character set committees, and the -National Information Standards Organization (NISO). - -BARONAS illustrated the procedures of TC l7l, which covers all aspects of -image management. When AIIM's national program has conceptualized a new -project, it is usually submitted to the international level, so that the -member countries of TC l7l can simultaneously work on the development of -the standard or the technical report. BARONAS also illustrated a classic -microfilm standard, MS23, which deals with numerous imaging concepts that -apply to electronic imaging. Originally developed in the l970s, revised -in the l980s, and revised again in l991, this standard is scheduled for -another revision. MS23 is an active standard whereby users may propose -new density ranges and new methods of evaluating film images in the -standard's revision. - -BARONAS detailed several electronic image-management standards, for -instance, ANSI/AIIM MS44, a quality-control guideline for scanning 8.5" -by 11" black-and-white office documents. This standard is used with the -IEEE fax image--a continuous tone photographic image with gray scales, -text, and several continuous tone pictures--and AIIM test target number -2, a representative document used in office document management. - -BARONAS next outlined the four categories of EIM standardization in which -AIIM standards are being developed: transfer and retrieval, evaluation, -optical disc and document scanning applications, and design and -conversion of documents. She detailed several of the main projects of -each: 1) in the category of image transfer and retrieval, a bi-level -image transfer format, ANSI/AIIM MS53, which is a proposed standard that -describes a file header for image transfer between unlike systems when -the images are compressed using G3 and G4 compression; 2) the category of -image evaluation, which includes the AIIM-proposed TR26 tutorial on image -resolution (this technical report will treat the differences and -similarities between classical or photographic and electronic imaging); -3) design and conversion, which includes a proposed technical report -called "Forms Design Optimization for EIM" (this report considers how -general-purpose business forms can be best designed so that scanning is -optimized; reprographic characteristics such as type, rules, background, -tint, and color will likewise be treated in the technical report); 4) -disk and document scanning applications includes a project a) on planning -platters and disk management, b) on generating an application profile for -EIM when images are stored and distributed on CD-ROM, and c) on -evaluating SCSI2, and how a common command set can be generated for SCSI2 -so that document scanners are more easily integrated. (ANSI/AIIM MS53 -will also apply to compressed images.) - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -BATTIN * The implications of standards for preservation * A major -obstacle to successful cooperation * A hindrance to access in the digital -environment * Standards a double-edged sword for those concerned with the -preservation of the human record * Near-term prognosis for reliable -archival standards * Preservation concerns for electronic media * Need -for reconceptualizing our preservation principles * Standards in the real -world and the politics of reproduction * Need to redefine the concept of -archival and to begin to think in terms of life cycles * Cooperation and -the La Guardia Eight * Concerns generated by discussions on the problems -of preserving text and image * General principles to be adopted in a -world without standards * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Patricia BATTIN, president, the Commission on Preservation and Access -(CPA), addressed the implications of standards for preservation. She -listed several areas where the library profession and the analog world of -the printed book had made enormous contributions over the past hundred -years--for example, in bibliographic formats, binding standards, and, most -important, in determining what constitutes longevity or archival quality. - -Although standards have lightened the preservation burden through the -development of national and international collaborative programs, -nevertheless, a pervasive mistrust of other people's standards remains a -major obstacle to successful cooperation, BATTIN said. - -The zeal to achieve perfection, regardless of the cost, has hindered -rather than facilitated access in some instances, and in the digital -environment, where no real standards exist, has brought an ironically -just reward. - -BATTIN argued that standards are a double-edged sword for those concerned -with the preservation of the human record, that is, the provision of -access to recorded knowledge in a multitude of media as far into the -future as possible. Standards are essential to facilitate -interconnectivity and access, but, BATTIN said, as LYNCH pointed out -yesterday, if set too soon they can hinder creativity, expansion of -capability, and the broadening of access. The characteristics of -standards for digital imagery differ radically from those for analog -imagery. And the nature of digital technology implies continuing -volatility and change. To reiterate, precipitous standard-setting can -inhibit creativity, but delayed standard-setting results in chaos. - -Since in BATTIN'S opinion the near-term prognosis for reliable archival -standards, as defined by librarians in the analog world, is poor, two -alternatives remain: standing pat with the old technology, or -reconceptualizing. - -Preservation concerns for electronic media fall into two general domains. -One is the continuing assurance of access to knowledge originally -generated, stored, disseminated, and used in electronic form. This -domain contains several subdivisions, including 1) the closed, -proprietary systems discussed the previous day, bundled information such -as electronic journals and government agency records, and electronically -produced or captured raw data; and 2) the application of digital -technologies to the reformatting of materials originally published on a -deteriorating analog medium such as acid paper or videotape. - -The preservation of electronic media requires a reconceptualizing of our -preservation principles during a volatile, standardless transition which -may last far longer than any of us envision today. BATTIN urged the -necessity of shifting focus from assessing, measuring, and setting -standards for the permanence of the medium to the concept of managing -continuing access to information stored on a variety of media and -requiring a variety of ever-changing hardware and software for access--a -fundamental shift for the library profession. - -BATTIN offered a primer on how to move forward with reasonable confidence -in a world without standards. Her comments fell roughly into two sections: -1) standards in the real world and 2) the politics of reproduction. - -In regard to real-world standards, BATTIN argued the need to redefine the -concept of archive and to begin to think in terms of life cycles. In -the past, the naive assumption that paper would last forever produced a -cavalier attitude toward life cycles. The transient nature of the -electronic media has compelled people to recognize and accept upfront the -concept of life cycles in place of permanency. - -Digital standards have to be developed and set in a cooperative context -to ensure efficient exchange of information. Moreover, during this -transition period, greater flexibility concerning how concepts such as -backup copies and archival copies in the CXP are defined is necessary, -or the opportunity to move forward will be lost. - -In terms of cooperation, particularly in the university setting, BATTIN -also argued the need to avoid going off in a hundred different -directions. The CPA has catalyzed a small group of universities called -the La Guardia Eight--because La Guardia Airport is where meetings take -place--Harvard, Yale, Cornell, Princeton, Penn State, Tennessee, -Stanford, and USC, to develop a digital preservation consortium to look -at all these issues and develop de facto standards as we move along, -instead of waiting for something that is officially blessed. Continuing -to apply analog values and definitions of standards to the digital -environment, BATTIN said, will effectively lead to forfeiture of the -benefits of digital technology to research and scholarship. - -Under the second rubric, the politics of reproduction, BATTIN reiterated -an oft-made argument concerning the electronic library, namely, that it -is more difficult to transform than to create, and nowhere is that belief -expressed more dramatically than in the conversion of brittle books to -new media. Preserving information published in electronic media involves -making sure the information remains accessible and that digital -information is not lost through reproduction. In the analog world of -photocopies and microfilm, the issue of fidelity to the original becomes -paramount, as do issues of "Whose fidelity?" and "Whose original?" - -BATTIN elaborated these arguments with a few examples from a recent study -conducted by the CPA on the problems of preserving text and image. -Discussions with scholars, librarians, and curators in a variety of -disciplines dependent on text and image generated a variety of concerns, -for example: 1) Copy what is, not what the technology is capable of. -This is very important for the history of ideas. Scholars wish to know -what the author saw and worked from. And make available at the -workstation the opportunity to erase all the defects and enhance the -presentation. 2) The fidelity of reproduction--what is good enough, what -can we afford, and the difference it makes--issues of subjective versus -objective resolution. 3) The differences between primary and secondary -users. Restricting the definition of primary user to the one in whose -discipline the material has been published runs one headlong into the -reality that these printed books have had a host of other users from a -host of other disciplines, who not only were looking for very different -things, but who also shared values very different from those of the -primary user. 4) The relationship of the standard of reproduction to new -capabilities of scholarship--the browsing standard versus an archival -standard. How good must the archival standard be? Can a distinction be -drawn between potential users in setting standards for reproduction? -Archival storage, use copies, browsing copies--ought an attempt to set -standards even be made? 5) Finally, costs. How much are we prepared to -pay to capture absolute fidelity? What are the trade-offs between vastly -enhanced access, degrees of fidelity, and costs? - -These standards, BATTIN concluded, serve to complicate further the -reproduction process, and add to the long list of technical standards -that are necessary to ensure widespread access. Ways to articulate and -analyze the costs that are attached to the different levels of standards -must be found. - -Given the chaos concerning standards, which promises to linger for the -foreseeable future, BATTIN urged adoption of the following general -principles: - - * Strive to understand the changing information requirements of - scholarly disciplines as more and more technology is integrated into - the process of research and scholarly communication in order to meet - future scholarly needs, not to build for the past. Capture - deteriorating information at the highest affordable resolution, even - though the dissemination and display technologies will lag. - - * Develop cooperative mechanisms to foster agreement on protocols - for document structure and other interchange mechanisms necessary - for widespread dissemination and use before official standards are - set. - - * Accept that, in a transition period, de facto standards will have - to be developed. - - * Capture information in a way that keeps all options open and - provides for total convertibility: OCR, scanning of microfilm, - producing microfilm from scanned documents, etc. - - * Work closely with the generators of information and the builders - of networks and databases to ensure that continuing accessibility is - a primary concern from the beginning. - - * Piggyback on standards under development for the broad market, and - avoid library-specific standards; work with the vendors, in order to - take advantage of that which is being standardized for the rest of - the world. - - * Concentrate efforts on managing permanence in the digital world, - rather than perfecting the longevity of a particular medium. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -DISCUSSION * Additional comments on TIFF * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -During the brief discussion period that followed BATTIN's presentation, -BARONAS explained that TIFF was not developed in collaboration with or -under the auspices of AIIM. TIFF is a company product, not a standard, -is owned by two corporations, and is always changing. BARONAS also -observed that ANSI/AIIM MS53, a bi-level image file transfer format that -allows unlike systems to exchange images, is compatible with TIFF as well -as with DEC's architecture and IBM's MODCA/IOCA. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -HOOTON * Several questions to be considered in discussing text conversion -* -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -HOOTON introduced the final topic, text conversion, by noting that it is -becoming an increasingly important part of the imaging business. Many -people now realize that it enhances their system to be able to have more -and more character data as part of their imaging system. Re the issue of -OCR versus rekeying, HOOTON posed several questions: How does one get -text into computer-readable form? Does one use automated processes? -Does one attempt to eliminate the use of operators where possible? -Standards for accuracy, he said, are extremely important: it makes a -major difference in cost and time whether one sets as a standard 98.5 -percent acceptance or 99.5 percent. He mentioned outsourcing as a -possibility for converting text. Finally, what one does with the image -to prepare it for the recognition process is also important, he said, -because such preparation changes how recognition is viewed, as well as -facilitates recognition itself. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -LESK * Roles of participants in CORE * Data flow * The scanning process * -The image interface * Results of experiments involving the use of -electronic resources and traditional paper copies * Testing the issue of -serendipity * Conclusions * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Michael LESK, executive director, Computer Science Research, Bell -Communications Research, Inc. (Bellcore), discussed the Chemical Online -Retrieval Experiment (CORE), a cooperative project involving Cornell -University, OCLC, Bellcore, and the American Chemical Society (ACS). - -LESK spoke on 1) how the scanning was performed, including the unusual -feature of page segmentation, and 2) the use made of the text and the -image in experiments. - -Working with the chemistry journals (because ACS has been saving its -typesetting tapes since the mid-1970s and thus has a significant back-run -of the most important chemistry journals in the United States), CORE is -attempting to create an automated chemical library. Approximately a -quarter of the pages by square inch are made up of images of -quasi-pictorial material; dealing with the graphic components of the -pages is extremely important. LESK described the roles of participants -in CORE: 1) ACS provides copyright permission, journals on paper, -journals on microfilm, and some of the definitions of the files; 2) at -Bellcore, LESK chiefly performs the data preparation, while Dennis Egan -performs experiments on the users of chemical abstracts, and supplies the -indexing and numerous magnetic tapes; 3) Cornell provides the site of the -experiment; 4) OCLC develops retrieval software and other user interfaces. -Various manufacturers and publishers have furnished other help. - -Concerning data flow, Bellcore receives microfilm and paper from ACS; the -microfilm is scanned by outside vendors, while the paper is scanned -inhouse on an Improvision scanner, twenty pages per minute at 300 dpi, -which provides sufficient quality for all practical uses. LESK would -prefer to have more gray level, because one of the ACS journals prints on -some colored pages, which creates a problem. - -Bellcore performs all this scanning, creates a page-image file, and also -selects from the pages the graphics, to mix with the text file (which is -discussed later in the Workshop). The user is always searching the ASCII -file, but she or he may see a display based on the ASCII or a display -based on the images. - -LESK illustrated how the program performs page analysis, and the image -interface. (The user types several words, is presented with a list-- -usually of the titles of articles contained in an issue--that derives -from the ASCII, clicks on an icon and receives an image that mirrors an -ACS page.) LESK also illustrated an alternative interface, based on text -on the ASCII, the so-called SuperBook interface from Bellcore. - -LESK next presented the results of an experiment conducted by Dennis Egan -and involving thirty-six students at Cornell, one third of them -undergraduate chemistry majors, one third senior undergraduate chemistry -majors, and one third graduate chemistry students. A third of them -received the paper journals, the traditional paper copies and chemical -abstracts on paper. A third received image displays of the pictures of -the pages, and a third received the text display with pop-up graphics. - -The students were given several questions made up by some chemistry -professors. The questions fell into five classes, ranging from very easy -to very difficult, and included questions designed to simulate browsing -as well as a traditional information retrieval-type task. - -LESK furnished the following results. In the straightforward question -search--the question being, what is the phosphorus oxygen bond distance -and hydroxy phosphate?--the students were told that they could take -fifteen minutes and, then, if they wished, give up. The students with -paper took more than fifteen minutes on average, and yet most of them -gave up. The students with either electronic format, text or image, -received good scores in reasonable time, hardly ever had to give up, and -usually found the right answer. - -In the browsing study, the students were given a list of eight topics, -told to imagine that an issue of the Journal of the American Chemical -Society had just appeared on their desks, and were also told to flip -through it and to find topics mentioned in the issue. The average scores -were about the same. (The students were told to answer yes or no about -whether or not particular topics appeared.) The errors, however, were -quite different. The students with paper rarely said that something -appeared when it had not. But they often failed to find something -actually mentioned in the issue. The computer people found numerous -things, but they also frequently said that a topic was mentioned when it -was not. (The reason, of course, was that they were performing word -searches. They were finding that words were mentioned and they were -concluding that they had accomplished their task.) - -This question also contained a trick to test the issue of serendipity. -The students were given another list of eight topics and instructed, -without taking a second look at the journal, to recall how many of this -new list of eight topics were in this particular issue. This was an -attempt to see if they performed better at remembering what they were not -looking for. They all performed about the same, paper or electronics, -about 62 percent accurate. In short, LESK said, people were not very -good when it came to serendipity, but they were no worse at it with -computers than they were with paper. - -(LESK gave a parenthetical illustration of the learning curve of students -who used SuperBook.) - -The students using the electronic systems started off worse than the ones -using print, but by the third of the three sessions in the series had -caught up to print. As one might expect, electronics provide a much -better means of finding what one wants to read; reading speeds, once the -object of the search has been found, are about the same. - -Almost none of the students could perform the hard task--the analogous -transformation. (It would require the expertise of organic chemists to -complete.) But an interesting result was that the students using the text -search performed terribly, while those using the image system did best. -That the text search system is driven by text offers the explanation. -Everything is focused on the text; to see the pictures, one must press -on an icon. Many students found the right article containing the answer -to the question, but they did not click on the icon to bring up the right -figure and see it. They did not know that they had found the right place, -and thus got it wrong. - -The short answer demonstrated by this experiment was that in the event -one does not know what to read, one needs the electronic systems; the -electronic systems hold no advantage at the moment if one knows what to -read, but neither do they impose a penalty. - -LESK concluded by commenting that, on one hand, the image system was easy -to use. On the other hand, the text display system, which represented -twenty man-years of work in programming and polishing, was not winning, -because the text was not being read, just searched. The much easier -system is highly competitive as well as remarkably effective for the -actual chemists. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -ERWAY * Most challenging aspect of working on AM * Assumptions guiding -AM's approach * Testing different types of service bureaus * AM's -requirement for 99.95 percent accuracy * Requirements for text-coding * -Additional factors influencing AM's approach to coding * Results of AM's -experience with rekeying * Other problems in dealing with service bureaus -* Quality control the most time-consuming aspect of contracting out -conversion * Long-term outlook uncertain * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -To Ricky ERWAY, associate coordinator, American Memory, Library of -Congress, the constant variety of conversion projects taking place -simultaneously represented perhaps the most challenging aspect of working -on AM. Thus, the challenge was not to find a solution for text -conversion but a tool kit of solutions to apply to LC's varied -collections that need to be converted. ERWAY limited her remarks to the -process of converting text to machine-readable form, and the variety of -LC's text collections, for example, bound volumes, microfilm, and -handwritten manuscripts. - -Two assumptions have guided AM's approach, ERWAY said: 1) A desire not -to perform the conversion inhouse. Because of the variety of formats and -types of texts, to capitalize the equipment and have the talents and -skills to operate them at LC would be extremely expensive. Further, the -natural inclination to upgrade to newer and better equipment each year -made it reasonable for AM to focus on what it did best and seek external -conversion services. Using service bureaus also allowed AM to have -several types of operations take place at the same time. 2) AM was not a -technology project, but an effort to improve access to library -collections. Hence, whether text was converted using OCR or rekeying -mattered little to AM. What mattered were cost and accuracy of results. - -AM considered different types of service bureaus and selected three to -perform several small tests in order to acquire a sense of the field. -The sample collections with which they worked included handwritten -correspondence, typewritten manuscripts from the 1940s, and -eighteenth-century printed broadsides on microfilm. On none of these -samples was OCR performed; they were all rekeyed. AM had several special -requirements for the three service bureaus it had engaged. For instance, -any errors in the original text were to be retained. Working from bound -volumes or anything that could not be sheet-fed also constituted a factor -eliminating companies that would have performed OCR. - -AM requires 99.95 percent accuracy, which, though it sounds high, often -means one or two errors per page. The initial batch of test samples -contained several handwritten materials for which AM did not require -text-coding. The results, ERWAY reported, were in all cases fairly -comparable: for the most part, all three service bureaus achieved 99.95 -percent accuracy. AM was satisfied with the work but surprised at the cost. - -As AM began converting whole collections, it retained the requirement for -99.95 percent accuracy and added requirements for text-coding. AM needed -to begin performing work more than three years ago before LC requirements -for SGML applications had been established. Since AM's goal was simply -to retain any of the intellectual content represented by the formatting -of the document (which would be lost if one performed a straight ASCII -conversion), AM used "SGML-like" codes. These codes resembled SGML tags -but were used without the benefit of document-type definitions. AM found -that many service bureaus were not yet SGML-proficient. - -Additional factors influencing the approach AM took with respect to -coding included: 1) the inability of any known microcomputer-based -user-retrieval software to take advantage of SGML coding; and 2) the -multiple inconsistencies in format of the older documents, which -confirmed AM in its desire not to attempt to force the different formats -to conform to a single document-type definition (DTD) and thus create the -need for a separate DTD for each document. - -The five text collections that AM has converted or is in the process of -converting include a collection of eighteenth-century broadsides, a -collection of pamphlets, two typescript document collections, and a -collection of 150 books. - -ERWAY next reviewed the results of AM's experience with rekeying, noting -again that because the bulk of AM's materials are historical, the quality -of the text often does not lend itself to OCR. While non-English -speakers are less likely to guess or elaborate or correct typos in the -original text, they are also less able to infer what we would; they also -are nearly incapable of converting handwritten text. Another -disadvantage of working with overseas keyers is that they are much less -likely to telephone with questions, especially on the coding, with the -result that they develop their own rules as they encounter new -situations. - -Government contracting procedures and time frames posed a major challenge -to performing the conversion. Many service bureaus are not accustomed to -retaining the image, even if they perform OCR. Thus, questions of image -format and storage media were somewhat novel to many of them. ERWAY also -remarked other problems in dealing with service bureaus, for example, -their inability to perform text conversion from the kind of microfilm -that LC uses for preservation purposes. - -But quality control, in ERWAY's experience, was the most time-consuming -aspect of contracting out conversion. AM has been attempting to perform -a 10-percent quality review, looking at either every tenth document or -every tenth page to make certain that the service bureaus are maintaining -99.95 percent accuracy. But even if they are complying with the -requirement for accuracy, finding errors produces a desire to correct -them and, in turn, to clean up the whole collection, which defeats the -purpose to some extent. Even a double entry requires a -character-by-character comparison to the original to meet the accuracy -requirement. LC is not accustomed to publish imperfect texts, which -makes attempting to deal with the industry standard an emotionally -fraught issue for AM. As was mentioned in the previous day's discussion, -going from 99.95 to 99.99 percent accuracy usually doubles costs and -means a third keying or another complete run-through of the text. - -Although AM has learned much from its experiences with various collections -and various service bureaus, ERWAY concluded pessimistically that no -breakthrough has been achieved. Incremental improvements have occurred -in some of the OCR technology, some of the processes, and some of the -standards acceptances, which, though they may lead to somewhat lower costs, -do not offer much encouragement to many people who are anxiously awaiting -the day that the entire contents of LC are available on-line. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -ZIDAR * Several answers to why one attempts to perform full-text -conversion * Per page cost of performing OCR * Typical problems -encountered during editing * Editing poor copy OCR vs. rekeying * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Judith ZIDAR, coordinator, National Agricultural Text Digitizing Program -(NATDP), National Agricultural Library (NAL), offered several answers to -the question of why one attempts to perform full-text conversion: 1) -Text in an image can be read by a human but not by a computer, so of -course it is not searchable and there is not much one can do with it. 2) -Some material simply requires word-level access. For instance, the legal -profession insists on full-text access to its material; with taxonomic or -geographic material, which entails numerous names, one virtually requires -word-level access. 3) Full text permits rapid browsing and searching, -something that cannot be achieved in an image with today's technology. -4) Text stored as ASCII and delivered in ASCII is standardized and highly -portable. 5) People just want full-text searching, even those who do not -know how to do it. NAL, for the most part, is performing OCR at an -actual cost per average-size page of approximately $7. NAL scans the -page to create the electronic image and passes it through the OCR device. - -ZIDAR next rehearsed several typical problems encountered during editing. -Praising the celerity of her student workers, ZIDAR observed that editing -requires approximately five to ten minutes per page, assuming that there -are no large tables to audit. Confusion among the three characters I, 1, -and l, constitutes perhaps the most common problem encountered. Zeroes -and O's also are frequently confused. Double M's create a particular -problem, even on clean pages. They are so wide in most fonts that they -touch, and the system simply cannot tell where one letter ends and the -other begins. Complex page formats occasionally fail to columnate -properly, which entails rescanning as though one were working with a -single column, entering the ASCII, and decolumnating for better -searching. With proportionally spaced text, OCR can have difficulty -discerning what is a space and what are merely spaces between letters, as -opposed to spaces between words, and therefore will merge text or break -up words where it should not. - -ZIDAR said that it can often take longer to edit a poor-copy OCR than to -key it from scratch. NAL has also experimented with partial editing of -text, whereby project workers go into and clean up the format, removing -stray characters but not running a spell-check. NAL corrects typos in -the title and authors' names, which provides a foothold for searching and -browsing. Even extremely poor-quality OCR (e.g., 60-percent accuracy) -can still be searched, because numerous words are correct, while the -important words are probably repeated often enough that they are likely -to be found correct somewhere. Librarians, however, cannot tolerate this -situation, though end users seem more willing to use this text for -searching, provided that NAL indicates that it is unedited. ZIDAR -concluded that rekeying of text may be the best route to take, in spite -of numerous problems with quality control and cost. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -DISCUSSION * Modifying an image before performing OCR * NAL's costs per -page *AM's costs per page and experience with Federal Prison Industries * -Elements comprising NATDP's costs per page * OCR and structured markup * -Distinction between the structure of a document and its representation -when put on the screen or printed * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -HOOTON prefaced the lengthy discussion that followed with several -comments about modifying an image before one reaches the point of -performing OCR. For example, in regard to an application containing a -significant amount of redundant data, such as form-type data, numerous -companies today are working on various kinds of form renewal, prior to -going through a recognition process, by using dropout colors. Thus, -acquiring access to form design or using electronic means are worth -considering. HOOTON also noted that conversion usually makes or breaks -one's imaging system. It is extremely important, extremely costly in -terms of either capital investment or service, and determines the quality -of the remainder of one's system, because it determines the character of -the raw material used by the system. - -Concerning the four projects undertaken by NAL, two inside and two -performed by outside contractors, ZIDAR revealed that an in-house service -bureau executed the first at a cost between $8 and $10 per page for -everything, including building of the database. The project undertaken -by the Consultative Group on International Agricultural Research (CGIAR) -cost approximately $10 per page for the conversion, plus some expenses -for the software and building of the database. The Acid Rain Project--a -two-disk set produced by the University of Vermont, consisting of -Canadian publications on acid rain--cost $6.70 per page for everything, -including keying of the text, which was double keyed, scanning of the -images, and building of the database. The in-house project offered -considerable ease of convenience and greater control of the process. On -the other hand, the service bureaus know their job and perform it -expeditiously, because they have more people. - -As a useful comparison, ERWAY revealed AM's costs as follows: $0.75 -cents to $0.85 cents per thousand characters, with an average page -containing 2,700 characters. Requirements for coding and imaging -increase the costs. Thus, conversion of the text, including the coding, -costs approximately $3 per page. (This figure does not include the -imaging and database-building included in the NAL costs.) AM also -enjoyed a happy experience with Federal Prison Industries, which -precluded the necessity of going through the request-for-proposal process -to award a contract, because it is another government agency. The -prisoners performed AM's rekeying just as well as other service bureaus -and proved handy as well. AM shipped them the books, which they would -photocopy on a book-edge scanner. They would perform the markup on -photocopies, return the books as soon as they were done with them, -perform the keying, and return the material to AM on WORM disks. - -ZIDAR detailed the elements that constitute the previously noted cost of -approximately $7 per page. Most significant is the editing, correction -of errors, and spell-checkings, which though they may sound easy to -perform require, in fact, a great deal of time. Reformatting text also -takes a while, but a significant amount of NAL's expenses are for equipment, -which was extremely expensive when purchased because it was one of the few -systems on the market. The costs of equipment are being amortized over -five years but are still quite high, nearly $2,000 per month. - -HOCKEY raised a general question concerning OCR and the amount of editing -required (substantial in her experience) to generate the kind of -structured markup necessary for manipulating the text on the computer or -loading it into any retrieval system. She wondered if the speakers could -extend the previous question about the cost-benefit of adding or exerting -structured markup. ERWAY noted that several OCR systems retain italics, -bolding, and other spatial formatting. While the material may not be in -the format desired, these systems possess the ability to remove the -original materials quickly from the hands of the people performing the -conversion, as well as to retain that information so that users can work -with it. HOCKEY rejoined that the current thinking on markup is that one -should not say that something is italic or bold so much as why it is that -way. To be sure, one needs to know that something was italicized, but -how can one get from one to the other? One can map from the structure to -the typographic representation. - -FLEISCHHAUER suggested that, given the 100 million items the Library -holds, it may not be possible for LC to do more than report that a thing -was in italics as opposed to why it was italics, although that may be -desirable in some contexts. Promising to talk a bit during the afternoon -session about several experiments OCLC performed on automatic recognition -of document elements, and which they hoped to extend, WEIBEL said that in -fact one can recognize the major elements of a document with a fairly -high degree of reliability, at least as good as OCR. STEVENS drew a -useful distinction between standard, generalized markup (i.e., defining -for a document-type definition the structure of the document), and what -he termed a style sheet, which had to do with italics, bolding, and other -forms of emphasis. Thus, two different components are at work, one being -the structure of the document itself (its logic), and the other being its -representation when it is put on the screen or printed. - - ****** - -SESSION V. APPROACHES TO PREPARING ELECTRONIC TEXTS - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -HOCKEY * Text in ASCII and the representation of electronic text versus -an image * The need to look at ways of using markup to assist retrieval * -The need for an encoding format that will be reusable and multifunctional -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Susan HOCKEY, director, Center for Electronic Texts in the Humanities -(CETH), Rutgers and Princeton Universities, announced that one talk -(WEIBEL's) was moved into this session from the morning and that David -Packard was unable to attend. The session would attempt to focus more on -what one can do with a text in ASCII and the representation of electronic -text rather than just an image, what one can do with a computer that -cannot be done with a book or an image. It would be argued that one can -do much more than just read a text, and from that starting point one can -use markup and methods of preparing the text to take full advantage of -the capability of the computer. That would lead to a discussion of what -the European Community calls REUSABILITY, what may better be termed -DURABILITY, that is, how to prepare or make a text that will last a long -time and that can be used for as many applications as possible, which -would lead to issues of improving intellectual access. - -HOCKEY urged the need to look at ways of using markup to facilitate retrieval, -not just for referencing or to help locate an item that is retrieved, but also to put markup tags in -a text to help retrieve the thing sought either with linguistic tagging or -interpretation. HOCKEY also argued that little advancement had occurred in -the software tools currently available for retrieving and searching text. -She pressed the desideratum of going beyond Boolean searches and performing -more sophisticated searching, which the insertion of more markup in the text -would facilitate. Thinking about electronic texts as opposed to images means -considering material that will never appear in print form, or print will not -be its primary form, that is, material which only appears in electronic form. -HOCKEY alluded to the history and the need for markup and tagging and -electronic text, which was developed through the use of computers in the -humanities; as MICHELSON had observed, Father Busa had started in 1949 -to prepare the first-ever text on the computer. - -HOCKEY remarked several large projects, particularly in Europe, for the -compilation of dictionaries, language studies, and language analysis, in -which people have built up archives of text and have begun to recognize -the need for an encoding format that will be reusable and multifunctional, -that can be used not just to print the text, which may be assumed to be a -byproduct of what one wants to do, but to structure it inside the computer -so that it can be searched, built into a Hypertext system, etc. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -WEIBEL * OCLC's approach to preparing electronic text: retroconversion, -keying of texts, more automated ways of developing data * Project ADAPT -and the CORE Project * Intelligent character recognition does not exist * -Advantages of SGML * Data should be free of procedural markup; -descriptive markup strongly advocated * OCLC's interface illustrated * -Storage requirements and costs for putting a lot of information on line * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Stuart WEIBEL, senior research scientist, Online Computer Library Center, -Inc. (OCLC), described OCLC's approach to preparing electronic text. He -argued that the electronic world into which we are moving must -accommodate not only the future but the past as well, and to some degree -even the present. Thus, starting out at one end with retroconversion and -keying of texts, one would like to move toward much more automated ways -of developing data. - -For example, Project ADAPT had to do with automatically converting -document images into a structured document database with OCR text as -indexing and also a little bit of automatic formatting and tagging of -that text. The CORE project hosted by Cornell University, Bellcore, -OCLC, the American Chemical Society, and Chemical Abstracts, constitutes -WEIBEL's principal concern at the moment. This project is an example of -converting text for which one already has a machine-readable version into -a format more suitable for electronic delivery and database searching. -(Since Michael LESK had previously described CORE, WEIBEL would say -little concerning it.) Borrowing a chemical phrase, de novo synthesis, -WEIBEL cited the Online Journal of Current Clinical Trials as an example -of de novo electronic publishing, that is, a form in which the primary -form of the information is electronic. - -Project ADAPT, then, which OCLC completed a couple of years ago and in -fact is about to resume, is a model in which one takes page images either -in paper or microfilm and converts them automatically to a searchable -electronic database, either on-line or local. The operating assumption -is that accepting some blemishes in the data, especially for -retroconversion of materials, will make it possible to accomplish more. -Not enough money is available to support perfect conversion. - -WEIBEL related several steps taken to perform image preprocessing -(processing on the image before performing optical character -recognition), as well as image postprocessing. He denied the existence -of intelligent character recognition and asserted that what is wanted is -page recognition, which is a long way off. OCLC has experimented with -merging of multiple optical character recognition systems that will -reduce errors from an unacceptable rate of 5 characters out of every -l,000 to an unacceptable rate of 2 characters out of every l,000, but it -is not good enough. It will never be perfect. - -Concerning the CORE Project, WEIBEL observed that Bellcore is taking the -topography files, extracting the page images, and converting those -topography files to SGML markup. LESK hands that data off to OCLC, which -builds that data into a Newton database, the same system that underlies -the on-line system in virtually all of the reference products at OCLC. -The long-term goal is to make the systems interoperable so that not just -Bellcore's system and OCLC's system can access this data, but other -systems can as well, and the key to that is the Z39.50 common command -language and the full-text extension. Z39.50 is fine for MARC records, -but is not enough to do it for full text (that is, make full texts -interoperable). - -WEIBEL next outlined the critical role of SGML for a variety of purposes, -for example, as noted by HOCKEY, in the world of extremely large -databases, using highly structured data to perform field searches. -WEIBEL argued that by building the structure of the data in (i.e., the -structure of the data originally on a printed page), it becomes easy to -look at a journal article even if one cannot read the characters and know -where the title or author is, or what the sections of that document would be. -OCLC wants to make that structure explicit in the database, because it will -be important for retrieval purposes. - -The second big advantage of SGML is that it gives one the ability to -build structure into the database that can be used for display purposes -without contaminating the data with instructions about how to format -things. The distinction lies between procedural markup, which tells one -where to put dots on the page, and descriptive markup, which describes -the elements of a document. - -WEIBEL believes that there should be no procedural markup in the data at -all, that the data should be completely unsullied by information about -italics or boldness. That should be left up to the display device, -whether that display device is a page printer or a screen display device. -By keeping one's database free of that kind of contamination, one can -make decisions down the road, for example, reorganize the data in ways -that are not cramped by built-in notions of what should be italic and -what should be bold. WEIBEL strongly advocated descriptive markup. As -an example, he illustrated the index structure in the CORE data. With -subsequent illustrated examples of markup, WEIBEL acknowledged the common -complaint that SGML is hard to read in its native form, although markup -decreases considerably once one gets into the body. Without the markup, -however, one would not have the structure in the data. One can pass -markup through a LaTeX processor and convert it relatively easily to a -printed version of the document. - -WEIBEL next illustrated an extremely cluttered screen dump of OCLC's -system, in order to show as much as possible the inherent capability on -the screen. (He noted parenthetically that he had become a supporter of -X-Windows as a result of the progress of the CORE Project.) WEIBEL also -illustrated the two major parts of the interface: l) a control box that -allows one to generate lists of items, which resembles a small table of -contents based on key words one wishes to search, and 2) a document -viewer, which is a separate process in and of itself. He demonstrated -how to follow links through the electronic database simply by selecting -the appropriate button and bringing them up. He also noted problems that -remain to be accommodated in the interface (e.g., as pointed out by LESK, -what happens when users do not click on the icon for the figure). - -Given the constraints of time, WEIBEL omitted a large number of ancillary -items in order to say a few words concerning storage requirements and -what will be required to put a lot of things on line. Since it is -extremely expensive to reconvert all of this data, especially if it is -just in paper form (and even if it is in electronic form in typesetting -tapes), he advocated building journals electronically from the start. In -that case, if one only has text graphics and indexing (which is all that -one needs with de novo electronic publishing, because there is no need to -go back and look at bit-maps of pages), one can get 10,000 journals of -full text, or almost 6 million pages per year. These pages can be put in -approximately 135 gigabytes of storage, which is not all that much, -WEIBEL said. For twenty years, something less than three terabytes would -be required. WEIBEL calculated the costs of storing this information as -follows: If a gigabyte costs approximately $1,000, then a terabyte costs -approximately $1 million to buy in terms of hardware. One also needs a -building to put it in and a staff like OCLC to handle that information. -So, to support a terabyte, multiply by five, which gives $5 million per -year for a supported terabyte of data. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -DISCUSSION * Tapes saved by ACS are the typography files originally -supporting publication of the journal * Cost of building tagged text into -the database * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -During the question-and-answer period that followed WEIBEL's -presentation, these clarifications emerged. The tapes saved by the -American Chemical Society are the typography files that originally -supported the publication of the journal. Although they are not tagged -in SGML, they are tagged in very fine detail. Every single sentence is -marked, all the registry numbers, all the publications issues, dates, and -volumes. No cost figures on tagging material on a per-megabyte basis -were available. Because ACS's typesetting system runs from tagged text, -there is no extra cost per article. It was unknown what it costs ACS to -keyboard the tagged text rather than just keyboard the text in the -cheapest process. In other words, since one intends to publish things -and will need to build tagged text into a typography system in any case, -if one does that in such a way that it can drive not only typography but -an electronic system (which is what ACS intends to do--move to SGML -publishing), the marginal cost is zero. The marginal cost represents the -cost of building tagged text into the database, which is small. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -SPERBERG-McQUEEN * Distinction between texts and computers * Implications -of recognizing that all representation is encoding * Dealing with -complicated representations of text entails the need for a grammar of -documents * Variety of forms of formal grammars * Text as a bit-mapped -image does not represent a serious attempt to represent text in -electronic form * SGML, the TEI, document-type declarations, and the -reusability and longevity of data * TEI conformance explicitly allows -extension or modification of the TEI tag set * Administrative background -of the TEI * Several design goals for the TEI tag set * An absolutely -fixed requirement of the TEI Guidelines * Challenges the TEI has -attempted to face * Good texts not beyond economic feasibility * The -issue of reproducibility or processability * The issue of mages as -simulacra for the text redux * One's model of text determines what one's -software can do with a text and has economic consequences * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Prior to speaking about SGML and markup, Michael SPERBERG-McQUEEN, editor, -Text Encoding Initiative (TEI), University of Illinois-Chicago, first drew -a distinction between texts and computers: Texts are abstract cultural -and linguistic objects while computers are complicated physical devices, -he said. Abstract objects cannot be placed inside physical devices; with -computers one can only represent text and act upon those representations. - -The recognition that all representation is encoding, SPERBERG-McQUEEN -argued, leads to the recognition of two things: 1) The topic description -for this session is slightly misleading, because there can be no discussion -of pros and cons of text-coding unless what one means is pros and cons of -working with text with computers. 2) No text can be represented in a -computer without some sort of encoding; images are one way of encoding text, -ASCII is another, SGML yet another. There is no encoding without some -information loss, that is, there is no perfect reproduction of a text that -allows one to do away with the original. Thus, the question becomes, -What is the most useful representation of text for a serious work? -This depends on what kind of serious work one is talking about. - -The projects demonstrated the previous day all involved highly complex -information and fairly complex manipulation of the textual material. -In order to use that complicated information, one has to calculate it -slowly or manually and store the result. It needs to be stored, therefore, -as part of one's representation of the text. Thus, one needs to store the -structure in the text. To deal with complicated representations of text, -one needs somehow to control the complexity of the representation of a text; -that means one needs a way of finding out whether a document and an -electronic representation of a document is legal or not; and that -means one needs a grammar of documents. - -SPERBERG-McQUEEN discussed the variety of forms of formal grammars, -implicit and explicit, as applied to text, and their capabilities. He -argued that these grammars correspond to different models of text that -different developers have. For example, one implicit model of the text -is that there is no internal structure, but just one thing after another, -a few characters and then perhaps a start-title command, and then a few -more characters and an end-title command. SPERBERG-McQUEEN also -distinguished several kinds of text that have a sort of hierarchical -structure that is not very well defined, which, typically, corresponds -to grammars that are not very well defined, as well as hierarchies that -are very well defined (e.g., the Thesaurus Linguae Graecae) and extremely -complicated things such as SGML, which handle strictly hierarchical data -very nicely. - -SPERBERG-McQUEEN conceded that one other model not illustrated on his two -displays was the model of text as a bit-mapped image, an image of a page, -and confessed to having been converted to a limited extent by the -Workshop to the view that electronic images constitute a promising, -probably superior alternative to microfilming. But he was not convinced -that electronic images represent a serious attempt to represent text in -electronic form. Many of their problems stem from the fact that they are -not direct attempts to represent the text but attempts to represent the -page, thus making them representations of representations. - -In this situation of increasingly complicated textual information and the -need to control that complexity in a useful way (which begs the question -of the need for good textual grammars), one has the introduction of SGML. -With SGML, one can develop specific document-type declarations -for specific text types or, as with the TEI, attempts to generate -general document-type declarations that can handle all sorts of text. -The TEI is an attempt to develop formats for text representation that -will ensure the kind of reusability and longevity of data discussed earlier. -It offers a way to stay alive in the state of permanent technological -revolution. - -It has been a continuing challenge in the TEI to create document grammars -that do some work in controlling the complexity of the textual object but -also allowing one to represent the real text that one will find. -Fundamental to the notion of the TEI is that TEI conformance allows one -the ability to extend or modify the TEI tag set so that it fits the text -that one is attempting to represent. - -SPERBERG-McQUEEN next outlined the administrative background of the TEI. -The TEI is an international project to develop and disseminate guidelines -for the encoding and interchange of machine-readable text. It is -sponsored by the Association for Computers in the Humanities, the -Association for Computational Linguistics, and the Association for -Literary and Linguistic Computing. Representatives of numerous other -professional societies sit on its advisory board. The TEI has a number -of affiliated projects that have provided assistance by testing drafts of -the guidelines. - -Among the design goals for the TEI tag set, the scheme first of all must -meet the needs of research, because the TEI came out of the research -community, which did not feel adequately served by existing tag sets. -The tag set must be extensive as well as compatible with existing and -emerging standards. In 1990, version 1.0 of the Guidelines was released -(SPERBERG-McQUEEN illustrated their contents). - -SPERBERG-McQUEEN noted that one problem besetting electronic text has -been the lack of adequate internal or external documentation for many -existing electronic texts. The TEI guidelines as currently formulated -contain few fixed requirements, but one of them is this: There must -always be a document header, an in-file SGML tag that provides -1) a bibliographic description of the electronic object one is talking -about (that is, who included it, when, what for, and under which title); -and 2) the copy text from which it was derived, if any. If there was -no copy text or if the copy text is unknown, then one states as much. -Version 2.0 of the Guidelines was scheduled to be completed in fall 1992 -and a revised third version is to be presented to the TEI advisory board -for its endorsement this coming winter. The TEI itself exists to provide -a markup language, not a marked-up text. - -Among the challenges the TEI has attempted to face is the need for a -markup language that will work for existing projects, that is, handle the -level of markup that people are using now to tag only chapter, section, -and paragraph divisions and not much else. At the same time, such a -language also will be able to scale up gracefully to handle the highly -detailed markup which many people foresee as the future destination of -much electronic text, and which is not the future destination but the -present home of numerous electronic texts in specialized areas. - -SPERBERG-McQUEEN dismissed the lowest-common-denominator approach as -unable to support the kind of applications that draw people who have -never been in the public library regularly before, and make them come -back. He advocated more interesting text and more intelligent text. -Asserting that it is not beyond economic feasibility to have good texts, -SPERBERG-McQUEEN noted that the TEI Guidelines listing 200-odd tags -contains tags that one is expected to enter every time the relevant -textual feature occurs. It contains all the tags that people need now, -and it is not expected that everyone will tag things in the same way. - -The question of how people will tag the text is in large part a function -of their reaction to what SPERBERG-McQUEEN termed the issue of -reproducibility. What one needs to be able to reproduce are the things -one wants to work with. Perhaps a more useful concept than that of -reproducibility or recoverability is that of processability, that is, -what can one get from an electronic text without reading it again -in the original. He illustrated this contention with a page from -Jan Comenius's bilingual Introduction to Latin. - -SPERBERG-McQUEEN returned at length to the issue of images as simulacra -for the text, in order to reiterate his belief that in the long run more -than images of pages of particular editions of the text are needed, -because just as second-generation photocopies and second-generation -microfilm degenerate, so second-generation representations tend to -degenerate, and one tends to overstress some relatively trivial aspects -of the text such as its layout on the page, which is not always -significant, despite what the text critics might say, and slight other -pieces of information such as the very important lexical ties between the -English and Latin versions of Comenius's bilingual text, for example. -Moreover, in many crucial respects it is easy to fool oneself concerning -what a scanned image of the text will accomplish. For example, in order -to study the transmission of texts, information concerning the text -carrier is necessary, which scanned images simply do not always handle. -Further, even the high-quality materials being produced at Cornell use -much of the information that one would need if studying those books as -physical objects. It is a choice that has been made. It is an arguably -justifiable choice, but one does not know what color those pen strokes in -the margin are or whether there was a stain on the page, because it has -been filtered out. One does not know whether there were rips in the page -because they do not show up, and on a couple of the marginal marks one -loses half of the mark because the pen is very light and the scanner -failed to pick it up, and so what is clearly a checkmark in the margin of -the original becomes a little scoop in the margin of the facsimile. -Standard problems for facsimile editions, not new to electronics, but -also true of light-lens photography, and are remarked here because it is -important that we not fool ourselves that even if we produce a very nice -image of this page with good contrast, we are not replacing the -manuscript any more than microfilm has replaced the manuscript. - -The TEI comes from the research community, where its first allegiance -lies, but it is not just an academic exercise. It has relevance far -beyond those who spend all of their time studying text, because one's -model of text determines what one's software can do with a text. Good -models lead to good software. Bad models lead to bad software. That has -economic consequences, and it is these economic consequences that have -led the European Community to help support the TEI, and that will lead, -SPERBERG-McQUEEN hoped, some software vendors to realize that if they -provide software with a better model of the text they can make a killing. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -DISCUSSION * Implications of different DTDs and tag sets * ODA versus SGML * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -During the discussion that followed, several additional points were made. -Neither AAP (i.e., Association of American Publishers) nor CALS (i.e., -Computer-aided Acquisition and Logistics Support) has a document-type -definition for ancient Greek drama, although the TEI will be able to -handle that. Given this state of affairs and assuming that the -technical-journal producers and the commercial vendors decide to use the -other two types, then an institution like the Library of Congress, which -might receive all of their publications, would have to be able to handle -three different types of document definitions and tag sets and be able to -distinguish among them. - -Office Document Architecture (ODA) has some advantages that flow from its -tight focus on office documents and clear directions for implementation. -Much of the ODA standard is easier to read and clearer at first reading -than the SGML standard, which is extremely general. What that means is -that if one wants to use graphics in TIFF and ODA, one is stuck, because -ODA defines graphics formats while TIFF does not, whereas SGML says the -world is not waiting for this work group to create another graphics format. -What is needed is an ability to use whatever graphics format one wants. - -The TEI provides a socket that allows one to connect the SGML document to -the graphics. The notation that the graphics are in is clearly a choice -that one needs to make based on her or his environment, and that is one -advantage. SGML is less megalomaniacal in attempting to define formats -for all kinds of information, though more megalomaniacal in attempting to -cover all sorts of documents. The other advantage is that the model of -text represented by SGML is simply an order of magnitude richer and more -flexible than the model of text offered by ODA. Both offer hierarchical -structures, but SGML recognizes that the hierarchical model of the text -that one is looking at may not have been in the minds of the designers, -whereas ODA does not. - -ODA is not really aiming for the kind of document that the TEI wants to -encompass. The TEI can handle the kind of material ODA has, as well as a -significantly broader range of material. ODA seems to be very much -focused on office documents, which is what it started out being called-- -office document architecture. - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -CALALUCA * Text-encoding from a publisher's perspective * -Responsibilities of a publisher * Reproduction of Migne's Latin series -whole and complete with SGML tags based on perceived need and expected -use * Particular decisions arising from the general decision to produce -and publish PLD * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -The final speaker in this session, Eric CALALUCA, vice president, -Chadwyck-Healey, Inc., spoke from the perspective of a publisher re -text-encoding, rather than as one qualified to discuss methods of -encoding data, and observed that the presenters sitting in the room, -whether they had chosen to or not, were acting as publishers: making -choices, gathering data, gathering information, and making assessments. -CALALUCA offered the hard-won conviction that in publishing very large -text files (such as PLD), one cannot avoid making personal judgments of -appropriateness and structure. - -In CALALUCA's view, encoding decisions stem from prior judgments. Two -notions have become axioms for him in the consideration of future sources -for electronic publication: 1) electronic text publishing is as personal -as any other kind of publishing, and questions of if and how to encode -the data are simply a consequence of that prior decision; 2) all -personal decisions are open to criticism, which is unavoidable. - -CALALUCA rehearsed his role as a publisher or, better, as an intermediary -between what is viewed as a sound idea and the people who would make use -of it. Finding the specialist to advise in this process is the core of -that function. The publisher must monitor and hug the fine line between -giving users what they want and suggesting what they might need. One -responsibility of a publisher is to represent the desires of scholars and -research librarians as opposed to bullheadedly forcing them into areas -they would not choose to enter. - -CALALUCA likened the questions being raised today about data structure -and standards to the decisions faced by the Abbe Migne himself during -production of the Patrologia series in the mid-nineteenth century. -Chadwyck-Healey's decision to reproduce Migne's Latin series whole and -complete with SGML tags was also based upon a perceived need and an -expected use. In the same way that Migne's work came to be far more than -a simple handbook for clerics, PLD is already far more than a database -for theologians. It is a bedrock source for the study of Western -civilization, CALALUCA asserted. - -In regard to the decision to produce and publish PLD, the editorial board -offered direct judgments on the question of appropriateness of these -texts for conversion, their encoding and their distribution, and -concluded that the best possible project was one that avoided overt -intrusions or exclusions in so important a resource. Thus, the general -decision to transmit the original collection as clearly as possible with -the widest possible avenues for use led to other decisions: 1) To encode -the data or not, SGML or not, TEI or not. Again, the expected user -community asserted the need for normative tagging structures of important -humanities texts, and the TEI seemed the most appropriate structure for -that purpose. Research librarians, who are trained to view the larger -impact of electronic text sources on 80 or 90 or 100 doctoral -disciplines, loudly approved the decision to include tagging. They see -what is coming better than the specialist who is completely focused on -one edition of Ambrose's De Anima, and they also understand that the -potential uses exceed present expectations. 2) What will be tagged and -what will not. Once again, the board realized that one must tag the -obvious. But in no way should one attempt to identify through encoding -schemes every single discrete area of a text that might someday be -searched. That was another decision. Searching by a column number, an -author, a word, a volume, permitting combination searches, and tagging -notations seemed logical choices as core elements. 3) How does one make -the data available? Tieing it to a CD-ROM edition creates limitations, -but a magnetic tape file that is very large, is accompanied by the -encoding specifications, and that allows one to make local modifications -also allows one to incorporate any changes one may desire within the -bounds of private research, though exporting tag files from a CD-ROM -could serve just as well. Since no one on the board could possibly -anticipate each and every way in which a scholar might choose to mine -this data bank, it was decided to satisfy the basics and make some -provisions for what might come. 4) Not to encode the database would rob -it of the interchangeability and portability these important texts should -accommodate. For CALALUCA, the extensive options presented by full-text -searching require care in text selection and strongly support encoding of -data to facilitate the widest possible search strategies. Better -software can always be created, but summoning the resources, the people, -and the energy to reconvert the text is another matter. - -PLD is being encoded, captured, and distributed, because to -Chadwyck-Healey and the board it offers the widest possible array of -future research applications that can be seen today. CALALUCA concluded -by urging the encoding of all important text sources in whatever way -seems most appropriate and durable at the time, without blanching at the -thought that one's work may require emendation in the future. (Thus, -Chadwyck-Healey produced a very large humanities text database before the -final release of the TEI Guidelines.) - - ****** - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -DISCUSSION * Creating texts with markup advocated * Trends in encoding * -The TEI and the issue of interchangeability of standards * A -misconception concerning the TEI * Implications for an institution like -LC in the event that a multiplicity of DTDs develops * Producing images -as a first step towards possible conversion to full text through -character recognition * The AAP tag sets as a common starting point and -the need for caution * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -HOCKEY prefaced the discussion that followed with several comments in -favor of creating texts with markup and on trends in encoding. In the -future, when many more texts are available for on-line searching, real -problems in finding what is wanted will develop, if one is faced with -millions of words of data. It therefore becomes important to consider -putting markup in texts to help searchers home in on the actual things -they wish to retrieve. Various approaches to refining retrieval methods -toward this end include building on a computer version of a dictionary -and letting the computer look up words in it to obtain more information -about the semantic structure or semantic field of a word, its grammatical -structure, and syntactic structure. - -HOCKEY commented on the present keen interest in the encoding world -in creating: 1) machine-readable versions of dictionaries that can be -initially tagged in SGML, which gives a structure to the dictionary entry; -these entries can then be converted into a more rigid or otherwise -different database structure inside the computer, which can be treated as -a dynamic tool for searching mechanisms; 2) large bodies of text to study -the language. In order to incorporate more sophisticated mechanisms, -more about how words behave needs to be known, which can be learned in -part from information in dictionaries. However, the last ten years have -seen much interest in studying the structure of printed dictionaries -converted into computer-readable form. The information one derives about -many words from those is only partial, one or two definitions of the -common or the usual meaning of a word, and then numerous definitions of -unusual usages. If the computer is using a dictionary to help retrieve -words in a text, it needs much more information about the common usages, -because those are the ones that occur over and over again. Hence the -current interest in developing large bodies of text in computer-readable -form in order to study the language. Several projects are engaged in -compiling, for example, 100 million words. HOCKEY described one with -which she was associated briefly at Oxford University involving -compilation of 100 million words of British English: about 10 percent of -that will contain detailed linguistic tagging encoded in SGML; it will -have word class taggings, with words identified as nouns, verbs, -adjectives, or other parts of speech. This tagging can then be used by -programs which will begin to learn a bit more about the structure of the -language, and then, can go to tag more text. - -HOCKEY said that the more that is tagged accurately, the more one can -refine the tagging process and thus the bigger body of text one can build -up with linguistic tagging incorporated into it. Hence, the more tagging -or annotation there is in the text, the more one may begin to learn about -language and the more it will help accomplish more intelligent OCR. She -recommended the development of software tools that will help one begin to -understand more about a text, which can then be applied to scanning -images of that text in that format and to using more intelligence to help -one interpret or understand the text. - -HOCKEY posited the need to think about common methods of text-encoding -for a long time to come, because building these large bodies of text is -extremely expensive and will only be done once. - -In the more general discussion on approaches to encoding that followed, -these points were made: - -BESSER identified the underlying problem with standards that all have to -struggle with in adopting a standard, namely, the tension between a very -highly defined standard that is very interchangeable but does not work -for everyone because something is lacking, and a standard that is less -defined, more open, more adaptable, but less interchangeable. Contending -that the way in which people use SGML is not sufficiently defined, BESSER -wondered 1) if people resist the TEI because they think it is too defined -in certain things they do not fit into, and 2) how progress with -interchangeability can be made without frightening people away. - -SPERBERG-McQUEEN replied that the published drafts of the TEI had met -with surprisingly little objection on the grounds that they do not allow -one to handle X or Y or Z. Particular concerns of the affiliated -projects have led, in practice, to discussions of how extensions are to -be made; the primary concern of any project has to be how it can be -represented locally, thus making interchange secondary. The TEI has -received much criticism based on the notion that everything in it is -required or even recommended, which, as it happens, is a misconception -from the beginning, because none of it is required and very little is -actually actively recommended for all cases, except that one document -one's source. - -SPERBERG-McQUEEN agreed with BESSER about this trade-off: all the -projects in a set of twenty TEI-conformant projects will not necessarily -tag the material in the same way. One result of the TEI will be that the -easiest problems will be solved--those dealing with the external form of -the information; but the problem that is hardest in interchange is that -one is not encoding what another wants, and vice versa. Thus, after -the adoption of a common notation, the differences in the underlying -conceptions of what is interesting about texts become more visible. -The success of a standard like the TEI will lie in the ability of -the recipient of interchanged texts to use some of what it contains -and to add the information that was not encoded that one wants, in a -layered way, so that texts can be gradually enriched and one does not -have to put in everything all at once. Hence, having a well-behaved -markup scheme is important. - -STEVENS followed up on the paradoxical analogy that BESSER alluded to in -the example of the MARC records, namely, the formats that are the same -except that they are different. STEVENS drew a parallel between -document-type definitions and MARC records for books and serials and maps, -where one has a tagging structure and there is a text-interchange. -STEVENS opined that the producers of the information will set the terms -for the standard (i.e., develop document-type definitions for the users -of their products), creating a situation that will be problematical for -an institution like the Library of Congress, which will have to deal with -the DTDs in the event that a multiplicity of them develops. Thus, -numerous people are seeking a standard but cannot find the tag set that -will be acceptable to them and their clients. SPERBERG-McQUEEN agreed -with this view, and said that the situation was in a way worse: attempting -to unify arbitrary DTDs resembled attempting to unify a MARC record with a -bibliographic record done according to the Prussian instructions. -According to STEVENS, this situation occurred very early in the process. - -WATERS recalled from early discussions on Project Open Book the concern -of many people that merely by producing images, POB was not really -enhancing intellectual access to the material. Nevertheless, not wishing -to overemphasize the opposition between imaging and full text, WATERS -stated that POB views getting the images as a first step toward possibly -converting to full text through character recognition, if the technology -is appropriate. WATERS also emphasized that encoding is involved even -with a set of images. - -SPERBERG-McQUEEN agreed with WATERS that one can create an SGML document -consisting wholly of images. At first sight, organizing graphic images -with an SGML document may not seem to offer great advantages, but the -advantages of the scheme WATERS described would be precisely that -ability to move into something that is more of a multimedia document: -a combination of transcribed text and page images. WEIBEL concurred in -this judgment, offering evidence from Project ADAPT, where a page is -divided into text elements and graphic elements, and in fact the text -elements are organized by columns and lines. These lines may be used as -the basis for distributing documents in a network environment. As one -develops software intelligent enough to recognize what those elements -are, it makes sense to apply SGML to an image initially, that may, in -fact, ultimately become more and more text, either through OCR or edited -OCR or even just through keying. For WATERS, the labor of composing the -document and saying this set of documents or this set of images belongs -to this document constitutes a significant investment. - -WEIBEL also made the point that the AAP tag sets, while not excessively -prescriptive, offer a common starting point; they do not define the -structure of the documents, though. They have some recommendations about -DTDs one could use as examples, but they do just suggest tag sets. For -example, the CORE project attempts to use the AAP markup as much as -possible, but there are clearly areas where structure must be added. -That in no way contradicts the use of AAP tag sets. - -SPERBERG-McQUEEN noted that the TEI prepared a long working paper early -on about the AAP tag set and what it lacked that the TEI thought it -needed, and a fairly long critique of the naming conventions, which has -led to a very different style of naming in the TEI. He stressed the -importance of the opposition between prescriptive markup, the kind that a -publisher or anybody can do when producing documents de novo, and -descriptive markup, in which one has to take what the text carrier -provides. In these particular tag sets it is easy to overemphasize this -opposition, because the AAP tag set is extremely flexible. Even if one -just used the DTDs, they allow almost anything to appear almost anywhere. - - ****** - -SESSION VI. COPYRIGHT ISSUES - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -PETERS * Several cautions concerning copyright in an electronic -environment * Review of copyright law in the United States * The notion -of the public good and the desirability of incentives to promote it * -What copyright protects * Works not protected by copyright * The rights -of copyright holders * Publishers' concerns in today's electronic -environment * Compulsory licenses * The price of copyright in a digital -medium and the need for cooperation * Additional clarifications * Rough -justice oftentimes the outcome in numerous copyright matters * Copyright -in an electronic society * Copyright law always only sets up the -boundaries; anything can be changed by contract * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -Marybeth PETERS, policy planning adviser to the Register of Copyrights, -Library of Congress, made several general comments and then opened the -floor to discussion of subjects of interest to the audience. - -Having attended several sessions in an effort to gain a sense of what -people did and where copyright would affect their lives, PETERS expressed -the following cautions: - - * If one takes and converts materials and puts them in new forms, - then, from a copyright point of view, one is creating something and - will receive some rights. - - * However, if what one is converting already exists, a question - immediately arises about the status of the materials in question. - - * Putting something in the public domain in the United States offers - some freedom from anxiety, but distributing it throughout the world - on a network is another matter, even if one has put it in the public - domain in the United States. Re foreign laws, very frequently a - work can be in the public domain in the United States but protected - in other countries. Thus, one must consider all of the places a - work may reach, lest one unwittingly become liable to being faced - with a suit for copyright infringement, or at least a letter - demanding discussion of what one is doing. - -PETERS reviewed copyright law in the United States. The U.S. -Constitution effectively states that Congress has the power to enact -copyright laws for two purposes: 1) to encourage the creation and -dissemination of intellectual works for the good of society as a whole; -and, significantly, 2) to give creators and those who package and -disseminate materials the economic rewards that are due them. - -Congress strives to strike a balance, which at times can become an -emotional issue. The United States has never accepted the notion of the -natural right of an author so much as it has accepted the notion of the -public good and the desirability of incentives to promote it. This state -of affairs, however, has created strains on the international level and -is the reason for several of the differences in the laws that we have. -Today the United States protects almost every kind of work that can be -called an expression of an author. The standard for gaining copyright -protection is simply originality. This is a low standard and means that -a work is not copied from something else, as well as shows a certain -minimal amount of authorship. One can also acquire copyright protection -for making a new version of preexisting material, provided it manifests -some spark of creativity. - -However, copyright does not protect ideas, methods, systems--only the way -that one expresses those things. Nor does copyright protect anything -that is mechanical, anything that does not involve choice, or criteria -concerning whether or not one should do a thing. For example, the -results of a process called declicking, in which one mechanically removes -impure sounds from old recordings, are not copyrightable. On the other -hand, the choice to record a song digitally and to increase the sound of -violins or to bring up the tympani constitutes the results of conversion -that are copyrightable. Moreover, if a work is protected by copyright in -the United States, one generally needs the permission of the copyright -owner to convert it. Normally, who will own the new--that is, converted- --material is a matter of contract. In the absence of a contract, the -person who creates the new material is the author and owner. But people -do not generally think about the copyright implications until after the -fact. PETERS stressed the need when dealing with copyrighted works to -think about copyright in advance. One's bargaining power is much greater -up front than it is down the road. - -PETERS next discussed works not protected by copyright, for example, any -work done by a federal employee as part of his or her official duties is -in the public domain in the United States. The issue is not wholly free -of doubt concerning whether or not the work is in the public domain -outside the United States. Other materials in the public domain include: -any works published more than seventy-five years ago, and any work -published in the United States more than twenty-eight years ago, whose -copyright was not renewed. In talking about the new technology and -putting material in a digital form to send all over the world, PETERS -cautioned, one must keep in mind that while the rights may not be an -issue in the United States, they may be in different parts of the world, -where most countries previously employed a copyright term of the life of -the author plus fifty years. - -PETERS next reviewed the economics of copyright holding. Simply, -economic rights are the rights to control the reproduction of a work in -any form. They belong to the author, or in the case of a work made for -hire, the employer. The second right, which is critical to conversion, -is the right to change a work. The right to make new versions is perhaps -one of the most significant rights of authors, particularly in an -electronic world. The third right is the right to publish the work and -the right to disseminate it, something that everyone who deals in an -electronic medium needs to know. The basic rule is if a copy is sold, -all rights of distribution are extinguished with the sale of that copy. -The key is that it must be sold. A number of companies overcome this -obstacle by leasing or renting their product. These companies argue that -if the material is rented or leased and not sold, they control the uses -of a work. The fourth right, and one very important in a digital world, -is a right of public performance, which means the right to show the work -sequentially. For example, copyright owners control the showing of a -CD-ROM product in a public place such as a public library. The reverse -side of public performance is something called the right of public -display. Moral rights also exist, which at the federal level apply only -to very limited visual works of art, but in theory may apply under -contract and other principles. Moral rights may include the right of an -author to have his or her name on a work, the right of attribution, and -the right to object to distortion or mutilation--the right of integrity. - -The way copyright law is worded gives much latitude to activities such as -preservation; to use of material for scholarly and research purposes when -the user does not make multiple copies; and to the generation of -facsimile copies of unpublished works by libraries for themselves and -other libraries. But the law does not allow anyone to become the -distributor of the product for the entire world. In today's electronic -environment, publishers are extremely concerned that the entire world is -networked and can obtain the information desired from a single copy in a -single library. Hence, if there is to be only one sale, which publishers -may choose to live with, they will obtain their money in other ways, for -example, from access and use. Hence, the development of site licenses -and other kinds of agreements to cover what publishers believe they -should be compensated for. Any solution that the United States takes -today has to consider the international arena. - -Noting that the United States is a member of the Berne Convention and -subscribes to its provisions, PETERS described the permissions process. -She also defined compulsory licenses. A compulsory license, of which the -United States has had a few, builds into the law the right to use a work -subject to certain terms and conditions. In the international arena, -however, the ability to use compulsory licenses is extremely limited. -Thus, clearinghouses and other collectives comprise one option that has -succeeded in providing for use of a work. Often overlooked when one -begins to use copyrighted material and put products together is how -expensive the permissions process and managing it is. According to -PETERS, the price of copyright in a digital medium, whatever solution is -worked out, will include managing and assembling the database. She -strongly recommended that publishers and librarians or people with -various backgrounds cooperate to work out administratively feasible -systems, in order to produce better results. - -In the lengthy question-and-answer period that followed PETERS's -presentation, the following points emerged: - - * The Copyright Office maintains that anything mechanical and - totally exhaustive probably is not protected. In the event that - what an individual did in developing potentially copyrightable - material is not understood, the Copyright Office will ask about the - creative choices the applicant chose to make or not to make. As a - practical matter, if one believes she or he has made enough of those - choices, that person has a right to assert a copyright and someone - else must assert that the work is not copyrightable. The more - mechanical, the more automatic, a thing is, the less likely it is to - be copyrightable. - - * Nearly all photographs are deemed to be copyrightable, but no one - worries about them much, because everyone is free to take the same - image. Thus, a photographic copyright represents what is called a - "thin" copyright. The photograph itself must be duplicated, in - order for copyright to be violated. - - * The Copyright Office takes the position that X-rays are not - copyrightable because they are mechanical. It can be argued - whether or not image enhancement in scanning can be protected. One - must exercise care with material created with public funds and - generally in the public domain. An article written by a federal - employee, if written as part of official duties, is not - copyrightable. However, control over a scientific article written - by a National Institutes of Health grantee (i.e., someone who - receives money from the U.S. government), depends on NIH policy. If - the government agency has no policy (and that policy can be - contained in its regulations, the contract, or the grant), the - author retains copyright. If a provision of the contract, grant, or - regulation states that there will be no copyright, then it does not - exist. When a work is created, copyright automatically comes into - existence unless something exists that says it does not. - - * An enhanced electronic copy of a print copy of an older reference - work in the public domain that does not contain copyrightable new - material is a purely mechanical rendition of the original work, and - is not copyrightable. - - * Usually, when a work enters the public domain, nothing can remove - it. For example, Congress recently passed into law the concept of - automatic renewal, which means that copyright on any work published - between l964 and l978 does not have to be renewed in order to - receive a seventy-five-year term. But any work not renewed before - 1964 is in the public domain. - - * Concerning whether or not the United States keeps track of when - authors die, nothing was ever done, nor is anything being done at - the moment by the Copyright Office. - - * Software that drives a mechanical process is itself copyrightable. - If one changes platforms, the software itself has a copyright. The - World Intellectual Property Organization will hold a symposium 28 - March through 2 April l993, at Harvard University, on digital - technology, and will study this entire issue. If one purchases a - computer software package, such as MacPaint, and creates something - new, one receives protection only for that which has been added. - -PETERS added that often in copyright matters, rough justice is the -outcome, for example, in collective licensing, ASCAP (i.e., American -Society of Composers, Authors, and Publishers), and BMI (i.e., Broadcast -Music, Inc.), where it may seem that the big guys receive more than their -due. Of course, people ought not to copy a creative product without -paying for it; there should be some compensation. But the truth of the -world, and it is not a great truth, is that the big guy gets played on -the radio more frequently than the little guy, who has to do much more -until he becomes a big guy. That is true of every author, every -composer, everyone, and, unfortunately, is part of life. - -Copyright always originates with the author, except in cases of works -made for hire. (Most software falls into this category.) When an author -sends his article to a journal, he has not relinquished copyright, though -he retains the right to relinquish it. The author receives absolutely -everything. The less prominent the author, the more leverage the -publisher will have in contract negotiations. In order to transfer the -rights, the author must sign an agreement giving them away. - -In an electronic society, it is important to be able to license a writer -and work out deals. With regard to use of a work, it usually is much -easier when a publisher holds the rights. In an electronic era, a real -problem arises when one is digitizing and making information available. -PETERS referred again to electronic licensing clearinghouses. Copyright -ought to remain with the author, but as one moves forward globally in the -electronic arena, a middleman who can handle the various rights becomes -increasingly necessary. - -The notion of copyright law is that it resides with the individual, but -in an on-line environment, where a work can be adapted and tinkered with -by many individuals, there is concern. If changes are authorized and -there is no agreement to the contrary, the person who changes a work owns -the changes. To put it another way, the person who acquires permission -to change a work technically will become the author and the owner, unless -some agreement to the contrary has been made. It is typical for the -original publisher to try to control all of the versions and all of the -uses. Copyright law always only sets up the boundaries. Anything can be -changed by contract. - - ****** - -SESSION VII. CONCLUSION - -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -GENERAL DISCUSSION * Two questions for discussion * Different emphases in -the Workshop * Bringing the text and image partisans together * -Desiderata in planning the long-term development of something * Questions -surrounding the issue of electronic deposit * Discussion of electronic -deposit as an allusion to the issue of standards * Need for a directory -of preservation projects in digital form and for access to their -digitized files * CETH's catalogue of machine-readable texts in the -humanities * What constitutes a publication in the electronic world? * -Need for LC to deal with the concept of on-line publishing * LC's Network -Development Office exploring the limits of MARC as a standard in terms -of handling electronic information * Magnitude of the problem and the -need for distributed responsibility in order to maintain and store -electronic information * Workshop participants to be viewed as a starting -point * Development of a network version of AM urged * A step toward AM's -construction of some sort of apparatus for network access * A delicate -and agonizing policy question for LC * Re the issue of electronic -deposit, LC urged to initiate a catalytic process in terms of distributed -responsibility * Suggestions for cooperative ventures * Commercial -publishers' fears * Strategic questions for getting the image and text -people to think through long-term cooperation * Clarification of the -driving force behind both the Perseus and the Cornell Xerox projects * -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -In his role as moderator of the concluding session, GIFFORD raised two -questions he believed would benefit from discussion: 1) Are there enough -commonalities among those of us that have been here for two days so that -we can see courses of action that should be taken in the future? And, if -so, what are they and who might take them? 2) Partly derivative from -that, but obviously very dangerous to LC as host, do you see a role for -the Library of Congress in all this? Of course, the Library of Congress -holds a rather special status in a number of these matters, because it is -not perceived as a player with an economic stake in them, but are there -roles that LC can play that can help advance us toward where we are heading? - -Describing himself as an uninformed observer of the technicalities of the -last two days, GIFFORD detected three different emphases in the Workshop: -1) people who are very deeply committed to text; 2) people who are almost -passionate about images; and 3) a few people who are very committed to -what happens to the networks. In other words, the new networking -dimension, the accessibility of the processability, the portability of -all this across the networks. How do we pull those three together? - -Adding a question that reflected HOCKEY's comment that this was the -fourth workshop she had attended in the previous thirty days, FLEISCHHAUER -wondered to what extent this meeting had reinvented the wheel, or if it -had contributed anything in the way of bringing together a different group -of people from those who normally appear on the workshop circuit. - -HOCKEY confessed to being struck at this meeting and the one the -Electronic Pierce Consortium organized the previous week that this was a -coming together of people working on texts and not images. Attempting to -bring the two together is something we ought to be thinking about for the -future: How one can think about working with image material to begin -with, but structuring it and digitizing it in such a way that at a later -stage it can be interpreted into text, and find a common way of building -text and images together so that they can be used jointly in the future, -with the network support to begin there because that is how people will -want to access it. - -In planning the long-term development of something, which is what is -being done in electronic text, HOCKEY stressed the importance not only -of discussing the technical aspects of how one does it but particularly -of thinking about what the people who use the stuff will want to do. -But conversely, there are numerous things that people start to do with -electronic text or material that nobody ever thought of in the beginning. - -LESK, in response to the question concerning the role of the Library of -Congress, remarked the often suggested desideratum of having electronic -deposit: Since everything is now computer-typeset, an entire decade of -material that was machine-readable exists, but the publishers frequently -did not save it; has LC taken any action to have its copyright deposit -operation start collecting these machine-readable versions? In the -absence of PETERS, GIFFORD replied that the question was being -actively considered but that that was only one dimension of the problem. -Another dimension is the whole question of the integrity of the original -electronic document. It becomes highly important in science to prove -authorship. How will that be done? - -ERWAY explained that, under the old policy, to make a claim for a -copyright for works that were published in electronic form, including -software, one had to submit a paper copy of the first and last twenty -pages of code--something that represented the work but did not include -the entire work itself and had little value to anyone. As a temporary -measure, LC has claimed the right to demand electronic versions of -electronic publications. This measure entails a proactive role for the -Library to say that it wants a particular electronic version. Publishers -then have perhaps a year to submit it. But the real problem for LC is -what to do with all this material in all these different formats. Will -the Library mount it? How will it give people access to it? How does LC -keep track of the appropriate computers, software, and media? The situation -is so hard to control, ERWAY said, that it makes sense for each publishing -house to maintain its own archive. But LC cannot enforce that either. - -GIFFORD acknowledged LESK's suggestion that establishing a priority -offered the solution, albeit a fairly complicated one. But who maintains -that register?, he asked. GRABER noted that LC does attempt to collect a -Macintosh version and the IBM-compatible version of software. It does -not collect other versions. But while true for software, BYRUM observed, -this reply does not speak to materials, that is, all the materials that -were published that were on somebody's microcomputer or driver tapes -at a publishing office across the country. LC does well to acquire -specific machine-readable products selectively that were intended to be -machine-readable. Materials that were in machine-readable form at one time, -BYRUM said, would be beyond LC's capability at the moment, insofar as -attempting to acquire, organize, and preserve them are concerned--and -preservation would be the most important consideration. In this -connection, GIFFORD reiterated the need to work out some sense of -distributive responsibility for a number of these issues, which -inevitably will require significant cooperation and discussion. -Nobody can do it all. - -LESK suggested that some publishers may look with favor on LC beginning -to serve as a depository of tapes in an electronic manuscript standard. -Publishers may view this as a service that they did not have to perform -and they might send in tapes. However, SPERBERG-McQUEEN countered, -although publishers have had equivalent services available to them for a -long time, the electronic text archive has never turned away or been -flooded with tapes and is forever sending feedback to the depositor. -Some publishers do send in tapes. - -ANDRE viewed this discussion as an allusion to the issue of standards. -She recommended that the AAP standard and the TEI, which has already been -somewhat harmonized internationally and which also shares several -compatibilities with the AAP, be harmonized to ensure sufficient -compatibility in the software. She drew the line at saying LC ought to -be the locus or forum for such harmonization. - -Taking the group in a slightly different direction, but one where at -least in the near term LC might play a helpful role, LYNCH remarked the -plans of a number of projects to carry out preservation by creating -digital images that will end up in on-line or near-line storage at some -institution. Presumably, LC will link this material somehow to its -on-line catalog in most cases. Thus, it is in a digital form. LYNCH had -the impression that many of these institutions would be willing to make -those files accessible to other people outside the institution, provided -that there is no copyright problem. This desideratum will require -propagating the knowledge that those digitized files exist, so that they -can end up in other on-line catalogs. Although uncertain about the -mechanism for achieving this result, LYNCH said that it warranted -scrutiny because it seemed to be connected to some of the basic issues of -cataloging and distribution of records. It would be foolish, given the -amount of work that all of us have to do and our meager resources, to -discover multiple institutions digitizing the same work. Re microforms, -LYNCH said, we are in pretty good shape. - -BATTIN called this a big problem and noted that the Cornell people (who -had already departed) were working on it. At issue from the beginning -was to learn how to catalog that information into RLIN and then into -OCLC, so that it would be accessible. That issue remains to be resolved. -LYNCH rejoined that putting it into OCLC or RLIN was helpful insofar as -somebody who is thinking of performing preservation activity on that work -could learn about it. It is not necessarily helpful for institutions to -make that available. BATTIN opined that the idea was that it not only be -for preservation purposes but for the convenience of people looking for -this material. She endorsed LYNCH's dictum that duplication of this -effort was to be avoided by every means. - -HOCKEY informed the Workshop about one major current activity of CETH, -namely a catalogue of machine-readable texts in the humanities. Held on -RLIN at present, the catalogue has been concentrated on ASCII as opposed -to digitized images of text. She is exploring ways to improve the -catalogue and make it more widely available, and welcomed suggestions -about these concerns. CETH owns the records, which are not just -restricted to RLIN, and can distribute them however it wishes. - -Taking up LESK's earlier question, BATTIN inquired whether LC, since it -is accepting electronic files and designing a mechanism for dealing with -that rather than putting books on shelves, would become responsible for -the National Copyright Depository of Electronic Materials. Of course -that could not be accomplished overnight, but it would be something LC -could plan for. GIFFORD acknowledged that much thought was being devoted -to that set of problems and returned the discussion to the issue raised -by LYNCH--whether or not putting the kind of records that both BATTIN and -HOCKEY have been talking about in RLIN is not a satisfactory solution. -It seemed to him that RLIN answered LYNCH's original point concerning -some kind of directory for these kinds of materials. In a situation -where somebody is attempting to decide whether or not to scan this or -film that or to learn whether or not someone has already done so, LYNCH -suggested, RLIN is helpful, but it is not helpful in the case of a local, -on-line catalogue. Further, one would like to have her or his system be -aware that that exists in digital form, so that one can present it to a -patron, even though one did not digitize it, if it is out of copyright. -The only way to make those linkages would be to perform a tremendous -amount of real-time look-up, which would be awkward at best, or -periodically to yank the whole file from RLIN and match it against one's -own stuff, which is a nuisance. - -But where, ERWAY inquired, does one stop including things that are -available with Internet, for instance, in one's local catalogue? -It almost seems that that is LC's means to acquire access to them. -That represents LC's new form of library loan. Perhaps LC's new on-line -catalogue is an amalgamation of all these catalogues on line. LYNCH -conceded that perhaps that was true in the very long term, but was not -applicable to scanning in the short term. In his view, the totals cited -by Yale, 10,000 books over perhaps a four-year period, and 1,000-1,500 -books from Cornell, were not big numbers, while searching all over -creation for relatively rare occurrences will prove to be less efficient. -As GIFFORD wondered if this would not be a separable file on RLIN and -could be requested from them, BATTIN interjected that it was easily -accessible to an institution. SEVERTSON pointed out that that file, cum -enhancements, was available with reference information on CD-ROM, which -makes it a little more available. - -In HOCKEY's view, the real question facing the Workshop is what to put in -this catalogue, because that raises the question of what constitutes a -publication in the electronic world. (WEIBEL interjected that Eric Joule -in OCLC's Office of Research is also wrestling with this particular -problem, while GIFFORD thought it sounded fairly generic.) HOCKEY -contended that a majority of texts in the humanities are in the hands -of either a small number of large research institutions or individuals -and are not generally available for anyone else to access at all. -She wondered if these texts ought to be catalogued. - -After argument proceeded back and forth for several minutes over why -cataloguing might be a necessary service, LEBRON suggested that this -issue involved the responsibility of a publisher. The fact that someone -has created something electronically and keeps it under his or her -control does not constitute publication. Publication implies -dissemination. While it would be important for a scholar to let other -people know that this creation exists, in many respects this is no -different from an unpublished manuscript. That is what is being accessed -in there, except that now one is not looking at it in the hard-copy but -in the electronic environment. - -LEBRON expressed puzzlement at the variety of ways electronic publishing -has been viewed. Much of what has been discussed throughout these two -days has concerned CD-ROM publishing, whereas in the on-line environment -that she confronts, the constraints and challenges are very different. -Sooner or later LC will have to deal with the concept of on-line -publishing. Taking up the comment ERWAY made earlier about storing -copies, LEBRON gave her own journal as an example. How would she deposit -OJCCT for copyright?, she asked, because the journal will exist in the -mainframe at OCLC and people will be able to access it. Here the -situation is different, ownership versus access, and is something that -arises with publication in the on-line environment, faster than is -sometimes realized. Lacking clear answers to all of these questions -herself, LEBRON did not anticipate that LC would be able to take a role -in helping to define some of them for quite a while. - -GREENFIELD observed that LC's Network Development Office is attempting, -among other things, to explore the limits of MARC as a standard in terms -of handling electronic information. GREENFIELD also noted that Rebecca -GUENTHER from that office gave a paper to the American Society for -Information Science (ASIS) summarizing several of the discussion papers -that were coming out of the Network Development Office. GREENFIELD said -he understood that that office had a list-server soliciting just the kind -of feedback received today concerning the difficulties of identifying and -cataloguing electronic information. GREENFIELD hoped that everybody -would be aware of that and somehow contribute to that conversation. - -Noting two of LC's roles, first, to act as a repository of record for -material that is copyrighted in this country, and second, to make -materials it holds available in some limited form to a clientele that -goes beyond Congress, BESSER suggested that it was incumbent on LC to -extend those responsibilities to all the things being published in -electronic form. This would mean eventually accepting electronic -formats. LC could require that at some point they be in a certain -limited set of formats, and then develop mechanisms for allowing people -to access those in the same way that other things are accessed. This -does not imply that they are on the network and available to everyone. -LC does that with most of its bibliographic records, BESSER said, which -end up migrating to the utility (e.g., OCLC) or somewhere else. But just -as most of LC's books are available in some form through interlibrary -loan or some other mechanism, so in the same way electronic formats ought -to be available to others in some format, though with some copyright -considerations. BESSER was not suggesting that these mechanisms be -established tomorrow, only that they seemed to fall within LC's purview, -and that there should be long-range plans to establish them. - -Acknowledging that those from LC in the room agreed with BESSER -concerning the need to confront difficult questions, GIFFORD underscored -the magnitude of the problem of what to keep and what to select. GIFFORD -noted that LC currently receives some 31,000 items per day, not counting -electronic materials, and argued for much more distributed responsibility -in order to maintain and store electronic information. - -BESSER responded that the assembled group could be viewed as a starting -point, whose initial operating premise could be helping to move in this -direction and defining how LC could do so, for example, in areas of -standardization or distribution of responsibility. - -FLEISCHHAUER added that AM was fully engaged, wrestling with some of the -questions that pertain to the conversion of older historical materials, -which would be one thing that the Library of Congress might do. Several -points mentioned by BESSER and several others on this question have a -much greater impact on those who are concerned with cataloguing and the -networking of bibliographic information, as well as preservation itself. - -Speaking directly to AM, which he considered was a largely uncopyrighted -database, LYNCH urged development of a network version of AM, or -consideration of making the data in it available to people interested in -doing network multimedia. On account of the current great shortage of -digital data that is both appealing and unencumbered by complex rights -problems, this course of action could have a significant effect on making -network multimedia a reality. - -In this connection, FLEISCHHAUER reported on a fragmentary prototype in -LC's Office of Information Technology Services that attempts to associate -digital images of photographs with cataloguing information in ways that -work within a local area network--a step, so to say, toward AM's -construction of some sort of apparatus for access. Further, AM has -attempted to use standard data forms in order to help make that -distinction between the access tools and the underlying data, and thus -believes that the database is networkable. - -A delicate and agonizing policy question for LC, however, which comes -back to resources and unfortunately has an impact on this, is to find -some appropriate, honorable, and legal cost-recovery possibilities. A -certain skittishness concerning cost-recovery has made people unsure -exactly what to do. AM would be highly receptive to discussing further -LYNCH's offer to test or demonstrate its database in a network -environment, FLEISCHHAUER said. - -Returning the discussion to what she viewed as the vital issue of -electronic deposit, BATTIN recommended that LC initiate a catalytic -process in terms of distributed responsibility, that is, bring together -the distributed organizations and set up a study group to look at all -these issues and see where we as a nation should move. The broader -issues of how we deal with the management of electronic information will -not disappear, but only grow worse. - -LESK took up this theme and suggested that LC attempt to persuade one -major library in each state to deal with its state equivalent publisher, -which might produce a cooperative project that would be equitably -distributed around the country, and one in which LC would be dealing with -a minimal number of publishers and minimal copyright problems. - -GRABER remarked the recent development in the scientific community of a -willingness to use SGML and either deposit or interchange on a fairly -standardized format. He wondered if a similar movement was taking place -in the humanities. Although the National Library of Medicine found only -a few publishers to cooperate in a like venture two or three years ago, a -new effort might generate a much larger number willing to cooperate. - -KIMBALL recounted his unit's (Machine-Readable Collections Reading Room) -troubles with the commercial publishers of electronic media in acquiring -materials for LC's collections, in particular the publishers' fear that -they would not be able to cover their costs and would lose control of -their products, that LC would give them away or sell them and make -profits from them. He doubted that the publishing industry was prepared -to move into this area at the moment, given its resistance to allowing LC -to use its machine-readable materials as the Library would like. - -The copyright law now addresses compact disk as a medium, and LC can -request one copy of that, or two copies if it is the only version, and -can request copies of software, but that fails to address magazines or -books or anything like that which is in machine-readable form. - -GIFFORD acknowledged the thorny nature of this issue, which he illustrated -with the example of the cumbersome process involved in putting a copy of a -scientific database on a LAN in LC's science reading room. He also -acknowledged that LC needs help and could enlist the energies and talents -of Workshop participants in thinking through a number of these problems. - -GIFFORD returned the discussion to getting the image and text people to -think through together where they want to go in the long term. MYLONAS -conceded that her experience at the Pierce Symposium the previous week at -Georgetown University and this week at LC had forced her to reevaluate -her perspective on the usefulness of text as images. MYLONAS framed the -issues in a series of questions: How do we acquire machine-readable -text? Do we take pictures of it and perform OCR on it later? Is it -important to obtain very high-quality images and text, etc.? -FLEISCHHAUER agreed with MYLONAS's framing of strategic questions, adding -that a large institution such as LC probably has to do all of those -things at different times. Thus, the trick is to exercise judgment. The -Workshop had added to his and AM's considerations in making those -judgments. Concerning future meetings or discussions, MYLONAS suggested -that screening priorities would be helpful. - -WEIBEL opined that the diversity reflected in this group was a sign both -of the health and of the immaturity of the field, and more time would -have to pass before we convince one another concerning standards. - -An exchange between MYLONAS and BATTIN clarified the point that the -driving force behind both the Perseus and the Cornell Xerox projects was -the preservation of knowledge for the future, not simply for particular -research use. In the case of Perseus, MYLONAS said, the assumption was -that the texts would not be entered again into electronically readable -form. SPERBERG-McQUEEN added that a scanned image would not serve as an -archival copy for purposes of preservation in the case of, say, the Bill -of Rights, in the sense that the scanned images are effectively the -archival copies for the Cornell mathematics books. - - - *** *** *** ****** *** *** *** - - - Appendix I: PROGRAM - - - - WORKSHOP - ON - ELECTRONIC - TEXTS - - - - 9-10 June 1992 - - Library of Congress - Washington, D.C. - - - - Supported by a Grant from the David and Lucile Packard Foundation - - -Tuesday, 9 June 1992 - -NATIONAL DEMONSTRATION LAB, ATRIUM, LIBRARY MADISON - -8:30 AM Coffee and Danish, registration - -9:00 AM Welcome - - Prosser Gifford, Director for Scholarly Programs, and Carl - Fleischhauer, Coordinator, American Memory, Library of - Congress - -9:l5 AM Session I. Content in a New Form: Who Will Use It and What - Will They Do? - - Broad description of the range of electronic information. - Characterization of who uses it and how it is or may be used. - In addition to a look at scholarly uses, this session will - include a presentation on use by students (K-12 and college) - and the general public. - - Moderator: James Daly - Avra Michelson, Archival Research and Evaluation Staff, - National Archives and Records Administration (Overview) - Susan H. Veccia, Team Leader, American Memory, User Evaluation, - and - Joanne Freeman, Associate Coordinator, American Memory, Library - of Congress (Beyond the scholar) - -10:30- -11:00 AM Break - -11:00 AM Session II. Show and Tell. - - Each presentation to consist of a fifteen-minute - statement/show; group discussion will follow lunch. - - Moderator: Jacqueline Hess, Director, National Demonstration - Lab - - 1. A classics project, stressing texts and text retrieval - more than multimedia: Perseus Project, Harvard - University - Elli Mylonas, Managing Editor - - 2. Other humanities projects employing the emerging norms of - the Text Encoding Initiative (TEI): Chadwyck-Healey's - The English Poetry Full Text Database and/or Patrologia - Latina Database - Eric M. Calaluca, Vice President, Chadwyck-Healey, Inc. - - 3. American Memory - Carl Fleischhauer, Coordinator, and - Ricky Erway, Associate Coordinator, Library of Congress - - 4. Founding Fathers example from Packard Humanities - Institute: The Papers of George Washington, University - of Virginia - Dorothy Twohig, Managing Editor, and/or - David Woodley Packard - - 5. An electronic medical journal offering graphics and - full-text searchability: The Online Journal of Current - Clinical Trials, American Association for the Advancement - of Science - Maria L. Lebron, Managing Editor - - 6. A project that offers facsimile images of pages but omits - searchable text: Cornell math books - Lynne K. Personius, Assistant Director, Cornell - Information Technologies for Scholarly Information - Sources, Cornell University - -12:30 PM Lunch (Dining Room A, Library Madison 620. Exhibits - available.) - -1:30 PM Session II. Show and Tell (Cont'd.). - -3:00- -3:30 PM Break - -3:30- -5:30 PM Session III. Distribution, Networks, and Networking: Options - for Dissemination. - - Published disks: University presses and public-sector - publishers, private-sector publishers - Computer networks - - Moderator: Robert G. Zich, Special Assistant to the Associate - Librarian for Special Projects, Library of Congress - Clifford A. Lynch, Director, Library Automation, University of - California - Howard Besser, School of Library and Information Science, - University of Pittsburgh - Ronald L. Larsen, Associate Director of Libraries for - Information Technology, University of Maryland at College - Park - Edwin B. Brownrigg, Executive Director, Memex Research - Institute - -6:30 PM Reception (Montpelier Room, Library Madison 619.) - - ****** - -Wednesday, 10 June 1992 - -DINING ROOM A, LIBRARY MADISON 620 - -8:30 AM Coffee and Danish - -9:00 AM Session IV. Image Capture, Text Capture, Overview of Text and - Image Storage Formats. - - Moderator: William L. Hooton, Vice President of Operations, - I-NET - - A) Principal Methods for Image Capture of Text: - Direct scanning - Use of microform - - Anne R. Kenney, Assistant Director, Department of Preservation - and Conservation, Cornell University - Pamela Q.J. Andre, Associate Director, Automation, and - Judith A. Zidar, Coordinator, National Agricultural Text - Digitizing Program (NATDP), National Agricultural Library - (NAL) - Donald J. Waters, Head, Systems Office, Yale University Library - - B) Special Problems: - Bound volumes - Conservation - Reproducing printed halftones - - Carl Fleischhauer, Coordinator, American Memory, Library of - Congress - George Thoma, Chief, Communications Engineering Branch, - National Library of Medicine (NLM) - -10:30- -11:00 AM Break - -11:00 AM Session IV. Image Capture, Text Capture, Overview of Text and - Image Storage Formats (Cont'd.). - - C) Image Standards and Implications for Preservation - - Jean Baronas, Senior Manager, Department of Standards and - Technology, Association for Information and Image Management - (AIIM) - Patricia Battin, President, The Commission on Preservation and - Access (CPA) - - D) Text Conversion: - OCR vs. rekeying - Standards of accuracy and use of imperfect texts - Service bureaus - - Stuart Weibel, Senior Research Specialist, Online Computer - Library Center, Inc. (OCLC) - Michael Lesk, Executive Director, Computer Science Research, - Bellcore - Ricky Erway, Associate Coordinator, American Memory, Library of - Congress - Pamela Q.J. Andre, Associate Director, Automation, and - Judith A. Zidar, Coordinator, National Agricultural Text - Digitizing Program (NATDP), National Agricultural Library - (NAL) - -12:30- -1:30 PM Lunch - -1:30 PM Session V. Approaches to Preparing Electronic Texts. - - Discussion of approaches to structuring text for the computer; - pros and cons of text coding, description of methods in - practice, and comparison of text-coding methods. - - Moderator: Susan Hockey, Director, Center for Electronic Texts - in the Humanities (CETH), Rutgers and Princeton Universities - David Woodley Packard - C.M. Sperberg-McQueen, Editor, Text Encoding Initiative (TEI), - University of Illinois-Chicago - Eric M. Calaluca, Vice President, Chadwyck-Healey, Inc. - -3:30- -4:00 PM Break - -4:00 PM Session VI. Copyright Issues. - - Marybeth Peters, Policy Planning Adviser to the Register of - Copyrights, Library of Congress - -5:00 PM Session VII. Conclusion. - - General discussion. - What topics were omitted or given short shrift that anyone - would like to talk about now? - Is there a "group" here? What should the group do next, if - anything? What should the Library of Congress do next, if - anything? - Moderator: Prosser Gifford, Director for Scholarly Programs, - Library of Congress - -6:00 PM Adjourn - - - *** *** *** ****** *** *** *** - - - Appendix II: ABSTRACTS - - -SESSION I - -Avra MICHELSON Forecasting the Use of Electronic Texts by - Social Sciences and Humanities Scholars - -This presentation explores the ways in which electronic texts are likely -to be used by the non-scientific scholarly community. Many of the -remarks are drawn from a report the speaker coauthored with Jeff -Rothenberg, a computer scientist at The RAND Corporation. - -The speaker assesses 1) current scholarly use of information technology -and 2) the key trends in information technology most relevant to the -research process, in order to predict how social sciences and humanities -scholars are apt to use electronic texts. In introducing the topic, -current use of electronic texts is explored broadly within the context of -scholarly communication. From the perspective of scholarly -communication, the work of humanities and social sciences scholars -involves five processes: 1) identification of sources, 2) communication -with colleagues, 3) interpretation and analysis of data, 4) dissemination -of research findings, and 5) curriculum development and instruction. The -extent to which computation currently permeates aspects of scholarly -communication represents a viable indicator of the prospects for -electronic texts. - -The discussion of current practice is balanced by an analysis of key -trends in the scholarly use of information technology. These include the -trends toward end-user computing and connectivity, which provide a -framework for forecasting the use of electronic texts through this -millennium. The presentation concludes with a summary of the ways in -which the nonscientific scholarly community can be expected to use -electronic texts, and the implications of that use for information -providers. - -Susan VECCIA and Joanne FREEMAN Electronic Archives for the Public: - Use of American Memory in Public and - School Libraries - -This joint discussion focuses on nonscholarly applications of electronic -library materials, specifically addressing use of the Library of Congress -American Memory (AM) program in a small number of public and school -libraries throughout the United States. AM consists of selected Library -of Congress primary archival materials, stored on optical media -(CD-ROM/videodisc), and presented with little or no editing. Many -collections are accompanied by electronic introductions and user's guides -offering background information and historical context. Collections -represent a variety of formats including photographs, graphic arts, -motion pictures, recorded sound, music, broadsides and manuscripts, -books, and pamphlets. - -In 1991, the Library of Congress began a nationwide evaluation of AM in -different types of institutions. Test sites include public libraries, -elementary and secondary school libraries, college and university -libraries, state libraries, and special libraries. Susan VECCIA and -Joanne FREEMAN will discuss their observations on the use of AM by the -nonscholarly community, using evidence gleaned from this ongoing -evaluation effort. - -VECCIA will comment on the overall goals of the evaluation project, and -the types of public and school libraries included in this study. Her -comments on nonscholarly use of AM will focus on the public library as a -cultural and community institution, often bridging the gap between formal -and informal education. FREEMAN will discuss the use of AM in school -libraries. Use by students and teachers has revealed some broad -questions about the use of electronic resources, as well as definite -benefits gained by the "nonscholar." Topics will include the problem of -grasping content and context in an electronic environment, the stumbling -blocks created by "new" technologies, and the unique skills and interests -awakened through use of electronic resources. - -SESSION II - -Elli MYLONAS The Perseus Project: Interactive Sources and - Studies in Classical Greece - -The Perseus Project (5) has just released Perseus 1.0, the first publicly -available version of its hypertextual database of multimedia materials on -classical Greece. Perseus is designed to be used by a wide audience, -comprised of readers at the student and scholar levels. As such, it must -be able to locate information using different strategies, and it must -contain enough detail to serve the different needs of its users. In -addition, it must be delivered so that it is affordable to its target -audience. [These problems and the solutions we chose are described in -Mylonas, "An Interface to Classical Greek Civilization," JASIS 43:2, -March 1992.] - -In order to achieve its objective, the project staff decided to make a -conscious separation between selecting and converting textual, database, -and image data on the one hand, and putting it into a delivery system on -the other. That way, it is possible to create the electronic data -without thinking about the restrictions of the delivery system. We have -made a great effort to choose system-independent formats for our data, -and to put as much thought and work as possible into structuring it so -that the translation from paper to electronic form will enhance the value -of the data. [A discussion of these solutions as of two years ago is in -Elli Mylonas, Gregory Crane, Kenneth Morrell, and D. Neel Smith, "The -Perseus Project: Data in the Electronic Age," in Accessing Antiquity: -The Computerization of Classical Databases, J. Solomon and T. Worthen -(eds.), University of Arizona Press, in press.] - -Much of the work on Perseus is focused on collecting and converting the -data on which the project is based. At the same time, it is necessary to -provide means of access to the information, in order to make it usable, -and them to investigate how it is used. As we learn more about what -students and scholars from different backgrounds do with Perseus, we can -adjust our data collection, and also modify the system to accommodate -them. In creating a delivery system for general use, we have tried to -avoid favoring any one type of use by allowing multiple forms of access -to and navigation through the system. - -The way text is handled exemplifies some of these principles. All text -in Perseus is tagged using SGML, following the guidelines of the Text -Encoding Initiative (TEI). This markup is used to index the text, and -process it so that it can be imported into HyperCard. No SGML markup -remains in the text that reaches the user, because currently it would be -too expensive to create a system that acts on SGML in real time. -However, the regularity provided by SGML is essential for verifying the -content of the texts, and greatly speeds all the processing performed on -them. The fact that the texts exist in SGML ensures that they will be -relatively easy to port to different hardware and software, and so will -outlast the current delivery platform. Finally, the SGML markup -incorporates existing canonical reference systems (chapter, verse, line, -etc.); indexing and navigation are based on these features. This ensures -that the same canonical reference will always resolve to the same point -within a text, and that all versions of our texts, regardless of delivery -platform (even paper printouts) will function the same way. - -In order to provide tools for users, the text is processed by a -morphological analyzer, and the results are stored in a database. -Together with the index, the Greek-English Lexicon, and the index of all -the English words in the definitions of the lexicon, the morphological -analyses comprise a set of linguistic tools that allow users of all -levels to work with the textual information, and to accomplish different -tasks. For example, students who read no Greek may explore a concept as -it appears in Greek texts by using the English-Greek index, and then -looking up works in the texts and translations, or scholars may do -detailed morphological studies of word use by using the morphological -analyses of the texts. Because these tools were not designed for any one -use, the same tools and the same data can be used by both students and -scholars. - -NOTES: - (5) Perseus is based at Harvard University, with collaborators at - several other universities. The project has been funded primarily - by the Annenberg/CPB Project, as well as by Harvard University, - Apple Computer, and others. It is published by Yale University - Press. Perseus runs on Macintosh computers, under the HyperCard - program. - -Eric CALALUCA - -Chadwyck-Healey embarked last year on two distinct yet related full-text -humanities database projects. - -The English Poetry Full-Text Database and the Patrologia Latina Database -represent new approaches to linguistic research resources. The size and -complexity of the projects present problems for electronic publishers, -but surmountable ones if they remain abreast of the latest possibilities -in data capture and retrieval software techniques. - -The issues which required address prior to the commencement of the -projects were legion: - - 1. Editorial selection (or exclusion) of materials in each - database - - 2. Deciding whether or not to incorporate a normative encoding - structure into the databases? - A. If one is selected, should it be SGML? - B. If SGML, then the TEI? - - 3. Deliver as CD-ROM, magnetic tape, or both? - - 4. Can one produce retrieval software advanced enough for the - postdoctoral linguist, yet accessible enough for unattended - general use? Should one try? - - 5. Re fair and liberal networking policies, what are the risks to - an electronic publisher? - - 6. How does the emergence of national and international education - networks affect the use and viability of research projects - requiring high investment? Do the new European Community - directives concerning database protection necessitate two - distinct publishing projects, one for North America and one for - overseas? - -From new notions of "scholarly fair use" to the future of optical media, -virtually every issue related to electronic publishing was aired. The -result is two projects which have been constructed to provide the quality -research resources with the fewest encumbrances to use by teachers and -private scholars. - -Dorothy TWOHIG - -In spring 1988 the editors of the papers of George Washington, John -Adams, Thomas Jefferson, James Madison, and Benjamin Franklin were -approached by classics scholar David Packard on behalf of the Packard -Humanities Foundation with a proposal to produce a CD-ROM edition of the -complete papers of each of the Founding Fathers. This electronic edition -will supplement the published volumes, making the documents widely -available to students and researchers at reasonable cost. We estimate -that our CD-ROM edition of Washington's Papers will be substantially -completed within the next two years and ready for publication. Within -the next ten years or so, similar CD-ROM editions of the Franklin, Adams, -Jefferson, and Madison papers also will be available. At the Library of -Congress's session on technology, I would like to discuss not only the -experience of the Washington Papers in producing the CD-ROM edition, but -the impact technology has had on these major editorial projects. -Already, we are editing our volumes with an eye to the material that will -be readily available in the CD-ROM edition. The completed electronic -edition will provide immense possibilities for the searching of documents -for information in a way never possible before. The kind of technical -innovations that are currently available and on the drawing board will -soon revolutionize historical research and the production of historical -documents. Unfortunately, much of this new technology is not being used -in the planning stages of historical projects, simply because many -historians are aware only in the vaguest way of its existence. At least -two major new historical editing projects are considering microfilm -editions, simply because they are not aware of the possibilities of -electronic alternatives and the advantages of the new technology in terms -of flexibility and research potential compared to microfilm. In fact, -too many of us in history and literature are still at the stage of -struggling with our PCs. There are many historical editorial projects in -progress presently, and an equal number of literary projects. While the -two fields have somewhat different approaches to textual editing, there -are ways in which electronic technology can be of service to both. - -Since few of the editors involved in the Founding Fathers CD-ROM editions -are technical experts in any sense, I hope to point out in my discussion -of our experience how many of these electronic innovations can be used -successfully by scholars who are novices in the world of new technology. -One of the major concerns of the sponsors of the multitude of new -scholarly editions is the limited audience reached by the published -volumes. Most of these editions are being published in small quantities -and the publishers' price for them puts them out of the reach not only of -individual scholars but of most public libraries and all but the largest -educational institutions. However, little attention is being given to -ways in which technology can bypass conventional publication to make -historical and literary documents more widely available. - -What attracted us most to the CD-ROM edition of The Papers of George -Washington was the fact that David Packard's aim was to make a complete -edition of all of the 135,000 documents we have collected available in an -inexpensive format that would be placed in public libraries, small -colleges, and even high schools. This would provide an audience far -beyond our present 1,000-copy, $45 published edition. Since the CD-ROM -edition will carry none of the explanatory annotation that appears in the -published volumes, we also feel that the use of the CD-ROM will lead many -researchers to seek out the published volumes. - -In addition to ignorance of new technical advances, I have found that too -many editors--and historians and literary scholars--are resistant and -even hostile to suggestions that electronic technology may enhance their -work. I intend to discuss some of the arguments traditionalists are -advancing to resist technology, ranging from distrust of the speed with -which it changes (we are already wondering what is out there that is -better than CD-ROM) to suspicion of the technical language used to -describe electronic developments. - -Maria LEBRON - -The Online Journal of Current Clinical Trials, a joint venture of the -American Association for the Advancement of Science (AAAS) and the Online -Computer Library Center, Inc. (OCLC), is the first peer-reviewed journal -to provide full text, tabular material, and line illustrations on line. -This presentation will discuss the genesis and start-up period of the -journal. Topics of discussion will include historical overview, -day-to-day management of the editorial peer review, and manuscript -tagging and publication. A demonstration of the journal and its features -will accompany the presentation. - -Lynne PERSONIUS - -Cornell University Library, Cornell Information Technologies, and Xerox -Corporation, with the support of the Commission on Preservation and -Access, and Sun Microsystems, Inc., have been collaborating in a project -to test a prototype system for recording brittle books as digital images -and producing, on demand, high-quality archival paper replacements. The -project goes beyond that, however, to investigate some of the issues -surrounding scanning, storing, retrieving, and providing access to -digital images in a network environment. - -The Joint Study in Digital Preservation began in January 1990. Xerox -provided the College Library Access and Storage System (CLASS) software, -a prototype 600-dots-per-inch (dpi) scanner, and the hardware necessary -to support network printing on the DocuTech printer housed in Cornell's -Computing and Communications Center (CCC). - -The Cornell staff using the hardware and software became an integral part -of the development and testing process for enhancements to the CLASS -software system. The collaborative nature of this relationship is -resulting in a system that is specifically tailored to the preservation -application. - -A digital library of 1,000 volumes (or approximately 300,000 images) has -been created and is stored on an optical jukebox that resides in CCC. -The library includes a collection of select mathematics monographs that -provides mathematics faculty with an opportunity to use the electronic -library. The remaining volumes were chosen for the library to test the -various capabilities of the scanning system. - -One project objective is to provide users of the Cornell library and the -library staff with the ability to request facsimiles of digitized images -or to retrieve the actual electronic image for browsing. A prototype -viewing workstation has been created by Xerox, with input into the design -by a committee of Cornell librarians and computer professionals. This -will allow us to experiment with patron access to the images that make up -the digital library. The viewing station provides search, retrieval, and -(ultimately) printing functions with enhancements to facilitate -navigation through multiple documents. - -Cornell currently is working to extend access to the digital library to -readers using workstations from their offices. This year is devoted to -the development of a network resident image conversion and delivery -server, and client software that will support readers who use Apple -Macintosh computers, IBM windows platforms, and Sun workstations. -Equipment for this development was provided by Sun Microsystems with -support from the Commission on Preservation and Access. - -During the show-and-tell session of the Workshop on Electronic Texts, a -prototype view station will be demonstrated. In addition, a display of -original library books that have been digitized will be available for -review with associated printed copies for comparison. The fifteen-minute -overview of the project will include a slide presentation that -constitutes a "tour" of the preservation digitizing process. - -The final network-connected version of the viewing station will provide -library users with another mechanism for accessing the digital library, -and will also provide the capability of viewing images directly. This -will not require special software, although a powerful computer with good -graphics will be needed. - -The Joint Study in Digital Preservation has generated a great deal of -interest in the library community. Unfortunately, or perhaps -fortunately, this project serves to raise a vast number of other issues -surrounding the use of digital technology for the preservation and use of -deteriorating library materials, which subsequent projects will need to -examine. Much work remains. - -SESSION III - -Howard BESSER Networking Multimedia Databases - -What do we have to consider in building and distributing databases of -visual materials in a multi-user environment? This presentation examines -a variety of concerns that need to be addressed before a multimedia -database can be set up in a networked environment. - -In the past it has not been feasible to implement databases of visual -materials in shared-user environments because of technological barriers. -Each of the two basic models for multi-user multimedia databases has -posed its own problem. The analog multimedia storage model (represented -by Project Athena's parallel analog and digital networks) has required an -incredibly complex (and expensive) infrastructure. The economies of -scale that make multi-user setups cheaper per user served do not operate -in an environment that requires a computer workstation, videodisc player, -and two display devices for each user. - -The digital multimedia storage model has required vast amounts of storage -space (as much as one gigabyte per thirty still images). In the past the -cost of such a large amount of storage space made this model a -prohibitive choice as well. But plunging storage costs are finally -making this second alternative viable. - -If storage no longer poses such an impediment, what do we need to -consider in building digitally stored multi-user databases of visual -materials? This presentation will examine the networking and -telecommunication constraints that must be overcome before such databases -can become commonplace and useful to a large number of people. - -The key problem is the vast size of multimedia documents, and how this -affects not only storage but telecommunications transmission time. -Anything slower than T-1 speed is impractical for files of 1 megabyte or -larger (which is likely to be small for a multimedia document). For -instance, even on a 56 Kb line it would take three minutes to transfer a -1-megabyte file. And these figures assume ideal circumstances, and do -not take into consideration other users contending for network bandwidth, -disk access time, or the time needed for remote display. Current common -telephone transmission rates would be completely impractical; few users -would be willing to wait the hour necessary to transmit a single image at -2400 baud. - -This necessitates compression, which itself raises a number of other -issues. In order to decrease file sizes significantly, we must employ -lossy compression algorithms. But how much quality can we afford to -lose? To date there has been only one significant study done of -image-quality needs for a particular user group, and this study did not -look at loss resulting from compression. Only after identifying -image-quality needs can we begin to address storage and network bandwidth -needs. - -Experience with X-Windows-based applications (such as Imagequery, the -University of California at Berkeley image database) demonstrates the -utility of a client-server topology, but also points to the limitation of -current software for a distributed environment. For example, -applications like Imagequery can incorporate compression, but current X -implementations do not permit decompression at the end user's -workstation. Such decompression at the host computer alleviates storage -capacity problems while doing nothing to address problems of -telecommunications bandwidth. - -We need to examine the effects on network through-put of moving -multimedia documents around on a network. We need to examine various -topologies that will help us avoid bottlenecks around servers and -gateways. Experience with applications such as these raise still broader -questions. How closely is the multimedia document tied to the software -for viewing it? Can it be accessed and viewed from other applications? -Experience with the MARC format (and more recently with the Z39.50 -protocols) shows how useful it can be to store documents in a form in -which they can be accessed by a variety of application software. - -Finally, from an intellectual-access standpoint, we need to address the -issue of providing access to these multimedia documents in -interdisciplinary environments. We need to examine terminology and -indexing strategies that will allow us to provide access to this material -in a cross-disciplinary way. - -Ronald LARSEN Directions in High-Performance Networking for - Libraries - -The pace at which computing technology has advanced over the past forty -years shows no sign of abating. Roughly speaking, each five-year period -has yielded an order-of-magnitude improvement in price and performance of -computing equipment. No fundamental hurdles are likely to prevent this -pace from continuing for at least the next decade. It is only in the -past five years, though, that computing has become ubiquitous in -libraries, affecting all staff and patrons, directly or indirectly. - -During these same five years, communications rates on the Internet, the -principal academic computing network, have grown from 56 kbps to 1.5 -Mbps, and the NSFNet backbone is now running 45 Mbps. Over the next five -years, communication rates on the backbone are expected to exceed 1 Gbps. -Growth in both the population of network users and the volume of network -traffic has continued to grow geometrically, at rates approaching 15 -percent per month. This flood of capacity and use, likened by some to -"drinking from a firehose," creates immense opportunities and challenges -for libraries. Libraries must anticipate the future implications of this -technology, participate in its development, and deploy it to ensure -access to the world's information resources. - -The infrastructure for the information age is being put in place. -Libraries face strategic decisions about their role in the development, -deployment, and use of this infrastructure. The emerging infrastructure -is much more than computers and communication lines. It is more than the -ability to compute at a remote site, send electronic mail to a peer -across the country, or move a file from one library to another. The next -five years will witness substantial development of the information -infrastructure of the network. - -In order to provide appropriate leadership, library professionals must -have a fundamental understanding of and appreciation for computer -networking, from local area networks to the National Research and -Education Network (NREN). This presentation addresses these -fundamentals, and how they relate to libraries today and in the near -future. - -Edwin BROWNRIGG Electronic Library Visions and Realities - -The electronic library has been a vision desired by many--and rejected by -some--since Vannevar Bush coined the term memex to describe an automated, -intelligent, personal information system. Variations on this vision have -included Ted Nelson's Xanadau, Alan Kay's Dynabook, and Lancaster's -"paperless library," with the most recent incarnation being the -"Knowledge Navigator" described by John Scully of Apple. But the reality -of library service has been less visionary and the leap to the electronic -library has eluded universities, publishers, and information technology -files. - -The Memex Research Institute (MemRI), an independent, nonprofit research -and development organization, has created an Electronic Library Program -of shared research and development in order to make the collective vision -more concrete. The program is working toward the creation of large, -indexed publicly available electronic image collections of published -documents in academic, special, and public libraries. This strategic -plan is the result of the first stage of the program, which has been an -investigation of the information technologies available to support such -an effort, the economic parameters of electronic service compared to -traditional library operations, and the business and political factors -affecting the shift from print distribution to electronic networked -access. - -The strategic plan envisions a combination of publicly searchable access -databases, image (and text) document collections stored on network "file -servers," local and remote network access, and an intellectual property -management-control system. This combination of technology and -information content is defined in this plan as an E-library or E-library -collection. Some participating sponsors are already developing projects -based on MemRI's recommended directions. - -The E-library strategy projected in this plan is a visionary one that can -enable major changes and improvements in academic, public, and special -library service. This vision is, though, one that can be realized with -today's technology. At the same time, it will challenge the political -and social structure within which libraries operate: in academic -libraries, the traditional emphasis on local collections, extending to -accreditation issues; in public libraries, the potential of electronic -branch and central libraries fully available to the public; and for -special libraries, new opportunities for shared collections and networks. - -The environment in which this strategic plan has been developed is, at -the moment, dominated by a sense of library limits. The continued -expansion and rapid growth of local academic library collections is now -clearly at an end. Corporate libraries, and even law libraries, are -faced with operating within a difficult economic climate, as well as with -very active competition from commercial information sources. For -example, public libraries may be seen as a desirable but not critical -municipal service in a time when the budgets of safety and health -agencies are being cut back. - -Further, libraries in general have a very high labor-to-cost ratio in -their budgets, and labor costs are still increasing, notwithstanding -automation investments. It is difficult for libraries to obtain capital, -startup, or seed funding for innovative activities, and those -technology-intensive initiatives that offer the potential of decreased -labor costs can provoke the opposition of library staff. - -However, libraries have achieved some considerable successes in the past -two decades by improving both their service and their credibility within -their organizations--and these positive changes have been accomplished -mostly with judicious use of information technologies. The advances in -computing and information technology have been well-chronicled: the -continuing precipitous drop in computing costs, the growth of the -Internet and private networks, and the explosive increase in publicly -available information databases. - -For example, OCLC has become one of the largest computer network -organizations in the world by creating a cooperative cataloging network -of more than 6,000 libraries worldwide. On-line public access catalogs -now serve millions of users on more than 50,000 dedicated terminals in -the United States alone. The University of California MELVYL on-line -catalog system has now expanded into an index database reference service -and supports more than six million searches a year. And, libraries have -become the largest group of customers of CD-ROM publishing technology; -more than 30,000 optical media publications such as those offered by -InfoTrac and Silver Platter are subscribed to by U.S. libraries. - -This march of technology continues and in the next decade will result in -further innovations that are extremely difficult to predict. What is -clear is that libraries can now go beyond automation of their order files -and catalogs to automation of their collections themselves--and it is -possible to circumvent the fiscal limitations that appear to obtain -today. - -This Electronic Library Strategic Plan recommends a paradigm shift in -library service, and demonstrates the steps necessary to provide improved -library services with limited capacities and operating investments. - -SESSION IV-A - -Anne KENNEY - -The Cornell/Xerox Joint Study in Digital Preservation resulted in the -recording of 1,000 brittle books as 600-dpi digital images and the -production, on demand, of high-quality and archivally sound paper -replacements. The project, which was supported by the Commission on -Preservation and Access, also investigated some of the issues surrounding -scanning, storing, retrieving, and providing access to digital images in -a network environment. - -Anne Kenney will focus on some of the issues surrounding direct scanning -as identified in the Cornell Xerox Project. Among those to be discussed -are: image versus text capture; indexing and access; image-capture -capabilities; a comparison to photocopy and microfilm; production and -cost analysis; storage formats, protocols, and standards; and the use of -this scanning technology for preservation purposes. - -The 600-dpi digital images produced in the Cornell Xerox Project proved -highly acceptable for creating paper replacements of deteriorating -originals. The 1,000 scanned volumes provided an array of image-capture -challenges that are common to nineteenth-century printing techniques and -embrittled material, and that defy the use of text-conversion processes. -These challenges include diminished contrast between text and background, -fragile and deteriorated pages, uneven printing, elaborate type faces, -faint and bold text adjacency, handwritten text and annotations, nonRoman -languages, and a proliferation of illustrated material embedded in text. -The latter category included high-frequency and low-frequency halftones, -continuous tone photographs, intricate mathematical drawings, maps, -etchings, reverse-polarity drawings, and engravings. - -The Xerox prototype scanning system provided a number of important -features for capturing this diverse material. Technicians used multiple -threshold settings, filters, line art and halftone definitions, -autosegmentation, windowing, and software-editing programs to optimize -image capture. At the same time, this project focused on production. -The goal was to make scanning as affordable and acceptable as -photocopying and microfilming for preservation reformatting. A -time-and-cost study conducted during the last three months of this -project confirmed the economic viability of digital scanning, and these -findings will be discussed here. - -From the outset, the Cornell Xerox Project was predicated on the use of -nonproprietary standards and the use of common protocols when standards -did not exist. Digital files were created as TIFF images which were -compressed prior to storage using Group 4 CCITT compression. The Xerox -software is MS DOS based and utilizes off-the shelf programs such as -Microsoft Windows and Wang Image Wizard. The digital library is designed -to be hardware-independent and to provide interchangeability with other -institutions through network connections. Access to the digital files -themselves is two-tiered: Bibliographic records for the computer files -are created in RLIN and Cornell's local system and access into the actual -digital images comprising a book is provided through a document control -structure and a networked image file-server, both of which will be -described. - -The presentation will conclude with a discussion of some of the issues -surrounding the use of this technology as a preservation tool (storage, -refreshing, backup). - -Pamela ANDRE and Judith ZIDAR - -The National Agricultural Library (NAL) has had extensive experience with -raster scanning of printed materials. Since 1987, the Library has -participated in the National Agricultural Text Digitizing Project (NATDP) -a cooperative effort between NAL and forty-five land grant university -libraries. An overview of the project will be presented, giving its -history and NAL's strategy for the future. - -An in-depth discussion of NATDP will follow, including a description of -the scanning process, from the gathering of the printed materials to the -archiving of the electronic pages. The type of equipment required for a -stand-alone scanning workstation and the importance of file management -software will be discussed. Issues concerning the images themselves will -be addressed briefly, such as image format; black and white versus color; -gray scale versus dithering; and resolution. - -Also described will be a study currently in progress by NAL to evaluate -the usefulness of converting microfilm to electronic images in order to -improve access. With the cooperation of Tuskegee University, NAL has -selected three reels of microfilm from a collection of sixty-seven reels -containing the papers, letters, and drawings of George Washington Carver. -The three reels were converted into 3,500 electronic images using a -specialized microfilm scanner. The selection, filming, and indexing of -this material will be discussed. - -Donald WATERS - -Project Open Book, the Yale University Library's effort to convert 10, -000 books from microfilm to digital imagery, is currently in an advanced -state of planning and organization. The Yale Library has selected a -major vendor to serve as a partner in the project and as systems -integrator. In its proposal, the successful vendor helped isolate areas -of risk and uncertainty as well as key issues to be addressed during the -life of the project. The Yale Library is now poised to decide what -material it will convert to digital image form and to seek funding, -initially for the first phase and then for the entire project. - -The proposal that Yale accepted for the implementation of Project Open -Book will provide at the end of three phases a conversion subsystem, -browsing stations distributed on the campus network within the Yale -Library, a subsystem for storing 10,000 books at 200 and 600 dots per -inch, and network access to the image printers. Pricing for the system -implementation assumes the existence of Yale's campus ethernet network -and its high-speed image printers, and includes other requisite hardware -and software, as well as system integration services. Proposed operating -costs include hardware and software maintenance, but do not include -estimates for the facilities management of the storage devices and image -servers. - -Yale selected its vendor partner in a formal process, partly funded by -the Commission for Preservation and Access. Following a request for -proposal, the Yale Library selected two vendors as finalists to work with -Yale staff to generate a detailed analysis of requirements for Project -Open Book. Each vendor used the results of the requirements analysis to -generate and submit a formal proposal for the entire project. This -competitive process not only enabled the Yale Library to select its -primary vendor partner but also revealed much about the state of the -imaging industry, about the varying, corporate commitments to the markets -for imaging technology, and about the varying organizational dynamics -through which major companies are responding to and seeking to develop -these markets. - -Project Open Book is focused specifically on the conversion of images -from microfilm to digital form. The technology for scanning microfilm is -readily available but is changing rapidly. In its project requirements, -the Yale Library emphasized features of the technology that affect the -technical quality of digital image production and the costs of creating -and storing the image library: What levels of digital resolution can be -achieved by scanning microfilm? How does variation in the quality of -microfilm, particularly in film produced to preservation standards, -affect the quality of the digital images? What technologies can an -operator effectively and economically apply when scanning film to -separate two-up images and to control for and correct image -imperfections? How can quality control best be integrated into -digitizing work flow that includes document indexing and storage? - -The actual and expected uses of digital images--storage, browsing, -printing, and OCR--help determine the standards for measuring their -quality. Browsing is especially important, but the facilities available -for readers to browse image documents is perhaps the weakest aspect of -imaging technology and most in need of development. As it defined its -requirements, the Yale Library concentrated on some fundamental aspects -of usability for image documents: Does the system have sufficient -flexibility to handle the full range of document types, including -monographs, multi-part and multivolume sets, and serials, as well as -manuscript collections? What conventions are necessary to identify a -document uniquely for storage and retrieval? Where is the database of -record for storing bibliographic information about the image document? -How are basic internal structures of documents, such as pagination, made -accessible to the reader? How are the image documents physically -presented on the screen to the reader? - -The Yale Library designed Project Open Book on the assumption that -microfilm is more than adequate as a medium for preserving the content of -deteriorated library materials. As planning in the project has advanced, -it is increasingly clear that the challenge of digital image technology -and the key to the success of efforts like Project Open Book is to -provide a means of both preserving and improving access to those -deteriorated materials. - -SESSION IV-B - -George THOMA - -In the use of electronic imaging for document preservation, there are -several issues to consider, such as: ensuring adequate image quality, -maintaining substantial conversion rates (through-put), providing unique -identification for automated access and retrieval, and accommodating -bound volumes and fragile material. - -To maintain high image quality, image processing functions are required -to correct the deficiencies in the scanned image. Some commercially -available systems include these functions, while some do not. The -scanned raw image must be processed to correct contrast deficiencies-- -both poor overall contrast resulting from light print and/or dark -background, and variable contrast resulting from stains and -bleed-through. Furthermore, the scan density must be adequate to allow -legibility of print and sufficient fidelity in the pseudo-halftoned gray -material. Borders or page-edge effects must be removed for both -compactibility and aesthetics. Page skew must be corrected for aesthetic -reasons and to enable accurate character recognition if desired. -Compound images consisting of both two-toned text and gray-scale -illustrations must be processed appropriately to retain the quality of -each. - -SESSION IV-C - -Jean BARONAS - -Standards publications being developed by scientists, engineers, and -business managers in Association for Information and Image Management -(AIIM) standards committees can be applied to electronic image management -(EIM) processes including: document (image) transfer, retrieval and -evaluation; optical disk and document scanning; and document design and -conversion. When combined with EIM system planning and operations, -standards can assist in generating image databases that are -interchangeable among a variety of systems. The applications of -different approaches for image-tagging, indexing, compression, and -transfer often cause uncertainty concerning EIM system compatibility, -calibration, performance, and upward compatibility, until standard -implementation parameters are established. The AIIM standards that are -being developed for these applications can be used to decrease the -uncertainty, successfully integrate imaging processes, and promote "open -systems." AIIM is an accredited American National Standards Institute -(ANSI) standards developer with more than twenty committees comprised of -300 volunteers representing users, vendors, and manufacturers. The -standards publications that are developed in these committees have -national acceptance and provide the basis for international harmonization -in the development of new International Organization for Standardization -(ISO) standards. - -This presentation describes the development of AIIM's EIM standards and a -new effort at AIIM, a database on standards projects in a wide framework -of imaging industries including capture, recording, processing, -duplication, distribution, display, evaluation, and preservation. The -AIIM Imagery Database will cover imaging standards being developed by -many organizations in many different countries. It will contain -standards publications' dates, origins, related national and -international projects, status, key words, and abstracts. The ANSI Image -Technology Standards Board requested that such a database be established, -as did the ISO/International Electrotechnical Commission Joint Task Force -on Imagery. AIIM will take on the leadership role for the database and -coordinate its development with several standards developers. - -Patricia BATTIN - - Characteristics of standards for digital imagery: - - * Nature of digital technology implies continuing volatility. - - * Precipitous standard-setting not possible and probably not - desirable. - - * Standards are a complex issue involving the medium, the - hardware, the software, and the technical capacity for - reproductive fidelity and clarity. - - * The prognosis for reliable archival standards (as defined by - librarians) in the foreseeable future is poor. - - Significant potential and attractiveness of digital technology as a - preservation medium and access mechanism. - - Productive use of digital imagery for preservation requires a - reconceptualizing of preservation principles in a volatile, - standardless world. - - Concept of managing continuing access in the digital environment - rather than focusing on the permanence of the medium and long-term - archival standards developed for the analog world. - - Transition period: How long and what to do? - - * Redefine "archival." - - * Remove the burden of "archival copy" from paper artifacts. - - * Use digital technology for storage, develop management - strategies for refreshing medium, hardware and software. - - * Create acid-free paper copies for transition period backup - until we develop reliable procedures for ensuring continuing - access to digital files. - -SESSION IV-D - -Stuart WEIBEL The Role of SGML Markup in the CORE Project (6) - -The emergence of high-speed telecommunications networks as a basic -feature of the scholarly workplace is driving the demand for electronic -document delivery. Three distinct categories of electronic -publishing/republishing are necessary to support access demands in this -emerging environment: - - 1.) Conversion of paper or microfilm archives to electronic format - 2.) Conversion of electronic files to formats tailored to - electronic retrieval and display - 3.) Primary electronic publishing (materials for which the - electronic version is the primary format) - -OCLC has experimental or product development activities in each of these -areas. Among the challenges that lie ahead is the integration of these -three types of information stores in coherent distributed systems. - -The CORE (Chemistry Online Retrieval Experiment) Project is a model for -the conversion of large text and graphics collections for which -electronic typesetting files are available (category 2). The American -Chemical Society has made available computer typography files dating from -1980 for its twenty journals. This collection of some 250 journal-years -is being converted to an electronic format that will be accessible -through several end-user applications. - -The use of Standard Generalized Markup Language (SGML) offers the means -to capture the structural richness of the original articles in a way that -will support a variety of retrieval, navigation, and display options -necessary to navigate effectively in very large text databases. - -An SGML document consists of text that is marked up with descriptive tags -that specify the function of a given element within the document. As a -formal language construct, an SGML document can be parsed against a -document-type definition (DTD) that unambiguously defines what elements -are allowed and where in the document they can (or must) occur. This -formalized map of article structure allows the user interface design to -be uncoupled from the underlying database system, an important step -toward interoperability. Demonstration of this separability is a part of -the CORE project, wherein user interface designs born of very different -philosophies will access the same database. - -NOTES: - (6) The CORE project is a collaboration among Cornell University's - Mann Library, Bell Communications Research (Bellcore), the American - Chemical Society (ACS), the Chemical Abstracts Service (CAS), and - OCLC. - -Michael LESK The CORE Electronic Chemistry Library - -A major on-line file of chemical journal literature complete with -graphics is being developed to test the usability of fully electronic -access to documents, as a joint project of Cornell University, the -American Chemical Society, the Chemical Abstracts Service, OCLC, and -Bellcore (with additional support from Sun Microsystems, Springer-Verlag, -DigitaI Equipment Corporation, Sony Corporation of America, and Apple -Computers). Our file contains the American Chemical Society's on-line -journals, supplemented with the graphics from the paper publication. The -indexing of the articles from Chemical Abstracts Documents is available -in both image and text format, and several different interfaces can be -used. Our goals are (1) to assess the effectiveness and acceptability of -electronic access to primary journals as compared with paper, and (2) to -identify the most desirable functions of the user interface to an -electronic system of journals, including in particular a comparison of -page-image display with ASCII display interfaces. Early experiments with -chemistry students on a variety of tasks suggest that searching tasks are -completed much faster with any electronic system than with paper, but -that for reading all versions of the articles are roughly equivalent. - -Pamela ANDRE and Judith ZIDAR - -Text conversion is far more expensive and time-consuming than image -capture alone. NAL's experience with optical character recognition (OCR) -will be related and compared with the experience of having text rekeyed. -What factors affect OCR accuracy? How accurate does full text have to be -in order to be useful? How do different users react to imperfect text? -These are questions that will be explored. For many, a service bureau -may be a better solution than performing the work inhouse; this will also -be discussed. - -SESSION VI - -Marybeth PETERS - -Copyright law protects creative works. Protection granted by the law to -authors and disseminators of works includes the right to do or authorize -the following: reproduce the work, prepare derivative works, distribute -the work to the public, and publicly perform or display the work. In -addition, copyright owners of sound recordings and computer programs have -the right to control rental of their works. These rights are not -unlimited; there are a number of exceptions and limitations. - -An electronic environment places strains on the copyright system. -Copyright owners want to control uses of their work and be paid for any -use; the public wants quick and easy access at little or no cost. The -marketplace is working in this area. Contracts, guidelines on electronic -use, and collective licensing are in use and being refined. - -Issues concerning the ability to change works without detection are more -difficult to deal with. Questions concerning the integrity of the work -and the status of the changed version under the copyright law are to be -addressed. These are public policy issues which require informed -dialogue. - - - *** *** *** ****** *** *** *** - - - Appendix III: DIRECTORY OF PARTICIPANTS - - -PRESENTERS: - - Pamela Q.J. Andre - Associate Director, Automation - National Agricultural Library - 10301 Baltimore Boulevard - Beltsville, MD 20705-2351 - Phone: (301) 504-6813 - Fax: (301) 504-7473 - E-mail: INTERNET: PANDRE@ASRR.ARSUSDA.GOV - - Jean Baronas, Senior Manager - Department of Standards and Technology - Association for Information and Image Management (AIIM) - 1100 Wayne Avenue, Suite 1100 - Silver Spring, MD 20910 - Phone: (301) 587-8202 - Fax: (301) 587-2711 - - Patricia Battin, President - The Commission on Preservation and Access - 1400 16th Street, N.W. - Suite 740 - Washington, DC 20036-2217 - Phone: (202) 939-3400 - Fax: (202) 939-3407 - E-mail: CPA@GWUVM.BITNET - - Howard Besser - Centre Canadien d'Architecture - (Canadian Center for Architecture) - 1920, rue Baile - Montreal, Quebec H3H 2S6 - CANADA - Phone: (514) 939-7001 - Fax: (514) 939-7020 - E-mail: howard@lis.pitt.edu - - Edwin B. Brownrigg, Executive Director - Memex Research Institute - 422 Bonita Avenue - Roseville, CA 95678 - Phone: (916) 784-2298 - Fax: (916) 786-7559 - E-mail: BITNET: MEMEX@CALSTATE.2 - - Eric M. Calaluca, Vice President - Chadwyck-Healey, Inc. - 1101 King Street - Alexandria, VA 223l4 - Phone: (800) 752-05l5 - Fax: (703) 683-7589 - - James Daly - 4015 Deepwood Road - Baltimore, MD 21218-1404 - Phone: (410) 235-0763 - - Ricky Erway, Associate Coordinator - American Memory - Library of Congress - Phone: (202) 707-6233 - Fax: (202) 707-3764 - - Carl Fleischhauer, Coordinator - American Memory - Library of Congress - Phone: (202) 707-6233 - Fax: (202) 707-3764 - - Joanne Freeman - 2000 Jefferson Park Avenue, No. 7 - Charlottesville, VA 22903 - - Prosser Gifford - Director for Scholarly Programs - Library of Congress - Phone: (202) 707-1517 - Fax: (202) 707-9898 - E-mail: pgif@seq1.loc.gov - - Jacqueline Hess, Director - National Demonstration Laboratory - for Interactive Information Technologies - Library of Congress - Phone: (202) 707-4157 - Fax: (202) 707-2829 - - Susan Hockey, Director - Center for Electronic Texts in the Humanities (CETH) - Alexander Library - Rutgers University - 169 College Avenue - New Brunswick, NJ 08903 - Phone: (908) 932-1384 - Fax: (908) 932-1386 - E-mail: hockey@zodiac.rutgers.edu - - William L. Hooton, Vice President - Business & Technical Development - Imaging & Information Systems Group - I-NET - 6430 Rockledge Drive, Suite 400 - Bethesda, MD 208l7 - Phone: (301) 564-6750 - Fax: (513) 564-6867 - - Anne R. Kenney, Associate Director - Department of Preservation and Conservation - 701 Olin Library - Cornell University - Ithaca, NY 14853 - Phone: (607) 255-6875 - Fax: (607) 255-9346 - E-mail: LYDY@CORNELLA.BITNET - - Ronald L. Larsen - Associate Director for Information Technology - University of Maryland at College Park - Room B0224, McKeldin Library - College Park, MD 20742-7011 - Phone: (301) 405-9194 - Fax: (301) 314-9865 - E-mail: rlarsen@libr.umd.edu - - Maria L. Lebron, Managing Editor - The Online Journal of Current Clinical Trials - l333 H Street, N.W. - Washington, DC 20005 - Phone: (202) 326-6735 - Fax: (202) 842-2868 - E-mail: PUBSAAAS@GWUVM.BITNET - - Michael Lesk, Executive Director - Computer Science Research - Bell Communications Research, Inc. - Rm 2A-385 - 445 South Street - Morristown, NJ 07960-l9l0 - Phone: (201) 829-4070 - Fax: (201) 829-5981 - E-mail: lesk@bellcore.com (Internet) or bellcore!lesk (uucp) - - Clifford A. Lynch - Director, Library Automation - University of California, - Office of the President - 300 Lakeside Drive, 8th Floor - Oakland, CA 94612-3350 - Phone: (510) 987-0522 - Fax: (510) 839-3573 - E-mail: calur@uccmvsa - - Avra Michelson - National Archives and Records Administration - NSZ Rm. 14N - 7th & Pennsylvania, N.W. - Washington, D.C. 20408 - Phone: (202) 501-5544 - Fax: (202) 501-5533 - E-mail: tmi@cu.nih.gov - - Elli Mylonas, Managing Editor - Perseus Project - Department of the Classics - Harvard University - 319 Boylston Hall - Cambridge, MA 02138 - Phone: (617) 495-9025, (617) 495-0456 (direct) - Fax: (617) 496-8886 - E-mail: Elli@IKAROS.Harvard.EDU or elli@wjh12.harvard.edu - - David Woodley Packard - Packard Humanities Institute - 300 Second Street, Suite 201 - Los Altos, CA 94002 - Phone: (415) 948-0150 (PHI) - Fax: (415) 948-5793 - - Lynne K. Personius, Assistant Director - Cornell Information Technologies for - Scholarly Information Sources - 502 Olin Library - Cornell University - Ithaca, NY 14853 - Phone: (607) 255-3393 - Fax: (607) 255-9346 - E-mail: JRN@CORNELLC.BITNET - - Marybeth Peters - Policy Planning Adviser to the - Register of Copyrights - Library of Congress - Office LM 403 - Phone: (202) 707-8350 - Fax: (202) 707-8366 - - C. Michael Sperberg-McQueen - Editor, Text Encoding Initiative - Computer Center (M/C 135) - University of Illinois at Chicago - Box 6998 - Chicago, IL 60680 - Phone: (312) 413-0317 - Fax: (312) 996-6834 - E-mail: u35395@uicvm..cc.uic.edu or u35395@uicvm.bitnet - - George R. Thoma, Chief - Communications Engineering Branch - National Library of Medicine - 8600 Rockville Pike - Bethesda, MD 20894 - Phone: (301) 496-4496 - Fax: (301) 402-0341 - E-mail: thoma@lhc.nlm.nih.gov - - Dorothy Twohig, Editor - The Papers of George Washington - 504 Alderman Library - University of Virginia - Charlottesville, VA 22903-2498 - Phone: (804) 924-0523 - Fax: (804) 924-4337 - - Susan H. Veccia, Team leader - American Memory, User Evaluation - Library of Congress - American Memory Evaluation Project - Phone: (202) 707-9104 - Fax: (202) 707-3764 - E-mail: svec@seq1.loc.gov - - Donald J. Waters, Head - Systems Office - Yale University Library - New Haven, CT 06520 - Phone: (203) 432-4889 - Fax: (203) 432-7231 - E-mail: DWATERS@YALEVM.BITNET or DWATERS@YALEVM.YCC.YALE.EDU - - Stuart Weibel, Senior Research Scientist - OCLC - 6565 Frantz Road - Dublin, OH 43017 - Phone: (614) 764-608l - Fax: (614) 764-2344 - E-mail: INTERNET: Stu@rsch.oclc.org - - Robert G. Zich - Special Assistant to the Associate Librarian - for Special Projects - Library of Congress - Phone: (202) 707-6233 - Fax: (202) 707-3764 - E-mail: rzic@seq1.loc.gov - - Judith A. Zidar, Coordinator - National Agricultural Text Digitizing Program - Information Systems Division - National Agricultural Library - 10301 Baltimore Boulevard - Beltsville, MD 20705-2351 - Phone: (301) 504-6813 or 504-5853 - Fax: (301) 504-7473 - E-mail: INTERNET: JZIDAR@ASRR.ARSUSDA.GOV - - -OBSERVERS: - - Helen Aguera, Program Officer - Division of Research - Room 318 - National Endowment for the Humanities - 1100 Pennsylvania Avenue, N.W. - Washington, D.C. 20506 - Phone: (202) 786-0358 - Fax: (202) 786-0243 - - M. Ellyn Blanton, Deputy Director - National Demonstration Laboratory - for Interactive Information Technologies - Library of Congress - Phone: (202) 707-4157 - Fax: (202) 707-2829 - - Charles M. Dollar - National Archives and Records Administration - NSZ Rm. 14N - 7th & Pennsylvania, N.W. - Washington, DC 20408 - Phone: (202) 501-5532 - Fax: (202) 501-5512 - - Jeffrey Field, Deputy to the Director - Division of Preservation and Access - Room 802 - National Endowment for the Humanities - 1100 Pennsylvania Avenue, N.W. - Washington, DC 20506 - Phone: (202) 786-0570 - Fax: (202) 786-0243 - - Lorrin Garson - American Chemical Society - Research and Development Department - 1155 16th Street, N.W. - Washington, D.C. 20036 - Phone: (202) 872-4541 - Fax: E-mail: INTERNET: LRG96@ACS.ORG - - William M. Holmes, Jr. - National Archives and Records Administration - NSZ Rm. 14N - 7th & Pennsylvania, N.W. - Washington, DC 20408 - Phone: (202) 501-5540 - Fax: (202) 501-5512 - E-mail: WHOLMES@AMERICAN.EDU - - Sperling Martin - Information Resource Management - 20030 Doolittle Street - Gaithersburg, MD 20879 - Phone: (301) 924-1803 - - Michael Neuman, Director - The Center for Text and Technology - Academic Computing Center - 238 Reiss Science Building - Georgetown University - Washington, DC 20057 - Phone: (202) 687-6096 - Fax: (202) 687-6003 - E-mail: neuman@guvax.bitnet, neuman@guvax.georgetown.edu - - Barbara Paulson, Program Officer - Division of Preservation and Access - Room 802 - National Endowment for the Humanities - 1100 Pennsylvania Avenue, N.W. - Washington, DC 20506 - Phone: (202) 786-0577 - Fax: (202) 786-0243 - - Allen H. Renear - Senior Academic Planning Analyst - Brown University Computing and Information Services - 115 Waterman Street - Campus Box 1885 - Providence, R.I. 02912 - Phone: (401) 863-7312 - Fax: (401) 863-7329 - E-mail: BITNET: Allen@BROWNVM or - INTERNET: Allen@brownvm.brown.edu - - Susan M. Severtson, President - Chadwyck-Healey, Inc. - 1101 King Street - Alexandria, VA 223l4 - Phone: (800) 752-05l5 - Fax: (703) 683-7589 - - Frank Withrow - U.S. Department of Education - 555 New Jersey Avenue, N.W. - Washington, DC 20208-5644 - Phone: (202) 219-2200 - Fax: (202) 219-2106 - - -(LC STAFF) - - Linda L. Arret - Machine-Readable Collections Reading Room LJ 132 - (202) 707-1490 - - John D. Byrum, Jr. - Descriptive Cataloging Division LM 540 - (202) 707-5194 - - Mary Jane Cavallo - Science and Technology Division LA 5210 - (202) 707-1219 - - Susan Thea David - Congressional Research Service LM 226 - (202) 707-7169 - - Robert Dierker - Senior Adviser for Multimedia Activities LM 608 - (202) 707-6151 - - William W. Ellis - Associate Librarian for Science and Technology LM 611 - (202) 707-6928 - - Ronald Gephart - Manuscript Division LM 102 - (202) 707-5097 - - James Graber - Information Technology Services LM G51 - (202) 707-9628 - - Rich Greenfield - American Memory LM 603 - (202) 707-6233 - - Rebecca Guenther - Network Development LM 639 - (202) 707-5092 - - Kenneth E. Harris - Preservation LM G21 - (202) 707-5213 - - Staley Hitchcock - Manuscript Division LM 102 - (202) 707-5383 - - Bohdan Kantor - Office of Special Projects LM 612 - (202) 707-0180 - - John W. Kimball, Jr - Machine-Readable Collections Reading Room LJ 132 - (202) 707-6560 - - Basil Manns - Information Technology Services LM G51 - (202) 707-8345 - - Sally Hart McCallum - Network Development LM 639 - (202) 707-6237 - - Dana J. Pratt - Publishing Office LM 602 - (202) 707-6027 - - Jane Riefenhauser - American Memory LM 603 - (202) 707-6233 - - William Z. Schenck - Collections Development LM 650 - (202) 707-7706 - - Chandru J. Shahani - Preservation Research and Testing Office (R&T) LM G38 - (202) 707-5607 - - William J. Sittig - Collections Development LM 650 - (202) 707-7050 - - Paul Smith - Manuscript Division LM 102 - (202) 707-5097 - - James L. Stevens - Information Technology Services LM G51 - (202) 707-9688 - - Karen Stuart - Manuscript Division LM 130 - (202) 707-5389 - - Tamara Swora - Preservation Microfilming Office LM G05 - (202) 707-6293 - - Sarah Thomas - Collections Cataloging LM 642 - (202) 707-5333 - - - END - ************************************************************* - -Note: This file has been edited for use on computer networks. This -editing required the removal of diacritics, underlining, and fonts such -as italics and bold. - -kde 11/92 - -[A few of the italics (when used for emphasis) were replaced by CAPS mh] - -*End of The Project Gutenberg Etext of LOC WORKSHOP ON ELECTRONIC ETEXTS - diff --git a/src/snappy/snappy/testdata/paper-100k.pdf b/src/snappy/snappy/testdata/paper-100k.pdf deleted file mode 100644 index b3325e4a2b..0000000000 --- a/src/snappy/snappy/testdata/paper-100k.pdf +++ /dev/null @@ -1,598 +0,0 @@ - - - C=10 M=100 Y=50 K=0 - CMYK - PROCESS - 10.000002 - 100.000000 - 50.000000 - 0.000000 - - - C=0 M=95 Y=20 K=0 - CMYK - PROCESS - 0.000000 - 94.999999 - 19.999999 - 0.000000 - - - C=25 M=25 Y=40 K=0 - CMYK - PROCESS - 25.000000 - 25.000000 - 39.999998 - 0.000000 - - - C=40 M=45 Y=50 K=5 - CMYK - PROCESS - 39.999998 - 44.999999 - 50.000000 - 5.000001 - - - C=50 M=50 Y=60 K=25 - CMYK - PROCESS - 50.000000 - 50.000000 - 60.000002 - 25.000000 - - - C=55 M=60 Y=65 K=40 - CMYK - PROCESS - 55.000001 - 60.000002 - 64.999998 - 39.999998 - - - C=25 M=40 Y=65 K=0 - CMYK - PROCESS - 25.000000 - 39.999998 - 64.999998 - 0.000000 - - - C=30 M=50 Y=75 K=10 - CMYK - PROCESS - 30.000001 - 50.000000 - 75.000000 - 10.000002 - - - C=35 M=60 Y=80 K=25 - CMYK - PROCESS - 35.000002 - 60.000002 - 80.000001 - 25.000000 - - - C=40 M=65 Y=90 K=35 - CMYK - PROCESS - 39.999998 - 64.999998 - 90.000004 - 35.000002 - - - C=40 M=70 Y=100 K=50 - CMYK - PROCESS - 39.999998 - 69.999999 - 100.000000 - 50.000000 - - - C=50 M=70 Y=80 K=70 - CMYK - PROCESS - 50.000000 - 69.999999 - 80.000001 - 69.999999 - - - - - - Grays - 1 - - - - C=0 M=0 Y=0 K=100 - CMYK - PROCESS - 0.000000 - 0.000000 - 0.000000 - 100.000000 - - - C=0 M=0 Y=0 K=90 - CMYK - PROCESS - 0.000000 - 0.000000 - 0.000000 - 89.999402 - - - C=0 M=0 Y=0 K=80 - CMYK - PROCESS - 0.000000 - 0.000000 - 0.000000 - 79.998797 - - - C=0 M=0 Y=0 K=70 - CMYK - PROCESS - 0.000000 - 0.000000 - 0.000000 - 69.999701 - - - C=0 M=0 Y=0 K=60 - CMYK - PROCESS - 0.000000 - 0.000000 - 0.000000 - 59.999102 - - - C=0 M=0 Y=0 K=50 - CMYK - PROCESS - 0.000000 - 0.000000 - 0.000000 - 50.000000 - - - C=0 M=0 Y=0 K=40 - CMYK - PROCESS - 0.000000 - 0.000000 - 0.000000 - 39.999402 - - - C=0 M=0 Y=0 K=30 - CMYK - PROCESS - 0.000000 - 0.000000 - 0.000000 - 29.998803 - - - C=0 M=0 Y=0 K=20 - CMYK - PROCESS - 0.000000 - 0.000000 - 0.000000 - 19.999701 - - - C=0 M=0 Y=0 K=10 - CMYK - PROCESS - 0.000000 - 0.000000 - 0.000000 - 9.999102 - - - C=0 M=0 Y=0 K=5 - CMYK - PROCESS - 0.000000 - 0.000000 - 0.000000 - 4.998803 - - - - - - Brights - 1 - - - - C=0 M=100 Y=100 K=0 - CMYK - PROCESS - 0.000000 - 100.000000 - 100.000000 - 0.000000 - - - C=0 M=75 Y=100 K=0 - CMYK - PROCESS - 0.000000 - 75.000000 - 100.000000 - 0.000000 - - - C=0 M=10 Y=95 K=0 - CMYK - PROCESS - 0.000000 - 10.000002 - 94.999999 - 0.000000 - - - C=85 M=10 Y=100 K=0 - CMYK - PROCESS - 84.999996 - 10.000002 - 100.000000 - 0.000000 - - - C=100 M=90 Y=0 K=0 - CMYK - PROCESS - 100.000000 - 90.000004 - 0.000000 - 0.000000 - - - C=60 M=90 Y=0 K=0 - CMYK - PROCESS - 60.000002 - 90.000004 - 0.003099 - 0.003099 - - - - - - - - - Adobe PDF library 9.00 - - - - - - - - - - - - - - - - - - - - - - - - - -endstream endobj 145 0 obj<> endobj 1 0 obj<> endobj 2 0 obj<>/Font<>/ProcSet[/PDF/Text]/ExtGState<>>> endobj 3 0 obj<>stream -hÞ”[MsÜF’½ëWðnmU(s™e{¥ÝñØkjw²`7ÈÆ¨hhÒœÝ_±‡ù½›ïe€&›rl(BÑÄG¡ª2óåËúæ_o’‹ûáÍ·ß|óƒ»H.>Þ½)V¥sæ"–þ§ËWq’\X¯âØ¥÷obÞïïåÇÇ5þ{|ó)ú¥^×íxyºl•D]ÿE~gÅ*vMû¥Þè_YôþÇAÚ¨jqÕÙèÝ·?ób¾*¢]ýPïøW¹rÑØñ‰UÝ×mž©?ôõ04]‹»±\¹}ºüüñßÞ\¯Ê²¼¸NVIîd=ßɼöuÕÊp6wòñîN~¹re¢ßŽU;6c565î–2éc³®v¸„uì» gƒ¿ŠèSšü3Í>_áïD04í½¬îçQwñ#*Îåã¿Èׇ}µ“ÁL%´ÇýmÝË_9f€¹˜ÜÊ0Ü“²^YצYÓN¾9nëpsìe)ë¾9Œ²òŠÃ&ò„|÷€O›"–Ý~lÆíüýms¿•=2yT­×ǾZ?­ø'Ñ=ÊV÷Wø;“ù¨`L)·T0¦XåA4&ÅåÝq'×»êIGJd½×©Å·ÍC7bb©1QßíêðtÓrJ1EãÊ\ES·Ã±çR!â"º«dîwÇ -?‰ÖÝþ°«G³ÞqÏ p§Û¢õÝ_ßâ§‘«}}؉øü+.ÅDûöAèþ¹˜É¤$&þ¼ -*÷vÐoˆ¼:UçTæ¿išÍ‘ksØô÷?ây'ÒÛVƒ^4Ñm]Oß½ëŽA½©Ä$x‹I;#Šúй4Õ.|ö®ëý®oîýŽQˆwÇv­KÊ,ăñ2kd‡6ÕX‹³,–‰4#.CÍ›¿ ²]ó¥Þ=é‹F6­õw¡â–QD1ü{~Û´Õ(µ}ÒËE´œK_ßw•*hZ@CtûEAËgÛ/Ê)rjöòìJÿ´Ñ‡vS×è\a¼ #ŸxhêGý­F𿨓õ¶ïöøØü}l¶cYŒh)ùª¨â(»·ÇTþæNšÒÉþ¨ñÈSb”²áû[,Ê”¥W%üÊ£MswW÷/S2²¨ÌXËGåO¨¥ªáï5Œ´Ìåþr>ë®ýû,ž„Ø ¼Îb`'%ÉóÍÅE,Bþ>ö|$•G0§,1%ñž@ÜèÏT/¿2Ž;ë‡,žBQC)e¸‡™]…MÎR™Ø¶±~˜Rmê[Qž¾ -P c§ ƒ] î©QÉkO‡NFšáJ_¶Øù•ɇ·Íz{θ‡C½nîš5”ÚÉ<Âòe’ƒÚH²˜¥‚Q`Su/JCSI£cÛüvôf“F·M·ëî¡asÖ£ßpΪ?™äŸÆÂ²óy»·Ý€˜'°#‘ó¡°ø;¥nåi*s¨ð#–}ðêÞõO¸‚ß×ëmÕ6າˆY‚Â^õzÉ .R`cß­aôXg|_޽~¬á"ÒÜhjñ@÷þͼ ú,Îø=qr‚Ðf²Î®½Â¥Œš40ÆP“Ûu}€ž`‘Ë@4Ë ë;ÂzRìÏ—¶{í»¯u,"ÞM¡ØOµ&SÔ›&´©÷"a™*W`èÕ"IˆF$—,Ñb¥OÚè¦És=<¦Ò#jáâå¬ú{ˆ~ñ›rå-"ß"· .êYF}V$¹[ù'=ùžªJ’}ÛJéZÄgŽÂ6`v©õÆ&v—‹¬Àeøœ¬z|$Üã¥lUr«»«iÚƒþ]ªÀ³øŽ=Xê3M7ª˜‰-ÉuÕ®• ÛîQ/ç1y°Ü8âöî8ˆÑ@š®ôv…—’å´pËÎÓ:c²‘Ș‰…€ei$ˆŸeTW=]C -Çè]•¼E³Á;ÍÈ»p×~Í -åU{¯»Q*0÷5á.õxr"ÎCŽ¾ë»¡;l›]uùñï³$ÍJĘ‘C…8Þ÷22´?¡Õá×@Hr… ü4AïØÉð$[ˆ­Z«ë3‰£X+!M²·Í?86À[T°¢>yúÙœh×ÝÒ°q ¢Pç$áð -ŒY¸p%«öb¥#XŠ5¡|–b¥^Q*B;óN™ºËJ:”à§3RÕÿüã…ò»¬Èå*ðÄ›9"‰a½­÷x¼pNA -è -S²b' –Uäp‹~tÜ…å6ûC×äs$Œt€Wh¿eÞ¢»+hªq², GFÙIHÆø[W5‡SØa<DèŽìßXÝî¦ÝSq-¾Í˜Ô1æ¨+£"G[»†‘!&f,Ý­pág‘ âä|ùž‰ùç­v0EÂQÍ`ÒŽIYZå)Ž+S ÄÔåðˆwMïï¹@Å]ÁàÚçG\¡Ñµc¬v[ŸøCÝ?0˜!ÿ¨Öâÿ8äÖC1Rµ<*—ªåùŸ`yqY¦ˆ!K5¦_¨Ñq7ß|èM ¾õQS›:¦Y0âªްYuÈIaf>]"B”ç] <-W½{0psõïÛæ¶¹¼f^HãGØè¾Ñ¸ÍÆÁ†dV`)0¥ÉÐÒØYohjVÆBÕ訅ôù¤aRpvã)øP¬¾ßO¢ûÓí%‰Ãâ̹ Wˆ-%Œ~©×— >ì-œ@¨Üe‚\›:¹‘Ô¬¸ ‡+pÌXÈËðI”ûRt/€·¸'* ÓO€.©áXIMh=N`B—šû©epxcš_ ±¾~¿»dâ¦~–§žÐR„‡'%¤ÚWº( &­£o×·+,NyL'³$RxÜa9™KBˆYXW2¿ÆòÓ¨ò³/0Ã,sJý1yX>(f$ÆWò(»J -쇋®ŒÃD~äŸ1R­ÎáîûîQg#¨p©øpœ2 :}R·ŠHX0 ‹â= ³#Î1pëë:º­]³cö®ÕQ3&ŸsdÊëÙÖ̤j¸¾×íoF?¦ÛË8âV&Ñþ–Ó’™âñSnÞ#ÅÂ:tÂb0£2.£»±¡×žz••D-º‹;„¸+,ø=߃`®p©ð!jΰL “D]asÉ ›ÀäáF½cÊÌT óÊ\0ø¦>I/LPaªf¡¿ rF“´ HKìØ™e(ÕÎçO/ìe£ì;ex~ÎZôYï þPŽÉò3c³»d|¾¸Võ4ádOЇÒ)óñZ~Fë$¸Ö•K$tI¦‰@[µAuÆ0\¼d‚ ™FdõÕZ¸sËj†?K~ºoXŽå&=xÕï ìØ6U8¬~.PTZ;@°WaNCnuÿ›ðùè¡ùPä(Ψ-ñ&âfM’¿Ȳñ!<™ó±×4¬lÿ×ÈÄømC ãåÑ5cÂ^A®Ö—Y‹1xU_§–2Ðg¦t´i¦´Mc¡¾%='0Ä>ÿâ·¢ÖÚ“uWHh*ZC‘w3ÿ¨‚ÌH£¶ÛVwAûðкÛa Hœ¯‰Êð“*^¶I˜Ø½SÄ®¡lÖ«p*>Q„!:MÖ¥¥€Ml±µ’™¡Õ²"rÙ9ù1LAéëDà‹m]X؆¡IÓ)ÑW”'Szó»¾S4CBå…lĉ‡™&6¼q“j¦È‚Ÿ©:î ·ŠS³”H+z·ý ãG?_KtÉŒb~£Ùî> 4=t£Uÿ¦® *¡8g2a¨¼Šj£DÖÒ&§üý_ß©Büô¬å{õ -™ Åg­B$E»Ä³Mõt|G -þǨ>#!›8ÂJM:>ž„3ðw•Îy².ê#®­Á’˜3—Ÿ:0QãIó.޵8k±"t›NÈZ}õGÍøØ%@i"çÜ·µL¥ž€·5)³½w?/Æ>Ñ+ú$´.&Ž¡NØô3ꔈ{[ª“-R 韹¡n>Êuš e›ã‰P 4~ð€z¥£åZÝË](œiæîð~ð|¢Máë 6A8°*¡Ÿî‰®;Ù:±üMãõê‡ùh‚!÷¥GͰþÁÖ#;ÌB­Î¡±jPëDía•¦h±¶S~‚¯È—wjyÇ¡Q£|¨ÃãáE‰½êQ÷©ú'ࢳ»ªX -Î|J1c@«Ø"ëA¾'cÝeI3ÈŠ°Z²G£#s>]žME÷Ìnó,ÓÑR\ÉFuNT':òƒnÉöjœD“JÁXI…¹gc÷ëq«¸Ðm¼†7ó̰¬Ž‚5“zÚŽDyò®Öý¬ú¶F ÇAN;·etS?L°£óÙ…1g«B†üÔþBÐ@¨Ï3V̶žºžuÙD»|±“Ão‚nh®ÓAìJF*§ƒgyÆhL¤“V¨²â±VÎBb¬eh£¿¯‚Ì×”†|é0*n7AHRiDª£ÆH‹‚§Ä*ÎH,puÉ¢—)?Ëe —÷°;šÐÉÍ55§îåÎܬÓ_눉8Û3¯¼SíYéMÙˆ tþ¾mî4„BXIâÞŽA…õ•<.}ûú"!‡.ðüõÌd>?3Aq«ÝæÌ‹xîHÁã—Šžt} lh*Qô„®ðLPô3ÉC{ËA+Í¥Þ[Ù²Ìü½“Äþêz'ñw’—/ýéÙKiž„·ŠsoÉEúú›×óý$ö¤¡(ž -{giÉÿ´â0sä -úäIÌÑŸŽ›¬â8õ48²'eö—ŪLL"ã\FxË _¬BOù!¬óÑ'o¯=µ`$žjð† Ï̵õ4ËÝ©Â#,$Y¡·†×»ÛØãÛµì½ÈR²…Gíª,|{`²Œ§öWlÐŒš•/†¬Âpïí¿«aÕšÉ%ã/·÷Š—è[Ó$¦G’¢RŸ"/ŸAØiôŒ£;F«ÓË6ä”’+um`P­þ,ÎåÑkë‹€À••¿¥‘ŠŒ^T½tÄÇfTˆ‚'Íã)É{.\¯Ur!|©ÖOÚÄ -ÛùÙS¹ªÔËvíÿ* - ¡ó«…Å!Xwµrñ»»Fá,ÄûäýXÑ•vvºhë™0z +õ'wJ)s² üüî]hµízoá‰/1#œ—AËû-—ø+Æ/ÇÎ6ñ=ân–ò„f©Ý˜`7‰µötÄòåˆ/­-óÉî(þÀ†¨¿ežÍ>Ίe£h"ÙAOàä'Þê¡ñ¶yôám(‡K@ ®6®~J2U#œ -Òã<‹â†²ÖãrñJqÃä¢óé[ä $ÊÓê‚o0-ó¸xf>f¥A´Q'n¼C*Ë9»Ṳ́ÇOÚ–œè VJ|×vœœØ‚ðª?2*“×( XЦdø\îÓ0)IPÐù«sföèOˆœ§ñ.Í7Î'‡£N£ -„àÅâ8ÉltGÖšÈü®,Ìœ¡Œ¬Kñ‰dîÆG´ÆdOšH^e1g³µ›pÆ5ö%Æ‹$æ$¯Aé¤/9hoZK¿Ä`_Z%SæBõPVçß[þZ¦ì´P7‘ô/¬¥±ŽwV•S6p½O®´‡Quîl6à ×” ˜­F±akï׊¬–'d§yvÕèyi¸ù*m4,Å>éÑ ÜG]ž“Õ 9D7ÿ"˜¶*™éœ¨ºWíAØh8ªD\©›1¥qšuÄ51Ëc¯ƒ÷u«YÔéñyÜתkÒæÌŒÏݱ+ezuœˆÝ¡80T,•ŠÉÀôäÜJµ®™*y‚+š¢Â”L^5•³Fæ–µ¿îzãV1àÜ›gª¼ì¡eþu×­µL[yzÝü#ä·¦cƒñŒA¬m“´×GôüDÛþL-d>ô©šâ{[sGžíÉ•,£ê5yþ¥i5,çiKàèäÖç ôv7eÈä™W -ïĺ‰ái´”[v¡Ÿªx~ÊÖe@UpžéRDOÿï¢ÂUhâåV•F;€uCǾ4Ö&Èä!ˆÖ¼æ3Ð,§3xeÁ(ÏCHϵÍìŬ,Ì{Ë¢j ¯ðAsùJè6ǯBäõ OÆÌÏ€+œ}ø ɯp9)êÈeš;Á)¨g…ùäe»ÓrŸb­Z«Ã‘7N}Ç£4)[V~¥ñæš‹ãóVû@õ‡›¿©P?œe·ýÏ_~‡ -—%Šø_ßþ ëæ¼-wQ[ž ól‡¯²EÏ6bÙ¤çåjc{޷뫾ÖÀs”ÈÉøLÆ2=éÂÿZ%Ë‘H0èÛi4>v:ò26¿ -#œDiæyé -m—È8#ˆuïK˜€àhÑæK#ziT”\Ýûá =e̽òݲ±ž%œ>â¸'o?þ¬¹Þ¨'–{H4Ày±'›ªõ•LŸ=ÇÌëÞ‡x‹ŒŸ¯…ŸÇ‹»jí1|}óc£ª‘^i‹¾ïÝÉÕùtB×}¥[Ñ~¾„VÀ;-9¼l¯ÔNï§[pô#[rÂÙ–øùäë«s¨n!à†¹OŒEtôp·`ÓÜôÖí|v+bþE‚R»šyoXT€`Ûãz§Uw(#äE¸ ¥žRõm÷à3Oý•+´©-ÖÍBoU`úÇÆ{ÌmóŠäÎUÐî”jë›0ÎvU0ù{òÜÕØÓ4AÔ#x/kqC8øÉ&‹(Ž£/^Ôs²äÓY×g2›ê"@grÞ½É6Ò™™â6˜ÚðÕÑL9À9·.o³KùœMPºWtôu)="kúÔRfH©ûkßÊÓoØQ‹Î¤Ä¼B[ÎHi}?Üqí‹sSŠg“°©èxËOhï¢ý” ­S )·C¥Ìa)žÔºYð:ìk=ƱYóÅÑ—".òS²èar/{˜DÒ¦Lç¢t:µ h¢MlÈæÏÚ²KL¾ŒbxD®ºÑÌAÆ/­'–V˜å¥#”_lÇ×wŨŽ{ù-“å™P3´¯°ŒaæÄÚç„ô09úpŒ,Æœ,†ÿsÕ¾;Ð+šW!ÀEëÏ _Ehí¾çÔ­•D6•vÃ$Ñtxéd›ôŒ¢ß&ÜwÑc£my82Ñ+pÔÕFO)ŠW%_6‘AˆgYý<ÈUÈ*:p|+ó<öá¬ðºîµ„Æt}8…,!e„óÉü4@áË„R\s!{ô>ú%!–e -éÌþ¶·É0ÒZw?ŒO~cÇ=L"RÈ'mSQhkŸ£Y¯ð9 -¨ëŸtË žÿ>·ç}½¯T-ŒwÆS0k Í»ªG ®‚Ý÷µÿKâËV6Uøg½’l×ûšç"ñªcéOGžQ¢ëe÷âtd=ÎÙyyÜ<…*‘J-V›Þ©Òoq€ z[áå…X@4¯Va`ñ) ‚º? Ù-aoN`,‡ÝiîšÙÀ´*¦Í…æ¿ü™v6j›øi–dçØÅS…4DÎõš¸ :QßæÜð°ƒ>ü·Z‹¼l­êúQ]güÎõYêà"ÁïÍb}$ˆ âP#í™è‰òqŠc²¥ÍiGY^;ò;®äaEv0ÌÐqಙ±Þ•“¢º¢ -Œ…¡øª^ÌJ÷d49[ŸºaArë]½÷ îŒvFMTQÒ¨8ÃvǾ¹=2IžÇ>V´l“¹;öãVy Èg½;®›¦Ó]áâŒ(—f„¤¬7#6vûæ7Ãã[M Å?oª} 2´ -€£ŒCf© `Ü ôsthC“ÿ‰BV.ÿ]àXA™+YýýDZ’mGÓ'̇ ˜ó£Li7ŒõÓ‚F©¾¥ðÿœè[нÿ¨Ð¤§­ E¦¼¸.e‘ÂQuù?ÿå§›°ØwÝþp9–bË¿¥÷„I±)ÿp6»ôøø¸:ìºA(?cï𳫮Ǚ -ÇtZzy]:œþ­jZËM±—iœX§e§ÿ«Û÷µúï=arÝ?`KhŇaÀ &ˤk¢¯%óûuÇÆ&e/þO€¦±.µ -endstream endobj 4 0 obj<> endobj 5 0 obj<>/ProcSet[/PDF/Text]/ExtGState<>>> endobj 6 0 obj<>stream -hÞÌ[Û’äÆq}çWì‹#0Ž™.uá‡%)YT¥][K>`z03»M=Ãa8üþ^ç9Y…KO/I…eKÁ.¦ª²2Ož¼Ô¯þí]öæaøäÓ÷Ÿüê7îMöæýý'å¦r®x“ÊáÒ–›ÔöÏ‹I3óæýþ“”ôrñ~‹ÿ=ò!ùíp¬®2¿©’ôê¦0~S$õUš øC^•?ø«Oöu•Yù廦Ço©üÖÝã*ß”I½Ý^eÕÆ&Í0´W™Ì"¹Ý5úœI¶òn±É“n_ã¦KÆö°‘»…‘ë·».½ÜoxÅÈ8õî*ËäßÝ5~±xåñ*Ëå£Õ'»v1ˤ›«ÌÉ﮾}ÿ;Y×M¶É¼Á|.ë;ö ^Ë“»Vfhäý±}šr©“»g,-O°2—æae¶²r5Èœø¬ÇVF.“9z½h¾™ìøµLæ"Z™ÿI…éÒLÆå¤Éã˱ƒÜ‹y]Cû#„“͛ŚÊÜèššZÌ·H,=¶ -¿Ì=‘-·.Ï!þnçmrÛj|T&ÞõíUžb·!|ÑáËSU26ýS2É®ÖMxÁ•Ìñ¶Ÿu¨¦ÁVeÆÅÝÕéøË¢ÂšÞÿ3V‚ù@Ínwøº“A®nŒLÇR ú‡›õëÔÇñ܃îÝɈ.¶œG‘´ÇQÅÒv Ãh‹‘Éy -•ßl{¡Júf‡Uù¤[Ì¢HºÃðI‰Jã‹Ï­l‡3òÆQÕj×^Q7ó¢¶âÂçó*•Ïížfá“Ã(~^zä ÞΖšWNž>4?Œxˆ{ÜLzÛan2Âp›Xé3^)ñ©BÀšñbå©jaØVUϹIïÌ,‡¡6œý¯~S(žT"¹#\„ˈ'N.r—åÀ“Ég¢X7NF…b¢ÙX`ßR¥Ä´ Ñ¼ÃØ··'™”LÎë†è-ÅŽT^ýÍ™ñu>€½1ïÚÃÃly–OFÝaûK*í à!KîpEÝÙq¸’›¡UÅÜcÈðaÁA[ƹ©>ŠªÎoÒ,{ãd~EšzÂOõ;$æÚŽØ!5z‚Д‡þí»;H[6y§Áyg¢n:(âBôµ¥frûË„š ¡S3]%³ÄS™èCƒ©8Ž;7ÍœsÔUÞlªªZÃÊeT ø~Àë¸VX\|þû·ºQåÒ¶Ðñ|9Yu$¯«ò/ðÚ÷úÚI Q&]->7k³ÂB–.k¤3Mn~Ôå7óºÚq£c•ÉûGhå €.€‚]Ó~Óäjuk»ø·ºƒ·–W·õ 3ž'ªÂ6- S -0F(=8G;ŒqKkÕola»“§º7ÈÛ—ø†x‰¤~“|Ù( ¨e˜ Ööövнév'Uƒ‘Ô ÊøN J¼ïá;%õþ­fÖC=ÂÓYò.Â_³•äÌm…Ë?1¤‡çY ?f“¯šñQ—ÛÝ JÝLrßõ—¬ç®ë€O»AÅöÍ•`hÚö¡°zïÚXE›o¯õȲpˆŠ"ªðN™²÷ÇF©ãžK Ë3oj’<öy8ªo¯ûAA£D­ d6–üvÉy船L{§`ÕaÈÒÉ$=`.Ä;JEA§‡NöšTøˆß^UñHß mÇÝ Öâ“ëK¶{_ouêí -S*›™¹¹Í¡C+·9 öuôÐ7£ZË -s1@µ4)Ljƒ{ØÑ?5*õâÑè<ð góœ²z BÄ›ªè‘¾ö“€Ø1eø è‹ÅjE<µZÀ“\&¡…¦Ål )49ªkÁv5Om §r;”ávíuáÇ]§÷BX6y$§ ½k‡­FÈtÙä¢Ö=ù‹pÿa« Ñ ¿ãþŽqi´ìiƒ„ÓİT9p}eW÷hTÊ×Þ‘S0^Åþ­ò8{¦˜XG¾D|áÉsÍ÷AOÇ0ƒ}Àd~žeQø /8‹ix‚§]ˆÐe›K°§?dZ n~8FF¨Ë¥‚áôñs#³´¥cØ·nß©„F,ûp#QÈ“Zh¶e= ÿXËöæiäéÖ ÛÓÇ+1© vóÙ§_jìYÂå…v<Û Áœ¨½)¿UKЈ+’ð< êú›öá ° Z3,?Ëè•v§AtÄX~‚ÈôEwš~ÐðØHT)æ&zñÎÝûlEë^ÂÑP¨ºÉ9×”Ý(¯ìëö ¡NVEßn¨²”QGP‹¬À7êË /.þû›«Ò˜êIÕ$AçÒɇl˜g‘M"ïá$”!¹)ŽÂÇ,Âáæ¾ÛöT%ÛÜñÂþ>‰ë½ ±¤‚=¯Œ lW.á_æõæþB†XÀy߃A9¥ÇDqGl9õÇn€[°þgÃ%Ô6yíæÝQj»Ú"ÍÂÞ@²@êƒòH ~N·ÜÞ)56OI€¿?1š'©„Ðltœ÷"Þk}BwChh½}œ÷QxÅá.z@Œ™{È\e,à+¹Òbe²úŽ Ó£Pâ†ð˜± ¸AËœa^2½vêú„(ÚÇ[|aš™Œ -[Q†ÇvGç!ß&¿æJƒáÛrËÌGsHy!üÉ­RmØ/· < +±Pª¯?ûL½uÆ$¥¦'<ܾ©ÁTf.`­¦rÛBH‡&Fâh»R–3Ú€ÀNpz¯Òùs³ \õ:’ºdØ`‘j·{ù18æ c1;¶×ÄYL™1Üڧ&f³ŽÝ3y“åbFmx Ù'—#Šû3áÏÑ½É ü Yìš'*#ySåq9¢¼¿t Gç(zhïäþݵtÜ‘¸¨qLû#FßÊÀ”¢Ód·Ê,”£p™&§5°ÈB¦QX·€rb‹^c‹,×›‰ -²pë¿Â­4ÜÂòõNîdᎩ*nýËÙK¹Ïâ[6]Å1HI|¨÷à€¢.\‘dŸª’EÕ!æ¿;%´Ú ó©û—A›ªtÅÚ”çÀÉÞo¯•y™äSuiÖ³"NîÄÌ2Ro­µî‰¾üØ>Óß#Ó-Ϭ±‚?ž¿'ÀðÍ•ä7^–dÏÀ}8=<ÀJÈñWû‡·¤Ô½°Žé A Üp)a|áa°5Ö! œÊ2>hÈhe“†*ƒk$W{3•–EMY2ƒ<{J¹•²´ Ž’fÉï»±¾Ý½@P• 9ayóHf*ÛEКMC ÁzH¤u&j~D¾mõ‘lòMòÇí â*“C7Æk\ȃô~x‰uªA¨nÃ:*~R³·>ÕLóEÙöÂ,èõJˆ¬e—hGl1³³$*•™œi”o’cW,Ý=¶ý„*E¥œvasBœc>GY|Å72²Aœ£¬»öNŸô* ¡¶]ß7"·F“¼•zaù°r -³`Œ©¡’† ZhÇB\é&À_@»W†,ð䫵GÛòyZFãú׫›Ì -¶e %ˆÔ™¹ûÍÈ• :ê_qÇ&ŸÁ¿Ò §«ª\«Õûú»†ô¯Ýý ½“S˜HÚµ6>¨ã,è%·]NR ÒÎY YKbÌØÇfÊw[:^Ìø—ã®I¡é[úùŠL[`~¤)CY2æ=+Ø$T¿çÌð¦K^>œ1윕fVàh÷á3× > -`ÿÐîe’ŽÂ'…ý§kežZ¥DÈ.)ìS-È+¬Pš*×Ú±,¿þâbsfÜ&­¼û[›…ÀŒŒ0Qäb˜GÇ…ê3fµ"ñ±»Tzþ?.-gð÷E¨,ÿÛq¢6à:ñ¹Ò¼¸Dø¢`=<¢6l™XœÜ¶-cýö+\6C,` ­6Ý},°ÐR/CÇõž–ä¡õ‹ð6„¦EÐг¸žCV>mðN1`-dnC LOêô?Û-“?]CÎøY.í"n"5,à ‘)…8‡)–e7[ %7ö -´°%™s5lQœòrYx³–èZ,–"¾p¹ › ?¦¯9~œ9ƒË!`€Ýç¨R9r@ø:ÇìüšŽMö½®æ4~@K`^!ÌAòl)±ôÊOmw¸³L¼8³h®œ@/ªokÆÄ“›öš÷*ÖÜBÝ6àÚúW ’¹é8ag*Ƙ°³Y̸9ëÖìA,gêŒaa÷Nóч—Kê´ y -cÐ1ŠˆÙ›Gù6¤¾ýôf )J²ý»€'Ú^çÑNï»a‡ÒÔ@©õ=-› -[w®ÌÞ‹I `3¢&"ÚBSݨ±SñšÈiHÅÜ—h#ScÞɦږŶšƒ> ¦Ðm›ah†Îq%‚«ÂqUHnÈoÆî†K5%‰»ø&èb'l1´}`‹)Í4ÙàÅʘÐá H´Ý®{½Þ-?ZÄ>†Ó(ï³¼i,‹¯Ù ®Æ±Å%fH1ë̾)d4lcˆœKgËÂËY€xaÁëOt›uê¥K{™W­ú­Æ„mˆû¢}êuB¹OIé”/j®ñŒg/ò$ÄYú«2ÔΗêSh‘úP1eæŠÞî‹Ãv'¨©ÀœFMâØŒ¾µÚœ ò¿˜z` r~™plT¯²=÷¢€çù1ëýG°43ö"–ê€etÉËÀPøAþ×V`–wK³ÞÿeÞV—} -€½æºW!Xá³)CÎKÛfœÓ0`•Ô#¨R‰Ž»¢ñ&4RB‡.lø¡ì±71ï jæ‹*xÞ„¶²“òxüíÕW{6Ý®|µ'\DŽâ¦{ÖUþ•1$Ÿ÷ÝÐÛ]½«|¤p“ÇÛh»®GLÄ3‘-kÓn…¦uPäíño©ìŠT)Öðk91ЦÐpî…)ˆ² ¯tóÂ,Vr[*6.Àck*ä?šÙQøÓ`ûúY\X­­^yµÔÐh\´èú£ºÃØØ´šì&–#þpÐÀ¥XVš†zßè=*¤ÊàÅ¡~ /ØœÖC"](¸þÉ¿ÉF¾Z,á°_ +9ŒZg÷¢VÃÒØ4}g\5(ÿ¿¤oP;€Äú6IùŒ›)¼zDôHYr³_ƒ›) -é;¨ÏQ¦ÓÉZ63ëôîÙE ®Ö†°)krA²…Clóýü"¹œ–S" -Ùl­,ðµòfÛ„2à„oi5qõkUtŽáS²Ù„[2FÒüðØÞ¶cìßuÏš|È3¾ÖŸ - #S7©cÁÚHG°[ »šþiáÇ.ãØMï2ùùÔ>uë8Lt¼È}T€cÓS¹:kyh¡Íå”y•áQÀàNÝî”îa¯֒À€lb©`æ«Ö¾z­dè \Õýä/vZÎ1²þÎC|ÊsÇlÑâ+©'!þu"Ù,Žïë—XeN÷2`8²P-’YwÒRêU/hÚá´¿Õ‚˜çË,ï›¾ÑæTÜÚ¶ýöÔŽ¡A¼ä>Fé‰S‹e(´áxÄ £ñéE6ªo×­s‡ö}_!ôNû½@Á5þFã@Ñ—Õb§ôwÝ)y'xsvä“ã~óD¾d³ÌÍaùB¯W¹"ÃV-f”IÿÕ›záUyÁ¸”áÒŸerYŠ<Á˜jŠÉC²á–0Ÿ8;íØG–Yk,1)ÝžºÝS¸u K…Tò`Sµ! iþzA¬ËW)™Y!!¢åßgÙ`I“&³.ªÚlv§…‡C -SM™tè|,ç1=€î¥jù+õÖ!¹$—°¡Ú-sYH‹P‹) -=€ò‘\™ª²Yfy6}†ÔmZUùl_™föRþ,ä‹çc\,Jp#´ÝYãÛÀ1™Ë’ˆƒ†Ç!Ü/X2;?Å1çÎxR‚äPŒfw]—×V)‡Wy3öZ.&ã1ôVßTÚŽˆTãä˜È‚—<¬BnûòsY¸Q(â´(åÞѱs‡F©dÍ\n&«zPgÙ¦i²ŠI-üʲËSó¢§²IF|ätn>¸`óL´Ûô\2ŽÆ¯s­j ìlºìÒuÌ¢„F*Ç8;p¼áٽࢠí^.›ü"ÀÖ('Æ™ŽÇÚèœÕ¾¥A]YÐ5‡i„T `‘“×^ -çÙ¤}Š•öu”µ,v\bß¡㑜 Êøœr_æ# -jÆa“÷YÄâ‚åK5y¯ž?2_ÒÃúâBŽíL>»0ÌÈ÷Ùв2”TÚ´,äöûS­]*ûZûžðÀúï7ÉWï”M2MJÿy9Åâyû‚.ñî¸ýž©$†ƒ»®Ü3°ÁǼ™²°4ëAÀ3í2‡ÆxÊKhŒùx6tª3|ûæöå#‰!XPq-c¥Å_ïÌ[ -Rì)?¶ÛGTà ØÄçØÍ;¥1Q[Õ=;mts9CºŠ<ÓxÇi_ˆ>ô9xqy$ìò¢ ä ¯4r¨wìfcƒé[ßqó=Pm•ï"c’Oì«G±íªôÅÌ܈—ç’×™ ãÛ+Jç–X´ÞÍdZºÐޤ© m¿G·¹F¼å¢•P£êØhN^O;jòé,ln—Ïf‚wÍìÌtðËcÇ#–Q…*çF<÷-¤쵊…ýkÎAro”äå‚0{ªlõ¹ØÀ2'FB'`,ú¯[ -Mb 7,¤ÿû!t™M½—Á®*L¸iWý^jôÚat¦ßQ8ZêÌÍDG-;FtÔæZø˜•’?•‹Þ•Zí† Ïâ×ÇÂÄÝT>.‰pV1Ì”É*—a«Ò¶2Ÿ:0½à¤:¨lh³*%ÔºA[ïæ¢r`Ùýа5I{©ž Tmdžø9 -mQFëæ¬ëLusWÄî íªšbë4²î%> cŒeS¶Dí 8iHc˜–C"‰]:ˆm˜ùL1‘ÕãeìøðÁhC3ˆvø, Î:Õ/ÞXd¤Iÿ¦-¹6µåÇ|±³15kÜG}1«c>ñ­¥—iwšG÷S&óZ{›mr× Çvlôn¡¾‰ç\Cq˜GyWYö, ¦* ÖV« -Ã?Š˜Šì'ÄÄ#>È£h>ۼ纽åÚgö†ë¹¢Ð9˜©èÉ£œýñùR{yˆjÖð,–Ä_ ë•gÉ#4¼¡'7¶ÿ³$v뱜ÿ©èG>×­š2¦rJkÙ!¤Y,Ë3Óü!ј—ÿˆÎÄU?¹tVQ×%»Œ½Tyåbê7gÎþ¬è¨Ï‚,m 'ÕÔ”’.¨ºàL> £Ã'Ãã¡8ŠTrïBS6*Ÿ±wÚóˆmèv6Þ/’2x¡dRfëµYì€V¡k-Œ–JÏ}ÙîC\´Ð°eg>;Àdìy‘Ü0U¨ >³a™!ÅfT 9+K—û M -VÏB…¼ ÑŸâN½7—y ÖÞxúU³csɆG$˜•ÏåJìÍ/3÷ÚÅ"ˆ˜> -DãvË…‚<4јΛ|Ø€`íܾÀyæl\[æ> kû¶¼kGàšSiø%MB!‰MB¬™kŸñ Ë_´·Å_È•²þrž ]Õdª>Í™0— ê^þ÷Æ‹*_M˜ÿñ„nãgÃëx” îè«é r‘ÇCH»µÉ4‡¨þ´Šp¹ÅïŠiLèÛÍŠêÍØ[é[(¨¯¿üû˜ý쬆Êüê§ì:{ÑÖ5“ü§Ð†NåùùysÜuÃöŠ4Y^EÚ¦ëÑ'ãxˆ¹¸º©\…³¤¿«'MƒQGó438Å€­ŸünwÚ³cAX–â÷ð€©°%_ Nṯ¯eóûM–¦…É´Mé×ï?ùW)Ý» -endstream endobj 7 0 obj<> endobj 8 0 obj<>/XObject<>/ProcSet[/PDF/Text/ImageC]/ExtGState<>>> endobj 9 0 obj<>stream -hÞœZÉrãF½ë+t™pF„QPð­7íðÒ¶¾´ú’ 7Ð(ZމùŒùÞÉ—YÅÅ-M8&Ñ µdåòòeB_üóV]oÆ«×wW_|•_«ë»õ•OË<7×ýO3gܵ*ò´4>¿¾Û^e$M7ÕCµœš¾gs£UZ&‹z:Ôu‡Ÿ6uÉ×ßãr©Iî“ÙÇ»oé`eäd¥R–ö½{{• ³»_ñRËËÔ¹L…Wÿ¯²°.ÍH¾ð. ïTXfËÒ…W_^.£Ã\^VÞåŸïø!¹Ä:-’Ûýn×ÖÛº›ªá 7*R›|ÕlöC_&õÉ­}}?»á‹Í]¸4æz®Rå}!›-ûnÝ Û¦ÛÌæÚ*RIß-i¹6Ž–W›ªéð#Oódz¨&<z–Ñ"é÷, ­‡j[úá¿¡ÝP¯Ö>oTËåžÌÑÔ#Ës÷w:¾Q-é¿ë'1EžTÓt™ñ¡®Œ–4J¢Žõoûšå3ÊCÖ5ž -zšj1q‘tûí‚Wñ§)뺚H5c_Ý6Û¦­†öéæ$Ðz?ÐV´Úæ9­©Ÿênä+XW’F°u¢Ž³2Üö«ºÅ•,žð¾ û4ݲ݇¥¹ ÂÊÒŸx5¿­›/ª±^ÎÞÔ.A“5Lêe¹ÉuÒÖu _Í‹T‘®û-=“D:ùà²<‡6î‡ø´Ý·SóX M5…=óäëfµb×'¡óäûjøÔ?žNÿ—"Í-9‹N–tN5ÁØ6ÃÆ‰¶åWA'«§?â§§Ÿ"”ÍJz&¼ûáÍoßÉ€¡¹æãé¬U³bu‘ØìÐÜØlºfÝ,«nj¡DºF™4ÛÝÐ?ÖòóÒ¥0b¢S±Ö-ø,ŠÉ%èöêÅ(ÎíóQœ–eùÄp¡âªBÿ)†­³ªn…—síRE÷¸ ÉU5qdä3gA1>ô‡î~–F¼º«>±1 ¦T2õ›~{#Ábá#‡INÖ O"wãNMGJ¿ ×*6ÞùäÍë÷çáIrÎFô1R:m%dƾբųÉè|þ?GÌ®eÐpÚ“ m³y`ƒ:$EŽ!ËáMt.æ\ÀeÃ0‹ãÄ‚ú(‹8s@„HÄ ·?¼ÂPFÖê]‹«…Y†dœšnpz¾6p×q¿ÙÔã$°çèVÒ6Ay²çtèeœ\´žÎ”9óL#²à·¥ß„T“è „êvÕ05U %Ä÷ÛsàÎ3h¦éÖý° ²cž î6Øà[üÚ7'†.S&Ëj V7<Ô˜ÆXÇa{ÓÚâ,Š %ZB°Ðåss. ðЬ,)^rŸZc9Û~HîH)9ùÙÐï7ØNpÐØŒ]µOcŸ³Š-óXW `F°|»˜Í=é½éª˜  Ã+ÊZi%ñÐŒ´¢2º ãtZ3›Ã.ë`sÚD—0àC5,ú¡‘%Eó— -¨Ø³ÁKhæÓ>Ä -á-bìJjcSœÄÉ*XœjA—G®Ý#lÈS½ø Ý›Üòèƒt8Ò#8B„ጢó òaærzOæ#XS¢ó¯k -Žg²².,{˜e¬Ü’4È3 /oV4‘$‘i!Ua’O¾«Æ™¢Ä -Ÿ¦T¢¡Å™ÂÕa9˜£‘„,9ìÅñT€@@ŠlÞ=DTnÉË›™¢‡;z -! ¥€¸"%ß1ô€ŸÍ8ײår°¢-m®6SHÌØl‰8ÑîJpÒxP‚-=ŒF?:HO±Þ>ý1S`"@œÌÁQxªÂ=±3"êô–’ D@%V$ʲYhzØô,]-ã*`cÍÑh!ÚØ@Çã8Š’Øº©q”¡Õ4#¿Ô:‡’B–Æ Ž±„[$j/>EN7â›¶št¼XàRžÈnð¹Ä÷ÉWŒaª¶\bH'Ð&ëuÉT ´‡ <à/¦)x‹›¹•D1 *僆y9b›Û‘ëʾdCámðW-î–‘ºü¦Ç+lkÞ“LÃ<3î3!ÌáJëç\ÁåyW0Z`PËsH0É¢’XÍý–I½d÷.hæsÕcÅ$mV ¬bxΑ×ÌÚ²å1:oιÒZ$~Åñ$ÝĘüU»Ý ŽÑ“àPrD&S¼%ò«f^´8²Üú hm!;=U`óMÝsxÔ"É44ÐKšàa!2Ü„ô0±B)ª›Nð‚IŒ‡Ó7,—Jvý(‘‰{+á8ª8G;ã)÷í^¡ 6ô Ib=8=Ì »–¿Œ)´%$€9fåuÈ - Ç;Ü¢á <™Ÿõ4ÍX=R,‘ æä4B^2ˆòÁ:l©“P¯Ê(ï²ò3˜t"®'×TÌÎñŠE_Õ;#tZñ| u­$`Õ2`Pä žjv+böeDƒwwW¿]YhÇjNPTm§%UÜ\‚ÛkàÊÜõr{õÅ7[uý¶¿úIŠ÷À¯i¯"“¥á1ïsJo^R[,Z-Wu*Ånt»|¨A‰–RcX$W²ˆ$…À‘5ZuLç–£Ÿ Ó?ËP#5ª˜—+U«A)8‡Y2P’^r`ø”Y‘6q9Â1±ë\*rÉsà¼lR°ñ©ò¼`[.™Ïb)qŸ¼ºŸqUÇá^D<Ž.T‘Ø[*/§¡âĉèDI¤ -rѵü(ƒ6²âB¦ô\E†ŠúÎ2acôy¢1胰ûX)5¡¶™Ô[wýÏ7²ž2v»¯ãÁtRMbiË âŒUÔ#ù©eÚ¨$ÌÞ£dÂh3XòX×yÑ3i–±¬[_–ad›Â—ìváÑ0(“—Äg)®¼+àw‰Â²Ï}Ô’—[¸k. -bd˜|ΰ± -¤¤*ÇÓ…¶Ó‡$Mg(Ï£O!¢Ña27¨âfþX6fæü*Ÿ_€ -âåâlc^Œ60P•]Þäñd“ .OÂÔ(¿•ª4—ž·ªUÃà` -Ãl»ml ‰ÈåTu›¶alS0õPGþmOT +rsÉwì¡FÒb`¥ŒD^ÑOܸ)l(ï䈊ћöRÂlòi!8ýîÒ$·SäÕhù‰pÈ^Ìox^#™ýîöVv†WIA]cï8Ey},˜%T -ÃÂìö!ÏÛX {”»äÈCó{LL -x?WëgiÂæ{Ÿ,úiâîwDÖúsœh, -g=4èáI)ý=,AiSûAv—tò’V Hº8‘éøé' -Æ.”{Ÿ¼fgÉ@—Þ Þçè3î%×1tÍ•_É}vˆ•´ÀÐqØÏ2Ø>ÿþöl‹¯BM>Âd(§Öû.~Å)‹øE%Ó¢Ø8ê;­†æxËTaWbrRÇÚœlûÍ ÁŽ´”™¿Øeʪ¿îÈvEiòk¸qŒw°F!mæH´ŽôÚË|aË¢Œùâ~õì[ÉPœ%T¨ÖE¤6ÌÙñFùåDë(äÄ¿‚Öj!sªž48Ù…‘ÓM Ö±<ÙøX裸ËHW࢕ëÕ†Â5ŦœXÑÊãvä†ý ^âv %œ— -ã†OEЀ¸ßDÚ÷0yl³Ýoe¹“ø ú=¼) -ÆósVCuè„u˜³3WÕø ²¸p(wxJ4l_Eâ@£’‡[Xž›'4íÔTÄ\8&+‰Ô“ &! xd|0Œ0Â}G‰D}Ž@…:Fh¨Ï¾þd:Þ}Š\©è>áS¥FYlWDำp„|ò“Ö<Ê·æ1„¸b&ø¹`«DŸThcˆoŠ -iŒ×m*‡ùHTÔ%#„2¼|ÐÊ;!óñs{)º¹).Xl¤3™„ZËÅ%ò~F¨†pÇâ¼ú€ÊÏ@Ÿï×Ö¤›U*& ¤úÃ~ò^´$ -E™Nn2îGÑù ÀÌiü¯s°+Å•—¢½Ž½ Ùßq7šžtï|,ðÆXãóØEìÛ¾Ÿd¹âæ[Ëê崴‡èé)6ëF[€ÕB¼]ÛO©¼Sò)WޔϹ”Ðt<G\É|s$™Üëëeß­æÜ°V|ÍÙŸVHÓŒ¹ïø¸B.ßY,€ÿñëâçèo‰+MÚd”ûJFñD¿P¡ƒ‡¾Öš¤ô>|!¹GwÉæy$|¶ Þóè¬&ÃfäÞåtþ²™[÷ÌéL&Þβ„]Õq©Ö­BqM€V^Â=KÄõþgÌW#§‘64Íδ9ÉC€ä^ª÷©Žõø^¤ñ&“&Á?.‘Ê‘ò"Rëäž¹À;f þÇ QJÅÿ|ƒcÚ„˜.Tò¾®†‘gæJ€©1•k.<ëõºYrA!âÇP”É(Ck™h% Ä/M§ÏÔØö,þþ\®ÜH=§¤~fÈe/ˆð”£ñ‹·xóßós˜nF‚K&ðê‚à&‹†"bꇋö!ÚRÄ6ÞÓŸþÂàÄ+â_øÓõDLøý%:HÅ$]é,V}ó%)SQ53㯜_üÚjÓÝrѤ<è:MÉ ‘(¾”¥-m¯zžÎç­~âÍ„ ¯¤¿‰ÅVpD -™ÓßÒŸò½S£øó9†þÈw"·óxàM‡"žøþ»oå3Q‘¼é·»PÝs¢×@æ× aßÖÁ4ä_øF‡û‡”°n\Š#ÑÒÍLû„¤Œd`gó2/‘]¿­º}øÓ(@“&R‰ïy aÇ éÛý]GžF“¿*òËÌö›qä¦f‰†’’eê´¾V¢âØ0ÿ¯¹ à -endstream endobj 10 0 obj<> endobj 11 0 obj<>stream -hÞTP»nÃ0 ÜõStmt4¼äxèµ›]‘hW@M ´<øï+)N‚ <€GîH¹o-Ùò‹î0À`É0ÎnapÁÑ”«ÃÖeÔ“ò £¸[ç€SKƒƒºò;çÀ+ìNåÛkñò“ ²¥v}ùsŽD·xÿ‡R€š Bîß•ÿP‚̺Ù¯¡Ê}¹Y;ƒ³WYшPWØ\É<ÏnŠË ‹ëfQTÇFÄÝMªtÌ=^˜c¸|qŽÌ-áý)Þùä•Jü 0fdi` -endstream endobj 12 0 obj<>stream -hÞbd`ad`ddò ðò ðÑvL) 0q6q5µ‰ŠþæËùÝ÷«ægëyþ+‚Ýßy…@ÜHꀀ‘Ÿ™‘‘IH‹ïû¢ï³¾ÿmXñ»Ärj.+ˆr@tEñâ¼¼ââ¼¼ÅÅ+V,^¼BŽ ÀªÅ'c -endstream endobj 13 0 obj<> endobj 14 0 obj<>stream -hÞìÛO«+ÇÁ'àûÄlf˜Í+È:AÙ½Œ ÖÖÆzg6Yi“¥ !Ûƒ÷?€£p Z_o´t6ƒ áÞ…!Èp `4' ƒÁp¦¸‹vWÿÓ¿sԭ硸Ü#u—ZUÝ­î_U?>p6»ÝîEƒétª}ÆêîîîÅ æo-—Ëõz½ßïµ'À¥…K¯–˳ív«‰FéÄ<¿"Ü]Jõ.'ÏóÉdÒ~=¦•Fé¼y~n0×뵆¸„p¡Õy=–繆Ÿ³çù‘>À%ÌçóÎ+±,Ë4Àø\(϶ۭæ8£ý~ßç2l:j+€ñ¹\žïFà¼V«•™7«)ÏŸN§ó.7’ëõZ œK¸Bë™ç/—KÍ02My~x½ÏêÛív6›5ÝH. - p›Íæ ‡%ó<×hcrbž„[ŦH:ja€³X,µW\MWbY–i4€19=Ïl-¦…N—çyíµÖd2Ùï÷fVÜ‚³äù<àr²,«½ÖZ­Váݦ)úÛíVÓŒÆEóüÉd¢…N×”Øïv»ðîz½®}w¹\j:€Ñ8Kžn$k+Y,ZàDM×ZÓé´X Ïó¦‡%Ã[`Î’ç/—ËÚJÖëµ8QÓµV–e-À žç7Õ'ŒpŠÉdR{¹µßïã2ÛíÖ%À¸5¥ñËårÛj½^¯V«p‡Øôp÷f³Ñ¼' -]µ×Zóù¼²dÓ…Y¸rÓŒ#ДçŸh¹\j[€ÓÍçóÚË­õz]Y²ež†fKäù¡N pºý~ßtÅ•çù) 08çÍó'“I:U €ã:å¾i2–e`è.1?±Xì÷{m p¢étZ{¹µÙlj—_¯×µË‡z4&ÀÐ]"Ï7 àtÛí¶é‰È¦Uò<ïÖ®jÓ¤ƒv¹¿kn$Ã2³Ù¬=Òoz€yž7]_ív»–›fõ¡N 0\My~ÿ©õáÆ0,Üôd÷t:ÕȇZ¯×gv2Ô©a†ëô<¿°ÛíÜ9œKçSGujX€á:WžßRÕb±ÐÎýµÌ”8Q¨Yó Ôóüý~_[Õt:ÕÎý­V« åùËåRó Ôóü éÎQ;ô7™L.”燚ó<×ÂC$ϸ*ëõúÅ%…ú52À1Ïßívò|€-‹Ú ªét:?DX¾¶žÙl¦‘†èŒy~Ó½g¸ÔÎ}ì÷û¦ ›Íæ ªZæZ„·45Ààœ+Ïϲ¬é†qµZig€>š®©&“ɵ5MÑ_.—š`pNÌó·Ûíz½žÏç/š™ÐÓyø–Ñ<ϵ6À°4åùç2ŸÏ52@Ûíö¼$ò@OËå²ö‚j:]çb±¨­s6›ip€a¹hž*×Â}äy>™LÎ~MµÙlÌ»‡ËåùËåRóô´^¯›.«öûý)57 ¸Z–Käùáž1Ë2m Ðßl6«½² -¯ŸXójµjºfËó\Ë ÅyóüpWnOœBpkò<Ÿ7Øl6'V¾Ûíš*ßn·`(Öëõü«Õêî­,Ë­¢ö §‡‡Wîó,ûòåKí×ìÍë׿úégŸ|ª)àš½÷λ¿úé‡ïðæõk­WÎ5cuÿÕ«WÚ€ýâ‹_ýÇ´(ŸgÙÃÃ6«õáûx f¬Þ{çÝpÖ4¹¿¿y~(ï½ó®9¢pµ¾|ù²x &¹Zcd>ϲй¿ûècãª4ùÝG—#ý"PúÛ×_k¸6ÅAúÛ_ÿæ¯_|¡AÆ$Ž®†ÎýòåK @ª˜ñ›©>\¡?þþñ ýðýÞ¼~­MF#thù ì) €‘ùêÕ«ß}ôq,ŸgÙ¡å³O>­Íó¥úp!á ‹Çì¡3±Ã!_9Hÿò§? ~¯Ä›×¯Ë'äCWOGWîòðð aÆáó,kIãÏU>|ÿƒCSG Éï>ú8\á>tõßþú7•#4¼êü>»¿}ýu¹_]=ô`zúÕ¹£ñ4y~Œ•L…Ó˜çÿåOn:B¿ÏëÄ\ÔEóüPù—/_jägqézïwÃZùÓŸ4&‚Á‘ç•2-ÄG08òü±rB …øGž?VNÈ´ÁàÈóÇÊ €â#yþX9!ÐB|ƒ#Ï+'dZˆ`päùcå„ @ ñ Ž<¬œ®ÄÝÝÝ‹·¶Ûíõl•øèP¡ûŠ~ ª5xòü±rBnÙ~¿ß6Ëó¼iÅÍfs÷Öz½•t~Ðn·+–ϲ,ü¿vyþÑBOµôcKõé—Ê–,Viê&y>ÏNž?Vò|à–ŽVm`»Ùl¦ÓieÉÕjÕô»Ýn>ŸW–¯¤ƒòü£Å½Vm®Þ¿_ -áõårYY>ì é(€<Ÿg'Ï+y>pËÒD·=Ï_¯×åì7˜L&ÅŸËå2­·ÛÅf³YX>Ž„?+ѱ<ÿhíã2i®~P¿<¾ óÃë1ÃËÇ?C=•H_žÏ³“ç•<¸eEžß3wÝív1òÝï÷Å‹å¤w½^——o)ñd2)Gôqšwe@ž´¢éBoöYøÐ~ ‹EñVVŠFãàN¨­¼°<Ÿg'Ï+y>pËŠÜu³ÙôY8Næ¯ÌÇÎó¼˜ì]Éuc>Ÿ%yZ¬*Ž <Êóëõ:´I¹‰Ú»fµZõ©öÐ~‰ùüb±hªª<”#ÏçÙÉóÇJžܬ<Ïûççûý¾iòv°Z­Ò¨¿˜^ ù ›Í&”kóüíÏúja3еÂw<±•ž1>*Òõ>ß½xD¢g~~h¿ÄyûéÈBÜ…ÊQmž\„O,Öê3¨‘<¬äùÀÍŠ¹kŸ…³,k™ÌŸF¸»Ý®x¥iÒxñî|>¯”óü<ÏÊŴÿBøX MƒãGo…eÊk§¤úƒÈóûËÑ/E{Îf³–,ïE•!ì9ÅB¹Gjóùòþ­¬>¨ò`4‘ç•<¸Yëõºižvj±X”cóT%nÏÿërà˜ç‡UŠ ç©ðzebzܲÖd29: -¾þ:Ñgû¡ýÒ™ÿ§OU”óü8·¿Ot®„Ö‘K'yþXÉó€›U$±“ÉdþÖb±¯4åÞEÌnª­˜Mgqǘ·©Â˜ÙÆ|>®RTUž¿Ùlâ¬ûJ°Óã"Ìß"ÆÚá£c:Ý4½¼Óõçù±æ? M××Ú/±ò¬!-F…Êq•¢+=Ç\Ò)÷cø7~ñ°zèô8ÐgØ‚'Ï+y>Àà„ÛÀí/¥ÚpǺMq·ê wµáF8¦ñþ:܇6ÝY× -ŸnœÃ-pyªa¹´„-íMV «Ç<$V¶Íì•¡i2êYv¶güŽa»ûY9l9ñ@†¢itøihš;§ß§*óºÓé÷é¼îøJí4ìp:Š?aåSSLƒðÒŠ¿¤ÇMí¾þäùc%ÏœKäù-3Øû$ÛMÉl6+f/—ŸyoÏáËSéÊâDè¦í,ϻ묭¼m§¤ã6Ö Ô)y~LMÓ¸eît1\~bŠ?ãÏPíÔciÐ9ÏóÊ*-gÝ4Žî“÷©¹Épóüø8C¹×í—Ø¼MóÂë•YG÷Hgžß§fx”ç—<`p.‘ç7MW.¢Î2ôߤÅbQ¹GÞívéb•H$|Pšü‡ÛÕÊ„›åtƒÓq‡Ú‡BýY–•+ ÿ·áµ#1ݽMcÍóÓOO;:ìw%éw—çÃ-H“ÕÎyÝ•U:#ô´Â[Îó[¾ì)¿AG4re•ÎæM+”çóìäùc%Ïœ³çùiî] ·›f£Ei˜ßãËQj´f wiòþìü¬°LSD¿ßïÓ1‚–»é[p;yþ釡PF)ýQ‹lí¯Iü=ç„xÂiú9+~ËÊ?7}R÷b­øÀc¿Œ7|‘£Oz#ÈóË× GôKûNÚ¶õHyšAçHØæ³ÿ.3Jòü±’ç ÎÙóüøPy ½ã fg>ÿX—޶Ü`¦cåÁ‚bôùjñ~6*?þè|ûÚùü•§ Ú…ûñmIü¸PIøjóŸ…ÿWª-žQ,°Z­6›MŸO õ„Ãò±òPIh™þO´lÛAÝV ûIQIøOø³eú'êEË”¿`gåíûjî9±Ëb¢ê/wel“ðŸâ•ÙlVy<¤ÒéÀÐ¥á|ùÅp^JW©âÓì=ª|c%MQsí6ĪZ~²[¶¤Ó óü4œ?¢_j³÷BœcPþˆ£{¤i–BŸ-2yþXÉóçìy~e¢ûr¹\¯×•h¹gL³Ùö,zþKíy~Ëçîv»JUå(5­*|¯Î¦¨ m:ïºÒÅ}ýjµzQ'~ñðŸJÄÕ[¾þ~¿O·¶²z{ú*oª¡ÈˆúäùE/4mÃl6«]«Ož6¯©é -Óé´ç¨Gô¢KÜÚ¦é÷é~噫˜šVÆéЇ¹Ây»rŠo…˯Ç3mz>ŒQäç™J=éZå -ËçÕÚÅXíqÏ 7Ïc¸•ñ‘Cû%^¥ ?¢|ISî‘Ú¹q­J…í(ÆjýÜÐIž?Vò|€Á9ož¿ÙlÒ4>Ïó–Yôi6{ô=f–;Ô¶RŸ‰Óéýƒ¾Kšç·'Ò¡©Ó¡“J^é‡í¬h5¨ÕVf˜§Ãy~ûÆ·lCgžß¹y ÓDò| "œNk³ÖxLO2ñÔWy+®R9éÅçÅ*§ô¦zÊç™ðVåW ¾[9۔ϫáƒ*_*~V: ÑÓ•çùÅóqéëñ‹§ƒ#‡öËci(§|E‘+ÑÞ#ñÝ´GâZá­Ê—*ÿúŸòÀ7Bž?Vò|€Á9ož_‰mãóÝqrZçÓâu1i¸«Í²¬6$i‘ƼEdn®ÍÒíé¹bq·~\óV¶¿3rO?«iª|Yÿ0¿%Òo™Tß™uz†ùµÛЙç´y-ƒM;ª<n\ñ#8›ÍÂÉöî­ðŸxŽmT§ˆp/ÖŠ¯Ôžâ©#Ô\|PüñMãÜbáðÑÅqøˆ¸mq 3¬Õ”ÇeÂGT¶íE×t-®<Ï/~’B[ÅoÄÙJ\¿<þòÇ«ø òÞRÙ¸pñ)a±¸måK¬´Gâ®UÔ¾~±Vù‚-½6€”<¬äùƒsÆÀàœ1ÏOoùã i|=Êšojsì–l¿e“:ç?—ãÓ¦Ûít{úßü¦Ðÿ‘öôs+Ï5Ôå†Íó<Í«ËADÚei|”~J¦)¤QI¡ÓĻҕVJ§>¦ÛYžLØžçW>=‹I¿`Ӟг›:²tÿé\Šp)†\ço…ÿô|¾,œLÂùªX+œâ:,Ba±bù°bÓð_1nß –×jú -çù•Ï -ßèˆÇÜ*ž1> -_omiÞÐq±GÚ¯Žè—(´dø òÞRÛ¶¡Úbœ·ügŸ)ÿö•?+8âÉGn™<¬äùƒsÆ<¿2ñ¯2¼’ú†?[ªª Ø$|P¸«mº“­ “›L§ÓôÖûzòü4I¨ÌµKç–§-YÞ€J§„Õk›1ÒKGj*i!¥_ތʷ¨M?ÒÌ¿¥¡ZöðÚ¾«l^vÈ]ª<ŸJžvâ£'Ó4– ‡’ç•2Ààœ+ÏÏó¼=×MgA·Ï -Ûn·iÜÅ7Mœ ]ûŒyËtýr¬}=y~g÷•g­7U7 ÿC¡a›fà÷œÜž.7£Rye(J·6~ÐAy~¨?Ǫږ4_QžœÅß¾þúó,+Ê—/_>ïÆÈó{ -={-|©+ÜBy>ç"Ï+y>Ààœ+ÏOço6›òýÓã²ív»\.{û“ɤi–~±…‹Å¢g°_¾óPžŸnXKž:¨O_¨´[8ÿé³ÿ¤#M›úú®AÓÖÞPéŠñ ‘°ña¯hùÖOÖMò|àó,‹qÊï>úøy7FžßÓõ'œò|ngoç8ò|€Á9Wž?›Í:gYW–™N¸bÜívëõº3Û¯<Pk»ÝfYÖ™íÇ)èéHDX·çf‡%z*¡²ÍóÓ »ÿ~“¦×Sý7£§øeÛ*Ïó>ƒ8¡§*#POÙMò|@ž?Dò|n‡<¬äùƒs–O.¤­7#´aå­PgZCøÄÊqZ*}«v¸!ýOÜMò|@ž?DNn‡½}¬äùƒS´ö£ìJ&\NÔkµÏ…NÓѰ@S¤^oÉÌÓ:lj:Cûñm¤¼\.+ ¯V«ö +>.#Øï÷iø_ Òûx‚íÙÞPµV´mOÐMM‡aùQ`ÜäùC$áävØÛÇJž08'æùiÛ'¸®¬þ¬,pD¤ß”™é·Ì¥?"Ò?.Ì|ª<ÿ &jj™Îþ -Ö¹=#ýétZyt¢³¡ÚÒ‹'è¦,ËäùpãäùC$áävØÛÇJž08§äùéÔît†|­4¹ UU–Ùï÷ý·- H˦N§Ó>õL&“tKRi:}܆µ{²<ÿñí,ýö& --Óþ]Z"ý"!ï¹íãaKGú4TgÍÅwì|ºäBÝÔ4N$χÛ!Ï" '·ÃÞ>Vò|€ÁY¯×wGÙï÷›Í¦òbmH› -‹UVlJÑw»Ýjµjš^ϲ¬2[»IøˆårÙ”Z/‹Ðý'Ò‡%ÃG78´aMÂê•Vêì¾´ýÓJZ¶*ÔÚ¡ÜÚ¡¹Âw ߥOË„eBýqõÉdj‹›tèf”{*lCØ ÂÎptC›jû@ew -Úûg隸‹†¯9/9ôa`¸äùC$áävØÛÇJžÀåìv»íÏš¢Ýž¶%'¦îçÝ0n“<ˆ$œÜ{ûXÉó€èþþþó,‹¥çbåòåË—Mkýíë¯›Ö -o5­Õ´J(a3ݼs•rVöÞ;ïž½þÐ ×SþúÅåøèª¶í òáûÄoñ—?ýy(›ýððàÔÄ¡äùc%Ï¢žAAe±ri™¬^žÓ^)-qSÓ*E°|èæ)ÊÍ–¦c³åxi:0[Žeå¢=Ø¿üö׿)9´®rÍ¥<.Y¤Ê—/_¾|®aåûûû¦Ušf\?:µåÍë×M«„·šÖjZ¥²m®ð€±’ç+Š<_ž¯(Š¢t^n÷º®å²üÀQ¥ô¼æt…ŒÕEóüÏ>ùTž¯(ò|EQEž/Ï8ÝEóü–Û1y¾¢ÈóEQyþAM«Èó€1¬<ÿáááÐÍSy~ÿãEž¯(Š¢Èó®Ö°òü#6OQäùýy¾¢(Š"ϸZò|E‘çËóEQy>Àõ{óúu¸iŠ¥çbåòÙ'Ÿ6­ÞjZëË—/+ o6›»»»ívÛ´Êq›7”"=PäùŠ¢(Š<ÿQžpõÖëõ‹Ÿm6 Â-{óúõß¾þúôê©­ÿáá¡i•ûûûÚUÂëgÙ$¥ùêիϳLQŠ2ô1kåŒå½wÞ•çwn›k €‹úß~øß&“¢ü×bqhÐÑBgÔ2딉dÀÉóàúÉóàúýßÿú?ÿó¿ÿ¢ü¯ÿüÏß}ôñAåÍë×Ú.m>Ÿ¿øÙÝÝ€+$Ï€ë'Ï€ë'ÏžÑ~ÿãrùÝ‹ÿ¯(áÿáÍ)y>ð\v»&“ob˜_”ðŠHRò|àYl6yæe6{£} Bž<½õú_µI~,«Õ½V€2y>ðIJìûö0¿(›M®­ ’çOi¹ü®O˜ÊdòMžÿ¤Å  ÏžLÿ0¿(óù· €´Ûí¶Ûí~¿/¿(Ïž@žÿ4›½9(Ì/ÊÝÝ?µ5k·Û¥oÕ&öåÓÐ^ž\ÚÑa~Q¶ÛkCèo¿ÿ15¡ìv?hJˬV÷óù·E ÿ¿»ûgKɲtàhEö¾ÝnÓ·jûöwåùÀEív?L§?:Ì%¬žç?iIh±ßÿ¸^ÿk¹ü®r¸ÍçßJõ Yöý‰'¢Í&׌Jž Ån÷ÃdòÍ)ZQ‹hLH¯,û>íGYx׈Øf“Ÿ~"ò¸G烰Ýþû,a~Q²ì{M -=3üJY.¿»ñv;ñ)¡ò,};!‘ç?¯Í&_,þ1ŸÊrùÝ~ÿ£6Ôzý¯žùØlöf·û!PK†Å4,7(üÐÜÝýóÐ ßásÄé¨O }aŸ ?yþ3Z.¿«Ü×O&߸µ‡ŠƒÂü<ÿ)¬þíÌ*ãÂp;V«û³¤Ðóù·7ۆ皜÷ˆ.'Üçn6›»_ -/îv; ”<ÿ¹dÙ÷Mw÷Óéß·Ûk"x¬öj ˱X8ˆ:W •kanǹÂü¢l6ù ¶áy'ç;\BžçY–Íf³­&“Éb±X¯×Z yþ³è„|sö¸qýÃüÚ@¬OzFíÌ-ØïæŽÎ#n6{£µ·íöß—H¡ÃÁuSÏ‘]hr~Q6›ÜŽ -pŠív[žrŸeYí¤µh·Û…ef³Y\Ë,}`äùO)Ïêœ-l$<öŽû<À²Ùäõ¬V÷Úœ»\ÝòtÌÈtNÎï[l_=ô‘à‹Å¢¸Ͳì Ãòq@3×o~šÊc‰òüv‹Å?N‰MÂÍþvûo͈ƒ¥˜Ü:ërù]çñåàb¬²ìûCg݇0¬µÛýðØc,àFŽövè“Æ¯V÷î.§¸ ],G¬»Z­ŠÕÛ§ôŒ<¿EŸD±OY,þ‘ç?iOF¬s"ëdòM‘4öÔçјP§#‹ñ {uØ·ûŒ‡©˜á—u>,3Ÿ;úf¼»ûg{#ô^ìì g!€£m·Ûâ&t³Ù±ú~¿w Ü&y~“õú_g óã-–}¯U«öèìÐ0¿Vé<²n!–äÖtÎ  ì÷?¶WöJÂo܈۰3‡ïêèX.¿³Ó!æùGO°w Ü&y~­ÎÉÇ•ùüÛ#RMžWžÿtw÷ÏÐwE1.Sk:ý{Ëžt£…;«Ð;ÚŸÑèÆ -ÇZŸz:™ õŒxbyg~åû×Ö~~ Å/;Àbž¿^¯XÝü|àfÉóSáÆ¼}^_œ!Ù9‹ò\•yÆa6{SéÄðʈs°#l6yûnJs-ÿè<¬SŒFç¼úp¸õ¬ªój¬cagœœ_è<ÅyPà8ÅMèl6;bÝpëzâô~€’çWäùO3ñBY.¿+–¯Í{oyV䘬×ÿj -…âÀcWä~b[õ9$ÃèF༹qg¬ÞÝï_3žwr~¡sœåˆ:X,Å}høOžçýW̲¬Xq2™hFàÖÈóËòü§>á|X¦²b–}ßgJÿègEŽIçÔVMTØï¼tÌjè<¦FKrk:‡®}%ü6õ›³OÎ/„–ï©·j·ÛÅ[ÑÉd²\.7›MK°–ϲl:ƵŸš¸5òü²åò»>a~íìúýþÇöYÊ'Æ2<™žÃ:fcڧž+ãêœp»ZÝßòî}CÍç߯$3ìÃáEûçh¥£³÷γÙÈNe—˜œ_è¼BȲïíÆ‡Z¯×/êÌ©œáGËåR—sÐóƒOIžu†¡L&ß´çð›MÞ9Á²i’?×`»ýwÏG-ŒÈÚwøõú_ç;Y}Û~lÞÚŽšeßÿöÍ/ÄŽì<ðzôCD*a‡! Å&Æ,¤À;ì—ÆYðîãZ{`½YÖS/Æ »‚Ç ˜fÈ,fm‡‚dÿqÏNU´ØRÆÊÄÓ‰Ù†3šY:Es©ò¢XL¼Ñg§ÜËáγKiÆ|XzÞîKqÏHÖašë´Dg¤Ï èÁ"åÃF ì@ЧÒä|Žt =Ö ‚ -oÓÃá^¨Wƒü²ÒëÂKý ‚ ˆá0‚.ý_‘•-`YSúðÕqœ¬-zÞùü ˜ª¸²|IwREÜ=ÙF¢h¾TÎs隺¥H%aéYª=»dÒ—&õ£ÛûZ4øëûQÁKHË;£¬:9ŸoJ¢Ç:ADKA^ö ‚ ¢‡¸®ÛG<÷Þð wguunÍ4M~›Q%ÿ°, þäû~͵*g/ôÜç+ŠÜÜþVš.‡çé_èfQ—ùЛ$E9¸=ƒV­¿³òÅÝ4$ gåÊ| -EiK=~XåaÔêpX=Éù iü¥”ÀAQ'ð"¬"7~ãÉßþÜK¯fôg/ÿ!‚ :Cžïa²{á©øžoÛ6ûÆ4M×u‡ïD€KC=Oî¹Ï—¾•3-EóÜ—ºøҥ¤âÖá8;Š.Ô4×KO8o5Ð õgƒC±ølêÏÒ”ï(¸ 5Ï£5;>wà°íQ{›±žä|†t£ô) l‚ ˆrñ}õ1ƒÁÞÍK/ñù8ýëO?ÿM8à›G¯Ì?øÙWß~'õ€?µQל>}úÌ™3O=õ™«¶C]I]IèÆ“O>Ùê®ìÀÿžç±{IýçATâŽãÄ„ý°ƒb@¡Ï>_jÚ™,j®Ä¼Ab)¤‚K4]dAÕ§O)' < ·(ŽÉ¬}ï ÛÛÛë999¡¡Øj¨+©+ êÊâ ‡Ã.ù|×uSî ø#ëé_?|+ã8*ç÷ÙçK5»a\)%; g¸j€Ã÷£^5¾Hs,ù±ººGÍöGH‹9ÎNu—vÝ[ŽŽ©,¥äGj¡K‹ ‡w¥Û7ÚØ’u&ç7ÕwA]%Š"ö®-bš&ÓõüE;‰a1ó_Äç_Ü=f®þüÖ~¼<ž">ÿÚGÆææÑýK{÷6'íØ‚½¹¹ÉtÓññ1 ÈVC]Ù666¨+©+›¢c>ŸIï,Ý ÿ„°;õ<¯ñªŠ[U¶"öÖ竸Ü»4á–ÞýkFjc(“! gx»•ÓóêU#3â‡i®«Ÿì8;´ì4H#9Þx$®;\¤!°Šb|5ï­ ‚è*âÛhL×Ã[¶išü7–eÁÉðU¿Ä ‰ŠŠ¾Ÿ>·†q¥‘버Ì6zÈv«`ž´L‘¯kséÇJG*x—Ê¥‡3U6¡´QáöaªÔà íLbyƒÉùŠÓ¶º¸ AD@:KÍÊÀç™l¥¼ƒã>Ÿ |æç/íÝC|þædvq÷XL×'‚ ˆ¶Ð1ŸÏ2LÓ\Í€ÿ³±šMÕ•Œ%ç+¦è÷Óçã&°R¯%5l®{‹ê‚©Jº²º5í!¸¿ª4Vf -®¾ÛÕªž7–ŽÌe‡eÍm{¤®ô¡g)ŒU:èti@¡O¢f“óÒgJëÖ"‚ ˆÚàÆ^c“õ<ùëâqŠ~‰ï°¸Ïçß»ú(cäæÑ}Äç_Ü=ÞœÌÄt}êk‚ ¢-tÌçóç{*­!ü?cFêuñÿpzèó¥£R‘¢â“)¯²i2ÇC9ìðý¨žúÀHƒ¾nWwKZm¡}jRʽHGfî8£J¤@ fÕ6þ{‹t£V=.ÌU·O­DOÎW¬F· AÔ7© öø_µù|Qàßž>€ß >ÿÜèdþÿxíÎ õ5AÑ:æóyz€¶>‰8††aÖ{èóñ ùÒù¤2Ç4×)K¶þ®¯awúWT@†q¥žëG«¬xMv -T}#Åv8¼«É}2-A!ÝÀ_ëi|­¶Ð:$ç3¤‘bx¦ÓÈ'‚HÂïûÈ_uðù€wuŸùùËãG#ç·&ˆÒ?™?? ÃÕÂTZ½¬ä|†ã8YŸí›Ï—ŒrzáÝÞîuÈÏ츈f‡mj¨ €ÔÈB+ü3®­j€¾éàE ¢’?_|] -ÙJs2»¸{̾?{ý€úš ‚h óùšcÛ¶tw@VbCß|¾&úBV¨'²Ðƒ}YþEÌ Œö6c#þéïФÙÚ%î‰í -Q9jsËÐp›<âßÀjìº·à—¾Á¼¨ÓÍV‡tå¯9‘[šâ®s³ã§þð(¾Ѷ;‚ ˆTLÓdï¡A,ûYþ -œã³I¤>ÿòxÊüü…Ñ!üxóè>âó/íÝÛœÌø“=‚ ˆv@>¿‘¦F°,+õã½òùRwQ§ý“æZÖ ïR‚©T™Â µPVV¶Zš‹Ô¼©M%xZ¬þ“oÒ*nA%¶“•zHߤ)뢅ú8Îô;ÜHë<¿tgVý= 'u)øþ!­RY9‚ ˆ.Á-:àºnVZŒ(ŠÇaŸ2M³ÜšdùüÅãœüµ£ÛÓðýÉü!âóÏoMÄ®Ý9¡¾&‚ Zùüz€fxVƒ”T]ß+Ÿ+ôš#£h.u;ôú_O;ÃáûQmUÒMè)¢g*¯´V:oyð¼q#a&•W¬¥Oè8X—ªrØöHÿ Mxì‰ÝEýµ’nºÑ³1ñ0DýÉù üYÓÈ&‚ ý±,Kå¥uñ蟇Ðu]ñíð}¿”j¨øüçnDˆÒO¸<Öú¿”ƒƒƒõõõíííùœžS톺’º’ÐýýýÖueß|~žç9޳òø`0DQTõuyfB*|"'¹±?>Þ£qwT¿<÷ýHê©ô—Tš#Í®¿ëñ*i›¢‡Ã¬6žÝݔٓ†3©Íö¼qEW‡õPejÄZ²¸„ƒ}ËÚ(EãWt¨¹»›Úk€W¬Îmkê©gKRŠ>ADà•9öÒšõNšÜ–oÜeU#‡Ï¿¸{Œøü›G÷oOœßš¬íÌêÜë9>>¦Ùj¨+©+ êÊâôÇçAKà†Q©!‡`øµÇñ}?öOÎâqƒçy<íÁ4ÍX”¡ŸEsÏÛöøFÏ 4ib#ÕÆU¤Îv7FΠ…g‡™:¨¶#WÐMåÄJÓtõL)×VúIãbz®HR^ÃÜ—Åä&¦ÜFÕ°>”•ß"ùÌ.õ š^mCum¬0>¯)EŸ " x…÷YöÒªâóá6™¨V„>s2C|þ¥½{miü›7o2Ý4›ÍÚRgE¢( l[†™çya"Ÿ‚¡5DÁÇ>”QQæg‡»2uA`99G§ÔÐÀöö6ôãÆÆ†JW€„̶m>ÎáG|ï’Ê(Uo‡Ó¤?,Õ•úL®>ø|˜#†aœBKª˜æ0;àÒ0UÅIŸ/ž2Ó4aš‹¿/îóƒ`S4ð£†Y妹®a¯t×€æ ÆÌá#mkÛ£¦’f¥©’pXÖFývEÚé -4i8LçÙ]]–{n JÒlózrŒa­Æ[¯ y†»€›]öE×½¥[w‡w¥’5¯¶éîY輡@Ú׎O‚ ˆ¶†!“T¸ŒÍGŸ2ˆøüó[“µíññqÇ pEŽã – e¥kÆR7¡üÔ¡ÈÇ\EÑE÷¼+³XÊ7f,öˆçyÒr`̈©¢—êJXMÓDFi–âS¥¶mgÝ£ÊÇYª‹z´…ÖÍÊ>ø|X½¹Ì‡o\×eòÀ`01…^ -©ÿÉ >?ëƒ}~–™¬MF)È»Úú -iv±VJ?¦l/ÆRy¶¦¹îº·êläd˜)u”6x’æEëÓN7Tx{ÂðÓª1a"Hg1XÆa…YÊ™Ãx€6g|~L=ªÎÆGL}² ¡&ÒpFSA϶LpÍc‹ …­7ºÅG‚ ú’wÍ^Þ?øÁJ}þÉÉÉ|þË3Î^?@”¾´>bQYÀ pµTQ,õQE6ƒd9*>Ÿ— -(šR¯õà²EáÖ+V”ŠÏ·,KZ”ëºY>¿þ¶Â#Vbä(iÔsŒÒX­Ô?žÌp¦Ñ®yQ}ðù|‡Ir -ÃíêJQñùYw‘Ïç#Y¦ZüýºñthÛé¬ôó9ü¬¦®!yruuO¥ª ¦qJSôµÚ”¡ú®´†Ãáݶ,GM­H¾5¥ß«8Ùz“µiØÝ1ô—äŠÓG‡<¤ùÚî¹#‚è61—Êúúúk¯½†²··çlll°d˵#ÄçÿôŸßQ/*øœ§ÁÉT”bQ¯¿þº(óÇ¥+üõÙgŸ=}ú4’bÍ ÉÓO?½š—õÆo<ùä“<+8™<ÏÊÓ>ô¡qKÎä†ä•W^ɺÜp8äAÏóÄ?qS -ßdÝ \‘ÛN¸õ`Ž¢ë•,*õd^_b]+ -†Sì|îókn«¯}ík*I¹/¼ð?-k”ž9s&«Vb~òÇ>ö±X­’Mº¿¿+j0$cÌã7˜,**J½¨ÍÍMiQìœsçÎuÛçû¾Ï&r”ábgÖÓZù|n÷ù¸è{≷©UìL©åËJ)¯¨Vp¡’u-knœÅ} -Ú•o¿¸„Š„3w>Òýÿü™ŸÖ_«Ôq¥(úšõùÒœØWÿþûü ˜J§UjØ®ÎUô³Ï¼Ù „‡öYYÙ‚Ã4׋—CWTúõ¯íÒ½ÐÚŸ ¢aò¤PÅ(æçç;ßA -a)Ž›››óù£÷—ÉlŽøüW¶"õ¢RáÙ’± p**«¨3gÎdYúXQpEžkSܬ­­!µúÊW¾’šü,ú|äa óÇΡ\ª(•ü|^žŸ=ȃeYHQ| q'5?¿ž¶‚Í -ßøÆ7ð¢ž}öYƒH¥Ï=÷R+Q0Æj•lÒÔämÅ¡i½ª¨¨ñx¬R”J~þ+¯¼ÒmŸÏÆrßJ*Y;¹J§~ŸÓ\_4íóß~† ´/=ûtðù ó“ªôK¯UÎkRâá8;ÏÿùbÆUÑ®À§>þñ«_ë‰'ÞŠ]¨)ç#MÑOæi×P«Ø¸‚ ‚Û×Fj•:Úq|æOÞhÜç[ÖÞãÜšÖY«d~ûÅ*îs)7º‹‹îq` -ü…w ágŸy7¿o]þÝß{kY¥Ïùš×vߤkQƒOœØ¸:ÿ7?TYŽšõùxl1ù4ojm_çìõƒ,Ÿï]ݧžªÑsª¸ž<ëtnHðBø D|>^žüœz!ø¥çy,hUMî5è9K­Y'óä®> ìB¸óç]œÚq0á÷<àèû>Rf ‹[‰µU¥xÓIÛŸ§7§ÖF5ŒmÖP0ÚkP¦„ -¥?auƒ|¾¢ï6ëó¿ðÅ˸êI:ä¦ìJÍ¥º/©ôË­•çkHËÇ,ÏüÉ0®Tì -ôÝgŸy76`ªÜ;T˜ å/;J¡Î©éýêíŸö‚ßóx–Üâ}ÕÑyŸÏVïä¨F&~¹Q9i³çðù_þò—áµ”w޲>ÂÏažËmÛ£“““ØGøñàAú8põÔóÕkÅßú­©ÞŸþiØH­ MRÏçw¥ -(¦ô˪Õ÷‡{ð×4ùIûúÌ3ëçßÊj«o}k7G -ñK/Ý®´—íùRô«®W0*Ô«W[­²z0Šæxmÿê¯nÕ_+4”T>ýëÿ\s­¤ãêoÿöê|ðtðýBs0¦Š &Ÿ~úzk»tjÃí7þĉ+XT¥›qê¯?ð'TêÓ¼Áµ}¡¢¸Ù›A‘ -¼b§šØÜäöù—ÇSÄç_»sBUŽãàJVEŸoÛ6;MÔ¤‹e|>³¢¿å‰âYP3£\Ÿ¿ÒïSKø³|~ª æ†+}<íŸWÏìùV<|”ÂTâñˆ|íÏ£lb؋Dz΢R:ïóy Jú°`ë<,57{ŸŸoÖø~”CHÖƒÎuË"¦ŠMÌÒ/ˆT=5x@k8ÎÜlÍßçwñ(’J2¹6+IÎýzÀ}ô‚ní‰WضGMU .N “Ñ|Ó-ë0ÍuÏ—µöªokb³‰/#•"Í͆Y¯áÓÀ—£:¥7©†í)]ÞµõA=dYŸíÎÉ¥½{'ó‡·§Ÿ¿¶sDm[ܦ4ÞRŸÏÒ°³ö(šR®nD1Ë ÅŠYÊð{>jážPºÏ}²Ñö§ŠwþKè) ž‚~ä#_^T|>7áC™*£Ôó<¶×¾&ÛD±ýùlââÚ„; ø`†Fãµ¢¸Un&³ùÍ£û é¼Ïç#“ ¬sxŒ‡ªÔˆÏ¼¸a’««{ÍõÑ–žr§N¥×R·aˆ›‚Æô¼ñpxwñXb@ÅŠ›j?¤-’ùŒ|)ú5 h ʽì5ð®†)­•¶v—³»øü…ÉË–ˆrG.á¬K5(}i¤ÁÇ"¬“zúgm+†#]Þ5\E ‚ úÉR>s2cºþÂè~ô®îgùü³×ô¿÷ù|>wwwÇažMg †Yj…ŸSPwsCbYÖJ1¾O^KÅ”ÞÔbæ3×G©J9kG@¬+³®ëºß7Œ¿œ™ïQ4Ç ‰¢ÃG*rœÅ©îXYÙÒY–j›¢‡Nšš×R4 /Jc[0´ŸâtÎÒæ0ÅRBÐàpˆûk®± ¹—Màf¥ж—µMƒ×vãŽty×y0AôŠ¥|þµ;'ÜØÃF‡HŠþdöè_ “ùÛG÷Ù÷º±½½½¾¾þÔSOinòERefYJ4$80lŸ/5¥ISÄÿšª‚ `%dù|Ö•ÀÉÉIò¯®û}ÍM¾x¬¬|ï¦|#'µ>ëÅ$ü÷7ÝûR÷S}~Ö~ të»T79PlVW*îþP_ñ¤Ø¶ƒÀã)Ü…&kË/-î@‰M@ žŒèÚجYY.wÙsçüÖ¤H9}ðù !´„G‘9[.Mù|ék#ïÚ¸Þ±¬ ÍG—¢Ò‡sr¸©áð.®=³Ì´*îð3fʾ4aµŠ*¬sÔ†£aŠ>Lê–îwÀËõÛ3if»¶©Å­C*Ò .›ŠGºnk¾(áku#ïYmc‹ JÑ'‚hKùüÉlÎuýædviïâó¯ÝyäpÎ݈à{ï꾆Jssóõ×_o‘ÌÏrõû|&íc¶GÝ”&MÏg†ord„BW2s˜š Ü"™ÏŽ0Äœd>?æí91ÏŸêóù†‹ÜVM,vcc#µ+ë÷ùl &CHêeÚó |hÏÚLiƒdueœ½~@ùùËÞi,ö„/ïUW¦Ÿ¿ÐOžKmd+Þ «PúùÒò¡‹ë¯0œ­®îåˆ#äÛ>ЊœgÞ2øíÔŸ¢¯aˆA}„ã³Æ÷#}*£sK¶XØÕ7Uñ®®¶=Ò¿ u“熖Zð§¥èAp|߇Rx?µ,+öZ ¿´mÛó¼Š^®—òù‹÷k“›G÷ŸÏ¼ -ÿñòxªS“?âðððµ×^#ŸÏá†D´µ"0a(rkšfêXB€îºnÒØÇ|óYÕHíÊíííÝÝÝÔ¿¶Îçö:¿Tw+ú|èYöhv±»c¿Lõùb¿ÃØpg0,µ^‰Å²®ÜÛÛË:§,ŸŸUN†Pq)ŽÅ8T¢0€“Iø0ìùÜasê·œ#€Õ -²º²tbæ"EuÌçóÑžu u˜°\ìØdó·æz6èó¥B²æŒDÜFjžÎ'RDéC§@³Ã­‡ëÞZYÙR—]¼døl¹7åû‘mª“ùp§Q¤ãnV<"V³õ•Zèúã %6fBUjwKŸ\„âšYÅH†KK—ÓV,MZm¸“þw¡DLºs¤EÑg‚ ˆŠ€÷PÑðH3¢KÑ^Öç¯í1mrîF´t}ò`'œßš°/Œõì$GQCR»‰»Ç‚A©ÏgDQÄM+•:˜Û/â_<3¦µ“n0&îÔX¾ïóñPÊŠ'¥|ÏH,;ˆï…šºà0· ÉÖKýýåñ”?w -^¢o>_ôù Y]ÍO‡k—C“:"nŠ  à°¬²Ä8”V*‰¢¹çña£U…+E«ýö&ç+N™zê/­,S­ <µeÍT_á̲zAºšµEÛâq(¸ÍÞV&7øÿ$m ôATAEÉl|àS%æs.ëó7'3nN&³9×õ©œÀM‹wUÓMâA¨‡TšÅ4ÍT£ÅÅc2%8 .Å}>ày^RuÏ † %§Î è£ÜÁ¬ ›æ‹­ù†ñ—xrþ¢2ŸŸ´÷IßåóÓÚ¡„TY-ŽÛÜ>Ÿoëƒ&P¥üб}(Å}/TŒÏÙІôpL…­N°$F‡ì)Ï£‚W!ŸßÍú|ß4q€Ò\¸Ö)_é•~Æ•ÚÔSÍággÙ½15ZóÒÑ$E¿íÉù \çÖ“¢/µ»5ç9÷ -ÆêJ?uÓ²HWi¨O[ZO«”x­6 T7pîFÄäÉÚÎÑÍ£ûˆÏ‡‚l¹´wº¾ -DÙ¥¢:y&¶˜·¼XÆçÃP¬ÔçÇٲ†}«©Èç/ÞŸŸL×_¨ù|‘ xDYè‹]jDQÄï]Ü„¢>JÅr·¿"lgJêvBÉü|ñ4¾ðo?)´Á|~#4îó=oÜø«÷px·KRE¤¥}TµçT$ g0œl{$Íiì’‘êÇF/®%ëÉl/ŽÔ¯šæzu#J–ƤŠ'„¥Ì©R4µô*­‹#k"Ò5 +”‚ôŸJÑ'¢‡0o–TRà|®ô“Tqrøü‹»ÇLžœ½~?">Ÿ°¶sÄ~<¿5¡®¯.7bŠ> žçÓ§ê>Ÿ›U×u“c)‡]a™Øbi±a¿ì(í0Õù|Ñá‹n?ÙÅ|„ð|û,]ÏC?ȨPôù¢ô}*ü^b÷¨>JáŽø®Üí«RlÇA û A dÿêyôOo/ΟZ\,´DÏo„Æ}~Íñ×Õò¨q¯ÒöœØJ•¾m4tãP%ß [cz¶ÁMÕ!MÑ7ÍõfX‹ÂaRÅZ ”îqhé.¡–²Ô² ψe—Aé^Œ–¦^㱞æÒõ°u<<ÑÆ;"‚(Ϧö?>„Rר¤xç]“ÞÉõ -YîÔÓþù5 Qúâ•©8J¡pöŠ­´E|>û ´ 2 àº4ȳ·dÓñýbO?dþfèû˺VšNœY¹©¹‹ñù ™C³¬J[@úú_ƒ‚¨š*”¾i®·ÂÓÁÔóÆÐ–R ]i'žUÞ®p˜t5¨(I®‹‹Ð–ÚÝVãûÞ)±õPe`À9®{KºXµÚØhpwÍ®W t¤)úé#¢WðW×ÜoÊ%¾Ãæðù'ó‡ÜÏßž>¸´wñù×îœLfsþãæ„¸UÁ»’õfR| ®(á›äþnH<ÏK;P‚hQbéôE|>ÿ¬ã81¥?r½\J «íTçóB"tê& Tñ.›Xiðq©Aö©û| â†ÆŠ…mÛ΢±‘–:Èaâðñ–§Èí{ùÊe&[ZOë'¼;`p&ÿÊ.þÄ»Ð'wðtÕ硆zêàóƒ`Ú`~/ž[unsm”«ô]÷ÙE}€¾hÊw)9_eA¨(ÂhÛ£NÚݶÏ&ènÅUfYVð7 gЃ*¿í›ÂOo|ƒ@PŠ>A§í>¸vçäüÖäâî1|óè>âó×vŽàœ³×Øì#DEˆ’w+CüeVnsì489&Þ‹øü˜§…Y} |ß•Þ7*õù<‡<µÁSÅ»èâLÓ„Xßá^]Zlbæ<¿(ä±`Dª_ÊpBÉ™RÄsŠS Ú‡54¯yj ­Ïˆ+Cê(bå/¼}àôÃÇ>ÿÝ"—#Ÿß[Ÿ¿½®V—~&¡•&6×>&÷ú“–ß7¤[Ñ$êRr>_¤Þµ\».Í¿íLT±ÀxF[²Lã«G*ÝRøÓÜuoUwi<¼Ïú–6©4ç¡ÒV%‚Њ0 UW¾ï—˜«œÏçÇ@|þÙëpÂÅÝcöãù­ €Já³IŸ% }¾iš©þ¤ˆÏ_¤yZ˲báƒÞR©Ï‡^àIæÛg‰wX‹#M8_Êç/;^1XR²ò±ká° Rê+â9¡@¾a!õ¢©¶>#­¬Æ‰þÁÞ`ÇÊÊõ"—ëªÏ_)@ õÔÄçK³|+J?ƒ·`üºËBwœee h«–&7ö©….]v/9Ÿ!ì†q¥ÄIÚqAkœ¥‚¡¶=‚©!ͩ•JõꞪ †ªv·wCADx6æ²öFÔA¥¤q–âó/Œ¥?™ÍoOœ½~à]Ýßœh´ëàà`}}}{{{>ïÚ–íÁ``Û¶˜® ýëº.>ÞàS«(žç!% ‡CvZî'0¼á㢨1 nDºêpW¦ÎYF‘“Ù/S–$¹Âð.Nþ ~ã8Ž(«aøÁoTƒX¬zWÂÉ0¤ÅÑWd£ ýðk!àu^ªý³&T[Œ^Á0¹:±*eVòÀ ²=ÇöW>ÿöKEêÜUŸ¯y=5ñù ™Ôª"O^jíªÛÐ ¾‰MmW˜®‡›…F†šŽV'ˆöèY|<—î|ðÄãVg•K#_¶=*åBž7®çBDñù…oæ*å¨Tw×ÞPÅ…ÃpÖHV@=àwG>Ÿ ˆ^!戦ʱTƒ7´eeÍ•âó/§ˆÏ¿vçDÏ^ØØØXÌññ1ÉVC]I]It¯+ù^¶ÔÝ"¿ä pÿ½÷žÏ?|ËûŸEêL>¿-TäóñHøRúà6²í¯ÿD‘¦û~TÖµ¤á°Vïæˆ¢¹TÞoL•«Ð*¤A0•n¦(xtc¾ñ ž¼õ_´Æ 2zÞ˜¦'A½BLdeɇ®ë²ÔP–2mÛ¶˜Ì ß—’œ¿(Éçßž>@|þÚΑž]póæM¦›f3úOµÝPWv†íímèÇ êJêJÑ®gn^¸¶jþfÈ|þïœú_ó%·¼!Wì@Ï_–(š×):ðð%¼m$¦ø¨.1g´:9Ÿ Ž´1 ¦RKwT±/‰(ô¸4j–ûèÌCGš*_Åþ¯F6Ôܪ©÷Ø=AKE‘mÛ§–Ç4Í ˜²)ÅçÞÕý,ŸÒ¶ŽIvêJêJ¢{]麮eY™Éù‹ÅÎËÎ{Éù‹ÿj¾T°ÂäóÛBE>!³[%&õe½‹Çpx—–¢uàIªe)ân'çs¤æZ;wá*ÁÒt-e9Ûu©»ñ¹Ïúr/‡GߪØß×°hÄþu«ŽA´ß÷Å×RÃ0à½53M1eùü £C$Eÿöôõ5AQ.ƒÏÿÊç¿â|³`iäóÛBu>_*¸Êrì•j:‚h(šã±*økÚw>9Ÿ!M3.’i,]…|?¢ñ¬-ƒÁ¾4(¬rÀdÇMñ)©aûà«P¹Á |6uéíæycÛÁßPÈ " CÏóÇWTÃ0bÙøðKx]õ}¿ŠK—åó/§ˆÏ‡¿R/AåbÿÇè=Ÿÿó_ ¾[°4òù2 àF kÄ_Vçóµ$õù~„ Ú½N´Ïã#¼à<êIr>cuu¿Ù|û†pÛ ¬„4’5'™,½¬Æïvf5Þ8%®Ò¸[÷Â%A„”åóoO >ÿÂèšš ‚(Ãøerþïœúá÷ý( -•Ö1Ÿ·³ú˜VßS÷±»¨ÔçK5WÁsiö2¥ÅÀ4׫ÛêbÛ#<Ö·Æô¼ñ²«´Ìn›ÞÎ]iYêf‡ã씵ÑLs\÷Vé°¢ÐAQeù|À»ºŸåóáOÔÔAD¢(bIÚžç…a(þéÔ©ŸŸ:µøð'ÞýwŸ¿÷ôóGýãéú/ÿïý§,AÇ|~7¨ßç/döluu¯Háø‹?½ûÝ@šBŸ{œKSa ÎÐ66¦a\Y*Î(Íù‡eŠÆp‹pœß·HqmkEm‚ B¤DŸatˆ¤èßž> Ö&‚ –b0†qJÀu]þ×uúò^ŽÄgÍêöÿð¿½Ey®E>_Cñù¸ì*’ýÓr½Ahü•Z› ‚PÇ÷ýSi0¥‹˜ÌçÇÿøVž2ù| iÄçGѼ - XÖFßR‹‰Þ"õƦ¹¾¬7îar>_”ð`E3 hÛ#¼ÏÓèm#A0uœ˜V0T˜Æ§¸ .Û™o‡v+r !ˆµ¬ezÞ ùŠ%mqÝ[åê÷~&ç3¤f‰ÀïáãÒ\eZ…ˆî! „Á˜Ï½nH7ÎІ;‚ ¢: -úüÉlî]ÝÿêÛï\Ü=†Ï^?Ȳ+pµ6A¡H©2ÿ /á™rîFô«GYOœÕäyâÏצ|~Lñ—ôe3úà¥^j†Ã»ÔãD—f•Ã_Õ}Wo“ó9R!ŸLöýHªi":Œ4’‡mr”,W„¥ö'‚ ª£ Ï¿<žŠº~mçIÑ¿=}À>5™Íù÷ 2ŸÏÇãñññ1 ƒ¶ÓÛ®Œ¢h8AЙ; -Ãpmmmk ûnÙuÝ•ÇÀ7ð‘Š* ; VßÃ÷ýê®E³2 tnRæhå?ðgÊ—Ö'NŽ+’Ïצ|þB¦Îgg©Òl{„¿ø/[ A´iV¹úÈ—zé'ç3¤ .äƒ`꺷¤1ÄR¬&AhŽÊΔe£Ò• 8‡Ÿ ‚¨Ž‚>ÿöô¨ë¯Ý9AìÊ¥½{ì#bJƒloo¯?æää¤íýÈåÆp8Ì}²hHÇQ¹®iš5H•^ueŽ~ ü7\HªÌ謓ù²@«Ô ÿH¾Å„ñ£ýJ8}úô/~ñ‹ÔàfùUØí†¡2ìÕ‰¢Z@Û"–e‰ ã” (Ú*«ÂâÌÎA* Åg%ôlòöÿèÏ^@ž2üøëËyÔ(ù|mW¹F|¾ôm]]ú~„eW:¯"‰ÞbYÅsÂ¥©þ=‰ˆ­®îáišëp,¥ñsì• ˆ«‡Ê¤€'µb*2&µÀä<—ÇÓÉlŽ–ó[8ÿÒÞ=1¥¿A677™nê@^wé>ß0 i9Aˆž­AŸß¥®TÇ÷ý¤o/Ýç*ùÿ¢z-âó766>ùÉOB!®ë&ÿE\Ȳ,ø†ý& CøQ1è Ül–ɱm›×Aä”2©!3ŸÏà -©ÐèÊ"³’ ï$_Z{[Åç¿~9ÌqQòùÕ1Ì õ¦|þâQÌz÷‡*^Å$PÑééÿ–µ!-Dê±ûã¢óéúÒó“ ¢EÁTÅÀÃiÒ¢Td>M(‚ ¢Šûü £CæOàøñìõıÀ 7î‹)ý Þûáááöööîînú±tŸø¾—㺮&>¿K]©3Û±äüE5>?U­‹ÄÔkŸ]ÉRôSãìB±‘É2öU‚R X`Âó<î¡Y˜ZäF=Y‚øÙ$±HA²aù„ÂSKˆ)}‡èÁÁÌʽ½½¥Úß¶mÇq`xÃ7I™ÿOþ¶ŠÌ‡ãÆFžÕ€|~uœ*FS>_ªáõÎÁ­¾ëÞ YYÙ¢BtÛåi…ál8¼ëûÌ2JÎçHã#9Ó\§-BD·Qñð–µOE™/-‡ ‚ ŠSÜçÇòí×vŽÇróèþâý)ýÔ¥P…ÏO͉ÉÉ}~ogn2/½ -Ÿ/Í~‡¡R–Ï L–Ã*–z*#‡‡HØ-gèy2æ¥68 CÑTÃËNd±±hNgÖ±Øä|ô?¯"óÿûÚF¾ -Ï¯Ž–ú|xWysG¬¾JN`òЉÞƒ\:‰ß÷#¥M8` Êú¸¢Ì‡ÕŒëAD ÷ù±|ûkwNÍriïÞBHé?¿5¡.(…r}>ó†a …A žL>¿NÂ0dmîy^ìOåú|Þ¹xö;Óàüäâ>Ÿ._Í®EQÁ‹ò¨„eYxilG@ªW´Á<ëAʼn\|ÝÖÞé¬ R¥îç^zUÅçÿõ•wòÕ|~u¬‰>WýèQ÷fLHÆ>nYø§VW÷ôê*‚¨jØ+=«¼‡ÉùŒ(šã–ÊÌ'™Obm‘ÎetÔ<ª Èíýa|àô¯«È|8®Žþ%_Èç·…:}¾J‚}LŽÁ[?û¬ç¥'So=¡DM;\þûŠŠ4ô…ãì´ÎäÍçsšM¥ó½ï}ïàà€¢¬+ŠÓd>AQ'¥øüó[fQÖvŽàdz×Ór2(:ÿÍ íG+r}~EìÇq² -aÂͲ,nÀ’R%îè8†aÀ™mqŒ‚÷N¹>Nzu1¸€\Ú󼤤…3³F,œ i¸T’í Àe~†©ù½1x| -ó"r!ß÷EÕÉ€–WÙéÐì¨f½‰$çøŸQôù{?#Ÿßqêôù/·•#åÕóÆRi0Þ¥Þ$úƒb‚ëRLÏÞ¶gŽ¥ Ûñ˜cë¸zõêÑÑM%¢*azÑÌÃ7*!’ùADÍ”âó/íÝcåìõG‘ýµ#Ä´0Ï? )×çÃ÷,íÙ0ŒÔ‚ àÉÉY>Ÿ ÏTLÓ¤\ý|ð†M5´¥û|îÕ³²Ö™†eZ;µ´(в -¢ãx -zR°û¾Ï. -’Ž"$Þ$ÂkˆìIQAÑóËÅZUq"óÐIìBÉðY,z¢ÿ¨fõL­ÿÓÏ“=5V°Q -*±E˜20_HæAÚRŠÏ¿ytŸ»øqs2CdËÅÝc8¾Š!¢ ¥û|®×Rõ&OfÃ0Õ—Âï™q…¯pòð=àž¤mYu\X¨…5~ò¯¥û|îÕSÓàaxˆÁ…ÔÒøhßÃil$À7¢|Nfl¨Ä‚J¬4(J1¤èó˲¸*åˆ ’o"óé)–ÀûÚÚø%\ާ¾ã{„8à›ä>Æç^zUÅçÿý›Û¹«A>¿-ÔìóäûÛÅAä`8¼KÉù%²ºº'Ý+亷ÂvCÄûpœ•†d>A¡-¥ø|àÜè«o¿s~kߟÌ"²… |ÑùOfM¿ÒÞòo:‹‹+Z?q·‡YwÀå†ã8«2¸.C|>ONfG/Þ­LȧúRn,“ZRÌÖ.˜ ­ÔîƸÎÔP¥=XÓemàÝ}$ ܨ#>ñžk…“—ã%@·.Ò|>H©+ ÷Ò©Á¹àIìlcHê˜Ìîz¹Ï­àHcjƒ‹ñ,Öh©sñùð'îç=Ïã¿gÝJ íÆ?’ükãðý>l£GÖþ‚â3ð¼øÒÚÁ^ŽGÌ7îX(Èç·ƒú}þãáq^íËòƒÁ>õ#ÑOT4%ç«cÛ£TÁíLŽ‘ JÙ.D2Ÿ ‚hв|> jy¦÷³v&ÿñæÑÿgßÜ£âªÎþŸ?»Þµº^úÇûG»Ö»Þù½ï]ËÚMâ-ÈÜu !$$“û ¹z‰bÔÞMÆK¶VÆKÒX'*jm©£F£fLˆ¤Da A,r ad~ÏœÍl7ç²çÀœ3ÃÀ÷³ž•3‡3ûìËs2Ÿýœ+©ì‚3%‘ÃcÒ&jý†!Ê ëH|~$fSõÞ˜Ë7æ }©æTx!q²ê*#Ôt y—ðÎ7[°¢´ŽÜçÓ@k¼:‡Ybš*ìWýÙâêt¾¹#ÉNÜZÓ+ô‰•F˜iêAùüÄӠŧ«Ðwf$ÞÆœ×ëåÝÅvÄ«–_‚d‹-åð]!êñ© =Þ….Ïd¿äæRrì˾6,àóÓ…”øüØ$±Á꣨ŒfB¡+%¯Ø³NII3“Ô±nwm   Oˆ‹¢„ÏEXnR…>_äxÓ%‰r9ÙÝÅ®hìdåúÝá¾”]’N2Ÿâ¨qý°>Ÿ×Nkªè¹ …B‘x>?ɦŌŒtòùrÈ{›+t³lôù4Ðý6Õëãû24UØ+Ÿïr¹Ø„±ßGà³H2ÏÍ4õðôùfM²¾õ;q»bxŸà`»ò«>–9gQäæò豄j5áóÓ…úüØTIÈê‡B=D0š))iZ,­;·»–þ‹8Á`v¤)ùü‹]½åRVÛ>®½µµµá£§ÓÌç6¶L\nø|¾Êxð_¹ÏçžÍãñˆ‡¹\.z‘NÂ~5ô¥|/€I­2¬F¶q(«ªªêêêÂá°þÝô’ùˬ™ÂâÃAÝw&pa.÷ù‘X= ½x·¯¼JÜðllÂðêë@  ˜WP‹C©×ì4‹Ì®e¸Õ盵“š!ÖØkZeÑç»Ýnýæˆ(ÃéZƒƒÝ@IæªÔw>ë ÉUS¿Èž·³SrsÙ±ÿr"m†ÏORîócf(V¿¤¤ #€DéÓ²¢ðz/Ð1ô_Zh°÷‡ðû[ ó¤#ù|ÂwºÅL¹Ð[ÃáÚ«‰OßaõùVJsÍÖø|Âív3 Ë_ ƒ|〽bæK Kmé#œpû4’U*úwÓ«>_èlÙ‚ëó­¬h³ƒõ>Ÿ›qìhbhž0<ý ;RÄårº}q(‡ Ù³upyNŸ¨—]A³a1,Ú`ÞŸÔ3bXÙ˜3;'GÜ)àçO•Û—¯J±ÙlzÐ|з_äÁ¯Ð»»¼Uâó7nUi3|~º0L|~lÚ Âê»\UŠÆ‰Þ|{|¾æ’’&ú—Öú|<žzÈ|i‡s>¿¬¶]b]:®¤üÚªªªš+6¥“Ï¿0¼‡|>/³ú?×ëõ²W¸”Ô?Ó[lGÀPìÛhõÙP==\~:ù|j­•›dŸÏ7Mö -M öŠ_h±ÙG+ŠBçä…úá,^K]]cuu5 å|þ˜AÂ/p°—®ˆo -6 æ‹k° Ù3+îñx$OFØŽ8”q;“²Ÿcf(óL¹ñÉm¥èˆò”ïX"m†ÏO†•ÏMž»\Uq Œ%0ÜÈ̬†Ì^8çóÏ|Ý-/Ãáò;;;£®ébeäLIµÓ‡|¾¢(ܲW˜’ÍÌÌäÇH|>?I  wEÃD®5ÃýCi](µnøGÜÑK•ÏÄü3¯`çÏ_ˆŠ8îGƒAŸÏG«qû|›@Êdú|>9E».og Ùçeâ>ŸA+Ëï÷S¯jܾ¸r&ËW¥¾WhˆÛíV^vO(è’ÜV¦¯oU^žH›áóÓ…aèóô_bõÝîZŒ0ÜP”pFƧùÒç|~[OX"^JÏ)è|qÈç¬À>###¢ÊXv€ÏçãÄõù"Š¢ˆõâÅV žO•Ïçͬ )Á,«ø‡ƒJ&tQáêKLJàó%×(ŸŸüê,~ðD3‡‡‰Ï …Btul¼¬oX$ÃÇ7DgëYôTáÙc_ TDNxi|~º0l}>ÃÐêgfV+Jc C‚Á.È|púº]¢’ îðz½Ù*ÌMZœóùDé9Eâ^ºÃ}˜ÏváœÏ÷ûý\rû*ÖÕúR¶Héo @îܬÙðÞÖˆtý¶û|>j4 xuºfˆõgãÛìY ^篟º|î%âë,ú|~uVßØÒ¬…È`|>ßÕûpÈ>Ÿš!¿3ÚÒ™ÎÁg”!*ÔU’Jɱï¬}‘Z¿-ë >˜S°8ÿÿþÇ5äøàĉ$4’¾õ»ÝµÙÙçé_`˜C7k‰Ì÷xêÑE†5*cHÎãDdZ÷§fµ¢±S¢_Î|ÝùlÎù|EQØ‹‡Ðfffj–›~I²#YU¿!ðùC#îVˆs>?SÐ4¸\ÂkŠêõgãY|¦ÃÊg‰o™ý­¬??Â/Šæ­dŸ—.™«xúÉ×ón¡Ïû0Ÿoq£gxú|±ÜZË'ÿ;î°ä†Rx ½rï5‘ÎP"Í€ÏOÒÂç ½ðxê!óÀ!¬ø|+ßÇáó5ýé„Y­ië‘è—òúÌg»pÎçn·›‰GC¹jè ¹54±ôbâžvÔÂÂl¯ÄQŸÏ޵A¯ŽõgãžÙåriäDuã’­6ñˆDž¢²î±ycX{ Ÿ.¡³‰Çè¯(î݇®…¯}«¹1ñ†v—-éâß?og©ä†2v~säõÌ[ŸŸ.ÀçÀ ôJßë½€n€ÄÏw¨?ª”–èßi<~nŽú|^KÌ…B⻆¾TttZ:{d†~àŸb¨CA\¸˜Õ „f8œðùïª7Þ†gëÞ½^/~Š~æ›D†ù<îSVT]z0äMbM½]¢B­åeù’þ1ƒAó¨K$±“¸N©ÏëgŸÏÇUÿð|"FÜà0“ùDÑ‘JÉ eåüÒÈ'Þ[ŸŸ.ÀçÀ!*+ÿ]RÒÄ"êA‡€-Àç;ÔŸyž²Úv‰¹ØÕ‹)m Žú|EQ$ÒÌ—jv4˜éPÞ±fäÎù|BtÚfÕéš³Ñaâ_éñx<ú¶ñ½Ãw­3(ŸÏ>—/‰‡7›½Öe¾×ëMp!ë‘‹qjö0ÜA£&‰{(¾óÝÿœºp)ýð½ü·äV²»¼u磕ý½!Á{ -|~ºPýÙgœ81ähooG@Ò€Ïw¨?íòùÝá¾ÃçÛ~qê_Ç›.ѯ'›»$†Çëõf«X‘äfó×%¢wÈt³·hqéÕhFF†Çã1¬-VàþÓívëßåÃa¨‹-Ì£0œNü-3møµ™R^ÛfffîJD„m‹@ HwIæ§úPþ„½(?Ov#ÙøûÞþ»äØt§XûÄѱóó%·t÷I¤1ðù€íÀç;ÔŸvùü†Ž+\­Ð¯»zs/ ]¨Œš|[àeØÃÓÐJ…B|2ÈÏJú].WjL36§.õ-ïça¾w¦ß}àL(XÏo…ž‘ÜJJŽ}É~(«M¨î>°ø|‡úÓ.ŸßÖ接¦­‡^9x¶UâaºÃ}tÌ™¯»égßé–†Ž+I»öp8ÜÒÒÒÙÙ‰e•îÐP677ž¡ …BlÙú|¾9”ï¾û.»ÀAÕƒ´[•¢?×ÃþÚ'ŽZ‘ù'›»i3|>`;ðùõ§]>?"üŠÆ¨É)¯ï¨æüŸoc¿ÒÁI»öººº*•îîn¬¬´f¥×ëåë å-·ÜboRÃdUúý~š´4²ìé þ¤‰žï|÷?ùmBîóÅhë 'Òføütáþ}÷,ÎrTöú’|¾Cýi£:ã¿ôœB¿Ö´õHô øì׃g[“ví555L7¡D?Ý…C©(JFFÆÈ«`¯®®~óÍ7‘œGÆPjV%Ÿ´ìÑþ˜‰!cçç[ôù¼>?ñÛGÊ}>uõ ÝŽyG™!ù/Ðh `qþÿýkÈñÁ‰X¡4àóêO}þ™¯»¹ié÷QHT 30 Wø+»z“sííííuuuXVéÎèÊ@ 0òJôi(,X@×åõz1±ÓšÖÖVZ•MMMü~»!‚Á ø«ž…ûaw„¢#•»ËOY)ÎgO„%Bj}>õ -ç1րχÏ€t>ß¡þ´Ñç‹¿¦­‡^)=§H$L[O˜Žá¿žlîÂ<À -,¤}V³‘‘¡( -Æw$!ç³Û¼½äØìŽp×s/[)Îç·›DH¡Ïû>?.ðùFÀç;ÔŸ6úüˆ ðËë;è×ãM—$B† ü²Úvöëáóm˜çXAQÊ`Á`pÄ\Q(¢+¢1¸# ±Ÿ†Øï÷KdõUÙ³ù ¢ìØ3}~âL¡Ï÷z½ìs].u–€ÑçÓÏù|ƒŠ .  iÀç;ÔŸöúüŠÆN&Xžm¥_/võJ„LYm;s²¹‹¿ÒîÃT€ƒ¦8Ÿß‚ Y¸ï‘þ;ȇ§J߯”Ü>v—‡ÄûH‚¤Ðç»\.&óñdŠDŸÿχ€á |¾Cýi¯Ï¯iëá¾¥­'L¯øN·Hœ @‡ñ_éÏ1Õ`d )΃c¤ì.?Åîw=sÚŠÌçÏy%H -}>ûP¿ß? -§G(òx<™™™Ôô¿‘¸'Àç@ŸïPÚëó»Ã}\³4t\¡WÊë;$Z† üƒg[Ù¯t0¦:ŒB¡¦8ßãñHd>Ão ÷Énwªã;Ålã8ARîóGáHü~?Ÿø|Iˆþ¹Äþ•°Äöl;|¾C>Ÿ(«m5Ë™¯»%Z¦¢±“Ž¡Ù¯϶bªÀÀív‹ÅùŠ¢èý­ˆßïg÷‚]‡ë ´Kno~úÕÅ®ÞãM—ìz¤+…>ŸÕQ57B¡ïpÇS©âõzãþa‚>ÿÅ^ ¿B ,>8ñCk}‹@ #/ðí04D]o ðùùüîp_CÇ^3I?H´ ø5m=üLõQ-F¶Ýæ÷ûEA‡€Ä¡‰T#nÑïÈ# ú|>ZSôoJ.Ÿ -ÛH¼›xFFFÿ_žð¸Ç$w’c-Á`»í)(U>Ÿ’ž7âaRÊÃIÐ狎@ ò=èÐGß"ÄÈ‹Ñö} -`ðùõg4Bé9E"g.võòcè_LõAáõz³U‚Áàæ¯>k†Äãñð?ñûýCn¿¢(™™™­7Êצ€fñÒ˜²á°âÇ̦¡äÃÊl\hÂð?¬šs‚P(DÍàÏa‰óŠ•Ç]f¸Ýn‰»Î ú[ævÜŠn.K9¾¤WÔpŸO=¯¨È‹óé–ÔŸžr]•Ý#¹eøÊöM¿ú|‚åÀá°|’Ÿ ƒÝÀ…ÏG àóŸH#àóêÏ$øüãM—$ræds;Œ‰}0(˜Ù³8ŸÍæ¯.Wü;u(2qC€‰GŸÏǬ5,33“ @ ®Ô9ÌW‹ãÈ…¤•mv°&ÍZ©ëÍyÊkŒ­Ü&hÊÎ.qÈ1ô®ÖïPôA No6|Ôó†çaõÞt™løè_·Û’[^ à[ôƒ¼[ú'Û…€½gá¾É-cìüË••—ímjj}>ßÖdÛ£•RFÀÃ&üBW=Ø¿…ÏG àóŸ£–dúü‹]½9sø|[’¯½µµµººº®®.§û8Úî󉸥þ>ŸÏ.ŸÏÄ£ø -+ëµXó?’†Ò:LjV®>?nQ7¯ÁN<™ÐPVUU%2”š¢tjLI ·Û-‡gffêM¸uŸ¯Ÿ´‘Aî86` ßpéÑ[ú]9öxBÒ¬f(5;€²þ<áq ì.o•Ü2¾ó]꼑ãóÙƒ!ò‡ìʷÄA%+ 6úüŽýÑfŒ¿zÆøçŒÿIÎøŸª‘™3þš™ã¯9~ìÌñã¢1nü¬h\§Æõ³ÆÝ0{ܳÇޤƄÙc'RÌ;iÎØÉs®¥Èšsmöœk§ÌÆÔ¹×PL›{ÍtŠyј¡FN42gª1k~4fÏÏœ£ÆÜhü”bÞÍ?‹›Õ¸E 7Å-?¡¸U±ÈÃ…Ñø1‹E±Èb1[£‘¯‹%ѸÚ, -îqËÀ¸™Ç æˆ%óÆÜ1g`̳ÆÌ‘30f1Ý ò£ñ“hLSÆ”‘=0²„˜¬‹Ic¢úc1‹›DÞM?e±hB,T#W (&RdÞªÆsO>æÐ2ÏɺvF,¦ŒiÙј‹)Ñ›‹,Š)ј‹I±˜¨ÆŠ©ã(nŠÅ±¸AëYLw],ÆGc¼ã(¦‹kcqM,2cñS5~‹ÇâêéÑBñ#5®šq ö+{ëêœh†añ!Õ°l™ÑœÃÒε±ä3VHAãfõg!<]KJ7Ì{c,nÏQ,MMRÓOVY±”•=·?k©‰ëÛÜÕŸ¾bLŸÇ4©Œe³Ù&9MŸÖÌ2Û­²ÌfœÓX*Ò—Qš²š…ÔD4Ø\do:Òd¤¸IÉÆ¼d˜$©IŸÌ”>G¦©Üþ4õm¦¢pÇâ–XÜL1©?æÇb^\37s(&÷ÇìXÌŠÅÌXäPdQ\+É]†é‹g0yÓç1ÃT¦Ïf† í:]BëÏi&iM’Ùâæ·«&fÂçÀp#™>Ÿðn‘ø™îp_2¯½ºººJ¥³³3ÝÇÑ ŸoX~,ÂJI÷KÌêÍëÖÏ9’†Ò"\jÑ Ÿ·zVStH2Ip(Å–¸ÝnÃfñêô“\¾”E¡‰*®ÍaüäfS7 Š HÐÊòÔ_©ÙÕ%íé ýPj¶ZL‹ó‰2¾ÿCÙþoÑ%óªÛÛœBŸ?¨$ø|}þ5[æM{sÏÌ¿ì™ó×Ýó+vßZ±sáßv.~kgAåŽÂ··{ޝ9V¼þïÆw¼[ßÝæ}·hû{E»ßÛzÛû[ï<±åî6ßóÁæû>Üüó7ýêäÆß|´ñÀGúxÃ#Ÿl8øÉúÇO­{âÔÚ'ƒkŸútí3Ÿ®=tz͑ӫŸ;½ú…3«ÊªV=»ê•³+_=»òõ³ž?æùKõŠŠs+Þ:·¢òÜòwÎ-?þ÷Â÷j -OÔ,ûðü²Î/ûøü²Sç—~úùÒÓŸ/­ú¢àìÕµKÎÕ.©©]r¾vÉuKjëòëBùõ¡ü†úÅê7Ö/þ²>¯©>ïŸõyÍ ÑøWC^Ë?Q|ýEÊŠ…mþ[Ž ¹r/5F£«1·[Ë_F£çËÜ+ÑXÐÛÔa5¾Q£/·j"b_Þi¼5ráÖ>Š,èkXÐW¯FhA_Ý‚¾Z5¾XÐ÷ù‚¾ó¹}5¹}Ïí;§Fuî7Ÿå~sVªÜoNÇâÓÜo‚¹ßœÊ ’þ87üQ,N.  Æ‰…½ï/ì}Owö_ØûŽÇõ¾½¨·R·õþmQo…]Ôû—E½o.ºòfÞ•?ç]y#ïÊëj¼–w¥<ïÊ«Ñèy9¯çh,y=/åõ”åõ¼˜×óBÞåçcñÜâËGÔøãâˇ_>¤Æ³‹/?³øòÓj<•ÙŸ¹4ÝOæwÿ!¿û 5~Ÿßý»üîÇ—Dã±%]Æâ·KºYÒõ𒮇–t=¸¤Ë·ä‹K.=Ðüû‚öýÊþ‚ÖK[,ý—oéW¾e;eÿô-kò-k|pÙ…—ýã¡Âú‡ -CÖ>\øÅÃË?xùù‡—·|ph™}ríK¥kËJ×¾PºîùÒuò¯;â_ÿGÿúCO­ö© Ï<½áé§7øŸÞPúô†?<½á‰g6üþ™?»ñ±g7<´é·‡6=rhÓÇ6?xx³ïðæ‡7?ðÇÍ¿ùãæ_ÙüË#[~qdËÏl¹ï¹­ûžÛzÏŸŠJþTt×óE{Ÿ/ºãù¢ÛŸ/ºí…m{^ضëÅm;_ܶýEoq™×[æ-*+ÞZV¼ù¥âM/o|©xC xÝÑâµG·¯>º}ÕÑí+îXñòŽå/ï(|eçÒWv¼²sÉ«;¿º3ïÕ‹^Ý™[¾kAù.÷k»nym÷ͯïžÿúï™óúžY¯ï™ùÆžœ7öLÿóžiÞ3åÍÛXPb™þæžœ¿DÓˬ¿F3̼Šh’¹¹b—»b¥š‹f›¼·¢‘_¹cI厥•;–Un_þööoo_ùvñªcÅ«¯}‡RPñ5 m>¾mËñmEïnÛönQñ{Ñt´ã½¢ïíyoëž÷·ÞþþÖ;NlÙ{bË]'6³ìt/%¨6ßÿá&ÊQ¿8MS¿þhãmØÿÑJV¾7W3[ˆe¶Ëlߦµ¯(­©9­õ‹(›µ«ÙŒ¥².5ƒQîb)«O’…bYÈZ"êã‰È,iÒÑÉÜð‡æé¨?#©éh°éµþŒMJ¯y‰'%5/]æyéO&y闞ΗšòYjú6;ýv`ve§ýÆ JÙ¿ôk£%¤©eõj¦ª‹fªå_¨iŠâï¬8§Æg¿]qö·+ª]qZࣞSz>yÔóÑAŠ•>¶òƒÇVžxlÕ{GãÝÇW½£ÆÛ¿[Uù»UoýnuÅï£ñ—'V¿ùÄš??±æu5^ûÃÚWÕxùɵ”¸OFWYéºþÜUÍ]ÑôõÔ€ôõ”š¾¢ì™o3X4‰Úô¨Ä:ÔŸÄöÿ±?ýú¥²þ<ö³#[îWSÙ½ÑT¶•RÙݱlv§šÐn{¾ˆ²Ùn]BÛf”ÓÖGÓÚv1­y^îÏl˄̖¯f6Š…±ävëkÑüvókÑä6/–ßf«ùbÒC«àó`¸‘dŸ_^ß!Q45m=ɼö††¦›zz’ú¹N`¯Ïg¢^_Ü+Â}2·úCöKŠ¢PK4…ÊLõX¬ÏIC9¨×›v{}>\C1Ρ©"œH2©««£q¬®®ÂPŠ2V>sè]3!oq)ñÃ4åîq}>ƒ?Û’‘‘‘àL`Ý®ïsj¿fÔh‰%³>_3”VŠóy*»§¯¿$¹YL(èº'wS¤5ho›S^Ÿo‹¹qx"yŒÅbö€Ï‡Ï‡Ï‡Ï‡Ï‡Ï‡Ï‡Ï‡Ï‡Ï€QK’}~M[DÑ”×w$ùò;;;G†¶×çsÙ ÍNÂá?ØX/J ËPÑHþÑ0”ûÇÌZÛëóÅQ6; MÍÁ &“!%ŸÀq-‰µâ¿mq)y×Å]4½ã®2+ð½ yƒC¡3ÿVR„-„Ãaq(­ç³Rϸ³*‹Ž(’›Å÷Øüùÿ‹ô(ö¶9…>TŸŸŸŸŸŸŸŸŸŸ`È$Ùçw‡û$ŠÆwº#24ìõù¼’VâEy ?7`z©(Šßï§ÓruIÇ»ÝnI#飙÷£?IÐsŽ`¨Yé÷;ìõùt¯½7; MÍ´1ühMY^ÃÏ£²²eS©"Ÿ|[Áâ6?^óŠÅ¥·ëâú|³쪡ã 7&Ĩ1ìl©*ê¶RœÏ·HˆïýàkÉbwy«ë¿>ŒTØÏ…>?ú4D `ø½Îg©ÐÙø ¥…ÊÓ>|>|>|>|>|>|>|>|>|>|>`dC_ékc‰ -}?¥/’èN’}>qø|›DÔ\ìêÅ  {}~DÐõ†g…¿™Ï§uÇT°!n·[#]éWf†322,jÞÑ ÷·Ô‡úwm÷ù¢®7<‰(üÍ>šŸD ·™NäX¹"Þf3­mxùŒ!,%®"5{^ úüÁ®Ûß!ôïR;™É§nIá½ÏJq>ï1c~0vþç’ÛļÞYû"ç|¶·sú|6“iÖi&îC$îRZoá¿ðùðùðùðùðùðùðùðùðùðù€4…Õ1z½^ú2hXvÈ‹KõtÃê3’ïóO6wIDÍñ¦K”!`»ÏçºÒ°ZR|×ÐçÓÚäK/33³$† ìxW®1aòãÂ=›ÏÈbÙîóy»áÇiÞ5<Ÿ-4èl&Ð|†Ä}ÃÊñ©• r´²”èöÁ‹ç5·‹>Ÿoʈ~°«FßÃâ}ÎÆþÐív§ö~g¥8_<Æã).<ð‰ä6qUvO ø¦HkÐö¦ŽBŸÏ&‰f^‰3œ¦"Ÿ~loÃçÃçÃçÃçÃçÃçÃçÃçÃçÃçF ¼ìÐLžV—‰E¡ëÙ$ßç·õ„%¢¦ôœ’üNèS”ÞÊÊá}æ"…ûZ•ñ`µ÷rŸ/Vàë?N¬Þ7ôù\0ê%0­;¾rù¤:º$»Ã} W†P;ã^ /Æ6Î|8¨KãÎ>LŸX¯AS½ox66ÜúàˆP¶mø¬ÇJŽÒOª¡!_J@€.™–~Ù¢Ïç.öê`W~ÐE+ˆÆp§;ÉX)Ρy"¹G”kÉø†ÈQG¾J$ÍçÓ Òœ·/i¤Jƒ•­[+î‚ñáàS‘ïÜÙ8£àóáóáóáóáóáóáóáóáóáó£ -½ÐȱºL¢ôQ œ|ŸO<Û*Ñ5m=ádö@8T22ZÇŒþAí ›¸J±‚×:Ÿ(í5‹KTý†>_s* |¯ý 3Evé)=»z}§[$Snøµ“Z+¿^Âmø®($­#÷ùi¯o —Òú³Në—cvZ³c×°Ö—’¡Øä]G7)Ã=:@|jLô¨ƒZ5†—/®VºÁÉ÷’ƒ•â|ºSkÿwÜ„ïÿðjúµ¦­G²F -´çו}üNÜ•2’æóùÿO¸0l·kpõ÷6ú-<öÿ.Ã'Dìmø|ø|ø|ø|ø|ø|ø|ø|ø|ø|Àˆ‡1Šf^£VDáOßI¹3aEq¶#N_’ãó/võ>ßVVÛÎ\}Ec§Dלùº;™=.2ŸÅ¿M†É ŸÏš¦XóºÜçZzEQ˜Ûd~X¿¢í]¡¥ç”´ù,žm•_ŽÜ7:áóyi®¦n\ÿºÄç›e: › q/y¸ù|ºïè éy×YA£Fµjä—χ&îXÛˆ_Eó¢•â|êÆy;ïgóÿd}sy}‡Ôçeq¥ äû|þTª|>k‰8p|kF“½nãüχχχχχχχχχÏŒxå÷!z¹AÇð\.—¾Ÿ]E‰~r|þáómÌÀT4vÒ¯òò˲Úö¤]~8L#™ÏÂðB¸ ¢Q^,÷ùš:|ަnßÐç‹V“þC_·¯?›˜±éÏý~ÿRnJ|¾ÙRr»Ýâ=H³:¬û|½Ôª1k6û+³A7|¬ÀÆ[‰x]’mqG#:W}Á&ÿñ¦Kò§i¶>þñðù4 -4‹hEðµC¯” »hbÔ¶0iÈØô¦ ‡>>>>ß:ðùðùðùðùðùðùÀ ï¼üë¶™—qáJÓ!¹‘.$ÇçózËÒs -{E¢k|§[Ø1¬ŒÿàÙÖîpŸC û&J/™¯è C^Ùkñ`ÏèÔ}ÄHòú|EQØßŠÅÌt~:fP–ÒÒÎçK&|\6(Efv°ÞçëÕ}ÄHòžMLÚ\ì{<C·oh5%;¼…ܱ'¸Ekq)‰î]ì1£š™XºC62‘U3¨ `;¢·w»ÝúVIŠó©7®ÊžÍ'ÿÉæ.ÉÒ¸û•O~xJܶ—¤ùüá¿d6Ùø:Òï71ó¯y¨Ä–†Ï‡Ï‡Ï‡Ï‡Ï‡Ï‡Ï‡Ï‡Ï‡ÏŒlÄâI³c¸zÊ0‘Ÿ„Ïç‹{žÑ@r|¾XßÖ¦WÊjÛ%Ò†Žöds—­ -‡Ã---_]}ùüK‹õëÂ^ŸÏ— ׉úW }~D•“ôŠXÉ,ZJzËÆGcØPvvû=¶1”.!>%U>Ÿ [_Lé_‰˜ÒÓyÌÔ.½.ÎøجÊ}B›ïˆBÞúyøÓ †O¦èu¨†¼jRèó©I|\Ì ú}Ãâ|·Û]xà^r/_­÷=úWþsCÇÛ¯eú|q&‹;núQfÓÒÆø|ø|ø|ø|ø|ø|ø|ø|ø|ø|À(Á°$R/q 5$òEr$‘ŸßîãæÌ×Ýô -ý+‘6¬ðòðù6+†sÈÔÕÕUUU}öþûJA’‘1ÌM~›ËÕenòùúj|}ž™Ïçús½§¥SÙ¥ôÙPÝÝ݆oºtðlë07ù¾Ó-4óåO£¤ÊçGtÕø†ûò¦#}>¥eQÿjž“š4iÒÐ|>oϲÜã'ç¡õ¥Ä¯7AŸ?äU“BŸ/Ú`~Õ\ÿÊ‹óéÈüÂåâÖ­|î|ºV󗽤ÐçƒAútÉl… ËífÛFl¶Ó»6îÃÂçÃçÃçÃçÃçÃçÃçÃçÃçÃçF¼"TRx,\ìŒÂ2<=Éñùœoë K¤ÍÁ³­tÌÉæ.þŠMª©©aج®;pÈçG -|½ÞXðù"@ÀãñpÑ缇ñC)'…>_#ð5zŸaý£™Ûç{¯<¥¿ôÒK¥*o¼ñFe ®²+upÿÉíº¸Ù$WkŽ·¾” {Ï.Ÿ?ØU“*ŸÏ»]Ó|¶È‹ó#÷vÅ'¹ôQt¤~ÿ‰²ŸËë;]_ÉÿA+Ó†­'˜EE±wvÁçÃçÃçÃçÃçÃçÃçÃçÃçÃçFV¾ý‰ßǃÁ älðù‘$ú|.çy]eé9E¢nÚz»zù¯ WloR{{{]]]ccãGç|¾Ïçã«IüY¿âD¿Ä\«Ù´ý阑4”q‘[kç|>ßN¥i þ¬o›x¶P(Ä&ƒYY¯f6²¡ljj’ŸÖn¼yµ¿•U ñ¢Ö—_âƒ`‰øüDV ß±±|:.4¸¼Ïé¾·"Þ… ˼ù ôã`EÍYÉMaÿß.hžó²´ðùìÈðh!|>|>|>|>|>|>|>|>|>|>`4`åÛ×)q¿ÃçG’èóõr¾¢±S¢nN6wÑ1϶²_7]Âü—àœÏkòÅZ}ýªM³|’Jéä̺ 7¨†ï:çó#BM¾¦V_2¬\z›9v³ÏÂlá§¢.’oæòV‰byPK‰þŠõ†æÒñù‰¬šäßΨø&ø[âë†ðm ñA­3åù¥ïWJn -÷má?w‡ûœ¸¨4ªÏ‡Ï‡Ï‡Ï‡Ï‡Ï‡Ï‡Ï‡Ï‡Ï‡Ï‡Ï¤V¾ýq#ÿ†È-%|~ÒÌ*—ó‘†_eµítLy}Géæ9ó_‚s>?ÓGÜ^z½^ÃU)š(·Û-iÿÍ©À ÆZãÒ5}ë„Ï矋}Í õgã•üfíá—#),·xE¢aÎÈÈ0[ ➯Og­,%z‹F¿'âó‡¼jøí,™Ž—·Vó„ß+1Cœ6ü¹-Šæ²«%w„ÝåMOžúJ¼;8Á0÷ù4ÃùûÜèä4vÔ ùŽ¡½-™·~¿ŸÞÕÏy}þU3®»eÞø­ó®ß:÷†­so*š3±hΤms²¶ÍÎöΞâ=Ý;k†wVŽw֬♳‹gÎÝž3_[väܺ#gÁŽœ…;)fäíš±x׌%»¦ìž¾t÷ôe»§î™¶bÏ4Ïž©«ÔX½gêÚÛ¦¬»mÊúÛ¦l¸}ÊÆÛ§lº={óÙ[îÈÞzGÖ6Š;³¼wfß™µýά{³vîÍÚµ7k÷Þ¬=wM¦¸í®É·ß5ùŽ»&Ýy÷¤½wOºëîIwGc"EÉÝïQc_ÉÄ{K&ÞW2ñþ’ ?cqÏ„Ÿ«ñ‹{nú¥¿Ú_«ñ›hܸŽ߯þXˆ…/ˆ¼/Å{c±O{nŒF‰wRÜ¥Æ^5îŒÅjÜ®Æmjì»ÕØ‹7EcÇM>ŠíjÇÂ+ĶX©±U-Ñ8°yBlRc£b±^uj¬Æ~Š5j¬¦˜UB¬TËj,W£Pe±XÚP¨±$ùj,ž¼X,ŠÆoÔøuÞ¤_åMúeÞdŠ_äMþùâÉ?‹Åý‹³îËϺ7?kŸ÷äg•,ɺ[·^ô;´Ì7.ŸF±aù´õ+¢±nÅ´µ+¦¯Y1}µ'«ÔX©†gåô+g,_9£Pe«f,휂U9KVåä¯ÊY¬FÞªœE«r®îÜÕ9 (Öäܺ&ǽ&ç–53o¦X;s¾óÔ˜»vÖœu³f¯›5K™ëf嬧˜M1cýìéfOÛ0{ªS6ÌÎÞ0;kã“7Ι¤ÆÄs&lœ{ÓÆ¹7nœ{æþ¸>ó®Û4oüæyã6ϫƵ[æ]³%úïX5Æm¦—ëb&Eso,ЦŠ ”p¶EÎd5çDÃÛŸy¦ª1Í;‹¥ –…rŠgÎ,žÉrÑœh:Šf¤y±¤DqóŽhjrDzӂ9¹j‚¢XD±«?SåïšÎ’ËWjÊšN)‹byâš¶rÏÔ•BúZË`ýIì¶hS#[HeÙEwd© Í{gˆ9Í0­‰™MLn,³í˜ÙÄ´&æ4–Íx*ÛK\ÑLeœ…,'¢½‘<iÒËEšt´Ý(y¦#ž‘Ô¤t`ËÀŒ¤IJ&%!/í—&𿥕ó’&5jSSüì´x@vÒ$¨_Å”>Gݟߟ¦î¥)1SQÜ¥ÆÞ‚¬;Õ¸£ ëvŠ¥Ù·-ÍÞ‹ÝjìZš½séŠK§lW£xÙo,¶©QT8•bkáÔ-jl.œº‰bùT–¸ús×rž» ÒË`!ƒ±$¶l@›Á’˜>-ZmœÊx6»eí·ÙL“ÐxN›©Ëi<­M‹¥5}f›Ël<¹EóÛ&ãüF‘™?> ô}Sþ][<@þ½8èÝÂ($™>_/ç}§[$§;Üwæën§ 2GŽú| ÓT>ú|þbFF½ÎÍ3ý@¿r_dh¤Å5+VDë{Þ ŸÏå¼™ 7<›¸Ç*¶™~æoy<I;­_µÏ.–ÞéZ*cÐÏ|[ÊìCy“èo³Ï ï¢D|þW ¿ áC‡†8¨£ø^ ý ö¿!b¡{Kï[o˜»¦Ir;øÍ¡jÍÓ[NdŸwïC‚Ù/Cn‰~àÄhÖÑ@Ó1öÎ"¶¦ 7vÅ]3ýÚ·Ñç#ˆ‡|:”åз1òbø_ O¸K1ô–ô ×L³hðx¿¦­‡ ö -7ü†AÇ·õ„Å_1ÿÍpÔ狳hª‘#&>_\bÉñQ£®RÍ$˜s>?"d`C±lx6c7,Ø–çGãóÙÇq (ÁìÙ¾ -âbø@">È«†?7¡Ùksîíé_qìâ¶_Óíü¡­«²{ŠŽ(’ÛÁËÇÿÅ÷é¾àÐu%Ùçk6ȬcoŸ?,ÛÝØÚ7ÜFtö°»ûÀç#ðù€Ï¤5\~ŸåßCåUdâwöQ.“éó»Ã}LÈпì±ü^åõ¡€³¢±óß G}>Á©Þ‚šù|6» E®ËåJš‘0±¦ß[‰8ïó¹ú3ÌÀfÍ -q Í$¥t¹Ì Òç3|>Ÿ¦žãv»%Ë$®Ï§)Mg ‡a³ôùC[5lyÎç…BÔb'ˆ7V³®ÓtÚÅ®ÞÃÁOŸ=üè÷~ðä^PrìËP¨>Þt©¡ãŠs•dŸ¸Afe ‰æ§oðúÚbàë°hÚ'ó>Uàóø|@ÀçÒ±T˜Õnñ·ÄÊ@IÕ½X,jïÃãéH2}>ÑÖ>ÙÜÅ«+»Ã}‡sðl+SÑØÉ~=|¾ ó?íP¥²²²$†ÏçKZ ñ†º1Éõض@­õûý|2¸&ßÞOᅪԱjxwÒD«Y›ãªiãÝóŠì{rï™PÐ%¹Ü´19W‘|ŸÏaIÉDö'Íöœa°ÿ-¸Ýî$·Ð Ÿÿ¾{é ‚EÙ /8´~Ñ·1òbø™ [ÄgÃÙ÷Pú®§)hÔ—_*ŠDçâüHÒ}¾^~o»z:® >Êf,ãI6.Á(ÝÔô¥ï)i†ã[Lg(rxŒë¿B…Ú%7‚9+{’s£Ð糇;4~H|~òÿ«à„Ï|Øsßfè·ÖòÃF!)÷ùÇ›.I4ÎÉæ®ˆZÕ±«ƒ€få¦Üâ‚ÔÂwv|)Uš@`L<Œ18SR¹7û;ß•=¨Ur¬e̘Ëɹú|ö ‰¾ÁiØÅjÒ|>'0Tôf–^0d¾¦gRåó/võJLÎáóm# q¹\))èÖÀi&¤° ¡PHó|œÓYzÔå™ì;ÿ²ä.°p_‡ËÕœœkI¡ÏOm±âóYý›äÂçÀH" -ù|>úv™­âõzÍjÛDŸŸ™™©y´|4“rŸOøN·HdNw¸Ï¡Ïmmm­®®®«« ‡Ã˜ iÍèJæGX‰> eUUV¥xq~ò‹ºEè–*—ù.—‹MÑ`0èñxèNÝ?c[ƒÊÿ¡h—ÜÆÎ¿ì]ûa2×Ô¨òùÌÒûý~ñE}ðÉ–ü Dø|ЗtúJßXC¡zCd8øüòú‰Ì©iëqès««««T:;;1ÒšQ;”g„•ècUZ‡eïÔ>köÿÙ7ûà6ª{ïëOÊ 3âþhfîTÓçÎô™¹£ççÂ-5}á5¡KH€„„n)ÜR¨!ô¦´æ¥o’JHÀ"“@J‚ LE0o /Â/ØØoLŒ¯C­ŒËŠ…õü¼':9ìJÇ+k­]IßÏ|ÇcÉ«ÝÕžõ9»Ÿýp8ì›gŸ}–-L£ {Ge6\:é”iIÿO¡¢«O¯Ì×ñ‚ÏÇãÔ² R‚Á Sÿõt]$>saXohÚ½ -ø|@Ä >¿óHZ"sZŽÏÓv™9Ìd29PÍÔmSêºNÿÂj é¬jÇžžüWÎ -µ;µ¾‹³3Dû]ŒÅ‹³¦æglÃYúw2’þå†1ÿÉ}¹ÝÊ#Wþù#Yqð)^ `JŸOôí{n8× ´ Út±'ðù€ˆ|~:+«ÏlêNÌߦS©´am€¦DSÑu]UÕH$"YÀï÷Ës0eËsSMŸbÏ t}ÒçË-¹S6?ëôE“¡³ïͽ®Ì·vÑçÓ1¡ÃeÇäÓbt0¹{/Ÿx<Λ2p{O—Š¢ð?Ñ/ŽçG£Qö4cÝ|> âŸO4÷ê¥321…–€Ê ºåbJßN%9w³´kay,ö™Ï÷^ã¾QIçÒ)ÓÑÕgæFb•ùâ.ú|>+ŠÂ\=;¢·WUÕï÷MÓœÝ:µ”üimÔq™ÏˆXç›Ì·ÏÿäËáø‘5œKJâx:l¤ÓœO)]_O·ýÓ„ôé=žO(S’3é3ÒŸÏ'F>Mö:6“FŒhcý R¾ìûÌÈ¡/û†Œ|>Þ7<þ1åÆ?ÿøpj&_¤>þWªw4Õ{„r´7q´W?Ú›<Ú36ÑóåDÏøDOj¢çhú£‰ôGéôG“鎥»§&»³“Ý_MvOgºs™®šJöð|um5v ê$“ÅÒ=“´½LHst¶¤º§g͸4_Ζ1IJ£Ï–„4GldT–¯(ÿbù¨p¾°—ÃÒŒHó?ö2,Íç³eÈFÍ–ÏÇ‚{%ÀÜ {ÛFGqü¾¸ºðˆÏo>*Q:ûOàÌ€ -`*W ÉR>pHà+ù€°¡Éï5<.éùoÚ®ûOÌíôWì»»èó™½b«ÏÏíó7^G"ëc:¨¹­šÝ©CMçfDß®à’ÖG eú|ñã‚< Þ?O=Ž-‚ Hí·K€¹aG#”„ƒ“Ö«úxºëóG&¦$V§¥?‰3æ›x<ÎÝ;s¹V‘+ÛCQ¾¼X†m¶{v·Kzþ³–O„ξ7÷v¨b_ßEŸo ÁŽ›Uq³§-Õ·ƒ§AÌÀqÏ¡3DòÀhVàó>AÏTðùót<Ýõù„Ú1*;éì4N~˜?"‘Ȭ2ß$ü øECN£L_2ÓÒŸlJ±¿Ê»ýo~gê·Ûö?ÛÙ921U™#àºÏ/HØè‡MK²÷C!gs°‰Šâs„J~ß9gø|ÏGAàóU„Éç7”uw}ÏÊûü‘‰©æ^Â\MëÁq‰ØéKfpòÀ<‡Mös“ù&)Ø›ôAMÓ¸À?Ö÷ÅaIŸÓö‘…k>g¿ÓèP™ƒà¢ÏgV21µëãAIŸ¿~ÃÃMÿü€ýÎëùç}>kõëjší‰©xžµ‚SCv0dS**ùeùqö‚Ïÿ÷+ÎùÞƒ×Ô@δæ¯39ËFþCÈ÷çjÊÙùü€òЉ4äseãÕ?4ò£!–ùÉÆÐ¹WQÎÛ¸ê|–¦U4­º°iÕEMW-Ü4“E›®ºxÓJŠòðL.yxåâGV^úÈÊ¥F.Û¼âòÍ+–ÍäÊ囯\±ùÊ•[®¼jËòУ˯~tù5.ûÙcË~þز뚗]ß¼ìÍWÜÐ|ÅÍWü*ry8rù-_¶æñËnÛºô×Û–®Û¶ôömKŸXrÇKî~òÒ?<¹øÏ-‹ïyê’û¶_¢nWØ®<´CiÚñÓGž¹øÑg.Žì\´mç–gnßµpçs=½pOô‚Öèßs~ÛÞóc{Ïko=÷­ÖŸ¼S[êß6Oÿì5v ê+ÏÙ+dO>»ó‰Zò\>»fòö³Bv²œ{"Ïäót>;òÙ~î[¦åé{n¨üü,}>;VŠ¢ˆoÒU BûFW8¼±ÔÒ%vAØ,¢2—Oš¦ÑOŒXž’&K:èóÿÏ/6¼ôk/çœòò×nó#!?¶ä'/ϹFÎrþ+ÇsÁ+·]øÊZ–‹(mk¶­]4“[)·ÝúÓ¶[#—´­YüêšK,yuÍÒ¬¹ìk.ÿÇš+bk–ÅnY»åÊØ-+b7¯ŒÝ|Õk7¯zíæ«_[};Õÿ¹oõµ¯Ïäº×Ã׿¾¡ò«ßøÕ¯Þ¸iõ7ÝüæMkÞ¼éÖ7o¼í­×½õËÛßþåoß¹¡ñîz熻ÿyÃÿù‹{öÿ×½ïþ×}ï^¯¾{ýƒï]¿ñýëþàç›?¸ö±øµxíþ쩎ÿ|ºóšg»®ÙÝ}ÍóÝW¿ðQ襞U¯ö®Ú×{Õ¯|§Å{ý+>üäÊîO—|`ÙeƒÚ埼ì‹Áˇ–ŽZ2ùù¥_ /Î _RSß1_ÿó5v ê$Ÿ2rh&Ó,Ÿ-žÉ ‘ƒB´|Œò©‘OŒô³\:“>#éÒ“ÏG—~EéÒe¤ÓH‡Ä|0“,ËûFÞËç]!ûüsÉLÞ9‘©·¼eäM!oi7òº}Kgòš‘Ø×ó#¯iòŠ‘—¼4“c/]6“¿yÑÈ Bþ–O«‘ç…ì½,CÙcd·¨‘çŒìò¬‘3™¤<#äi#;.ŸÉv!Oi1ò¤'Œl3²UÌ“‰i>‘ôcF5²EÈf#y˜eÙñl2Ò´l‚²QÈCFþjäA!¹ßˆ:“£<ŒÜgä/È\òZø"ø|€SÐ-!ÝBì—‹>dbJ¬Õ¤wZú“½CËì?<Á~oîÕÑvP>4h²Q sªŠ¢Ì*ói=º®›>HC ÈlµÔoóùVƒ½’Þþw{?nkû½øÀ·2¸èó骆m—öA|“·Î¬‡zΰ§´Î -\8™¦XJÉχχχÏGàóáóáóáóáóÕ Ä~™¸èó µc”›¶¡½äº¾`è¯}É ™ÌdËÜz6›M¥R8 ª4e-5åáÇє•$‰PÿOÃe1EÌ«Äå2ßô,ÀÔ”ÔcóÞ»óHº¹S“ôöϼ¬5}p€ËÿŠ -}>këózǤô­‡º|èJ)°g:áp¸±8âã†9ŸŸŸŸÀçÃçÃçÃçÃçGÓ4º e7¤ûöq×ç·gƦ©;‘ûzž5-ýÉtvZ4Ben}`` Ë Nç@5ƒ¦DS‚y‚VŸ "‘ˆ¼)©Ç>1Ùê_ŸHºzÊkí‡øï}ÉLž¬»>¿º®«ªª( - Óô‹ƒ•ù­ÓW -tÍààqžó…|>|>|>|>ŸŸŸŸŸ¨%âñ8ľ}ÜõùÖzû¦î„Dò¤³ÓͽºSE›}}}L7¡¸ÚASÖ ===hJï`§2¿ Ì·6å®c¬ën~/þn׋’~þ/Ïõ· ¥ØïjÇh%¿¯7}þ¼ŸŸŸŸŸÀçÃçÃç#ðùï ûlF¹ã3Ö«w}>ÁÎþÃ9¡b¿`ú’™öá£bI9Œ á4¨vД5C"‘ ¦Æ¡p›2Ÿ³Ó”jÇ(ëºÛ_^ÛôÏ$ýü‡ï÷:øÜ¶$êÐçG"‘ÆR Cäàq†Ï‡Ï‡Ï‡ÏGàóáóáóáóáó  r±_çVßuŸ¢h³WÏ}½bßšÖƒãƒãÇøË‘‰)œÞà8eÊ|b¿}×;$|ã¾Ïµ¾Qñn%¿uú|W€Ï‡Ï‡Ï‡ÏGàóáóáóáóáóÀ&ž#ÅfÕ‹ë>¿óHš«›d&›ÎNKT«É7•ôp -]×mÊü`0hs|^Uã¾Ñ…kR’N~ÏîvêØùK*ùÝ=âói7f-›¯êKø|ø|ø|ø|>>>>>ìFM¦>ß]Ÿ/ -üÁñcôNKRb{F&¦xI?Óû¬P÷N{8¶ÿ]׃Á M™O Û\í»½¬Ó^rçxã¾QI¯uõóbþÖƒã>b®û|j2¿ßoçøÓ’Õ{fÂçÃçÃçÃç#ðùðùðùðùðù0+Lã¼M†Ïw×ççŸÌdé¥Xœi ýU,陘Âé "4ä‰3Ñlsöe> ¦š¦•°C;ý¿¹ûÁ³–ž¾hRÒ½?ÔúÁ´ñŒ`püuõ.ÎϹíómN‹€ÏÏÁçÃçÃçÃç#ðùðùðùðùðù€ÚE¢ñ@8ŽÇãu~ˆ¼àóÓÙéÁñcLæ#SáÓÒŸ¤eÔŽãžíÃGqž#‰Pgnïì¸w ÅGr™_ÚÐy ’kñN[çó^r縤{_ÿä»GÏEŸO '^ŸÐ¥K£§JèB¨¡h?<Îðùðùðùðù|>|>|>|>|>0 ñíãŸo¥©;!q>´@ÛPŠý>8~ ‘HÄ*äƒÁ ñKŸ-8bÚ”ù4àÒRt`}!¹î ŸoóI§LK:vÊ© ¾*]Í:‰‹>ŸÏŒP+{¬O*0/>>>>χχχχÏ4þð¦Ïo=(«áìKfh™Áñc#ShA@CݸÕäÓ;6K©iÜ´érƒÁ ®ë¦ÓØ*DFb¹_ð[«}¾O_4)éØoÚ®û|ô]&]<’.ú|¶Q:˜Þ®}ŸOgêóáóáóáóKn>>>>>Š_ÞôùGÒíÓ6”BÃ@îë -Z4ùVñnEÓ4^>7™Oã/_@Q”ÛØ§Änÿ_>ßzŸ¯ûÚ-IIÇ~Öò ŸvÉ+³Â›fµ3™ÂYè)&EUUv}åHe¾é8ÃçÃçÃçÃç#ðùðùðùðùðù€º‚nBÃá°µ(¿$¼éóÓÙi‰öiêN á ÷u í—OÓ >·/óiåk _ -¹ûåŒÏ·þÔG%½:å¤S¦ƒßz'—Ñ=r0+¼iö`%zð£¦g»§–nÎåÇ>>>>χχχχÏÔš¦Aã;ˆ7}>ÑÜ«KÌO2“-‰D¢§§g`` ›Ízê»4e=7eWWš²$TU¥ž¼¤ÒnÞóÛF«Ì§wÄØú5åÏ·Åù[ÏZ>!éÒWnóùr‘ëB¹‘˜‹GÒEŸOXtŽƒ ++vX4'fPØñù´!É)í Ïÿ÷+ÎùÞƒ×Ô@δæ¯39ËFþCÈ÷çjÊÙùü€òЉ4äseãÕ?4ò£!–ùÉÆÐ¹WQÎÛ¸ê|–¦U4­º°iÕEMW-Ü4“E›®ºxÓJŠòðL.yxåâGV^úÈÊ¥F.Û¼âòÍ+–ÍäÊ囯\±ùÊ•[®¼jËòУ˯~tù5.ûÙcË~þز뚗]ß¼ìÍWÜÐ|ÅÍWü*ry8rù-_¶æñËnÛºô×Û–®Û¶ôömKŸXrÇKî~òÒ?<¹øÏ-‹ïyê’û¶_¢nWØ®<´CiÚñÓGž¹øÑg.Žì\´mç–gnßµpçs=½pOô‚Öèßs~ÛÞóc{Ïko=÷­ÖŸ¼S[êß6O]G¨úÊóFö -Ù“Ïî|¢–<—Ï®™¼ý¬,çžÈ3ù<ÏŽ|¶Ÿû–)Oia9o&OyBȶãy“gk>çɧù|s3ò¨-ùl¶ä‘|6²IH“‘…ò‘¿žÈyÀ’û…¨F6äsŸ%¹àDÖ¹WÈ=Fþ|<í<ÊçBþ`ä÷–Ü=“×Yî2r§;X.<žF!¿3ò[!·ù%ëX.šÉùõEûXn³d­[¬rËL^s³‘Õù„‘Ò²yE|> |¬ß‘ãé5Ÿß>,+æì<’.===]©T -gBUƒ¦DS›Äb±‚Ä‹ -…¬+áÛ’eXSþô§O>ÿ͵­ I—~ú¢Iÿɺþx nëósùý‚Ó 8X¢/ñùš¦ÑgŽÐKëã$}>‚ ¨÷ÏS¿c‹ R{Áý`n˜|¾¢(åáH±Y O¯ùüÁñcù³ëÀ˜›dæ0“Éà?«ªASÖ ÔŽ===hÊX,fÕ˜å@k ‡Ã¾R å ®G”ùÅÆÖ” <äó­?uA»¤?oÜ7êóåBgGro‡\?æ.ú|:°t0y•‚üÒ¥¤éŽÀöÍ‘KºîbßÂ:­ƒþD_ŸÞ× Ø´ëFáó>AÏTÖúü2©üM±7§×|>¡vŒó?ô'G6‘J¥  k4emÍfë¹)u]F£¼>™~:¥ôK-˧M[]+ƒv/ ‹í!kÊo|Åç[ú¢$>Éã>_.ºZÉÄÜ=þîúü\)W8´d…÷?¸T0QŠ¢ÐvM¥ðùŸ ‚Àçªøüy:žôù»ŒIÐàø1ü;jMÓTUeõÏŽP´rfDí ãñxÁµE";2_$´tÓÊ Ý’Îü» ™ÀiZn·ûwîú|qÖƒ×|>o÷P¨Òs(ØUŠé>AàóAø|@A7• ŽRÌZÔ ^öùGÒÔ6”¿ zÑu=KÊæm -sÉú©‡g¥þöQE²QîuíÎÈèÓÖ5î+:ÙŠþäóåÂ竹^ÕõqÑ竪*¶;R*VŠ@gd›µ1Сp¼>¨^¼ì󓙬Äç7÷êh>@õR° ŸëÜ2Ÿ5ÏÁäª 5JËØÙ½‘‰©]Æz¥û» »%=ùÊ c'2ý‡è‡ô{ûðQw[ÄEŸÏŠó©É¢Ñ¨NÂbgfå…މu»ðùê¯ùüd&ÛÔP;Fû’zÙÜ«KDP:;T)&ß®(Šªª¦:ä9‰D$5ÿÅ q¶ä{×±|þç’nüêköÞ|ÛÓü¥»-â¢Ïg¥¹ÂÛµïóËœ-27Ø%Šõ|>€ºÅk>¿}ø¨X~ß6”’ˆ Î#iþÁd&KAƒª…H$Bo(rª${n&Ÿ=Jp\Õª£’Þ›'Ñôo-oìöȬ+×}¾³Tì0«Ïƒž¢%A¥ ­[ÿŸ nñšÏïKf¸çIf²âKkZŽ›>Ūú ~Ðuzò¹™|¿ß?ªvdbÊŽÌß²7–|æßøËý‡'Ü=’.ú|æÕ]ÑæÞ$ÓÉYlR|>‹ÅÂápƒ¢(š¦9¾¯ùütvÚT~/qAjÇ(ûTK’½³ëÀÎ@@ƒB(òûý¾9ACŒãeùŒý‡'ìøü—žòÝö?ñ—Ôÿ»{<]ôù‘HÄ;±ëÈe~>PÓPHãÑ< Ð`Î4Ðý{Á¿Òõ+Õ³Bï;kõ½æós9O?%:hdb*÷uw”Ìdq‚j›h4ª(Šo®X,æünˆäzÕ\F—÷ÛdbJ4<âKkZú“ìS¦ª~; t¤Óiœ“U šMYÛP‡¯ªªX³77Eqv†× 2zn§Ÿùü‘¿/´Sœÿôs¯· ¥ØïjǨ޳‹>¿Ø¤¼bØ1ðö·kgmlI:…\9¦=„ÏÔl––”èx„b -=‰ð‹7Õr‹‹Å¸ÕwêžÚƒ>ŸhêN0ÉÓ6”_L:;³TõÛ¡¯¯™CW;hÊš¡§§§š’n½©kUËÖŒñxÜô0wÎPo§¢;Ò’4¾”lxq~‹ïÝ®íøü×^ý˜—ñ·÷BÃÁçϺ¤G.àóµG±À© Y LŠ)tEQŠÉ|†®ëÜí8R­áMŸßzpœIž¦î„ø²`ú’Z&™ÉšÞ™•±±±¡¡!œÕš²fH$Ô”ÃÃÃÕûâñ8/¤Ÿ›Ò§;÷p8\~5>ƒ† ›*€6:G]lçGWÿoÿÉwN[wß«‡ìøü—^îá¿LLy¡í\ôù‘H¤±œÒ;6}>?2ðù0Oˆ£°È|M¬%Rì¾Øï÷Óû@@òÙh4ê`µ†7}~_2Ã=O2“_Zà ;MUýPaâñ8ëÆKõùº®G"‘P($~¼Lh(¡uÚÙº¦i¦Y4ДðµßçZ|ÓÖù|ë)û>ŸUæ¯ß½÷sñ¹­pÑçW:+ò𫎆âˆç†ê yŸ¨=h,¶^85#”O1…ÎއÒÏêº>—úÉ"xÓç§³Ó\ûtI‹/­á.¨m(å5;¨"‘ˆx'Nꬳ¨èæ]UUV#í ´B›&?g<#w›~·ÿÙRZ®Å¹î &ómúügZ»G&¦ÔŽQÖÉ{¤ëÄç‹_³$èÜpdb`ùÀçjêŸÅÙy¡PÈ#½.ÈÍæógõ5ïó‰]Ƙö™˜¢—-ýI‰Jf²9KU?N3@ňD"¢ù¤{ðY—ïÙ‚¶[ÒÔ­p8,~< ÆãñÒ¾y[ƒXœOùæw[¹¡{mkBÒi¿Öþ…±N|~.?°$EÑ4Í#ûŸ¨ah ¦ñ&ÀkSèlV;êóƒãǸ–o>*QCûO°Åø;ôYœf€Ê`’ùòΙnÒYWï ~¿? -•¤[­»1—:ÀCÑ\‹O]ù}.óóy±qßh±›þt$®y®=ãói7è2€ÏÚô»ªªº&‹ø9À£äG<ó|>€ -SL¡³RIºy—|–‹£h4ZþžxÙ狌LLI|~s¯ÎcÚŸ^¦³Ó8ÍÀTâN]t±%u]…BΚü`0H[,Õôjšfz Ùm»ú–oøO¾Ëäó¿}F\Òc¯Ü0VÊ‚ÊáºÏ§vä¿àSÕiwÍ6çHy@%Ï€*BÓ´˜£¸2™‘ß›‡ÃaºæõoôíèMúS±{vÚÛ@ À>^R)f1ªÅçjǨDñJ~¨¼ UæS¯ÎºwG €†9¢¸ƒs/Ànñ…ξÜRœ¿~ášÏ%Ýõé‹&ÝxK;,•ß:ïvÎP(äàFÙD€9>Íqø|¨"Lò¤|bn” J ¿·–ßÓ;Á`ÐYý^E>¿õà¸Dµ ¥ðߨ0¼šZRâN£ ïºË„¶ -…ʶt]W…Fœ2 ³ãÛ~a•ù>ßæ›¶ë’îúœ ¿òfkºëóÅs‰ÚE|ÈB;&Îì¨:ýî8ðùPEԆϧoA÷æüæ½ &ÍbZxîå”Eާ÷}~_2#DMÝ üw*L4õ듳 Ö‡¼®ÓаÃêóO]Ð*é«oÚ®—÷ aqÑçG"¶]EQŠM¤sŒ=ñ§ŸuþŸ¨a¨·wk -9À_„®Öhè^ž¾ÝÈso/ñùÖæU‘Ï'ÔŽQ‰&™˜Â?À#°ør†§`0‡zzë8±Øg…Šóן¾è=IG½pMÊíQWò\óù¬ü>ÈßÃùx¸C+o”Bg£G¦ÀçjêÛi à#õº°ú¨yølt¿ßO×?tgªiÿ+ýN×Hô>+oóøŒuºxw>—÷ùôÓÙÕåóÛ†RMD-im‰D¢§§g`` ›Íâß§ªAS¢)½F<ƒsÓøÔ«ªj<ˆ¦% úü•I:êoŸq̳ßÈEŸÏŽËöˆ.fÜ:] ðK#9Þ˜\Ÿ¨=èÊÁÚë:ÛÛx ºÚá&D^É@åæßËJß]ãÍG…Fuùü‘‰)‰&jêN”´¶žžž.ƒT*åýïДhÊj!Ú´£Zž&ú`uUâÅbŸ56¾Xp¯èó÷HER/×|¾ý ƒlÔvpÈæWDv@}>ÌÅzc”è VÑ4]ðƒA›×<ü’Éû5óJuù|¢©;!Qú#SöW588ÈÌa&“Á?QUƒ¦¬¨{zzª·)y§jßä;åHiøSU•:óJ–óÅZ_eþ7¿ó˜¤‹^¹aÌËòµ}>{lÓ@€ÖL;Àæ•ЉËÃfÐOï8%ø|@íÁæb[qvj6€wàþ$ÚüÝ–²„B!º*òùmC)‰,¢¿–´¶T*\ )kƒl6[½MIÃJ±›ñb„ÃaG©¦i4–‰“*vûÿƒÿ÷gÑ矵üo’.úôE“ñ¸w[ÐEŸÏÎ;b˜owê‘ Ûn àç!{Çtþ°K…J>'’Ÿ¨=ødsu^{€†+”9|Šnc]Üsºe…B´\ªÏZ¨É ¼#;Pu>dbJ"‹šºøwT]×™hµ u¹q'Ôv4-ø!^on*Χ¬Ü𾤋>ó’ÉÁñcžmD}>‹ý~¿ÜÛðrzûÕ rØ3 UPâ¬ßú<ˆ]¨Ä½ñ<>P{Pÿ/>—gPŸŒ#€Z¥Ÿ_ùÛvN±2Œ`0(¹e®sŸO4u'$¾¨/‰"m@E¡›?–º[Ÿõ¹­-ÒRp£Ô™W¾8ÿ¤S8}Q”"éœç<‘ªb¸èó5Mã§G±æSU•-#–Ó—‰u6»* Ÿ¦%Ù‹GJôáó5 õÆâÈ -…œêí<7ó%UŽñw÷¹˜ð)výV‡>?™É6u'ÔŽQæêÛ†RSÔzpÿ€òá–^®ßi1kA]1‚Á`ù÷æÑh´à¨A7þòêng‰<ôKKÒ›-î¢ÏÏ Ã1+ÈTU5–‡þ$§Šós…|>›`½$`»ç‘Kø|@ C×Ô-Ãä æáwÁ¡PÈæGøm{0¬ü³ûe.Òé%íÝ¡Óþ‹ïË¿¬³‡ÎË>¿}ø(³@ͽ:½™˜’˜"µc”0™ÉRð(S/]l±’d¾ýJŽ8R°jmêÉç÷Æ?¥ÍD@×'ýþ¹Ï_ÛªÙ÷ùÔ¥{³ÑÝõùÖ–-Hù“;DXi¸N:‘ -H°%áó8Ýu–t«+ë¤ò - ‹ím,ãû¦ºK­CŸßy$ÍEóóͽºD±2~ú)¾›˜´j±a"Ú—ùjX¶]Vï`©vQDr-¾™:±­;nmá2ÿÔ›ìË|ÊÈÄ”7ÛÝuŸÏW,Å7=¸q¼¹Ãá°õIS÷t‚±º}]×ù¥-ï…–‚Ï€€Ý~òHMÓ -.ÆnK¹¡_\™Ì(WètÃ.Ù½:ôùéì4AGÒôÎþÃYÔzpŸhéO2´ëÀ½Lf²³ú"kU?HˆÇãâ0á÷û‹•CÛ—ùÔµÚyj¬išjàÊ#æ¢dôÜ Áã2Ÿ2co7œõ°èóWnxß¾ÏgÏ[½‰w|~%¡Ë :ñL¢¾àîà“2Ï€Ú@×uEQ¼_0Éäi}>‰À´ŸõéóyA>¯ílîÕ%ʨ/™±Võ@1¨Cæ½.Šüyë¬XÈš MÐÚh[ö?RQÞçZ|ñ?.PÎ….¸M×'é½è“/‹2Ÿb_æ{¼7vÑç³R|:j ºå¤›b¹É…B.Ö@Úñù9¡:ÎdÚëÓçLL‰®>'~I (wþ¬ªßD6›M¥Rø¯©vДhÊ2‰F£¦é]ÅÆ>‘ùš¦ªEñJcˆäZ|ú–oN[Ǽ½ª¾§ë“÷Š2ÿ» O—äóÓÙiÏž~.úüªˆ½|> &¡kºx`RéR¤Ø$A€Z….‡"‘H8nhll¤ë"M>ß7vç>k%]ȱ%Å˹úôùDSw‚é ¶¡×—Ìd%ÊHíMg§Eço]áÀÀ@—A:êýêM‰¦,Q­óð4vÈ‹¨Å#­‡w¼V™ïÖÄ13‰x®ÅGQÎqu‰tݱîSqþÂ5ûìËüæ^Ý˧Ÿ‹>ŸÍ.ôûýè쟨=ÄÙÙv.'@… ìÎ]þp»Z’KžºõùmC)f„šºì^~_0GÒ¢ógUý"}}}Ì¢®»ÚASÖ ===®4%ï ‹Ý8S_ͰÎJ$)¶!êÕYÿoš2æ…gÍ'HÄs;ý¹_äº3¸·ohØ¡õ šd>em«fßç·õòéç¢Ï§!žm—NEwý 4x¹¥àóµG8.8¯GÀ#pw éöY²$¿´ãJ¿n}~_2Ã¥P2“¥wÄò{kZŽç„ª~öRdlll```hh'dµƒ¦¬‰5åððpå7M¬¦iÅþd-™›ƒÌ'Lë¡ÞCŸ‘Ñs»¹_ü ü'ߍ½ßÿ ¦%• #&™ê‚Möe>edbÊ˧Ÿ‹>Ÿ 3‡tV;ç 6gÄtršˆF£Þ)…ÏÔÅæÊojvãI7§Š¢4pÁB¿ðBww÷P¼qƒ¡P¨`9œ©(4dPŸ>ŸàRhÿá z)–ß[£vŒæ„ª~öJ¾̧Åh葯¯Šº\/ FèUs->}Ë7§­ãÞ>ý$Öúºµ8ÿÛgeáš}×né—ôÃk[ M¯ŠævÑç+Ë,FÁ€9@\æ³Çü ÜC”èÃçjq ‹¾pdPÛHª(M>Ÿ¹× -{ú î³dIú -¦oçÈ>T—Ï'Çq™Oì?P“ð>™Pœ€ÚF×uQwÓpÃï|M~F¼uÚ º~›õöœ¾c$¡¯ÀÊõÙtÕù|ÉLV⑚{uZ¦óHš~oêNÐÂøOÌ -u¶öý*uÈ´|Í|wU}‹ú`p«®OF6·Kd>åÇ×i’~ø–û&«å»»èóãñx¬œšcÈÎsÓåGÁ#À®¿T /N6lÒŠ}mŸ¨U¨{gw…ÑhG5õbá=¿7ïUéMnþ@·j÷ù9¡ü¾`àð%Çih°)ó©ç¬%™Ÿ›Þd–ÞïPÓ’Zß ÿ令>óµ[’’Nxõº¯ªå»»èóÝ‚]™Dze|¾¦iÖ§f6? ŸÕÝr™/Þ–ôù¹¯ósù_«Ð—eeawÓ+V¬X´h‘d%Ùlvtt4•JÉ·E Ðb´p%Wõü'£•Ôy$íÊ^aUXVå‘UE£Ñ‚unWE#‚8ÕKN(ª½Ã·Rè—\F§_äÅù>ß‹’xmkÂ4ÆzùXµµµÕ›Ï/øe ¾‡ôùtÙÆÿÑèZm0´¿ò2}þ³;wÒ§ayçíw橇Á±E©½ÔÉE2 2¨ªZÐÛóù9CÚ°?)ŠRÛÇZÿf¥«««££C²’.ƒt:]l™T*Å–¬äª^éøDb“žüè°+{…UaUX•VÅ$¤ÕO\Ÿ¯dZsÍö;Ö½0›Ì_ÿ|@Ò/¹s\Óæå ҟ쬊þjU[·n­7ŸÏ®ìÔçƒAñ´/>§’®Áø ûS]ÊôùâÇy@½žz[AÚK\$*ݲCÓ=©ÄççòÓÌï‘ìÔšvuu HVÒÓÓÃt‡¤Êqtt”-SùUýåƒ/$BÉ­½Âª°*¬ÊÅU½õÖ[gžy¦ØÑIV¥ë:Œv'v% ;{Õ××7ëôÔªb/uÎ*óC¡/½í¨¤û½ôÆ´g¿ uUÍÍÍõæóÙ/>Ó„a=üjÊ‘)ôïÆ+óí;|ø|ÏGAàóÕ/A7½/÷ùÅ>åeâñxC›¡»ï†â:ÍÍÍkÖ¬‘¬$‘H I–Éf³ƒƒƒ´˜D›ÌÓªv“¥}½]Ù+¬ -«ÂªÜZÕž={N9åîfý~¿ÉCŠ«ÒuÕÛVF­«¢-.X°@RÀìñÃNË‹ïëúd`Á½r™ nU”îk·$%Ýïêu_Ü«±±±9ìÕ|¯jïÞ½®û|:QEaC³„‚W5s@Ó4¶BU°â¦#@ÿŸ}³’¢¼÷ýþ­JÝηêƪS™:§NYÇœh+˜_`xµ£øÆ‹´ ¢Øˆb≎c£¶r_0Û®q±MÜ@<‡ã\B¼$\“,îÞŰÍ!ìÉ:=›v˜0÷7ýì>ôÎKOÏìÌÎtÏ÷S¿¢všž~yúy~Ïô§ÍާlýžÿmVö ’ðù|>@ àó~§q|>?£J6µ Ûš÷uÈþφ\„RÛá¼ßŠÅbÝÝÝ.žø\J\J'ªª:Íg(ÊzuË w•^E1ï¦h¡óM¨\é:­hq¾®ÚÔô‘Kî]Ó{î¹>ʊϰ%QRW¬”ÏO”賟š¦qÃωvÄûv¥vÊx”½Á -úü '|ù¢_ F|yÆå—L¿ü²é—_>íò¯M›ø©¯š2aÒ” áð„©á˦O¾lÆäË®™té¬I—^7éÒ믾töÕâ W‹7^%Þt•(]%~ó*ñæ«.¹ùÊKn‰9vÜÊãŠKn·ÇÅUˆÌöoµ€ Û7íã¼ÉŽ탟}uæDèt®µÏ‹Înæ¤Ké4§Ä´ðetîS™F˜l·ÆÕS&P³\9eÂS3MDñõ©©¹¾:m"µÅÄé—O°›±h\ê9Doq‰·¸Ø[|Å[üëôË7¼ùZ•ÒšÿÇTV\^øW/1Ý-¾Rz\ì9¼ôÉ¢}»èqh -ÇDgL;——™±Ÿ_ã1u8¾žßÈWŒŽ+1…"“²âêÑ1itLæÎDxtL9”è2éÎÓx8²bnÌpÄÌáÈäÒk1Ë×:â:v6æ1{8D6Ѱ¸‘ÇH&¿id’F¦!7çLI·äLOÎjôÄtq=Ÿ+³çPgÜz…c¶uœàœ-iœ‘¶â ˜™GæG{Š¯Ï™%3¥}­³fIê]|Šdó#u{63ÒøºøÊKàóUB–evoH÷¡Îåî>Ÿ×›ùèLáóó2”:ëâ”6ˆåýVGGG»{ý*¨p)q)9|:àÀ.ź®;=¼;…6•%ó Õç×û#é]R:fúíµÝEe¾ª~LñßvɽsÖ|ðA—Fe }>u-ï]±²>?wÔä…Ö©ÔîêÊç_zÿìðß -FÌØñè7ùÈ‚_¬^¦¯ZýŽòøÛ+ŸÞ|¿Úºâ•Ÿ,×Z–ýT[º­ùÞ÷__òÁ¦{>|uñîWýöå»?Þx÷7È^ZØùï ®¿ëÐú»¿¸àÈ‹ó½0ÿ¸:ÿ„:¿WÿWu^ßóó>{~žõÅÜøssûŸ›û·g‡c w&ì8Y¹ ÍÒ¾h¿t~aþ‘t¯_@GHÇIG»oƒüûòï^¾ûÿ¼²èׯ,оºhçk‹µéž_¾¾äç?^ònó’·›ïݬ-}ëeo´,ûñ›Ë^ýÉò oÝ·þ­û¨5žÝ¼â›ïjËkö5Ñco¯|tëƒÔ\Ê6åþwW-×W-yï¡Eï=´ðç«yÜÅâ«dâaŠù£cžsߎ;sâ;n‰ÛFÇ­#1§â‘[râf;¾IñËLH£bÍM#q#Åö57äÄ쑸>^7:®Ýþè[ÿ³J™mÊxuþ)Œ_‹©Ùñ(ibº{ìÈÄŒÑ1st\S(¶?:Ë×:âº|q}&ØE?ײ»ë6vðŽ4ªƒ±Ž7Ò oÎêœï?2‡ú­£;;6ëí¬ó;‡ÃÜ_d‚ç8ZðóÕ F†›sÊï­¾ÛŽEöØd±ø½‡î±cÉHÜ«¯¢Xª¯Z64œ—¿»ê>;VŒÄýÛV=°mÕÊ‘xp›BAÃÕH<ô޲:>lÇ#ï<¸fk&µã[[W~ëí•ß¶SÅ¿Ùñ·W>nÇo¯Œü,Of"“dÖmyà»#ñÔæ¾·ùþ§íøþæû)ýÐŽg6¯xæ§+~ôÓÏÚñ\ëŠç[W¨v¼ÐºâÅ·V¬ÏÄ}ÿþÖ}/½uß;6¾ußË?YþН¾¹üµ7—ozsÅë-Ëší œOٯŎ7[–ýäeo½A)qi«¶t³[´¥?k¾÷m;¶6ß»-™ä©ÿxÉ{?Î$Ò_¼¾ä};Ú^_²}Å=;6ÝCi–fÿØ´ø?_[LY÷¿^[L³ eàÿýê¢]v6¦øÍ+‹>²c=ËP¢Þ»ñîÿ›‰LÞþÃÙØ Ó¼³oÃÂý¶¿”I韼´°ãß3ÓÐÿ³g"Š?Ùó¥}óÅ4+õÐÄôÂü£/d¦š›øôôßê|š&(bö •™žì‰©²óQI‘pÄÀpd&Ê¿9‚²ßžL)¬áÈœÂgö¹PüõùyÿmŸ`¯}¦ì”ÿl·µCÝ&Ô8ÔDŸÚÍEM×a·$5é7,¤F¦§–ßc_>KÒµ£ëH×”.ñ;Í÷nÉÌ’K©Ÿ¼þæ2êH/ÙS$õCêŸÔ©WS·§A£†Æ—ôÜ]ðù€*¡iZÞ{CŸÏ+Ðüå±é°##TdƒÁðùDs§å¢•N žÉýJOO3‡ÉdƒÈ×àR†îînºŽå]Ê,-éž'ùÄá…B–>ë‰@gUHZéátkS&ÞËÿkÜøÍïŠÊüpxK:£ O-^û.‰÷†e+ûRÖ„ú|>Sw¢¿³ŠÆêÉ…Þ CRKwæ…;’þà?i¨ñ½o>>>>>>>>>>àwxaýk_îâóùí$Ý]6rÓÆçï>~ÒE+ííÌû­D" p)ƒA*•*ûR:ý<ÍîzÐKA2ßT¡i"ë‰@½Ëü˜‘qøLæSlsW1Œ^AXï.óiË:•YûD´õ7ï¹$^å™ÄßOù¨ûÕÐçó¿a*m–fù¢/P ЯI’Â6´¾®ë.o¸” -ÿé5Æ7àóáóáóáóáóáóáóáóáóáóÀYÛÆ5N^Ÿoš&¿£¤;h´[0|þ‰Á3.Z©¹Ó Øp»î.Ei -EÑ»Ì/´©,™_Ô”Ö˜C7ùÖ¦óoº4£÷GcY§Ä~²hq~4z„òmÏÀéôþˆKÖõcϯö#!UUiûÔó³–S÷¦³·×h˜Ð þ"ý¡¤â -ø|ø|ø|ø|ø|ø|ø|ø|ø|ø|@0pÖ}I’¤Úð{d^uæ40%½ßH|íó·êÿþþÚz0Î>n<sÑJC©³#Êù”Ó\䤮ëìe./ˆ¢X¨29«¼¿ÞßóÚ#s™¯-È´|$òѨu’–(¶•ùŠòaW<É]}QŸOá£þSCŸÏºeI5ê%Áæú܉žýpªÞ~]f,û…χχχχχχχχχÏ˲²t½{Õe:…èhª½G_û|âIúØvxÀÅ)íÿlˆ}k(u¶gàt<™Â q ìª(J“gdY.$ó ÃðÌOZéí"—ùʬ¹™‡·8W”çþ´¨ÌÅ–ôȃTú|°_/Õ{˃•7侓ŸŸŸŸŸŸŸŸŸŸŸ¨9š¦ñW¹ A7°†aÔÉÓ‘°7Ð]=°× \ŠNËÆ×>Ÿä· ¼j4o°uø·Ô}}¨Ø A 4+Š¢w™ï®U)óä\×/yÅŒôV™|kÓyáYæ”óšÖÎW|ò‘Ö¢2_ÖF/­LÉÓ»Ïßy,á£~RCŸÏvM¿^ -=EûજËáóáóáóáóáóáóáóáóáóáóáóu‚®ëtÓš%pè¾UQ”ú1ù¦iºhüB%£•µú¾öù;%˜2R÷õ¥íÂ{­ÄÖI;ªúyÅ> Àhš&‚÷4ë¥Þ>Rò¬Æ3ÖJ²Kb2ßxú‚Ðÿ|ÌiæuýSGû´•ùì+îMsƒ½<åjèó öþH–o¯ ü÷ ÚKĆÕ?ÐE¼Q‘XðùðùðùðùðùðùðùðùðùðùàG Ã(I19Ëõ+øHÂ×>ÿÄà™,k´íP¿‹Yê8Më4wZYû€ ÂiM²kíÙI·6iK' -ç¯ãZ^[X™=Ãøð/2ŸóSÚ,Éçûë5¨qðù–eE Ô»(Šš¦E])ãYRÙ¿:œT¤’>>>>>>>>>>|݉;o«%Ibeo¹*‰Ö¤åªªÒ:ÕN¾öùÄÆ1§œßÛ;èb–vKÐ:»ŸÌªØ˲JzJÅ@É|›ï|©å%I·¬Sü?pªþB!Ë;øW(mz—ùÍ–¿šk|¾sãïÕé…,Ëðùðùðùðùðùðùðùðùðùðùðù€šcFØFÓ4_¡5ÙWj"pø µ$IÞ«ì,ËâV¿RúÝï>籄SÎÇ“©¢rÉYÕÏ*öƒ{(òn))µR‚ X#(ʇN-‰|äü_Mk÷"ó%Iç_éŠ'K*ÎgP}Dà}>ƒ½#±aÄ~D¼A_{#ÀçÃçÃçÃçÃçÃçÃçÃçÃçÃç¿Aö~o8öÛɱÀŠóEQ,㻼â´"O"üîór¾+ž¤%Í–‹_Š'SiG‰éûŸö%>3N —T*ÕׇKðKÉ^VòòTÓ4ç PEQK÷¾ Þœ¼ ¬×õOG7Q{Q“O!Š-¬žß0zé¶Ã%ùüß™'ü5*ÇÁçóòƒ1â½z¡X' ÿ!ø|ø|ø|ø|ø|ø|ø|ø|ø|ø|(Ãçó -ùñ÷ùt;Ïv]Þý8ÿzE”ß}>±ñ@Œ¹£¶ÃiGÅ~ÞØÛ;Hëp+µÁøK{{ûÐБ¯éîîn·Á¥ ê¥Ôu)zú×} <§y! -Õä­ñ!S/¬ÅÃèÍZîEæÓw™Ì—åì#ê1þÐþ‰¿Få8øüzCQ” ->ð|>|>|>|>|>|>|>|>|>|> ᯊ3¸œ÷øÎ8ÝÀVä¥õ²žíºì÷Ö+xäðù\à«ûúècÏÀi¿ÔÜiÑ:û?:gø÷w ®Ûïtuu1 ŒKéw:::r/¥3c»ˆV˲$Iò.óiâ ¯4Z {—ùì)€ª~Ì–\þYI2Ÿ=-õרl@Ÿ_àóáóáóáóáóáóáóáóáóáó HI˜îèº>ÎÏAy»¶, >ßɉÁ3Ü õ œ¦%îE¤ñdj(u–üõ¡¿`@ùþþþîîîcÇŽ¡)üN,£KyüøqöÑ4MQ³$|Þ/RbÌZÓA\ -’)+R>ÿ©að(ó)týÓtæu°^AXÏ–\9÷—^4þ÷ÚºYþøÈ_—ÒÀçðùðùðùðùðùðùðùðùðùðù€¤R>¿&› yI’Êøº¦i|ŸOl;ÔÏkÃ.ºioï ­Óz0Î>Òw1 ¨C(Å ‚àE—$óiMÃ0 -픿í<£ûäcÛ=Ê|Mkg_žpËc×µ}ztÃÞøœµn öÍöoÕÐçSߦž©SÓ¦iR …B¾~µ>>>>>>>>>>ЀÐoØ79t“ö†$I.õ™Õ†°Zâ}¨a\pUäv>>?‹®xÒE71í¿·w}l=Ç€ ÞPÅ£„/IæS¢+”9³¶C™¶®(i¥wI™H˜E×µ¬S’¤—*óey_¨Ìº1ÝÚ”>U”ô’Mq—»cû_ýÛëjèóé7‰Ëë'NèwNM^-¬ uåó/šñÕK˜¸bö˯/¿næÒY×/™%Ý3sÎâ™w.š¹àîwËÓïY8mÙ]ÓV,˜ºrÁTeþ”Õó¦<2/üè¼ð·çNþ·¹“¿sòwN~òŽÉkîŽÉOÝ>ù{·O¢xúöIß¿-?¸mÒ3qõ3,n½úGŽx¶ÒAÛ¤}Ñ~鞺}ÛöAÒÑ>6wò·æ…×Ì Ó)Љ¬š?…ΈÎëþSï»kêò»¦-]8mÉÂé‹åé‹äéòÝÓïº{ÆüE3æ-šA­qû¢™·.δÌÍ÷̤&ºqÉ57,¹æú%×\{ï¬kî5séµ3–^;uÙµSf±œÅu“½Å¤œ¸:'®Ê×_™W8ã¾ë¿‘/¾î!¾–‰ÙYñÕûfoúek•{™Ërc…טPJL,%./öÅÊ_+™‹þuo‘·_}#«ûåtÎ|}xT'Ïn£†µÑbª#¦9bº#f,=3³ƒ†ö¬k–fÆ8Ŭ‘¸Ö×%O;®™=7äÄ#qÓ=,2É„Å7G‚2ÌÍ‹gÞ2sFe¡[eâ6;n‰;ì¸s$æÚ1/3xP6›÷ŒvÜeÇÂáȤ;Yž~·‹±ØŽ{2A&–dbÚ½vP¶\zWfv X~.2¹ô¾SWØA©õ;VÚñ …uyP~h^&VÛñ°ØYz=Ñð Ôým{ÞyÌÊçß±ƒæ 6 ±ˆØó›’جô];ì¹éÜôÄf¨ ÏPÃÓS5¦¤²'²¼Aè3#GûÃá>‹Ü6<ç²³ûž#èÜY#¬³Û„µOd¤Å¨õ¾c·ç·íùñÑ‘)òaûº(ŽYr…=KÒå¦>°xáð,I}‰O‘l~¤ŽM]ýºÌ´8‹Æ×·M†ÏT ~^ö½á8CwâN¿¤iZQ9o†³pTQ”ŠI }>¡îës1Nñdj(u¶õ`|ãXW<‰@ýëç)õÊ”™Þô‚KÚ4M3Kæ»Ôðמ„™Þ.f;Åž"Ø0zeöe~$ò_(~i•µé¼ôVöû¿þá¬Kjìê«ÐÔTjèóY7öRfÀ~ øå×N^êÊç#ˆÕª4ØÑ¶¼ðño}@ýá;ŸŸ¹%Ï*@ ‡Ã‘ÑÐj´×äó5+RœŸ®Ïo;<à"ööbÔPŸð¤Ä¼º‹át¾¯äNIÛqy .ˆµÎd>Åïݺ®*ëK•ùô_(œ¿Îxú‚ÌŽŽfJÂ/ -»½ý4g퀇óú¥†>Ÿí”Àãñõ”mšfÔ†þ(o ðù|>@ àó~‡n ™ýör/\?¨ªêQF9‘$©R2?\Ÿßw“NÍVN€ A‰Ñ‹W/Iæ»lGÓ´,™_Á[y²dþv1,x´Î{÷„õÑè‘‘†íuþ×°Ìß%¥3¡ÓsÖº=*½(œôP`^¿Àç×ôÓ®ÐÈ…ÏG àóŸhL4M£ûb­¦ö=‰…BM~ÅXÕçê¾>ïO¦0¨C,ËRm\¼ºw™ïîç)ÿ;W–뼸Ü!óµ¥™o×õOóµá)IÒ½Ë|Ãèåß ‡·œ«Ø_:1³»÷Bì© ¤×´Å\òêç>¶Ü‚뺠†>Ÿý ðòƒ„½ÜTŸ¶Ñuÿ.¢?r­þ}þSk×Ѫ“¯¼Šá¥_¹¸Ú»CT$èJñ«FW°qN|ÛÖwª4¢ÑÕ§cœ}íuE×§uœ_Aú"0¥Ö[ò'(À_Ð=#+ݬ‡ƒ¡ÛUö|A’¤°ºsgïT©d4À>¿í°[éÞÞA üˆ®ëe¾»Ÿ§¬ë\YQ”º>í|2Ÿ"ù(kEÓŒ‹bKy2?ÑÅ;Ø=yËÌÌîh§´ë̳ô/<ã’T—l¢ýú»kÕÐçÓÔïe"¦_¬óÓÜÈÑM- ØÐ0gW„}Ìú 4FŸ?ÐQ9}Q /Vð¨ÿ~Ð@N9ÿÛ={Š®Oë ÌØw`J€FÀ4MfÅ‹¢(J­nÛëŠûü®xÒE=5wZ/øŽ¬Šú²e~z´Ï¯í‹ZÅ) ósëó£Ñ#‚°¾l™OXÝ¿¥]諾Ìv—>4Ü2’”ž¾ô¤KR½rî`?)J }>ïØî]‘ÿtaº;x°B 竈ªªæ6 |>¨P¸ÁwÀç7˜R ðp5]¡PCOåöù„º¯ÏÅ>Å“)Œ|DeþpŠPUI’œò°I˜…d¾¦µ>=š| -Ql±¬Syv·K6ù*_LSÄÊÍ–KFýâ…gê¼!‹RCŸOЯ¶kµ€;â2?À¿[˜ÏϽ(Yï#Àçƒj… Ð||~#€)‚®ëMeQïe™U&Ø>¿íð€‹}ú¯?õvtttww§Rûþ&‹áRþR:_ªªˆÌ÷ '¢Ee¾e’åÞe>­\pw{äa™¿gT3¾ülÌ%®i‹ ‚ïGem}¾ógL(¢Ù9:u~nû\œŸ†Ï5 - 3øøüFS*ç­®(ŠtKÈ—ÐáAà«Ñ ²iš ÞnÁöù]ñ¤‹€Ú`ü¥Ý&‘H`ùšŽŽ\Ê:GÓ4–“Ýe{¡KIßò(ó³¼_HZéí¢‹Ì7͸(¶x—ùYUýyv·?â¬Ìgüñ÷.étÎÚIòý¨¬­ÏO{{…~º8QÀ烅 Ð||~#€) ¿Á0 ¾œÝŠ¢è\Y×ufõ³–7&Áöù„º¯ÏÅAíÝŸ1NÉd=Á×ôôô0sˆKYo˜¦IIÆù ÕÝ”vwwÓuìèèp^Jï2?¨ï[iZ{!!o½‚°Þ£É§5iýòŽÁýu§‹Âɬ¶Ï{)뜚û|v ì§K.¡P(À•ù ø|PC p:ƒï€Ïo0¥@€áR:ëŽ/·,˹Ü0ŒÀVr–ÛtAòùñdªgà4ûÛÝAí>ƒ‰D—²®ˆF£y=¼{ªI¥RÎKI©[Å—ù†Ñ[HæGÛ~-œ¿Î£ÌÅË:å}¿C©³”?)(£¦‹=ìÊüïÞÞÁB—Ò/¶æ>ä¢4;óW éïÀ›||>¨!P¸ÁwÀç7˜R ÀH’ÄnÀÅùi»Ÿ-§ûÁ¬¯pmšf#7]ð|~ÏÀiæ—vKÐÇ®xÒÅA5wZ>TMÓòJxZX’r§|žUØß€2?ñ™GòÊü¬¢}÷å¥îw÷ñ“,On;ÔbðŒK"åÑz0î󦮟߰À烅 Ð||~#€) 9=k9¿7Ï­Ã7M“ý—ÚØ?Ò‚çó¹ƒR÷õ±%îe¥¬ôt(u¶gà4ûP6ykòiaîCUw4MóhòA(uã¾#ù(Þ¢ëŸ:Ú§™¯ª—±Sž9Y•¾Ÿ¿íP¿¯Û>¿æ(Š’õkÄ0 Z’õÀΩÚÊ/ÎgŒ@>ø(\€Îà;àóL©` -ù|˲ØrºCÌýV( -’Ç.àù|giÏÀiZân¢ööÒ:ÄØ#€¡ÔY (ʆgcfÚ)ÔñTÞ‡…d~ÖkY Jþ’$ÑÁäý_¿ã]æ ÂúhôÈè–9¥ªG"Ñ.»ØÿÙ3‘º?åAßòuÃÂçûø|Pí~…‹Î€Îà àóL©`¸AÊG.²ºÐS€†"x>?="ç)vKÐÇ®xÒE@5wZ´ÿH+c@P6𦠂 ŠbV=­G,Ë¢ïŽQæÓBú¯àe¶‘ö*óE±Å4ãÎïÒGZÈþW–w¸ì¥õ`œ¥DJ§î)Ô~ -ŸïàóAµû.::ƒ/€Ïo0¥@€áR:× 15$Bî·àóÓõù¼ ã[â^\O¦š;-ö7} -€šF¹‡/ -åv˲r7Â(ðÕdYR©êÇe¾,ïȪÀ7Œ^AXï\¡Ð^(%:ß`rÅ)ëÙ¨ß{ |¾/€ÏÕîWP¸è è ¾>¿À” -Æ0ŒBåš’$±ÿÒuݹܲ,ܶ§êóÕ¤ñd*í0üycoïàÎc ö·º¯ -'”TUU-¯ÞÞ#”EiòŒ‹Ìw®&ËrÞÕꎄ™>-º–,ïð(óUõ㜖UÕ/þó“Y¶ß O˜”)…º?å±ûøI¿wuø|¿ÐñÉ'¿Ý³§ìèïï¯öB>ø(\€Îà;àóL©lB¡¿ ‡Ã\=q½C+8ÅŽ,ËÁóØeHŸO8]}z´áÏÖƒñƒgøGZ -48ÌáK’ä¬uW«sK«ëº3…ŽÊ‹ÌWÅm}HK·6eâ÷nì]ækZ»ûwåI·[›ÎKïÉÿæÂPê,øm‡ö6äEæSPõ{·‡Ï•òÁ@átߟß`J€`ã¼ wÚi˲¸¢?E‰D"¢(ò5«ZtZÿÕço;ÔÏ]=[â^b:”:»ñ@ŒýMßÅ€¥JJ†”!)é”.*¾Sþ -•G -C–Ì÷Mbé­Â°ÏßY0 —-ó-ë”(¶8Wxò–™î»s -üƒgx.uÊŸðù R@>ø(\€Îà;àóL©x4MãêÞi§UU-¤†DQlðF ªÏw*©¡ÔYZÒvxÀEFÑú»ŸÌú -ð ©Tª¯¯/‘H )ʆ¿²äRošf÷¨ëº³ø¿(´2}%廬 ó)i.'™/ë£Ñ#Î/Fo(ôÚ¹Î_§¯úò¹ÝÍߘÍKƒOüÊúÁ³g=çS‚ À¨„Ï•òÁ@átߟß`J€FÀ²,UU%IRŹœ>æÚ¡p8Lë7x‹ÕçÇ“)§«§%]ñ¤‹ŒÚv¨?÷+À/tww·Û á•InY¾ ´RD4­ì¾hƒ.ozöjFÞ­™¦éw™o¾ð…è+«-ëTîZÞe¾aôæ\Ó-|ñK«Œ§/6ù´ß˜Qè¸xœpÃ) -—´ù@ó¹Ò}J°•ðù R8åÃ¥_¹xîíw ê?èJñ«¶lÉ½èÆŒÓçO¾ò*ŒŽº1ú|4 /‚Æ |>42¦i*ж‘e¹Pg£TŸŸvT™î>~’>¥Ü -MÕ}}ίl;Ô¾á#ººº˜9D‰¾˲¢Ñ¨Ç§–”C¡Kªª’çc„òpÑò¾àrN뙟´ÒÛEf×§/Î_×Ôô£P赬µÆ"ó IÒÙ -ÒDÙÚtް̧ý&ݺKƒ+7[MMé%›â.i³eÛ ¶2ý›»ŽŽßJø|P)œ>áÇ€2jp²D1ÂQ†ÏG 9>%À>¿+žT÷õm<‹'SlɶCý.nŠÖßÛ;È?òoú§¿¿¿»»ûرchŠh4ªªª,Ë¢(òÊöz80˲ò¾'UÊQE7Nç -…ü(ó­Mç‰_ZÅÍüè““ÌOgžžÄŸ¼ãVuÁÕÃ&Ÿbì.óÓö£ÏžÓŸûüÙ/\ðw—„IñÉÎnZŸVλX,F£òøñãþ>ðù "ÀçC_ŸŸ@rê™ûü\ö6äâ¦Ú8køO žA÷õiš4Š?%úU‚öNG(B©&? -E£Ñ^³™O!M”¹™W”ù*c—ùöGΙ| -úè MK75¥¯œ;è’0<ß_ÓnUàóA¥€Ï‡2¾>>ä Ô3 åóãÉ”‹žÚx –¶ëÁøîã'Ñ7@ýcšfQ+.IR­¯l“O(ŠbϧG9ö'o™Éͼ(¶ðU*#ó‰]Òð¾¶ -飺÷c¤Ù ©)½r³å’0'Üpªv=«ZÀçƒJñÛ={^TÕ‰5«vÊ–`œÔ;[·¢72Ô‚=l'_y•S㤎=ZôÊÒ:HÈHÎ@h(ŸO4wº*ÔäáÔAh8+Š¢ëz­”¸iš²,—gò[–ÏØfŽ]_õe§™·¬Sìÿ+&󉘑ÙÝ.)ó‡g ##ó¿pÁß]RedW­¼I>€2ȪwEƒPÿ8_@xQUÑ  @ÝÂýs¥²8*¥=Äçïít‘T;%0Ä@m1 CUUMÓ<®/IR(¢ñKcY×uÓ4k{üÌä—é,‚Y–Ï9ª§· -ÆÓç¯ãrž›ùJÊür‘åŒÏŸýpÂ%UÎY;@ëOÀçPÐGøøü ‚„  nϯR{6ˆÏ?1xÆER5wZb`œ1MSÓ4EQh :S“ê·Û+:‹¬S( Q Ãh„+nY§B¡×¸œ×´v¶¼d¾e¥!ãó×´Å\RåEá$­¼ËŸ@@à;àóƒ -2€º>¿JíÙ >ŸØxÀÍSÅ“)Œ2Pm,Ë¢¡GƒN—Ju_œ‹išŠ¢¸œHQ軾{x1Âá-\Î+ʇ™EI«d>Aס©)ýÅ Ýž{FvõÑ:¡ Þ#ÂçPÐGøøü ‚„  n1M3ZY–¥ž‘HDÓ4þ¿¬––;Ë_i¹eYÜž èówK¸¨ª½½ƒe ÚH’䮸iÊuu~º®¥ Ÿ™|JA–„¹œ‡·d>'-ù¦ï—!ó5­×öW -šššÒ³vK’ô¿´Ž¢ðÒÀçPÐGøøü ‚„ ÀwhšÆ‘{É=ý/³ú´¦a Þn èó{N»¨ªÖƒqŒ&Pmr58%%EQ(ÕRÒu]–å±ä3h#ŸY¨ª$í/Š-MM?¢-ë”w™ -½æ”ù¼ž_U?®à±ÉrÆç¯is{‰é‹ž¡uêþqS9ÀçPÐGøøü ‚„ À_X–ÅäýëEÑú\é£>¿Ñ|>¡îës±UC©³SÀ;ÑhT×õˆûÃDŽa’$ɲÌÞòÅiVJã³lãñ±ÏÕÌÿ¨ÏÉÈütZžûS/2Xþ·É©px ÿ¯Hä£ -XÊ0ZÂßvIkÚbMMiQ ìX†Ï T ððùA €¿PU•Ý€kšæñ+¦i²¯D"‘FnºÆôùm‡\„Õþφ0¦üE,ëèèèîîN¥RUÝå ¦îeY¦!“+·iI–Η²«$IM‚Íýù…óR† -…øwé0ÖoßøáKeÈ|VÞÏBÖ;‹öÇΙhtóóoº¤ÇÙ'ššÒ^nýÇmTVø|ÊúߟTø ®›J*¶geŸbP ½Ñ˜>¿+žtVÛõcLù‹ŽŽŽv›D"Q½½8]Ÿ ~oLÊ¢¬ßéÒÇmÐKM>¿”mmmÎÇ%”¨ö.•ñî3c”ùâ—VO_îTÇr»Ÿ¤Œwbð ûO¦\r#Å/:×O$…d¾³Ì»Y[Ë mŠ% Qi¼Ð1ÐñÐKJ;õ9‚$I^Ú§ h³´ýR§¯¯oÉ’%Y‚Ö¹iâ—VUFæSü^)û@6ˆeù|u_ŸKb|èñ¿<þîpæl=wßx*•*4*ëyPÀçP*ÐGøøü ‚„ À_(ŠÂnÀ#‘ˆÇ¯˜¦É¾ -5ôLÇ}¾ eT,³Æ»â}SYUÓ¹¨žpjšÍãïþši¨çö˜ôñ»?Þ⢭Ú°íœ<Óz0N#…1 ÃãQÑšQW¼ËO^s>öM9*ï zqݯ ÇÎàQÂ{iy§ s1Ï>uò%Aç¨ë:°MÕ„¶O°Œ#¤ šõ‚€êë{ÌùNÌ'Ý^1™¿§ü‡¼8Ÿ‚½¸ä\’‘]}Ñ>ãw?¼1Ÿ@@à;àóƒ -2¡ë:÷r^ŸeYܰø³¸Ï/¯bÙ‹,­ì¦¼\_Z'÷‹n¸ƒ›¨/\ð.æJÝ×Ç6Õz0ΖÐ×]ŽÊ‹ Î{Tå‰e/ºÛ㦼•ÇÿÎàeSÎÁ -…ø“øüE€e>š¦it²üu¤êA]Žv4–Æt>h ­•÷P .HZéíbÆ·ïýÞSÌИ^’Ì·‡Ã‘ŠË|¢¹ÓbÉmãXÖ’¼ñÝ–£NáO¦‚7^àó(è#||~PABà;¸­*jè†ÝYÚu¹.¸øüq¶Á7UvIöç>ÿ?¸‰š¾t -yâW†‹¼:1x&íðù ž³~u}nª‚Á²¬¼þÙù‰÷÷>ñtø ʨ´Gºjcß|sŠpþº¢>_×?ÍݤñáÑïüS¥d~Úñ¤’ç·pɇo:|¸÷ïY‚|>e}€ï€Ï*HÈüˆa%Õ£Bæ§>ߣþõ5]ñ¤³üžÂÅ_1ÍO¦¯°€‰F£”ÁdY.úd§þ5~ HZé­Â°u§?#­Ô©†ÿeYQ™‰|”³|›•ùÎRüÝÇOÒ’¡ÔY÷âüWßèu>ܤõƒ:¬àó(è#||~PABàS,ËŠD"E+TC¡÷¢ñ`ÓP>ŸP÷õ9Ëï7ˆ¹(¬žÓ´Ns§Å>n;ÔjE >AIU’$MÓ ñ‹°K:'Þ;UË:e½é„];¡¨Ì—$½àf+'óÓŽâ|ʇÌÌï>~Ò%®i‹uV#dBø|ÊúߟTø˲4MË_ápXQ˜|'æóÛ8ËïwK¸X,Z™Öi„ªTP‡ÔVàó´@)Â0 \OÕω÷]’e„õQÿ ¥hq¾(¶Ðú·|HK \ No newline at end of file diff --git a/src/snappy/snappy/testdata/plrabn12.txt b/src/snappy/snappy/testdata/plrabn12.txt deleted file mode 100644 index 34088b82cd..0000000000 --- a/src/snappy/snappy/testdata/plrabn12.txt +++ /dev/null @@ -1,10699 +0,0 @@ - -This is the February 1992 Project Gutenberg release of: - -Paradise Lost by John Milton - -The oldest etext known to Project Gutenberg (ca. 1964-1965) -(If you know of any older ones, please let us know.) - - -Introduction (one page) - -This etext was originally created in 1964-1965 according to Dr. -Joseph Raben of Queens College, NY, to whom it is attributed by -Project Gutenberg. We had heard of this etext for years but it -was not until 1991 that we actually managed to track it down to -a specific location, and then it took months to convince people -to let us have a copy, then more months for them actually to do -the copying and get it to us. Then another month to convert to -something we could massage with our favorite 486 in DOS. After -that is was only a matter of days to get it into this shape you -will see below. The original was, of course, in CAPS only, and -so were all the other etexts of the 60's and early 70's. Don't -let anyone fool you into thinking any etext with both upper and -lower case is an original; all those original Project Gutenberg -etexts were also in upper case and were translated or rewritten -many times to get them into their current condition. They have -been worked on by many people throughout the world. - -In the course of our searches for Professor Raben and his etext -we were never able to determine where copies were or which of a -variety of editions he may have used as a source. We did get a -little information here and there, but even after we received a -copy of the etext we were unwilling to release it without first -determining that it was in fact Public Domain and finding Raben -to verify this and get his permission. Interested enough, in a -totally unrelated action to our searches for him, the professor -subscribed to the Project Gutenberg listserver and we happened, -by accident, to notice his name. (We don't really look at every -subscription request as the computers usually handle them.) The -etext was then properly identified, copyright analyzed, and the -current edition prepared. - -To give you an estimation of the difference in the original and -what we have today: the original was probably entered on cards -commonly known at the time as "IBM cards" (Do Not Fold, Spindle -or Mutilate) and probably took in excess of 100,000 of them. A -single card could hold 80 characters (hence 80 characters is an -accepted standard for so many computer margins), and the entire -original edition we received in all caps was over 800,000 chars -in length, including line enumeration, symbols for caps and the -punctuation marks, etc., since they were not available keyboard -characters at the time (probably the keyboards operated at baud -rates of around 113, meaning the typists had to type slowly for -the keyboard to keep up). - -This is the second version of Paradise Lost released by Project -Gutenberg. The first was released as our October, 1991 etext. - - - - - -Paradise Lost - - - - -Book I - - -Of Man's first disobedience, and the fruit -Of that forbidden tree whose mortal taste -Brought death into the World, and all our woe, -With loss of Eden, till one greater Man -Restore us, and regain the blissful seat, -Sing, Heavenly Muse, that, on the secret top -Of Oreb, or of Sinai, didst inspire -That shepherd who first taught the chosen seed -In the beginning how the heavens and earth -Rose out of Chaos: or, if Sion hill -Delight thee more, and Siloa's brook that flowed -Fast by the oracle of God, I thence -Invoke thy aid to my adventurous song, -That with no middle flight intends to soar -Above th' Aonian mount, while it pursues -Things unattempted yet in prose or rhyme. -And chiefly thou, O Spirit, that dost prefer -Before all temples th' upright heart and pure, -Instruct me, for thou know'st; thou from the first -Wast present, and, with mighty wings outspread, -Dove-like sat'st brooding on the vast Abyss, -And mad'st it pregnant: what in me is dark -Illumine, what is low raise and support; -That, to the height of this great argument, -I may assert Eternal Providence, -And justify the ways of God to men. - Say first--for Heaven hides nothing from thy view, -Nor the deep tract of Hell--say first what cause -Moved our grand parents, in that happy state, -Favoured of Heaven so highly, to fall off -From their Creator, and transgress his will -For one restraint, lords of the World besides. -Who first seduced them to that foul revolt? - Th' infernal Serpent; he it was whose guile, -Stirred up with envy and revenge, deceived -The mother of mankind, what time his pride -Had cast him out from Heaven, with all his host -Of rebel Angels, by whose aid, aspiring -To set himself in glory above his peers, -He trusted to have equalled the Most High, -If he opposed, and with ambitious aim -Against the throne and monarchy of God, -Raised impious war in Heaven and battle proud, -With vain attempt. Him the Almighty Power -Hurled headlong flaming from th' ethereal sky, -With hideous ruin and combustion, down -To bottomless perdition, there to dwell -In adamantine chains and penal fire, -Who durst defy th' Omnipotent to arms. - Nine times the space that measures day and night -To mortal men, he, with his horrid crew, -Lay vanquished, rolling in the fiery gulf, -Confounded, though immortal. But his doom -Reserved him to more wrath; for now the thought -Both of lost happiness and lasting pain -Torments him: round he throws his baleful eyes, -That witnessed huge affliction and dismay, -Mixed with obdurate pride and steadfast hate. -At once, as far as Angels ken, he views -The dismal situation waste and wild. -A dungeon horrible, on all sides round, -As one great furnace flamed; yet from those flames -No light; but rather darkness visible -Served only to discover sights of woe, -Regions of sorrow, doleful shades, where peace -And rest can never dwell, hope never comes -That comes to all, but torture without end -Still urges, and a fiery deluge, fed -With ever-burning sulphur unconsumed. -Such place Eternal Justice has prepared -For those rebellious; here their prison ordained -In utter darkness, and their portion set, -As far removed from God and light of Heaven -As from the centre thrice to th' utmost pole. -Oh how unlike the place from whence they fell! -There the companions of his fall, o'erwhelmed -With floods and whirlwinds of tempestuous fire, -He soon discerns; and, weltering by his side, -One next himself in power, and next in crime, -Long after known in Palestine, and named -Beelzebub. To whom th' Arch-Enemy, -And thence in Heaven called Satan, with bold words -Breaking the horrid silence, thus began:-- - "If thou beest he--but O how fallen! how changed -From him who, in the happy realms of light -Clothed with transcendent brightness, didst outshine -Myriads, though bright!--if he whom mutual league, -United thoughts and counsels, equal hope -And hazard in the glorious enterprise -Joined with me once, now misery hath joined -In equal ruin; into what pit thou seest -From what height fallen: so much the stronger proved -He with his thunder; and till then who knew -The force of those dire arms? Yet not for those, -Nor what the potent Victor in his rage -Can else inflict, do I repent, or change, -Though changed in outward lustre, that fixed mind, -And high disdain from sense of injured merit, -That with the Mightiest raised me to contend, -And to the fierce contentions brought along -Innumerable force of Spirits armed, -That durst dislike his reign, and, me preferring, -His utmost power with adverse power opposed -In dubious battle on the plains of Heaven, -And shook his throne. What though the field be lost? -All is not lost--the unconquerable will, -And study of revenge, immortal hate, -And courage never to submit or yield: -And what is else not to be overcome? -That glory never shall his wrath or might -Extort from me. To bow and sue for grace -With suppliant knee, and deify his power -Who, from the terror of this arm, so late -Doubted his empire--that were low indeed; -That were an ignominy and shame beneath -This downfall; since, by fate, the strength of Gods, -And this empyreal sybstance, cannot fail; -Since, through experience of this great event, -In arms not worse, in foresight much advanced, -We may with more successful hope resolve -To wage by force or guile eternal war, -Irreconcilable to our grand Foe, -Who now triumphs, and in th' excess of joy -Sole reigning holds the tyranny of Heaven." - So spake th' apostate Angel, though in pain, -Vaunting aloud, but racked with deep despair; -And him thus answered soon his bold compeer:-- - "O Prince, O Chief of many throned Powers -That led th' embattled Seraphim to war -Under thy conduct, and, in dreadful deeds -Fearless, endangered Heaven's perpetual King, -And put to proof his high supremacy, -Whether upheld by strength, or chance, or fate, -Too well I see and rue the dire event -That, with sad overthrow and foul defeat, -Hath lost us Heaven, and all this mighty host -In horrible destruction laid thus low, -As far as Gods and heavenly Essences -Can perish: for the mind and spirit remains -Invincible, and vigour soon returns, -Though all our glory extinct, and happy state -Here swallowed up in endless misery. -But what if he our Conqueror (whom I now -Of force believe almighty, since no less -Than such could have o'erpowered such force as ours) -Have left us this our spirit and strength entire, -Strongly to suffer and support our pains, -That we may so suffice his vengeful ire, -Or do him mightier service as his thralls -By right of war, whate'er his business be, -Here in the heart of Hell to work in fire, -Or do his errands in the gloomy Deep? -What can it the avail though yet we feel -Strength undiminished, or eternal being -To undergo eternal punishment?" - Whereto with speedy words th' Arch-Fiend replied:-- -"Fallen Cherub, to be weak is miserable, -Doing or suffering: but of this be sure-- -To do aught good never will be our task, -But ever to do ill our sole delight, -As being the contrary to his high will -Whom we resist. If then his providence -Out of our evil seek to bring forth good, -Our labour must be to pervert that end, -And out of good still to find means of evil; -Which ofttimes may succeed so as perhaps -Shall grieve him, if I fail not, and disturb -His inmost counsels from their destined aim. -But see! the angry Victor hath recalled -His ministers of vengeance and pursuit -Back to the gates of Heaven: the sulphurous hail, -Shot after us in storm, o'erblown hath laid -The fiery surge that from the precipice -Of Heaven received us falling; and the thunder, -Winged with red lightning and impetuous rage, -Perhaps hath spent his shafts, and ceases now -To bellow through the vast and boundless Deep. -Let us not slip th' occasion, whether scorn -Or satiate fury yield it from our Foe. -Seest thou yon dreary plain, forlorn and wild, -The seat of desolation, void of light, -Save what the glimmering of these livid flames -Casts pale and dreadful? Thither let us tend -From off the tossing of these fiery waves; -There rest, if any rest can harbour there; -And, re-assembling our afflicted powers, -Consult how we may henceforth most offend -Our enemy, our own loss how repair, -How overcome this dire calamity, -What reinforcement we may gain from hope, -If not, what resolution from despair." - Thus Satan, talking to his nearest mate, -With head uplift above the wave, and eyes -That sparkling blazed; his other parts besides -Prone on the flood, extended long and large, -Lay floating many a rood, in bulk as huge -As whom the fables name of monstrous size, -Titanian or Earth-born, that warred on Jove, -Briareos or Typhon, whom the den -By ancient Tarsus held, or that sea-beast -Leviathan, which God of all his works -Created hugest that swim th' ocean-stream. -Him, haply slumbering on the Norway foam, -The pilot of some small night-foundered skiff, -Deeming some island, oft, as seamen tell, -With fixed anchor in his scaly rind, -Moors by his side under the lee, while night -Invests the sea, and wished morn delays. -So stretched out huge in length the Arch-fiend lay, -Chained on the burning lake; nor ever thence -Had risen, or heaved his head, but that the will -And high permission of all-ruling Heaven -Left him at large to his own dark designs, -That with reiterated crimes he might -Heap on himself damnation, while he sought -Evil to others, and enraged might see -How all his malice served but to bring forth -Infinite goodness, grace, and mercy, shewn -On Man by him seduced, but on himself -Treble confusion, wrath, and vengeance poured. - Forthwith upright he rears from off the pool -His mighty stature; on each hand the flames -Driven backward slope their pointing spires, and,rolled -In billows, leave i' th' midst a horrid vale. -Then with expanded wings he steers his flight -Aloft, incumbent on the dusky air, -That felt unusual weight; till on dry land -He lights--if it were land that ever burned -With solid, as the lake with liquid fire, -And such appeared in hue as when the force -Of subterranean wind transprots a hill -Torn from Pelorus, or the shattered side -Of thundering Etna, whose combustible -And fuelled entrails, thence conceiving fire, -Sublimed with mineral fury, aid the winds, -And leave a singed bottom all involved -With stench and smoke. Such resting found the sole -Of unblest feet. Him followed his next mate; -Both glorying to have scaped the Stygian flood -As gods, and by their own recovered strength, -Not by the sufferance of supernal Power. - "Is this the region, this the soil, the clime," -Said then the lost Archangel, "this the seat -That we must change for Heaven?--this mournful gloom -For that celestial light? Be it so, since he -Who now is sovereign can dispose and bid -What shall be right: farthest from him is best -Whom reason hath equalled, force hath made supreme -Above his equals. Farewell, happy fields, -Where joy for ever dwells! Hail, horrors! hail, -Infernal world! and thou, profoundest Hell, -Receive thy new possessor--one who brings -A mind not to be changed by place or time. -The mind is its own place, and in itself -Can make a Heaven of Hell, a Hell of Heaven. -What matter where, if I be still the same, -And what I should be, all but less than he -Whom thunder hath made greater? Here at least -We shall be free; th' Almighty hath not built -Here for his envy, will not drive us hence: -Here we may reigh secure; and, in my choice, -To reign is worth ambition, though in Hell: -Better to reign in Hell than serve in Heaven. -But wherefore let we then our faithful friends, -Th' associates and co-partners of our loss, -Lie thus astonished on th' oblivious pool, -And call them not to share with us their part -In this unhappy mansion, or once more -With rallied arms to try what may be yet -Regained in Heaven, or what more lost in Hell?" - So Satan spake; and him Beelzebub -Thus answered:--"Leader of those armies bright -Which, but th' Omnipotent, none could have foiled! -If once they hear that voice, their liveliest pledge -Of hope in fears and dangers--heard so oft -In worst extremes, and on the perilous edge -Of battle, when it raged, in all assaults -Their surest signal--they will soon resume -New courage and revive, though now they lie -Grovelling and prostrate on yon lake of fire, -As we erewhile, astounded and amazed; -No wonder, fallen such a pernicious height!" - He scare had ceased when the superior Fiend -Was moving toward the shore; his ponderous shield, -Ethereal temper, massy, large, and round, -Behind him cast. The broad circumference -Hung on his shoulders like the moon, whose orb -Through optic glass the Tuscan artist views -At evening, from the top of Fesole, -Or in Valdarno, to descry new lands, -Rivers, or mountains, in her spotty globe. -His spear--to equal which the tallest pine -Hewn on Norwegian hills, to be the mast -Of some great ammiral, were but a wand-- -He walked with, to support uneasy steps -Over the burning marl, not like those steps -On Heaven's azure; and the torrid clime -Smote on him sore besides, vaulted with fire. -Nathless he so endured, till on the beach -Of that inflamed sea he stood, and called -His legions--Angel Forms, who lay entranced -Thick as autumnal leaves that strow the brooks -In Vallombrosa, where th' Etrurian shades -High over-arched embower; or scattered sedge -Afloat, when with fierce winds Orion armed -Hath vexed the Red-Sea coast, whose waves o'erthrew -Busiris and his Memphian chivalry, -While with perfidious hatred they pursued -The sojourners of Goshen, who beheld -From the safe shore their floating carcases -And broken chariot-wheels. So thick bestrown, -Abject and lost, lay these, covering the flood, -Under amazement of their hideous change. -He called so loud that all the hollow deep -Of Hell resounded:--"Princes, Potentates, -Warriors, the Flower of Heaven--once yours; now lost, -If such astonishment as this can seize -Eternal Spirits! Or have ye chosen this place -After the toil of battle to repose -Your wearied virtue, for the ease you find -To slumber here, as in the vales of Heaven? -Or in this abject posture have ye sworn -To adore the Conqueror, who now beholds -Cherub and Seraph rolling in the flood -With scattered arms and ensigns, till anon -His swift pursuers from Heaven-gates discern -Th' advantage, and, descending, tread us down -Thus drooping, or with linked thunderbolts -Transfix us to the bottom of this gulf? -Awake, arise, or be for ever fallen!" - They heard, and were abashed, and up they sprung -Upon the wing, as when men wont to watch -On duty, sleeping found by whom they dread, -Rouse and bestir themselves ere well awake. -Nor did they not perceive the evil plight -In which they were, or the fierce pains not feel; -Yet to their General's voice they soon obeyed -Innumerable. As when the potent rod -Of Amram's son, in Egypt's evil day, -Waved round the coast, up-called a pitchy cloud -Of locusts, warping on the eastern wind, -That o'er the realm of impious Pharaoh hung -Like Night, and darkened all the land of Nile; -So numberless were those bad Angels seen -Hovering on wing under the cope of Hell, -'Twixt upper, nether, and surrounding fires; -Till, as a signal given, th' uplifted spear -Of their great Sultan waving to direct -Their course, in even balance down they light -On the firm brimstone, and fill all the plain: -A multitude like which the populous North -Poured never from her frozen loins to pass -Rhene or the Danaw, when her barbarous sons -Came like a deluge on the South, and spread -Beneath Gibraltar to the Libyan sands. -Forthwith, form every squadron and each band, -The heads and leaders thither haste where stood -Their great Commander--godlike Shapes, and Forms -Excelling human; princely Dignities; -And Powers that erst in Heaven sat on thrones, -Though on their names in Heavenly records now -Be no memorial, blotted out and rased -By their rebellion from the Books of Life. -Nor had they yet among the sons of Eve -Got them new names, till, wandering o'er the earth, -Through God's high sufferance for the trial of man, -By falsities and lies the greatest part -Of mankind they corrupted to forsake -God their Creator, and th' invisible -Glory of him that made them to transform -Oft to the image of a brute, adorned -With gay religions full of pomp and gold, -And devils to adore for deities: -Then were they known to men by various names, -And various idols through the heathen world. - Say, Muse, their names then known, who first, who last, -Roused from the slumber on that fiery couch, -At their great Emperor's call, as next in worth -Came singly where he stood on the bare strand, -While the promiscuous crowd stood yet aloof? - The chief were those who, from the pit of Hell -Roaming to seek their prey on Earth, durst fix -Their seats, long after, next the seat of God, -Their altars by his altar, gods adored -Among the nations round, and durst abide -Jehovah thundering out of Sion, throned -Between the Cherubim; yea, often placed -Within his sanctuary itself their shrines, -Abominations; and with cursed things -His holy rites and solemn feasts profaned, -And with their darkness durst affront his light. -First, Moloch, horrid king, besmeared with blood -Of human sacrifice, and parents' tears; -Though, for the noise of drums and timbrels loud, -Their children's cries unheard that passed through fire -To his grim idol. Him the Ammonite -Worshiped in Rabba and her watery plain, -In Argob and in Basan, to the stream -Of utmost Arnon. Nor content with such -Audacious neighbourhood, the wisest heart -Of Solomon he led by fraoud to build -His temple right against the temple of God -On that opprobrious hill, and made his grove -The pleasant valley of Hinnom, Tophet thence -And black Gehenna called, the type of Hell. -Next Chemos, th' obscene dread of Moab's sons, -From Aroar to Nebo and the wild -Of southmost Abarim; in Hesebon -And Horonaim, Seon's real, beyond -The flowery dale of Sibma clad with vines, -And Eleale to th' Asphaltic Pool: -Peor his other name, when he enticed -Israel in Sittim, on their march from Nile, -To do him wanton rites, which cost them woe. -Yet thence his lustful orgies he enlarged -Even to that hill of scandal, by the grove -Of Moloch homicide, lust hard by hate, -Till good Josiah drove them thence to Hell. -With these came they who, from the bordering flood -Of old Euphrates to the brook that parts -Egypt from Syrian ground, had general names -Of Baalim and Ashtaroth--those male, -These feminine. For Spirits, when they please, -Can either sex assume, or both; so soft -And uncompounded is their essence pure, -Not tried or manacled with joint or limb, -Nor founded on the brittle strength of bones, -Like cumbrous flesh; but, in what shape they choose, -Dilated or condensed, bright or obscure, -Can execute their airy purposes, -And works of love or enmity fulfil. -For those the race of Israel oft forsook -Their Living Strength, and unfrequented left -His righteous altar, bowing lowly down -To bestial gods; for which their heads as low -Bowed down in battle, sunk before the spear -Of despicable foes. With these in troop -Came Astoreth, whom the Phoenicians called -Astarte, queen of heaven, with crescent horns; -To whose bright image nigntly by the moon -Sidonian virgins paid their vows and songs; -In Sion also not unsung, where stood -Her temple on th' offensive mountain, built -By that uxorious king whose heart, though large, -Beguiled by fair idolatresses, fell -To idols foul. Thammuz came next behind, -Whose annual wound in Lebanon allured -The Syrian damsels to lament his fate -In amorous ditties all a summer's day, -While smooth Adonis from his native rock -Ran purple to the sea, supposed with blood -Of Thammuz yearly wounded: the love-tale -Infected Sion's daughters with like heat, -Whose wanton passions in the sacred proch -Ezekiel saw, when, by the vision led, -His eye surveyed the dark idolatries -Of alienated Judah. Next came one -Who mourned in earnest, when the captive ark -Maimed his brute image, head and hands lopt off, -In his own temple, on the grunsel-edge, -Where he fell flat and shamed his worshippers: -Dagon his name, sea-monster,upward man -And downward fish; yet had his temple high -Reared in Azotus, dreaded through the coast -Of Palestine, in Gath and Ascalon, -And Accaron and Gaza's frontier bounds. -Him followed Rimmon, whose delightful seat -Was fair Damascus, on the fertile banks -Of Abbana and Pharphar, lucid streams. -He also against the house of God was bold: -A leper once he lost, and gained a king-- -Ahaz, his sottish conqueror, whom he drew -God's altar to disparage and displace -For one of Syrian mode, whereon to burn -His odious offerings, and adore the gods -Whom he had vanquished. After these appeared -A crew who, under names of old renown-- -Osiris, Isis, Orus, and their train-- -With monstrous shapes and sorceries abused -Fanatic Egypt and her priests to seek -Their wandering gods disguised in brutish forms -Rather than human. Nor did Israel scape -Th' infection, when their borrowed gold composed -The calf in Oreb; and the rebel king -Doubled that sin in Bethel and in Dan, -Likening his Maker to the grazed ox-- -Jehovah, who, in one night, when he passed -From Egypt marching, equalled with one stroke -Both her first-born and all her bleating gods. -Belial came last; than whom a Spirit more lewd -Fell not from Heaven, or more gross to love -Vice for itself. To him no temple stood -Or altar smoked; yet who more oft than he -In temples and at altars, when the priest -Turns atheist, as did Eli's sons, who filled -With lust and violence the house of God? -In courts and palaces he also reigns, -And in luxurious cities, where the noise -Of riot ascends above their loftiest towers, -And injury and outrage; and, when night -Darkens the streets, then wander forth the sons -Of Belial, flown with insolence and wine. -Witness the streets of Sodom, and that night -In Gibeah, when the hospitable door -Exposed a matron, to avoid worse rape. - These were the prime in order and in might: -The rest were long to tell; though far renowned -Th' Ionian gods--of Javan's issue held -Gods, yet confessed later than Heaven and Earth, -Their boasted parents;--Titan, Heaven's first-born, -With his enormous brood, and birthright seized -By younger Saturn: he from mightier Jove, -His own and Rhea's son, like measure found; -So Jove usurping reigned. These, first in Crete -And Ida known, thence on the snowy top -Of cold Olympus ruled the middle air, -Their highest heaven; or on the Delphian cliff, -Or in Dodona, and through all the bounds -Of Doric land; or who with Saturn old -Fled over Adria to th' Hesperian fields, -And o'er the Celtic roamed the utmost Isles. - All these and more came flocking; but with looks -Downcast and damp; yet such wherein appeared -Obscure some glimpse of joy to have found their Chief -Not in despair, to have found themselves not lost -In loss itself; which on his countenance cast -Like doubtful hue. But he, his wonted pride -Soon recollecting, with high words, that bore -Semblance of worth, not substance, gently raised -Their fainting courage, and dispelled their fears. -Then straight commands that, at the warlike sound -Of trumpets loud and clarions, be upreared -His mighty standard. That proud honour claimed -Azazel as his right, a Cherub tall: -Who forthwith from the glittering staff unfurled -Th' imperial ensign; which, full high advanced, -Shone like a meteor streaming to the wind, -With gems and golden lustre rich emblazed, -Seraphic arms and trophies; all the while -Sonorous metal blowing martial sounds: -At which the universal host up-sent -A shout that tore Hell's concave, and beyond -Frighted the reign of Chaos and old Night. -All in a moment through the gloom were seen -Ten thousand banners rise into the air, -With orient colours waving: with them rose -A forest huge of spears; and thronging helms -Appeared, and serried shields in thick array -Of depth immeasurable. Anon they move -In perfect phalanx to the Dorian mood -Of flutes and soft recorders--such as raised -To height of noblest temper heroes old -Arming to battle, and instead of rage -Deliberate valour breathed, firm, and unmoved -With dread of death to flight or foul retreat; -Nor wanting power to mitigate and swage -With solemn touches troubled thoughts, and chase -Anguish and doubt and fear and sorrow and pain -From mortal or immortal minds. Thus they, -Breathing united force with fixed thought, -Moved on in silence to soft pipes that charmed -Their painful steps o'er the burnt soil. And now -Advanced in view they stand--a horrid front -Of dreadful length and dazzling arms, in guise -Of warriors old, with ordered spear and shield, -Awaiting what command their mighty Chief -Had to impose. He through the armed files -Darts his experienced eye, and soon traverse -The whole battalion views--their order due, -Their visages and stature as of gods; -Their number last he sums. And now his heart -Distends with pride, and, hardening in his strength, -Glories: for never, since created Man, -Met such embodied force as, named with these, -Could merit more than that small infantry -Warred on by cranes--though all the giant brood -Of Phlegra with th' heroic race were joined -That fought at Thebes and Ilium, on each side -Mixed with auxiliar gods; and what resounds -In fable or romance of Uther's son, -Begirt with British and Armoric knights; -And all who since, baptized or infidel, -Jousted in Aspramont, or Montalban, -Damasco, or Marocco, or Trebisond, -Or whom Biserta sent from Afric shore -When Charlemain with all his peerage fell -By Fontarabbia. Thus far these beyond -Compare of mortal prowess, yet observed -Their dread Commander. He, above the rest -In shape and gesture proudly eminent, -Stood like a tower. His form had yet not lost -All her original brightness, nor appeared -Less than Archangel ruined, and th' excess -Of glory obscured: as when the sun new-risen -Looks through the horizontal misty air -Shorn of his beams, or, from behind the moon, -In dim eclipse, disastrous twilight sheds -On half the nations, and with fear of change -Perplexes monarchs. Darkened so, yet shone -Above them all th' Archangel: but his face -Deep scars of thunder had intrenched, and care -Sat on his faded cheek, but under brows -Of dauntless courage, and considerate pride -Waiting revenge. Cruel his eye, but cast -Signs of remorse and passion, to behold -The fellows of his crime, the followers rather -(Far other once beheld in bliss), condemned -For ever now to have their lot in pain-- -Millions of Spirits for his fault amerced -Of Heaven, and from eteranl splendours flung -For his revolt--yet faithful how they stood, -Their glory withered; as, when heaven's fire -Hath scathed the forest oaks or mountain pines, -With singed top their stately growth, though bare, -Stands on the blasted heath. He now prepared -To speak; whereat their doubled ranks they bend -From wing to wing, and half enclose him round -With all his peers: attention held them mute. -Thrice he assayed, and thrice, in spite of scorn, -Tears, such as Angels weep, burst forth: at last -Words interwove with sighs found out their way:-- - "O myriads of immortal Spirits! O Powers -Matchless, but with th' Almighth!--and that strife -Was not inglorious, though th' event was dire, -As this place testifies, and this dire change, -Hateful to utter. But what power of mind, -Forseeing or presaging, from the depth -Of knowledge past or present, could have feared -How such united force of gods, how such -As stood like these, could ever know repulse? -For who can yet believe, though after loss, -That all these puissant legions, whose exile -Hath emptied Heaven, shall fail to re-ascend, -Self-raised, and repossess their native seat? -For me, be witness all the host of Heaven, -If counsels different, or danger shunned -By me, have lost our hopes. But he who reigns -Monarch in Heaven till then as one secure -Sat on his throne, upheld by old repute, -Consent or custom, and his regal state -Put forth at full, but still his strength concealed-- -Which tempted our attempt, and wrought our fall. -Henceforth his might we know, and know our own, -So as not either to provoke, or dread -New war provoked: our better part remains -To work in close design, by fraud or guile, -What force effected not; that he no less -At length from us may find, who overcomes -By force hath overcome but half his foe. -Space may produce new Worlds; whereof so rife -There went a fame in Heaven that he ere long -Intended to create, and therein plant -A generation whom his choice regard -Should favour equal to the Sons of Heaven. -Thither, if but to pry, shall be perhaps -Our first eruption--thither, or elsewhere; -For this infernal pit shall never hold -Celestial Spirits in bondage, nor th' Abyss -Long under darkness cover. But these thoughts -Full counsel must mature. Peace is despaired; -For who can think submission? War, then, war -Open or understood, must be resolved." - He spake; and, to confirm his words, outflew -Millions of flaming swords, drawn from the thighs -Of mighty Cherubim; the sudden blaze -Far round illumined Hell. Highly they raged -Against the Highest, and fierce with grasped arms -Clashed on their sounding shields the din of war, -Hurling defiance toward the vault of Heaven. - There stood a hill not far, whose grisly top -Belched fire and rolling smoke; the rest entire -Shone with a glossy scurf--undoubted sign -That in his womb was hid metallic ore, -The work of sulphur. Thither, winged with speed, -A numerous brigade hastened: as when bands -Of pioneers, with spade and pickaxe armed, -Forerun the royal camp, to trench a field, -Or cast a rampart. Mammon led them on-- -Mammon, the least erected Spirit that fell -From Heaven; for even in Heaven his looks and thoughts -Were always downward bent, admiring more -The riches of heaven's pavement, trodden gold, -Than aught divine or holy else enjoyed -In vision beatific. By him first -Men also, and by his suggestion taught, -Ransacked the centre, and with impious hands -Rifled the bowels of their mother Earth -For treasures better hid. Soon had his crew -Opened into the hill a spacious wound, -And digged out ribs of gold. Let none admire -That riches grow in Hell; that soil may best -Deserve the precious bane. And here let those -Who boast in mortal things, and wondering tell -Of Babel, and the works of Memphian kings, -Learn how their greatest monuments of fame -And strength, and art, are easily outdone -By Spirits reprobate, and in an hour -What in an age they, with incessant toil -And hands innumerable, scarce perform. -Nigh on the plain, in many cells prepared, -That underneath had veins of liquid fire -Sluiced from the lake, a second multitude -With wondrous art founded the massy ore, -Severing each kind, and scummed the bullion-dross. -A third as soon had formed within the ground -A various mould, and from the boiling cells -By strange conveyance filled each hollow nook; -As in an organ, from one blast of wind, -To many a row of pipes the sound-board breathes. -Anon out of the earth a fabric huge -Rose like an exhalation, with the sound -Of dulcet symphonies and voices sweet-- -Built like a temple, where pilasters round -Were set, and Doric pillars overlaid -With golden architrave; nor did there want -Cornice or frieze, with bossy sculptures graven; -The roof was fretted gold. Not Babylon -Nor great Alcairo such magnificence -Equalled in all their glories, to enshrine -Belus or Serapis their gods, or seat -Their kings, when Egypt with Assyria strove -In wealth and luxury. Th' ascending pile -Stood fixed her stately height, and straight the doors, -Opening their brazen folds, discover, wide -Within, her ample spaces o'er the smooth -And level pavement: from the arched roof, -Pendent by subtle magic, many a row -Of starry lamps and blazing cressets, fed -With naptha and asphaltus, yielded light -As from a sky. The hasty multitude -Admiring entered; and the work some praise, -And some the architect. His hand was known -In Heaven by many a towered structure high, -Where sceptred Angels held their residence, -And sat as Princes, whom the supreme King -Exalted to such power, and gave to rule, -Each in his Hierarchy, the Orders bright. -Nor was his name unheard or unadored -In ancient Greece; and in Ausonian land -Men called him Mulciber; and how he fell -From Heaven they fabled, thrown by angry Jove -Sheer o'er the crystal battlements: from morn -To noon he fell, from noon to dewy eve, -A summer's day, and with the setting sun -Dropt from the zenith, like a falling star, -On Lemnos, th' Aegaean isle. Thus they relate, -Erring; for he with this rebellious rout -Fell long before; nor aught aviled him now -To have built in Heaven high towers; nor did he scape -By all his engines, but was headlong sent, -With his industrious crew, to build in Hell. - Meanwhile the winged Heralds, by command -Of sovereign power, with awful ceremony -And trumpet's sound, throughout the host proclaim -A solemn council forthwith to be held -At Pandemonium, the high capital -Of Satan and his peers. Their summons called -From every band and squared regiment -By place or choice the worthiest: they anon -With hundreds and with thousands trooping came -Attended. All access was thronged; the gates -And porches wide, but chief the spacious hall -(Though like a covered field, where champions bold -Wont ride in armed, and at the Soldan's chair -Defied the best of Paynim chivalry -To mortal combat, or career with lance), -Thick swarmed, both on the ground and in the air, -Brushed with the hiss of rustling wings. As bees -In spring-time, when the Sun with Taurus rides. -Pour forth their populous youth about the hive -In clusters; they among fresh dews and flowers -Fly to and fro, or on the smoothed plank, -The suburb of their straw-built citadel, -New rubbed with balm, expatiate, and confer -Their state-affairs: so thick the airy crowd -Swarmed and were straitened; till, the signal given, -Behold a wonder! They but now who seemed -In bigness to surpass Earth's giant sons, -Now less than smallest dwarfs, in narrow room -Throng numberless--like that pygmean race -Beyond the Indian mount; or faery elves, -Whose midnight revels, by a forest-side -Or fountain, some belated peasant sees, -Or dreams he sees, while overhead the Moon -Sits arbitress, and nearer to the Earth -Wheels her pale course: they, on their mirth and dance -Intent, with jocund music charm his ear; -At once with joy and fear his heart rebounds. -Thus incorporeal Spirits to smallest forms -Reduced their shapes immense, and were at large, -Though without number still, amidst the hall -Of that infernal court. But far within, -And in their own dimensions like themselves, -The great Seraphic Lords and Cherubim -In close recess and secret conclave sat, -A thousand demi-gods on golden seats, -Frequent and full. After short silence then, -And summons read, the great consult began. - - - -Book II - - -High on a throne of royal state, which far -Outshone the wealth or Ormus and of Ind, -Or where the gorgeous East with richest hand -Showers on her kings barbaric pearl and gold, -Satan exalted sat, by merit raised -To that bad eminence; and, from despair -Thus high uplifted beyond hope, aspires -Beyond thus high, insatiate to pursue -Vain war with Heaven; and, by success untaught, -His proud imaginations thus displayed:-- - "Powers and Dominions, Deities of Heaven!-- -For, since no deep within her gulf can hold -Immortal vigour, though oppressed and fallen, -I give not Heaven for lost: from this descent -Celestial Virtues rising will appear -More glorious and more dread than from no fall, -And trust themselves to fear no second fate!-- -Me though just right, and the fixed laws of Heaven, -Did first create your leader--next, free choice -With what besides in council or in fight -Hath been achieved of merit--yet this loss, -Thus far at least recovered, hath much more -Established in a safe, unenvied throne, -Yielded with full consent. The happier state -In Heaven, which follows dignity, might draw -Envy from each inferior; but who here -Will envy whom the highest place exposes -Foremost to stand against the Thunderer's aim -Your bulwark, and condemns to greatest share -Of endless pain? Where there is, then, no good -For which to strive, no strife can grow up there -From faction: for none sure will claim in Hell -Precedence; none whose portion is so small -Of present pain that with ambitious mind -Will covet more! With this advantage, then, -To union, and firm faith, and firm accord, -More than can be in Heaven, we now return -To claim our just inheritance of old, -Surer to prosper than prosperity -Could have assured us; and by what best way, -Whether of open war or covert guile, -We now debate. Who can advise may speak." - He ceased; and next him Moloch, sceptred king, -Stood up--the strongest and the fiercest Spirit -That fought in Heaven, now fiercer by despair. -His trust was with th' Eternal to be deemed -Equal in strength, and rather than be less -Cared not to be at all; with that care lost -Went all his fear: of God, or Hell, or worse, -He recked not, and these words thereafter spake:-- - "My sentence is for open war. Of wiles, -More unexpert, I boast not: them let those -Contrive who need, or when they need; not now. -For, while they sit contriving, shall the rest-- -Millions that stand in arms, and longing wait -The signal to ascend--sit lingering here, -Heaven's fugitives, and for their dwelling-place -Accept this dark opprobrious den of shame, -The prison of his ryranny who reigns -By our delay? No! let us rather choose, -Armed with Hell-flames and fury, all at once -O'er Heaven's high towers to force resistless way, -Turning our tortures into horrid arms -Against the Torturer; when, to meet the noise -Of his almighty engine, he shall hear -Infernal thunder, and, for lightning, see -Black fire and horror shot with equal rage -Among his Angels, and his throne itself -Mixed with Tartarean sulphur and strange fire, -His own invented torments. But perhaps -The way seems difficult, and steep to scale -With upright wing against a higher foe! -Let such bethink them, if the sleepy drench -Of that forgetful lake benumb not still, -That in our porper motion we ascend -Up to our native seat; descent and fall -To us is adverse. Who but felt of late, -When the fierce foe hung on our broken rear -Insulting, and pursued us through the Deep, -With what compulsion and laborious flight -We sunk thus low? Th' ascent is easy, then; -Th' event is feared! Should we again provoke -Our stronger, some worse way his wrath may find -To our destruction, if there be in Hell -Fear to be worse destroyed! What can be worse -Than to dwell here, driven out from bliss, condemned -In this abhorred deep to utter woe! -Where pain of unextinguishable fire -Must exercise us without hope of end -The vassals of his anger, when the scourge -Inexorably, and the torturing hour, -Calls us to penance? More destroyed than thus, -We should be quite abolished, and expire. -What fear we then? what doubt we to incense -His utmost ire? which, to the height enraged, -Will either quite consume us, and reduce -To nothing this essential--happier far -Than miserable to have eternal being!-- -Or, if our substance be indeed divine, -And cannot cease to be, we are at worst -On this side nothing; and by proof we feel -Our power sufficient to disturb his Heaven, -And with perpetual inroads to alarm, -Though inaccessible, his fatal throne: -Which, if not victory, is yet revenge." - He ended frowning, and his look denounced -Desperate revenge, and battle dangerous -To less than gods. On th' other side up rose -Belial, in act more graceful and humane. -A fairer person lost not Heaven; he seemed -For dignity composed, and high exploit. -But all was false and hollow; though his tongue -Dropped manna, and could make the worse appear -The better reason, to perplex and dash -Maturest counsels: for his thoughts were low-- - To vice industrious, but to nobler deeds -Timorous and slothful. Yet he pleased the ear, -And with persuasive accent thus began:-- - "I should be much for open war, O Peers, -As not behind in hate, if what was urged -Main reason to persuade immediate war -Did not dissuade me most, and seem to cast -Ominous conjecture on the whole success; -When he who most excels in fact of arms, -In what he counsels and in what excels -Mistrustful, grounds his courage on despair -And utter dissolution, as the scope -Of all his aim, after some dire revenge. -First, what revenge? The towers of Heaven are filled -With armed watch, that render all access -Impregnable: oft on the bodering Deep -Encamp their legions, or with obscure wing -Scout far and wide into the realm of Night, -Scorning surprise. Or, could we break our way -By force, and at our heels all Hell should rise -With blackest insurrection to confound -Heaven's purest light, yet our great Enemy, -All incorruptible, would on his throne -Sit unpolluted, and th' ethereal mould, -Incapable of stain, would soon expel -Her mischief, and purge off the baser fire, -Victorious. Thus repulsed, our final hope -Is flat despair: we must exasperate -Th' Almighty Victor to spend all his rage; -And that must end us; that must be our cure-- -To be no more. Sad cure! for who would lose, -Though full of pain, this intellectual being, -Those thoughts that wander through eternity, -To perish rather, swallowed up and lost -In the wide womb of uncreated Night, -Devoid of sense and motion? And who knows, -Let this be good, whether our angry Foe -Can give it, or will ever? How he can -Is doubtful; that he never will is sure. -Will he, so wise, let loose at once his ire, -Belike through impotence or unaware, -To give his enemies their wish, and end -Them in his anger whom his anger saves -To punish endless? 'Wherefore cease we, then?' -Say they who counsel war; 'we are decreed, -Reserved, and destined to eternal woe; -Whatever doing, what can we suffer more, -What can we suffer worse?' Is this, then, worst-- -Thus sitting, thus consulting, thus in arms? -What when we fled amain, pursued and struck -With Heaven's afflicting thunder, and besought -The Deep to shelter us? This Hell then seemed -A refuge from those wounds. Or when we lay -Chained on the burning lake? That sure was worse. -What if the breath that kindled those grim fires, -Awaked, should blow them into sevenfold rage, -And plunge us in the flames; or from above -Should intermitted vengeance arm again -His red right hand to plague us? What if all -Her stores were opened, and this firmament -Of Hell should spout her cataracts of fire, -Impendent horrors, threatening hideous fall -One day upon our heads; while we perhaps, -Designing or exhorting glorious war, -Caught in a fiery tempest, shall be hurled, -Each on his rock transfixed, the sport and prey -Or racking whirlwinds, or for ever sunk -Under yon boiling ocean, wrapt in chains, -There to converse with everlasting groans, -Unrespited, unpitied, unreprieved, -Ages of hopeless end? This would be worse. -War, therefore, open or concealed, alike -My voice dissuades; for what can force or guile -With him, or who deceive his mind, whose eye -Views all things at one view? He from Heaven's height -All these our motions vain sees and derides, -Not more almighty to resist our might -Than wise to frustrate all our plots and wiles. -Shall we, then, live thus vile--the race of Heaven -Thus trampled, thus expelled, to suffer here -Chains and these torments? Better these than worse, -By my advice; since fate inevitable -Subdues us, and omnipotent decree, -The Victor's will. To suffer, as to do, -Our strength is equal; nor the law unjust -That so ordains. This was at first resolved, -If we were wise, against so great a foe -Contending, and so doubtful what might fall. -I laugh when those who at the spear are bold -And venturous, if that fail them, shrink, and fear -What yet they know must follow--to endure -Exile, or igominy, or bonds, or pain, -The sentence of their Conqueror. This is now -Our doom; which if we can sustain and bear, -Our Supreme Foe in time may much remit -His anger, and perhaps, thus far removed, -Not mind us not offending, satisfied -With what is punished; whence these raging fires -Will slacken, if his breath stir not their flames. -Our purer essence then will overcome -Their noxious vapour; or, inured, not feel; -Or, changed at length, and to the place conformed -In temper and in nature, will receive -Familiar the fierce heat; and, void of pain, -This horror will grow mild, this darkness light; -Besides what hope the never-ending flight -Of future days may bring, what chance, what change -Worth waiting--since our present lot appears -For happy though but ill, for ill not worst, -If we procure not to ourselves more woe." - Thus Belial, with words clothed in reason's garb, -Counselled ignoble ease and peaceful sloth, -Not peace; and after him thus Mammon spake:-- - "Either to disenthrone the King of Heaven -We war, if war be best, or to regain -Our own right lost. Him to unthrone we then -May hope, when everlasting Fate shall yield -To fickle Chance, and Chaos judge the strife. -The former, vain to hope, argues as vain -The latter; for what place can be for us -Within Heaven's bound, unless Heaven's Lord supreme -We overpower? Suppose he should relent -And publish grace to all, on promise made -Of new subjection; with what eyes could we -Stand in his presence humble, and receive -Strict laws imposed, to celebrate his throne -With warbled hyms, and to his Godhead sing -Forced hallelujahs, while he lordly sits -Our envied sovereign, and his altar breathes -Ambrosial odours and ambrosial flowers, -Our servile offerings? This must be our task -In Heaven, this our delight. How wearisome -Eternity so spent in worship paid -To whom we hate! Let us not then pursue, -By force impossible, by leave obtained -Unacceptable, though in Heaven, our state -Of splendid vassalage; but rather seek -Our own good from ourselves, and from our own -Live to ourselves, though in this vast recess, -Free and to none accountable, preferring -Hard liberty before the easy yoke -Of servile pomp. Our greatness will appear -Then most conspicuous when great things of small, -Useful of hurtful, prosperous of adverse, -We can create, and in what place soe'er -Thrive under evil, and work ease out of pain -Through labour and endurance. This deep world -Of darkness do we dread? How oft amidst -Thick clouds and dark doth Heaven's all-ruling Sire -Choose to reside, his glory unobscured, -And with the majesty of darkness round -Covers his throne, from whence deep thunders roar. -Mustering their rage, and Heaven resembles Hell! -As he our darkness, cannot we his light -Imitate when we please? This desert soil -Wants not her hidden lustre, gems and gold; -Nor want we skill or art from whence to raise -Magnificence; and what can Heaven show more? -Our torments also may, in length of time, -Become our elements, these piercing fires -As soft as now severe, our temper changed -Into their temper; which must needs remove -The sensible of pain. All things invite -To peaceful counsels, and the settled state -Of order, how in safety best we may -Compose our present evils, with regard -Of what we are and where, dismissing quite -All thoughts of war. Ye have what I advise." - He scarce had finished, when such murmur filled -Th' assembly as when hollow rocks retain -The sound of blustering winds, which all night long -Had roused the sea, now with hoarse cadence lull -Seafaring men o'erwatched, whose bark by chance -Or pinnace, anchors in a craggy bay -After the tempest. Such applause was heard -As Mammon ended, and his sentence pleased, -Advising peace: for such another field -They dreaded worse than Hell; so much the fear -Of thunder and the sword of Michael -Wrought still within them; and no less desire -To found this nether empire, which might rise, -By policy and long process of time, -In emulation opposite to Heaven. -Which when Beelzebub perceived--than whom, -Satan except, none higher sat--with grave -Aspect he rose, and in his rising seemed -A pillar of state. Deep on his front engraven -Deliberation sat, and public care; -And princely counsel in his face yet shone, -Majestic, though in ruin. Sage he stood -With Atlantean shoulders, fit to bear -The weight of mightiest monarchies; his look -Drew audience and attention still as night -Or summer's noontide air, while thus he spake:-- - "Thrones and Imperial Powers, Offspring of Heaven, -Ethereal Virtues! or these titles now -Must we renounce, and, changing style, be called -Princes of Hell? for so the popular vote -Inclines--here to continue, and build up here -A growing empire; doubtless! while we dream, -And know not that the King of Heaven hath doomed -This place our dungeon, not our safe retreat -Beyond his potent arm, to live exempt -From Heaven's high jurisdiction, in new league -Banded against his throne, but to remain -In strictest bondage, though thus far removed, -Under th' inevitable curb, reserved -His captive multitude. For he, to be sure, -In height or depth, still first and last will reign -Sole king, and of his kingdom lose no part -By our revolt, but over Hell extend -His empire, and with iron sceptre rule -Us here, as with his golden those in Heaven. -What sit we then projecting peace and war? -War hath determined us and foiled with loss -Irreparable; terms of peace yet none -Vouchsafed or sought; for what peace will be given -To us enslaved, but custody severe, -And stripes and arbitrary punishment -Inflicted? and what peace can we return, -But, to our power, hostility and hate, -Untamed reluctance, and revenge, though slow, -Yet ever plotting how the Conqueror least -May reap his conquest, and may least rejoice -In doing what we most in suffering feel? -Nor will occasion want, nor shall we need -With dangerous expedition to invade -Heaven, whose high walls fear no assault or siege, -Or ambush from the Deep. What if we find -Some easier enterprise? There is a place -(If ancient and prophetic fame in Heaven -Err not)--another World, the happy seat -Of some new race, called Man, about this time -To be created like to us, though less -In power and excellence, but favoured more -Of him who rules above; so was his will -Pronounced among the Gods, and by an oath -That shook Heaven's whole circumference confirmed. -Thither let us bend all our thoughts, to learn -What creatures there inhabit, of what mould -Or substance, how endued, and what their power -And where their weakness: how attempted best, -By force of subtlety. Though Heaven be shut, -And Heaven's high Arbitrator sit secure -In his own strength, this place may lie exposed, -The utmost border of his kingdom, left -To their defence who hold it: here, perhaps, -Some advantageous act may be achieved -By sudden onset--either with Hell-fire -To waste his whole creation, or possess -All as our own, and drive, as we were driven, -The puny habitants; or, if not drive, -Seduce them to our party, that their God -May prove their foe, and with repenting hand -Abolish his own works. This would surpass -Common revenge, and interrupt his joy -In our confusion, and our joy upraise -In his disturbance; when his darling sons, -Hurled headlong to partake with us, shall curse -Their frail original, and faded bliss-- -Faded so soon! Advise if this be worth -Attempting, or to sit in darkness here -Hatching vain empires." Thus beelzebub -Pleaded his devilish counsel--first devised -By Satan, and in part proposed: for whence, -But from the author of all ill, could spring -So deep a malice, to confound the race -Of mankind in one root, and Earth with Hell -To mingle and involve, done all to spite -The great Creator? But their spite still serves -His glory to augment. The bold design -Pleased highly those infernal States, and joy -Sparkled in all their eyes: with full assent -They vote: whereat his speech he thus renews:-- -"Well have ye judged, well ended long debate, -Synod of Gods, and, like to what ye are, -Great things resolved, which from the lowest deep -Will once more lift us up, in spite of fate, -Nearer our ancient seat--perhaps in view -Of those bright confines, whence, with neighbouring arms, -And opportune excursion, we may chance -Re-enter Heaven; or else in some mild zone -Dwell, not unvisited of Heaven's fair light, -Secure, and at the brightening orient beam -Purge off this gloom: the soft delicious air, -To heal the scar of these corrosive fires, -Shall breathe her balm. But, first, whom shall we send -In search of this new World? whom shall we find -Sufficient? who shall tempt with wandering feet -The dark, unbottomed, infinite Abyss, -And through the palpable obscure find out -His uncouth way, or spread his airy flight, -Upborne with indefatigable wings -Over the vast abrupt, ere he arrive -The happy Isle? What strength, what art, can then -Suffice, or what evasion bear him safe, -Through the strict senteries and stations thick -Of Angels watching round? Here he had need -All circumspection: and we now no less -Choice in our suffrage; for on whom we send -The weight of all, and our last hope, relies." - This said, he sat; and expectation held -His look suspense, awaiting who appeared -To second, or oppose, or undertake -The perilous attempt. But all sat mute, -Pondering the danger with deep thoughts; and each -In other's countenance read his own dismay, -Astonished. None among the choice and prime -Of those Heaven-warring champions could be found -So hardy as to proffer or accept, -Alone, the dreadful voyage; till, at last, -Satan, whom now transcendent glory raised -Above his fellows, with monarchal pride -Conscious of highest worth, unmoved thus spake:-- - "O Progeny of Heaven! Empyreal Thrones! -With reason hath deep silence and demur -Seized us, though undismayed. Long is the way -And hard, that out of Hell leads up to light. -Our prison strong, this huge convex of fire, -Outrageous to devour, immures us round -Ninefold; and gates of burning adamant, -Barred over us, prohibit all egress. -These passed, if any pass, the void profound -Of unessential Night receives him next, -Wide-gaping, and with utter loss of being -Threatens him, plunged in that abortive gulf. -If thence he scape, into whatever world, -Or unknown region, what remains him less -Than unknown dangers, and as hard escape? -But I should ill become this throne, O Peers, -And this imperial sovereignty, adorned -With splendour, armed with power, if aught proposed -And judged of public moment in the shape -Of difficulty or danger, could deter -Me from attempting. Wherefore do I assume -These royalties, and not refuse to reign, -Refusing to accept as great a share -Of hazard as of honour, due alike -To him who reigns, and so much to him due -Of hazard more as he above the rest -High honoured sits? Go, therefore, mighty Powers, -Terror of Heaven, though fallen; intend at home, -While here shall be our home, what best may ease -The present misery, and render Hell -More tolerable; if there be cure or charm -To respite, or deceive, or slack the pain -Of this ill mansion: intermit no watch -Against a wakeful foe, while I abroad -Through all the coasts of dark destruction seek -Deliverance for us all. This enterprise -None shall partake with me." Thus saying, rose -The Monarch, and prevented all reply; -Prudent lest, from his resolution raised, -Others among the chief might offer now, -Certain to be refused, what erst they feared, -And, so refused, might in opinion stand -His rivals, winning cheap the high repute -Which he through hazard huge must earn. But they -Dreaded not more th' adventure than his voice -Forbidding; and at once with him they rose. -Their rising all at once was as the sound -Of thunder heard remote. Towards him they bend -With awful reverence prone, and as a God -Extol him equal to the Highest in Heaven. -Nor failed they to express how much they praised -That for the general safety he despised -His own: for neither do the Spirits damned -Lose all their virtue; lest bad men should boast -Their specious deeds on earth, which glory excites, -Or close ambition varnished o'er with zeal. - Thus they their doubtful consultations dark -Ended, rejoicing in their matchless Chief: -As, when from mountain-tops the dusky clouds -Ascending, while the north wind sleeps, o'erspread -Heaven's cheerful face, the louring element -Scowls o'er the darkened landscape snow or shower, -If chance the radiant sun, with farewell sweet, -Extend his evening beam, the fields revive, -The birds their notes renew, and bleating herds -Attest their joy, that hill and valley rings. -O shame to men! Devil with devil damned -Firm concord holds; men only disagree -Of creatures rational, though under hope -Of heavenly grace, and, God proclaiming peace, -Yet live in hatred, enmity, and strife -Among themselves, and levy cruel wars -Wasting the earth, each other to destroy: -As if (which might induce us to accord) -Man had not hellish foes enow besides, -That day and night for his destruction wait! - The Stygian council thus dissolved; and forth -In order came the grand infernal Peers: -Midst came their mighty Paramount, and seemed -Alone th' antagonist of Heaven, nor less -Than Hell's dread Emperor, with pomp supreme, -And god-like imitated state: him round -A globe of fiery Seraphim enclosed -With bright emblazonry, and horrent arms. -Then of their session ended they bid cry -With trumpet's regal sound the great result: -Toward the four winds four speedy Cherubim -Put to their mouths the sounding alchemy, -By herald's voice explained; the hollow Abyss -Heard far adn wide, and all the host of Hell -With deafening shout returned them loud acclaim. -Thence more at ease their minds, and somewhat raised -By false presumptuous hope, the ranged Powers -Disband; and, wandering, each his several way -Pursues, as inclination or sad choice -Leads him perplexed, where he may likeliest find -Truce to his restless thoughts, and entertain -The irksome hours, till his great Chief return. -Part on the plain, or in the air sublime, -Upon the wing or in swift race contend, -As at th' Olympian games or Pythian fields; -Part curb their fiery steeds, or shun the goal -With rapid wheels, or fronted brigades form: -As when, to warn proud cities, war appears -Waged in the troubled sky, and armies rush -To battle in the clouds; before each van -Prick forth the airy knights, and couch their spears, -Till thickest legions close; with feats of arms -From either end of heaven the welkin burns. -Others, with vast Typhoean rage, more fell, -Rend up both rocks and hills, and ride the air -In whirlwind; Hell scarce holds the wild uproar:-- -As when Alcides, from Oechalia crowned -With conquest, felt th' envenomed robe, and tore -Through pain up by the roots Thessalian pines, -And Lichas from the top of Oeta threw -Into th' Euboic sea. Others, more mild, -Retreated in a silent valley, sing -With notes angelical to many a harp -Their own heroic deeds, and hapless fall -By doom of battle, and complain that Fate -Free Virtue should enthrall to Force or Chance. -Their song was partial; but the harmony -(What could it less when Spirits immortal sing?) -Suspended Hell, and took with ravishment -The thronging audience. In discourse more sweet -(For Eloquence the Soul, Song charms the Sense) -Others apart sat on a hill retired, -In thoughts more elevate, and reasoned high -Of Providence, Foreknowledge, Will, and Fate-- -Fixed fate, free will, foreknowledge absolute, -And found no end, in wandering mazes lost. -Of good and evil much they argued then, -Of happiness and final misery, -Passion and apathy, and glory and shame: -Vain wisdom all, and false philosophy!-- -Yet, with a pleasing sorcery, could charm -Pain for a while or anguish, and excite -Fallacious hope, or arm th' obdured breast -With stubborn patience as with triple steel. -Another part, in squadrons and gross bands, -On bold adventure to discover wide -That dismal world, if any clime perhaps -Might yield them easier habitation, bend -Four ways their flying march, along the banks -Of four infernal rivers, that disgorge -Into the burning lake their baleful streams-- -Abhorred Styx, the flood of deadly hate; -Sad Acheron of sorrow, black and deep; -Cocytus, named of lamentation loud -Heard on the rueful stream; fierce Phlegeton, -Whose waves of torrent fire inflame with rage. -Far off from these, a slow and silent stream, -Lethe, the river of oblivion, rolls -Her watery labyrinth, whereof who drinks -Forthwith his former state and being forgets-- -Forgets both joy and grief, pleasure and pain. -Beyond this flood a frozen continent -Lies dark and wild, beat with perpetual storms -Of whirlwind and dire hail, which on firm land -Thaws not, but gathers heap, and ruin seems -Of ancient pile; all else deep snow and ice, -A gulf profound as that Serbonian bog -Betwixt Damiata and Mount Casius old, -Where armies whole have sunk: the parching air -Burns frore, and cold performs th' effect of fire. -Thither, by harpy-footed Furies haled, -At certain revolutions all the damned -Are brought; and feel by turns the bitter change -Of fierce extremes, extremes by change more fierce, -From beds of raging fire to starve in ice -Their soft ethereal warmth, and there to pine -Immovable, infixed, and frozen round -Periods of time,--thence hurried back to fire. -They ferry over this Lethean sound -Both to and fro, their sorrow to augment, -And wish and struggle, as they pass, to reach -The tempting stream, with one small drop to lose -In sweet forgetfulness all pain and woe, -All in one moment, and so near the brink; -But Fate withstands, and, to oppose th' attempt, -Medusa with Gorgonian terror guards -The ford, and of itself the water flies -All taste of living wight, as once it fled -The lip of Tantalus. Thus roving on -In confused march forlorn, th' adventurous bands, -With shuddering horror pale, and eyes aghast, -Viewed first their lamentable lot, and found -No rest. Through many a dark and dreary vale -They passed, and many a region dolorous, -O'er many a frozen, many a fiery alp, -Rocks, caves, lakes, fens, bogs, dens, and shades of death-- -A universe of death, which God by curse -Created evil, for evil only good; -Where all life dies, death lives, and Nature breeds, -Perverse, all monstrous, all prodigious things, -Obominable, inutterable, and worse -Than fables yet have feigned or fear conceived, -Gorgons, and Hydras, and Chimeras dire. - Meanwhile the Adversary of God and Man, -Satan, with thoughts inflamed of highest design, -Puts on swift wings, and toward the gates of Hell -Explores his solitary flight: sometimes -He scours the right hand coast, sometimes the left; -Now shaves with level wing the deep, then soars -Up to the fiery concave towering high. -As when far off at sea a fleet descried -Hangs in the clouds, by equinoctial winds -Close sailing from Bengala, or the isles -Of Ternate and Tidore, whence merchants bring -Their spicy drugs; they on the trading flood, -Through the wide Ethiopian to the Cape, -Ply stemming nightly toward the pole: so seemed -Far off the flying Fiend. At last appear -Hell-bounds, high reaching to the horrid roof, -And thrice threefold the gates; three folds were brass, -Three iron, three of adamantine rock, -Impenetrable, impaled with circling fire, -Yet unconsumed. Before the gates there sat -On either side a formidable Shape. -The one seemed woman to the waist, and fair, -But ended foul in many a scaly fold, -Voluminous and vast--a serpent armed -With mortal sting. About her middle round -A cry of Hell-hounds never-ceasing barked -With wide Cerberean mouths full loud, and rung -A hideous peal; yet, when they list, would creep, -If aught disturbed their noise, into her womb, -And kennel there; yet there still barked and howled -Within unseen. Far less abhorred than these -Vexed Scylla, bathing in the sea that parts -Calabria from the hoarse Trinacrian shore; -Nor uglier follow the night-hag, when, called -In secret, riding through the air she comes, -Lured with the smell of infant blood, to dance -With Lapland witches, while the labouring moon -Eclipses at their charms. The other Shape-- -If shape it might be called that shape had none -Distinguishable in member, joint, or limb; -Or substance might be called that shadow seemed, -For each seemed either--black it stood as Night, -Fierce as ten Furies, terrible as Hell, -And shook a dreadful dart: what seemed his head -The likeness of a kingly crown had on. -Satan was now at hand, and from his seat -The monster moving onward came as fast -With horrid strides; Hell trembled as he strode. -Th' undaunted Fiend what this might be admired-- -Admired, not feared (God and his Son except, -Created thing naught valued he nor shunned), -And with disdainful look thus first began:-- - "Whence and what art thou, execrable Shape, -That dar'st, though grim and terrible, advance -Thy miscreated front athwart my way -To yonder gates? Through them I mean to pass, -That be assured, without leave asked of thee. -Retire; or taste thy folly, and learn by proof, -Hell-born, not to contend with Spirits of Heaven." - To whom the Goblin, full of wrath, replied:-- -"Art thou that traitor Angel? art thou he, -Who first broke peace in Heaven and faith, till then -Unbroken, and in proud rebellious arms -Drew after him the third part of Heaven's sons, -Conjured against the Highest--for which both thou -And they, outcast from God, are here condemned -To waste eternal days in woe and pain? -And reckon'st thou thyself with Spirits of Heaven -Hell-doomed, and breath'st defiance here and scorn, -Where I reign king, and, to enrage thee more, -Thy king and lord? Back to thy punishment, -False fugitive; and to thy speed add wings, -Lest with a whip of scorpions I pursue -Thy lingering, or with one stroke of this dart -Strange horror seize thee, and pangs unfelt before." - So spake the grisly Terror, and in shape, -So speaking and so threatening, grew tenfold, -More dreadful and deform. On th' other side, -Incensed with indignation, Satan stood -Unterrified, and like a comet burned, -That fires the length of Ophiuchus huge -In th' arctic sky, and from his horrid hair -Shakes pestilence and war. Each at the head -Levelled his deadly aim; their fatal hands -No second stroke intend; and such a frown -Each cast at th' other as when two black clouds, -With heaven's artillery fraught, came rattling on -Over the Caspian,--then stand front to front -Hovering a space, till winds the signal blow -To join their dark encounter in mid-air. -So frowned the mighty combatants that Hell -Grew darker at their frown; so matched they stood; -For never but once more was wither like -To meet so great a foe. And now great deeds -Had been achieved, whereof all Hell had rung, -Had not the snaky Sorceress, that sat -Fast by Hell-gate and kept the fatal key, -Risen, and with hideous outcry rushed between. - "O father, what intends thy hand," she cried, -"Against thy only son? What fury, O son, -Possesses thee to bend that mortal dart -Against thy father's head? And know'st for whom? -For him who sits above, and laughs the while -At thee, ordained his drudge to execute -Whate'er his wrath, which he calls justice, bids-- -His wrath, which one day will destroy ye both!" - She spake, and at her words the hellish Pest -Forbore: then these to her Satan returned:-- - "So strange thy outcry, and thy words so strange -Thou interposest, that my sudden hand, -Prevented, spares to tell thee yet by deeds -What it intends, till first I know of thee -What thing thou art, thus double-formed, and why, -In this infernal vale first met, thou call'st -Me father, and that phantasm call'st my son. -I know thee not, nor ever saw till now -Sight more detestable than him and thee." - T' whom thus the Portress of Hell-gate replied:-- -"Hast thou forgot me, then; and do I seem -Now in thine eye so foul?--once deemed so fair -In Heaven, when at th' assembly, and in sight -Of all the Seraphim with thee combined -In bold conspiracy against Heaven's King, -All on a sudden miserable pain -Surprised thee, dim thine eyes and dizzy swum -In darkness, while thy head flames thick and fast -Threw forth, till on the left side opening wide, -Likest to thee in shape and countenance bright, -Then shining heavenly fair, a goddess armed, -Out of thy head I sprung. Amazement seized -All th' host of Heaven; back they recoiled afraid -At first, and called me Sin, and for a sign -Portentous held me; but, familiar grown, -I pleased, and with attractive graces won -The most averse--thee chiefly, who, full oft -Thyself in me thy perfect image viewing, -Becam'st enamoured; and such joy thou took'st -With me in secret that my womb conceived -A growing burden. Meanwhile war arose, -And fields were fought in Heaven: wherein remained -(For what could else?) to our Almighty Foe -Clear victory; to our part loss and rout -Through all the Empyrean. Down they fell, -Driven headlong from the pitch of Heaven, down -Into this Deep; and in the general fall -I also: at which time this powerful key -Into my hands was given, with charge to keep -These gates for ever shut, which none can pass -Without my opening. Pensive here I sat -Alone; but long I sat not, till my womb, -Pregnant by thee, and now excessive grown, -Prodigious motion felt and rueful throes. -At last this odious offspring whom thou seest, -Thine own begotten, breaking violent way, -Tore through my entrails, that, with fear and pain -Distorted, all my nether shape thus grew -Transformed: but he my inbred enemy -Forth issued, brandishing his fatal dart, -Made to destroy. I fled, and cried out Death! -Hell trembled at the hideous name, and sighed -From all her caves, and back resounded Death! -I fled; but he pursued (though more, it seems, -Inflamed with lust than rage), and, swifter far, -Me overtook, his mother, all dismayed, -And, in embraces forcible and foul -Engendering with me, of that rape begot -These yelling monsters, that with ceaseless cry -Surround me, as thou saw'st--hourly conceived -And hourly born, with sorrow infinite -To me; for, when they list, into the womb -That bred them they return, and howl, and gnaw -My bowels, their repast; then, bursting forth -Afresh, with conscious terrors vex me round, -That rest or intermission none I find. -Before mine eyes in opposition sits -Grim Death, my son and foe, who set them on, -And me, his parent, would full soon devour -For want of other prey, but that he knows -His end with mine involved, and knows that I -Should prove a bitter morsel, and his bane, -Whenever that shall be: so Fate pronounced. -But thou, O father, I forewarn thee, shun -His deadly arrow; neither vainly hope -To be invulnerable in those bright arms, -Through tempered heavenly; for that mortal dint, -Save he who reigns above, none can resist." - She finished; and the subtle Fiend his lore -Soon learned, now milder, and thus answered smooth:-- - "Dear daughter--since thou claim'st me for thy sire, -And my fair son here show'st me, the dear pledge -Of dalliance had with thee in Heaven, and joys -Then sweet, now sad to mention, through dire change -Befallen us unforeseen, unthought-of--know, -I come no enemy, but to set free -From out this dark and dismal house of pain -Both him and thee, and all the heavenly host -Of Spirits that, in our just pretences armed, -Fell with us from on high. From them I go -This uncouth errand sole, and one for all -Myself expose, with lonely steps to tread -Th' unfounded Deep, and through the void immense -To search, with wandering quest, a place foretold -Should be--and, by concurring signs, ere now -Created vast and round--a place of bliss -In the purlieus of Heaven; and therein placed -A race of upstart creatures, to supply -Perhaps our vacant room, though more removed, -Lest Heaven, surcharged with potent multitude, -Might hap to move new broils. Be this, or aught -Than this more secret, now designed, I haste -To know; and, this once known, shall soon return, -And bring ye to the place where thou and Death -Shall dwell at ease, and up and down unseen -Wing silently the buxom air, embalmed -With odours. There ye shall be fed and filled -Immeasurably; all things shall be your prey." - He ceased; for both seemed highly pleased, and Death -Grinned horrible a ghastly smile, to hear -His famine should be filled, and blessed his maw -Destined to that good hour. No less rejoiced -His mother bad, and thus bespake her sire:-- - "The key of this infernal Pit, by due -And by command of Heaven's all-powerful King, -I keep, by him forbidden to unlock -These adamantine gates; against all force -Death ready stands to interpose his dart, -Fearless to be o'ermatched by living might. -But what owe I to his commands above, -Who hates me, and hath hither thrust me down -Into this gloom of Tartarus profound, -To sit in hateful office here confined, -Inhabitant of Heaven and heavenly born-- -Here in perpetual agony and pain, -With terrors and with clamours compassed round -Of mine own brood, that on my bowels feed? -Thou art my father, thou my author, thou -My being gav'st me; whom should I obey -But thee? whom follow? Thou wilt bring me soon -To that new world of light and bliss, among -The gods who live at ease, where I shall reign -At thy right hand voluptuous, as beseems -Thy daughter and thy darling, without end." - Thus saying, from her side the fatal key, -Sad instrument of all our woe, she took; -And, towards the gate rolling her bestial train, -Forthwith the huge portcullis high up-drew, -Which, but herself, not all the Stygian Powers -Could once have moved; then in the key-hole turns -Th' intricate wards, and every bolt and bar -Of massy iron or solid rock with ease -Unfastens. On a sudden open fly, -With impetuous recoil and jarring sound, -Th' infernal doors, and on their hinges grate -Harsh thunder, that the lowest bottom shook -Of Erebus. She opened; but to shut -Excelled her power: the gates wide open stood, -That with extended wings a bannered host, -Under spread ensigns marching, mibht pass through -With horse and chariots ranked in loose array; -So wide they stood, and like a furnace-mouth -Cast forth redounding smoke and ruddy flame. -Before their eyes in sudden view appear -The secrets of the hoary Deep--a dark -Illimitable ocean, without bound, -Without dimension; where length, breadth, and height, -And time, and place, are lost; where eldest Night -And Chaos, ancestors of Nature, hold -Eternal anarchy, amidst the noise -Of endless wars, and by confusion stand. -For Hot, Cold, Moist, and Dry, four champions fierce, -Strive here for mastery, and to battle bring -Their embryon atoms: they around the flag -Of each his faction, in their several clans, -Light-armed or heavy, sharp, smooth, swift, or slow, -Swarm populous, unnumbered as the sands -Of Barca or Cyrene's torrid soil, -Levied to side with warring winds, and poise -Their lighter wings. To whom these most adhere -He rules a moment: Chaos umpire sits, -And by decision more embroils the fray -By which he reigns: next him, high arbiter, -Chance governs all. Into this wild Abyss, -The womb of Nature, and perhaps her grave, -Of neither sea, nor shore, nor air, nor fire, -But all these in their pregnant causes mixed -Confusedly, and which thus must ever fight, -Unless th' Almighty Maker them ordain -His dark materials to create more worlds-- -Into this wild Abyss the wary Fiend -Stood on the brink of Hell and looked a while, -Pondering his voyage; for no narrow frith -He had to cross. Nor was his ear less pealed -With noises loud and ruinous (to compare -Great things with small) than when Bellona storms -With all her battering engines, bent to rase -Some capital city; or less than if this frame -Of Heaven were falling, and these elements -In mutiny had from her axle torn -The steadfast Earth. At last his sail-broad vans -He spread for flight, and, in the surging smoke -Uplifted, spurns the ground; thence many a league, -As in a cloudy chair, ascending rides -Audacious; but, that seat soon failing, meets -A vast vacuity. All unawares, -Fluttering his pennons vain, plumb-down he drops -Ten thousand fathom deep, and to this hour -Down had been falling, had not, by ill chance, -The strong rebuff of some tumultuous cloud, -Instinct with fire and nitre, hurried him -As many miles aloft. That fury stayed-- -Quenched in a boggy Syrtis, neither sea, -Nor good dry land--nigh foundered, on he fares, -Treading the crude consistence, half on foot, -Half flying; behoves him now both oar and sail. -As when a gryphon through the wilderness -With winged course, o'er hill or moory dale, -Pursues the Arimaspian, who by stealth -Had from his wakeful custody purloined -The guarded gold; so eagerly the Fiend -O'er bog or steep, through strait, rough, dense, or rare, -With head, hands, wings, or feet, pursues his way, -And swims, or sinks, or wades, or creeps, or flies. -At length a universal hubbub wild -Of stunning sounds, and voices all confused, -Borne through the hollow dark, assaults his ear -With loudest vehemence. Thither he plies -Undaunted, to meet there whatever Power -Or Spirit of the nethermost Abyss -Might in that noise reside, of whom to ask -Which way the nearest coast of darkness lies -Bordering on light; when straight behold the throne -Of Chaos, and his dark pavilion spread -Wide on the wasteful Deep! With him enthroned -Sat sable-vested Night, eldest of things, -The consort of his reign; and by them stood -Orcus and Ades, and the dreaded name -Of Demogorgon; Rumour next, and Chance, -And Tumult, and Confusion, all embroiled, -And Discord with a thousand various mouths. - T' whom Satan, turning boldly, thus:--"Ye Powers -And Spirtis of this nethermost Abyss, -Chaos and ancient Night, I come no spy -With purpose to explore or to disturb -The secrets of your realm; but, by constraint -Wandering this darksome desert, as my way -Lies through your spacious empire up to light, -Alone and without guide, half lost, I seek, -What readiest path leads where your gloomy bounds -Confine with Heaven; or, if some other place, -From your dominion won, th' Ethereal King -Possesses lately, thither to arrive -I travel this profound. Direct my course: -Directed, no mean recompense it brings -To your behoof, if I that region lost, -All usurpation thence expelled, reduce -To her original darkness and your sway -(Which is my present journey), and once more -Erect the standard there of ancient Night. -Yours be th' advantage all, mine the revenge!" - Thus Satan; and him thus the Anarch old, -With faltering speech and visage incomposed, -Answered: "I know thee, stranger, who thou art-- *** -That mighty leading Angel, who of late -Made head against Heaven's King, though overthrown. -I saw and heard; for such a numerous host -Fled not in silence through the frighted Deep, -With ruin upon ruin, rout on rout, -Confusion worse confounded; and Heaven-gates -Poured out by millions her victorious bands, -Pursuing. I upon my frontiers here -Keep residence; if all I can will serve -That little which is left so to defend, -Encroached on still through our intestine broils -Weakening the sceptre of old Night: first, Hell, -Your dungeon, stretching far and wide beneath; -Now lately Heaven and Earth, another world -Hung o'er my realm, linked in a golden chain -To that side Heaven from whence your legions fell! -If that way be your walk, you have not far; -So much the nearer danger. Go, and speed; -Havoc, and spoil, and ruin, are my gain." - He ceased; and Satan stayed not to reply, -But, glad that now his sea should find a shore, -With fresh alacrity and force renewed -Springs upward, like a pyramid of fire, -Into the wild expanse, and through the shock -Of fighting elements, on all sides round -Environed, wins his way; harder beset -And more endangered than when Argo passed -Through Bosporus betwixt the justling rocks, -Or when Ulysses on the larboard shunned -Charybdis, and by th' other whirlpool steered. -So he with difficulty and labour hard -Moved on, with difficulty and labour he; -But, he once passed, soon after, when Man fell, -Strange alteration! Sin and Death amain, -Following his track (such was the will of Heaven) -Paved after him a broad and beaten way -Over the dark Abyss, whose boiling gulf -Tamely endured a bridge of wondrous length, -From Hell continued, reaching th' utmost orb -Of this frail World; by which the Spirits perverse -With easy intercourse pass to and fro -To tempt or punish mortals, except whom -God and good Angels guard by special grace. - But now at last the sacred influence -Of light appears, and from the walls of Heaven -Shoots far into the bosom of dim Night -A glimmering dawn. Here Nature first begins -Her farthest verge, and Chaos to retire, -As from her outmost works, a broken foe, -With tumult less and with less hostile din; -That Satan with less toil, and now with ease, -Wafts on the calmer wave by dubious light, -And, like a weather-beaten vessel, holds -Gladly the port, though shrouds and tackle torn; -Or in the emptier waste, resembling air, -Weighs his spread wings, at leisure to behold -Far off th' empyreal Heaven, extended wide -In circuit, undetermined square or round, -With opal towers and battlements adorned -Of living sapphire, once his native seat; -And, fast by, hanging in a golden chain, -This pendent World, in bigness as a star -Of smallest magnitude close by the moon. -Thither, full fraught with mischievous revenge, -Accursed, and in a cursed hour, he hies. - - - -Book III - - -Hail, holy Light, offspring of Heaven firstborn, -Or of the Eternal coeternal beam -May I express thee unblam'd? since God is light, -And never but in unapproached light -Dwelt from eternity, dwelt then in thee -Bright effluence of bright essence increate. -Or hear"st thou rather pure ethereal stream, -Whose fountain who shall tell? before the sun, -Before the Heavens thou wert, and at the voice -Of God, as with a mantle, didst invest *** -The rising world of waters dark and deep, -Won from the void and formless infinite. -Thee I re-visit now with bolder wing, -Escap'd the Stygian pool, though long detain'd -In that obscure sojourn, while in my flight -Through utter and through middle darkness borne, -With other notes than to the Orphean lyre -I sung of Chaos and eternal Night; -Taught by the heavenly Muse to venture down -The dark descent, and up to re-ascend, -Though hard and rare: Thee I revisit safe, -And feel thy sovran vital lamp; but thou -Revisit'st not these eyes, that roll in vain -To find thy piercing ray, and find no dawn; -So thick a drop serene hath quench'd their orbs, -Or dim suffusion veil'd. Yet not the more -Cease I to wander, where the Muses haunt, -Clear spring, or shady grove, or sunny hill, -Smit with the love of sacred song; but chief -Thee, Sion, and the flowery brooks beneath, -That wash thy hallow'd feet, and warbling flow, -Nightly I visit: nor sometimes forget -So were I equall'd with them in renown, -Thy sovran command, that Man should find grace; -Blind Thamyris, and blind Maeonides, -And Tiresias, and Phineus, prophets old: -Then feed on thoughts, that voluntary move -Harmonious numbers; as the wakeful bird -Sings darkling, and in shadiest covert hid -Tunes her nocturnal note. Thus with the year -Seasons return; but not to me returns -Day, or the sweet approach of even or morn, -Or sight of vernal bloom, or summer's rose, -Or flocks, or herds, or human face divine; -But cloud instead, and ever-during dark -Surrounds me, from the cheerful ways of men -Cut off, and for the book of knowledge fair -Presented with a universal blank -Of nature's works to me expung'd and ras'd, -And wisdom at one entrance quite shut out. -So much the rather thou, celestial Light, -Shine inward, and the mind through all her powers -Irradiate; there plant eyes, all mist from thence -Purge and disperse, that I may see and tell -Of things invisible to mortal sight. -Now had the Almighty Father from above, -From the pure empyrean where he sits -High thron'd above all highth, bent down his eye -His own works and their works at once to view: -About him all the Sanctities of Heaven -Stood thick as stars, and from his sight receiv'd -Beatitude past utterance; on his right -The radiant image of his glory sat, -His only son; on earth he first beheld -Our two first parents, yet the only two -Of mankind in the happy garden plac'd -Reaping immortal fruits of joy and love, -Uninterrupted joy, unrivall'd love, -In blissful solitude; he then survey'd -Hell and the gulf between, and Satan there -Coasting the wall of Heaven on this side Night -In the dun air sublime, and ready now -To stoop with wearied wings, and willing feet, -On the bare outside of this world, that seem'd -Firm land imbosom'd, without firmament, -Uncertain which, in ocean or in air. -Him God beholding from his prospect high, -Wherein past, present, future, he beholds, -Thus to his only Son foreseeing spake. -Only begotten Son, seest thou what rage -Transports our Adversary? whom no bounds -Prescrib'd no bars of Hell, nor all the chains -Heap'd on him there, nor yet the main abyss -Wide interrupt, can hold; so bent he seems -On desperate revenge, that shall redound -Upon his own rebellious head. And now, -Through all restraint broke loose, he wings his way -Not far off Heaven, in the precincts of light, -Directly towards the new created world, -And man there plac'd, with purpose to assay -If him by force he can destroy, or, worse, -By some false guile pervert; and shall pervert; -For man will hearken to his glozing lies, -And easily transgress the sole command, -Sole pledge of his obedience: So will fall -He and his faithless progeny: Whose fault? -Whose but his own? ingrate, he had of me -All he could have; I made him just and right, -Sufficient to have stood, though free to fall. -Such I created all the ethereal Powers -And Spirits, both them who stood, and them who fail'd; -Freely they stood who stood, and fell who fell. -Not free, what proof could they have given sincere -Of true allegiance, constant faith or love, -Where only what they needs must do appear'd, -Not what they would? what praise could they receive? -What pleasure I from such obedience paid, -When will and reason (reason also is choice) -Useless and vain, of freedom both despoil'd, -Made passive both, had serv'd necessity, -Not me? they therefore, as to right belong$ 'd, -So were created, nor can justly accuse -Their Maker, or their making, or their fate, -As if predestination over-rul'd -Their will dispos'd by absolute decree -Or high foreknowledge they themselves decreed -Their own revolt, not I; if I foreknew, -Foreknowledge had no influence on their fault, -Which had no less proved certain unforeknown. -So without least impulse or shadow of fate, -Or aught by me immutably foreseen, -They trespass, authors to themselves in all -Both what they judge, and what they choose; for so -I form'd them free: and free they must remain, -Till they enthrall themselves; I else must change -Their nature, and revoke the high decree -Unchangeable, eternal, which ordain'd -$THeir freedom: they themselves ordain'd their fall. -The first sort by their own suggestion fell, -Self-tempted, self-deprav'd: Man falls, deceiv'd -By the other first: Man therefore shall find grace, -The other none: In mercy and justice both, -Through Heaven and Earth, so shall my glory excel; -But Mercy, first and last, shall brightest shine. -Thus while God spake, ambrosial fragrance fill'd -All Heaven, and in the blessed Spirits elect -Sense of new joy ineffable diffus'd. -Beyond compare the Son of God was seen -Most glorious; in him all his Father shone -Substantially express'd; and in his face -Divine compassion visibly appear'd, -Love without end, and without measure grace, -Which uttering, thus he to his Father spake. -O Father, gracious was that word which clos'd -Thy sovran command, that Man should find grace; -, that Man should find grace; -For which both Heaven and earth shall high extol -Thy praises, with the innumerable sound -Of hymns and sacred songs, wherewith thy throne -Encompass'd shall resound thee ever blest. -For should Man finally be lost, should Man, -Thy creature late so lov'd, thy youngest son, -Fall circumvented thus by fraud, though join'd -With his own folly? that be from thee far, -That far be from thee, Father, who art judge -Of all things made, and judgest only right. -Or shall the Adversary thus obtain -His end, and frustrate thine? shall he fulfill -His malice, and thy goodness bring to nought, -Or proud return, though to his heavier doom, -Yet with revenge accomplish'd, and to Hell -Draw after him the whole race of mankind, -By him corrupted? or wilt thou thyself -Abolish thy creation, and unmake -For him, what for thy glory thou hast made? -So should thy goodness and thy greatness both -Be question'd and blasphem'd without defence. -To whom the great Creator thus replied. -O son, in whom my soul hath chief delight, -Son of my bosom, Son who art alone. -My word, my wisdom, and effectual might, -All hast thou spoken as my thoughts are, all -As my eternal purpose hath decreed; -Man shall not quite be lost, but sav'd who will; -Yet not of will in him, but grace in me -Freely vouchsaf'd; once more I will renew -His lapsed powers, though forfeit; and enthrall'd -By sin to foul exorbitant desires; -Upheld by me, yet once more he shall stand -On even ground against his mortal foe; -By me upheld, that he may know how frail -His fallen condition is, and to me owe -All his deliverance, and to none but me. -Some I have chosen of peculiar grace, -Elect above the rest; so is my will: -The rest shall hear me call, and oft be warn'd -Their sinful state, and to appease betimes -The incensed Deity, while offer'd grace -Invites; for I will clear their senses dark, -What may suffice, and soften stony hearts -To pray, repent, and bring obedience due. -To prayer, repentance, and obedience due, -Though but endeavour'd with sincere intent, -Mine ear shall not be slow, mine eye not shut. -And I will place within them as a guide, -My umpire Conscience; whom if they will hear, -Light after light, well us'd, they shall attain, -And to the end, persisting, safe arrive. -This my long sufferance, and my day of grace, -They who neglect and scorn, shall never taste; -But hard be harden'd, blind be blinded more, -That they may stumble on, and deeper fall; -And none but such from mercy I exclude. -But yet all is not done; Man disobeying, -Disloyal, breaks his fealty, and sins -Against the high supremacy of Heaven, -Affecting God-head, and, so losing all, -To expiate his treason hath nought left, -But to destruction sacred and devote, -He, with his whole posterity, must die, -Die he or justice must; unless for him -Some other able, and as willing, pay -The rigid satisfaction, death for death. -Say, heavenly Powers, where shall we find such love? -Which of you will be mortal, to redeem -Man's mortal crime, and just the unjust to save? -Dwells in all Heaven charity so dear? -And silence was in Heaven: $ on Man's behalf -He ask'd, but all the heavenly quire stood mute, -Patron or intercessour none appear'd, -Much less that durst upon his own head draw -The deadly forfeiture, and ransom set. -And now without redemption all mankind -Must have been lost, adjudg'd to Death and Hell -By doom severe, had not the Son of God, -In whom the fulness dwells of love divine, -His dearest mediation thus renew'd. -Father, thy word is past, Man shall find grace; -And shall grace not find means, that finds her way, -The speediest of thy winged messengers, -To visit all thy creatures, and to all -Comes unprevented, unimplor'd, unsought? -Happy for Man, so coming; he her aid -Can never seek, once dead in sins, and lost; -Atonement for himself, or offering meet, -Indebted and undone, hath none to bring; -Behold me then: me for him, life for life -I offer: on me let thine anger fall; -Account me Man; I for his sake will leave - Thy bosom, and this glory next to thee - Freely put off, and for him lastly die - Well pleased; on me let Death wreak all his rage. - Under his gloomy power I shall not long - Lie vanquished. Thou hast given me to possess - Life in myself for ever; by thee I live; - Though now to Death I yield, and am his due, - All that of me can die, yet, that debt paid, - $ thou wilt not leave me in the loathsome grave - His prey, nor suffer my unspotted soul - For ever with corruption there to dwell; - But I shall rise victorious, and subdue - My vanquisher, spoiled of his vaunted spoil. - Death his death's wound shall then receive, and stoop - Inglorious, of his mortal sting disarmed; - I through the ample air in triumph high - Shall lead Hell captive maugre Hell, and show -The powers of darkness bound. Thou, at the sight - Pleased, out of Heaven shalt look down and smile, - While, by thee raised, I ruin all my foes; - Death last, and with his carcase glut the grave; - Then, with the multitude of my redeemed, - Shall enter Heaven, long absent, and return, - Father, to see thy face, wherein no cloud - Of anger shall remain, but peace assured - And reconcilement: wrath shall be no more - Thenceforth, but in thy presence joy entire. - His words here ended; but his meek aspect - Silent yet spake, and breathed immortal love - To mortal men, above which only shone - Filial obedience: as a sacrifice - Glad to be offered, he attends the will - Of his great Father. Admiration seized - All Heaven, what this might mean, and whither tend, - Wondering; but soon th' Almighty thus replied. - O thou in Heaven and Earth the only peace - Found out for mankind under wrath, O thou - My sole complacence! Well thou know'st how dear - To me are all my works; nor Man the least, - Though last created, that for him I spare - Thee from my bosom and right hand, to save, - By losing thee a while, the whole race lost. - - 00021053 - Thou, therefore, whom thou only canst redeem, - Their nature also to thy nature join; - And be thyself Man among men on Earth, - Made flesh, when time shall be, of virgin seed, - By wondrous birth; be thou in Adam's room -The head of all mankind, though Adam's son. -As in him perish all men, so in thee, -As from a second root, shall be restored -As many as are restored, without thee none. -His crime makes guilty all his sons; thy merit, -Imputed, shall absolve them who renounce -Their own both righteous and unrighteous deeds, -And live in thee transplanted, and from thee -Receive new life. So Man, as is most just, -Shall satisfy for Man, be judged and die, -And dying rise, and rising with him raise -His brethren, ransomed with his own dear life. -So heavenly love shall outdo hellish hate, -Giving to death, and dying to redeem, -So dearly to redeem what hellish hate -So easily destroyed, and still destroys -In those who, when they may, accept not grace. -Nor shalt thou, by descending to assume -Man's nature, lessen or degrade thine own. -Because thou hast, though throned in highest bliss -Equal to God, and equally enjoying -God-like fruition, quitted all, to save -A world from utter loss, and hast been found -By merit more than birthright Son of God, -Found worthiest to be so by being good, -Far more than great or high; because in thee -Love hath abounded more than glory abounds; -Therefore thy humiliation shall exalt -With thee thy manhood also to this throne: -Here shalt thou sit incarnate, here shalt reign -Both God and Man, Son both of God and Man, -Anointed universal King; all power -I give thee; reign for ever, and assume -Thy merits; under thee, as head supreme, -Thrones, Princedoms, Powers, Dominions, I reduce: -All knees to thee shall bow, of them that bide -In Heaven, or Earth, or under Earth in Hell. -When thou, attended gloriously from Heaven, -Shalt in the sky appear, and from thee send -The summoning Arch-Angels to proclaim -Thy dread tribunal; forthwith from all winds, -The living, and forthwith the cited dead -Of all past ages, to the general doom -Shall hasten; such a peal shall rouse their sleep. -Then, all thy saints assembled, thou shalt judge -Bad Men and Angels; they, arraigned, shall sink -Beneath thy sentence; Hell, her numbers full, -Thenceforth shall be for ever shut. Mean while -The world shall burn, and from her ashes spring -New Heaven and Earth, wherein the just shall dwell, -And, after all their tribulations long, -See golden days, fruitful of golden deeds, -With joy and peace triumphing, and fair truth. -Then thou thy regal scepter shalt lay by, -For regal scepter then no more shall need, -God shall be all in all. But, all ye Gods, -Adore him, who to compass all this dies; -Adore the Son, and honour him as me. -No sooner had the Almighty ceased, but all -The multitude of Angels, with a shout -Loud as from numbers without number, sweet -As from blest voices, uttering joy, Heaven rung -With jubilee, and loud Hosannas filled -The eternal regions: Lowly reverent -Towards either throne they bow, and to the ground -With solemn adoration down they cast -Their crowns inwove with amarant and gold; -Immortal amarant, a flower which once -In Paradise, fast by the tree of life, -Began to bloom; but soon for man's offence -To Heaven removed, where first it grew, there grows, -And flowers aloft shading the fount of life, -And where the river of bliss through midst of Heaven -Rolls o'er Elysian flowers her amber stream; -With these that never fade the Spirits elect -Bind their resplendent locks inwreathed with beams; -Now in loose garlands thick thrown off, the bright -Pavement, that like a sea of jasper shone, -Impurpled with celestial roses smiled. -Then, crowned again, their golden harps they took, -Harps ever tuned, that glittering by their side -Like quivers hung, and with preamble sweet -Of charming symphony they introduce -Their sacred song, and waken raptures high; -No voice exempt, no voice but well could join -Melodious part, such concord is in Heaven. -Thee, Father, first they sung Omnipotent, -Immutable, Immortal, Infinite, -Eternal King; the Author of all being, -Fonntain of light, thyself invisible -Amidst the glorious brightness where thou sit'st -Throned inaccessible, but when thou shadest -The full blaze of thy beams, and, through a cloud -Drawn round about thee like a radiant shrine, -Dark with excessive bright thy skirts appear, -Yet dazzle Heaven, that brightest Seraphim -Approach not, but with both wings veil their eyes. -Thee next they sang of all creation first, -Begotten Son, Divine Similitude, -In whose conspicuous countenance, without cloud -Made visible, the Almighty Father shines, -Whom else no creature can behold; on thee -Impressed the effulgence of his glory abides, -Transfused on thee his ample Spirit rests. -He Heaven of Heavens and all the Powers therein -By thee created; and by thee threw down -The aspiring Dominations: Thou that day -Thy Father's dreadful thunder didst not spare, -Nor stop thy flaming chariot-wheels, that shook -Heaven's everlasting frame, while o'er the necks -Thou drovest of warring Angels disarrayed. -Back from pursuit thy Powers with loud acclaim -Thee only extolled, Son of thy Father's might, -To execute fierce vengeance on his foes, -Not so on Man: Him through their malice fallen, -Father of mercy and grace, thou didst not doom -So strictly, but much more to pity incline: -No sooner did thy dear and only Son -Perceive thee purposed not to doom frail Man -So strictly, but much more to pity inclined, -He to appease thy wrath, and end the strife -Of mercy and justice in thy face discerned, -Regardless of the bliss wherein he sat -Second to thee, offered himself to die -For Man's offence. O unexampled love, -Love no where to be found less than Divine! -Hail, Son of God, Saviour of Men! Thy name -Shall be the copious matter of my song -Henceforth, and never shall my heart thy praise -Forget, nor from thy Father's praise disjoin. -Thus they in Heaven, above the starry sphere, -Their happy hours in joy and hymning spent. -Mean while upon the firm opacous globe -Of this round world, whose first convex divides -The luminous inferiour orbs, enclosed -From Chaos, and the inroad of Darkness old, -Satan alighted walks: A globe far off -It seemed, now seems a boundless continent -Dark, waste, and wild, under the frown of Night -Starless exposed, and ever-threatening storms -Of Chaos blustering round, inclement sky; -Save on that side which from the wall of Heaven, -Though distant far, some small reflection gains -Of glimmering air less vexed with tempest loud: -Here walked the Fiend at large in spacious field. -As when a vultur on Imaus bred, -Whose snowy ridge the roving Tartar bounds, -Dislodging from a region scarce of prey -To gorge the flesh of lambs or yeanling kids, -On hills where flocks are fed, flies toward the springs -Of Ganges or Hydaspes, Indian streams; -But in his way lights on the barren plains -Of Sericana, where Chineses drive -With sails and wind their cany waggons light: -So, on this windy sea of land, the Fiend -Walked up and down alone, bent on his prey; -Alone, for other creature in this place, -Living or lifeless, to be found was none; -None yet, but store hereafter from the earth -Up hither like aereal vapours flew -Of all things transitory and vain, when sin -With vanity had filled the works of men: -Both all things vain, and all who in vain things -Built their fond hopes of glory or lasting fame, -Or happiness in this or the other life; -All who have their reward on earth, the fruits -Of painful superstition and blind zeal, -Nought seeking but the praise of men, here find -Fit retribution, empty as their deeds; -All the unaccomplished works of Nature's hand, -Abortive, monstrous, or unkindly mixed, -Dissolved on earth, fleet hither, and in vain, -Till final dissolution, wander here; -Not in the neighbouring moon as some have dreamed; -Those argent fields more likely habitants, -Translated Saints, or middle Spirits hold -Betwixt the angelical and human kind. -Hither of ill-joined sons and daughters born -First from the ancient world those giants came -With many a vain exploit, though then renowned: -The builders next of Babel on the plain -Of Sennaar, and still with vain design, -New Babels, had they wherewithal, would build: -Others came single; he, who, to be deemed -A God, leaped fondly into Aetna flames, -Empedocles; and he, who, to enjoy -Plato's Elysium, leaped into the sea, -Cleombrotus; and many more too long, -Embryos, and idiots, eremites, and friars -White, black, and gray, with all their trumpery. -Here pilgrims roam, that strayed so far to seek -In Golgotha him dead, who lives in Heaven; -And they, who to be sure of Paradise, -Dying, put on the weeds of Dominick, -Or in Franciscan think to pass disguised; -They pass the planets seven, and pass the fixed, -And that crystalling sphere whose balance weighs -The trepidation talked, and that first moved; -And now Saint Peter at Heaven's wicket seems -To wait them with his keys, and now at foot -Of Heaven's ascent they lift their feet, when lo -A violent cross wind from either coast -Blows them transverse, ten thousand leagues awry -Into the devious air: Then might ye see -Cowls, hoods, and habits, with their wearers, tost -And fluttered into rags; then reliques, beads, -Indulgences, dispenses, pardons, bulls, -The sport of winds: All these, upwhirled aloft, -Fly o'er the backside of the world far off -Into a Limbo large and broad, since called -The Paradise of Fools, to few unknown -Long after; now unpeopled, and untrod. -All this dark globe the Fiend found as he passed, -And long he wandered, till at last a gleam -Of dawning light turned thither-ward in haste -His travelled steps: far distant he descries -Ascending by degrees magnificent -Up to the wall of Heaven a structure high; -At top whereof, but far more rich, appeared -The work as of a kingly palace-gate, -With frontispiece of diamond and gold -Embellished; thick with sparkling orient gems -The portal shone, inimitable on earth -By model, or by shading pencil, drawn. -These stairs were such as whereon Jacob saw -Angels ascending and descending, bands -Of guardians bright, when he from Esau fled -To Padan-Aram, in the field of Luz -Dreaming by night under the open sky -And waking cried, This is the gate of Heaven. -Each stair mysteriously was meant, nor stood -There always, but drawn up to Heaven sometimes -Viewless; and underneath a bright sea flowed -Of jasper, or of liquid pearl, whereon -Who after came from earth, failing arrived -Wafted by Angels, or flew o'er the lake -Rapt in a chariot drawn by fiery steeds. -The stairs were then let down, whether to dare -The Fiend by easy ascent, or aggravate -His sad exclusion from the doors of bliss: -Direct against which opened from beneath, -Just o'er the blissful seat of Paradise, -A passage down to the Earth, a passage wide, -Wider by far than that of after-times -Over mount Sion, and, though that were large, -Over the Promised Land to God so dear; -By which, to visit oft those happy tribes, -On high behests his angels to and fro -Passed frequent, and his eye with choice regard -From Paneas, the fount of Jordan's flood, -To Beersaba, where the Holy Land -Borders on Egypt and the Arabian shore; -So wide the opening seemed, where bounds were set -To darkness, such as bound the ocean wave. -Satan from hence, now on the lower stair, -That scaled by steps of gold to Heaven-gate, -Looks down with wonder at the sudden view -Of all this world at once. As when a scout, -Through dark?;nd desart ways with?oeril gone -All?might,?;t?kast by break of cheerful dawn -Obtains the brow of some high-climbing hill, -Which to his eye discovers unaware -The goodly prospect of some foreign land -First seen, or some renowned metropolis -With glistering spires and pinnacles adorned, -Which now the rising sun gilds with his beams: -Such wonder seised, though after Heaven seen, -The Spirit malign, but much more envy seised, -At sight of all this world beheld so fair. -Round he surveys (and well might, where he stood -So high above the circling canopy -Of night's extended shade,) from eastern point -Of Libra to the fleecy star that bears -Andromeda far off Atlantick seas -Beyond the horizon; then from pole to pole -He views in breadth, and without longer pause -Down right into the world's first region throws -His flight precipitant, and winds with ease -Through the pure marble air his oblique way -Amongst innumerable stars, that shone -Stars distant, but nigh hand seemed other worlds; -Or other worlds they seemed, or happy isles, -Like those Hesperian gardens famed of old, -Fortunate fields, and groves, and flowery vales, -Thrice happy isles; but who dwelt happy there -He staid not to inquire: Above them all -The golden sun, in splendour likest Heaven, -Allured his eye; thither his course he bends -Through the calm firmament, (but up or down, -By center, or eccentrick, hard to tell, -Or longitude,) where the great luminary -Aloof the vulgar constellations thick, -That from his lordly eye keep distance due, -Dispenses light from far; they, as they move -Their starry dance in numbers that compute -Days, months, and years, towards his all-cheering lamp -Turn swift their various motions, or are turned -By his magnetick beam, that gently warms -The universe, and to each inward part -With gentle penetration, though unseen, -Shoots invisible virtue even to the deep; -So wonderously was set his station bright. -There lands the Fiend, a spot like which perhaps -Astronomer in the sun's lucent orb -Through his glazed optick tube yet never saw. -The place he found beyond expression bright, -Compared with aught on earth, metal or stone; -Not all parts like, but all alike informed -With radiant light, as glowing iron with fire; -If metal, part seemed gold, part silver clear; -If stone, carbuncle most or chrysolite, -Ruby or topaz, to the twelve that shone -In Aaron's breast-plate, and a stone besides -Imagined rather oft than elsewhere seen, -That stone, or like to that which here below -Philosophers in vain so long have sought, -In vain, though by their powerful art they bind -Volatile Hermes, and call up unbound -In various shapes old Proteus from the sea, -Drained through a limbeck to his native form. -What wonder then if fields and regions here -Breathe forth Elixir pure, and rivers run -Potable gold, when with one virtuous touch -The arch-chemick sun, so far from us remote, -Produces, with terrestrial humour mixed, -Here in the dark so many precious things -Of colour glorious, and effect so rare? -Here matter new to gaze the Devil met -Undazzled; far and wide his eye commands; -For sight no obstacle found here, nor shade, -But all sun-shine, as when his beams at noon -Culminate from the equator, as they now -Shot upward still direct, whence no way round -Shadow from body opaque can fall; and the air, -No where so clear, sharpened his visual ray -To objects distant far, whereby he soon -Saw within ken a glorious Angel stand, -The same whom John saw also in the sun: -His back was turned, but not his brightness hid; -Of beaming sunny rays a golden tiar -Circled his head, nor less his locks behind -Illustrious on his shoulders fledge with wings -Lay waving round; on some great charge employed -He seemed, or fixed in cogitation deep. -Glad was the Spirit impure, as now in hope -To find who might direct his wandering flight -To Paradise, the happy seat of Man, -His journey's end and our beginning woe. -But first he casts to change his proper shape, -Which else might work him danger or delay: -And now a stripling Cherub he appears, -Not of the prime, yet such as in his face -Youth smiled celestial, and to every limb -Suitable grace diffused, so well he feigned: -Under a coronet his flowing hair -In curls on either cheek played; wings he wore -Of many a coloured plume, sprinkled with gold; -His habit fit for speed succinct, and held -Before his decent steps a silver wand. -He drew not nigh unheard; the Angel bright, -Ere he drew nigh, his radiant visage turned, -Admonished by his ear, and straight was known -The Arch-Angel Uriel, one of the seven -Who in God's presence, nearest to his throne, -Stand ready at command, and are his eyes -That run through all the Heavens, or down to the Earth -Bear his swift errands over moist and dry, -O'er sea and land: him Satan thus accosts. -Uriel, for thou of those seven Spirits that stand -In sight of God's high throne, gloriously bright, -The first art wont his great authentick will -Interpreter through highest Heaven to bring, -Where all his sons thy embassy attend; -And here art likeliest by supreme decree -Like honour to obtain, and as his eye -To visit oft this new creation round; -Unspeakable desire to see, and know -All these his wonderous works, but chiefly Man, -His chief delight and favour, him for whom -All these his works so wonderous he ordained, -Hath brought me from the quires of Cherubim -Alone thus wandering. Brightest Seraph, tell -In which of all these shining orbs hath Man -His fixed seat, or fixed seat hath none, -But all these shining orbs his choice to dwell; -That I may find him, and with secret gaze -Or open admiration him behold, -On whom the great Creator hath bestowed -Worlds, and on whom hath all these graces poured; -That both in him and all things, as is meet, -The universal Maker we may praise; -Who justly hath driven out his rebel foes -To deepest Hell, and, to repair that loss, -Created this new happy race of Men -To serve him better: Wise are all his ways. -So spake the false dissembler unperceived; -For neither Man nor Angel can discern -Hypocrisy, the only evil that walks -Invisible, except to God alone, -By his permissive will, through Heaven and Earth: -And oft, though wisdom wake, suspicion sleeps -At wisdom's gate, and to simplicity -Resigns her charge, while goodness thinks no ill -Where no ill seems: Which now for once beguiled -Uriel, though regent of the sun, and held -The sharpest-sighted Spirit of all in Heaven; -Who to the fraudulent impostor foul, -In his uprightness, answer thus returned. -Fair Angel, thy desire, which tends to know -The works of God, thereby to glorify -The great Work-master, leads to no excess -That reaches blame, but rather merits praise -The more it seems excess, that led thee hither -From thy empyreal mansion thus alone, -To witness with thine eyes what some perhaps, -Contented with report, hear only in Heaven: -For wonderful indeed are all his works, -Pleasant to know, and worthiest to be all -Had in remembrance always with delight; -But what created mind can comprehend -Their number, or the wisdom infinite -That brought them forth, but hid their causes deep? -I saw when at his word the formless mass, -This world's material mould, came to a heap: -Confusion heard his voice, and wild uproar -Stood ruled, stood vast infinitude confined; -Till at his second bidding Darkness fled, -Light shone, and order from disorder sprung: -Swift to their several quarters hasted then -The cumbrous elements, earth, flood, air, fire; -And this ethereal quintessence of Heaven -Flew upward, spirited with various forms, -That rolled orbicular, and turned to stars -Numberless, as thou seest, and how they move; -Each had his place appointed, each his course; -The rest in circuit walls this universe. -Look downward on that globe, whose hither side -With light from hence, though but reflected, shines; -That place is Earth, the seat of Man; that light -His day, which else, as the other hemisphere, -Night would invade; but there the neighbouring moon -So call that opposite fair star) her aid -Timely interposes, and her monthly round -Still ending, still renewing, through mid Heaven, -With borrowed light her countenance triform -Hence fills and empties to enlighten the Earth, -And in her pale dominion checks the night. -That spot, to which I point, is Paradise, -Adam's abode; those lofty shades, his bower. -Thy way thou canst not miss, me mine requires. -Thus said, he turned; and Satan, bowing low, -As to superiour Spirits is wont in Heaven, -Where honour due and reverence none neglects, -Took leave, and toward the coast of earth beneath, -Down from the ecliptick, sped with hoped success, -Throws his steep flight in many an aery wheel; -Nor staid, till on Niphates' top he lights. - - - -Book IV - - -O, for that warning voice, which he, who saw -The Apocalypse, heard cry in Heaven aloud, -Then when the Dragon, put to second rout, -Came furious down to be revenged on men, -Woe to the inhabitants on earth! that now, -While time was, our first parents had been warned -The coming of their secret foe, and 'scaped, -Haply so 'scaped his mortal snare: For now -Satan, now first inflamed with rage, came down, -The tempter ere the accuser of mankind, -To wreak on innocent frail Man his loss -Of that first battle, and his flight to Hell: -Yet, not rejoicing in his speed, though bold -Far off and fearless, nor with cause to boast, -Begins his dire attempt; which nigh the birth -Now rolling boils in his tumultuous breast, -And like a devilish engine back recoils -Upon himself; horrour and doubt distract -His troubled thoughts, and from the bottom stir -The Hell within him; for within him Hell -He brings, and round about him, nor from Hell -One step, no more than from himself, can fly -By change of place: Now conscience wakes despair, -That slumbered; wakes the bitter memory -Of what he was, what is, and what must be -Worse; of worse deeds worse sufferings must ensue. -Sometimes towards Eden, which now in his view -Lay pleasant, his grieved look he fixes sad; -Sometimes towards Heaven, and the full-blazing sun, -Which now sat high in his meridian tower: -Then, much revolving, thus in sighs began. -O thou, that, with surpassing glory crowned, -Lookest from thy sole dominion like the God -Of this new world; at whose sight all the stars -Hide their diminished heads; to thee I call, -But with no friendly voice, and add thy name, -Of Sun! to tell thee how I hate thy beams, -That bring to my remembrance from what state -I fell, how glorious once above thy sphere; -Till pride and worse ambition threw me down -Warring in Heaven against Heaven's matchless King: -Ah, wherefore! he deserved no such return -From me, whom he created what I was -In that bright eminence, and with his good -Upbraided none; nor was his service hard. -What could be less than to afford him praise, -The easiest recompence, and pay him thanks, -How due! yet all his good proved ill in me, -And wrought but malice; lifted up so high -I sdeined subjection, and thought one step higher -Would set me highest, and in a moment quit -The debt immense of endless gratitude, -So burdensome still paying, still to owe, -Forgetful what from him I still received, -And understood not that a grateful mind -By owing owes not, but still pays, at once -Indebted and discharged; what burden then -O, had his powerful destiny ordained -Me some inferiour Angel, I had stood -Then happy; no unbounded hope had raised -Ambition! Yet why not some other Power -As great might have aspired, and me, though mean, -Drawn to his part; but other Powers as great -Fell not, but stand unshaken, from within -Or from without, to all temptations armed. -Hadst thou the same free will and power to stand? -Thou hadst: whom hast thou then or what to accuse, -But Heaven's free love dealt equally to all? -Be then his love accursed, since love or hate, -To me alike, it deals eternal woe. -Nay, cursed be thou; since against his thy will -Chose freely what it now so justly rues. -Me miserable! which way shall I fly -Infinite wrath, and infinite despair? -Which way I fly is Hell; myself am Hell; -And, in the lowest deep, a lower deep -Still threatening to devour me opens wide, -To which the Hell I suffer seems a Heaven. -O, then, at last relent: Is there no place -Left for repentance, none for pardon left? -None left but by submission; and that word -Disdain forbids me, and my dread of shame -Among the Spirits beneath, whom I seduced -With other promises and other vaunts -Than to submit, boasting I could subdue -The Omnipotent. Ay me! they little know -How dearly I abide that boast so vain, -Under what torments inwardly I groan, -While they adore me on the throne of Hell. -With diadem and scepter high advanced, -The lower still I fall, only supreme -In misery: Such joy ambition finds. -But say I could repent, and could obtain, -By act of grace, my former state; how soon -Would highth recall high thoughts, how soon unsay -What feigned submission swore? Ease would recant -Vows made in pain, as violent and void. -For never can true reconcilement grow, -Where wounds of deadly hate have pierced so deep: -Which would but lead me to a worse relapse -And heavier fall: so should I purchase dear -Short intermission bought with double smart. -This knows my Punisher; therefore as far -From granting he, as I from begging, peace; -All hope excluded thus, behold, in stead -Mankind created, and for him this world. -So farewell, hope; and with hope farewell, fear; -Farewell, remorse! all good to me is lost; -Evil, be thou my good; by thee at least -Divided empire with Heaven's King I hold, -By thee, and more than half perhaps will reign; -As Man ere long, and this new world, shall know. -Thus while he spake, each passion dimmed his face -Thrice changed with pale, ire, envy, and despair; -Which marred his borrowed visage, and betrayed -Him counterfeit, if any eye beheld. -For heavenly minds from such distempers foul -Are ever clear. Whereof he soon aware, -Each perturbation smoothed with outward calm, -Artificer of fraud; and was the first -That practised falsehood under saintly show, -Deep malice to conceal, couched with revenge: -Yet not enough had practised to deceive -Uriel once warned; whose eye pursued him down - The way he went, and on the Assyrian mount - Saw him disfigured, more than could befall - Spirit of happy sort; his gestures fierce - He marked and mad demeanour, then alone, - As he supposed, all unobserved, unseen. - So on he fares, and to the border comes - Of Eden, where delicious Paradise, - Now nearer, crowns with her enclosure green, - As with a rural mound, the champaign head - Of a steep wilderness, whose hairy sides -Access denied; and overhead upgrew - Insuperable height of loftiest shade, - Cedar, and pine, and fir, and branching palm, - A sylvan scene, and, as the ranks ascend, - Shade above shade, a woody theatre - Of stateliest view. Yet higher than their tops - The verdurous wall of Paradise upsprung; - - 00081429 -Which to our general sire gave prospect large -Into his nether empire neighbouring round. -And higher than that wall a circling row -Of goodliest trees, loaden with fairest fruit, -Blossoms and fruits at once of golden hue, -Appeared, with gay enamelled colours mixed: -On which the sun more glad impressed his beams -Than in fair evening cloud, or humid bow, -When God hath showered the earth; so lovely seemed -That landskip: And of pure now purer air -Meets his approach, and to the heart inspires -Vernal delight and joy, able to drive -All sadness but despair: Now gentle gales, -Fanning their odoriferous wings, dispense -Native perfumes, and whisper whence they stole -Those balmy spoils. As when to them who fail -Beyond the Cape of Hope, and now are past -Mozambick, off at sea north-east winds blow -Sabean odours from the spicy shore -Of Araby the blest; with such delay -Well pleased they slack their course, and many a league -Cheered with the grateful smell old Ocean smiles: -So entertained those odorous sweets the Fiend, -Who came their bane; though with them better pleased -Than Asmodeus with the fishy fume -That drove him, though enamoured, from the spouse -Of Tobit's son, and with a vengeance sent -From Media post to Egypt, there fast bound. -Now to the ascent of that steep savage hill -Satan had journeyed on, pensive and slow; -But further way found none, so thick entwined, -As one continued brake, the undergrowth -Of shrubs and tangling bushes had perplexed -All path of man or beast that passed that way. -One gate there only was, and that looked east -On the other side: which when the arch-felon saw, -Due entrance he disdained; and, in contempt, -At one flight bound high over-leaped all bound -Of hill or highest wall, and sheer within -Lights on his feet. As when a prowling wolf, -Whom hunger drives to seek new haunt for prey, -Watching where shepherds pen their flocks at eve -In hurdled cotes amid the field secure, -Leaps o'er the fence with ease into the fold: -Or as a thief, bent to unhoard the cash -Of some rich burgher, whose substantial doors, -Cross-barred and bolted fast, fear no assault, -In at the window climbs, or o'er the tiles: -So clomb this first grand thief into God's fold; -So since into his church lewd hirelings climb. -Thence up he flew, and on the tree of life, -The middle tree and highest there that grew, -Sat like a cormorant; yet not true life -Thereby regained, but sat devising death -To them who lived; nor on the virtue thought -Of that life-giving plant, but only used -For prospect, what well used had been the pledge -Of immortality. So little knows -Any, but God alone, to value right -The good before him, but perverts best things -To worst abuse, or to their meanest use. -Beneath him with new wonder now he views, -To all delight of human sense exposed, -In narrow room, Nature's whole wealth, yea more, -A Heaven on Earth: For blissful Paradise -Of God the garden was, by him in the east -Of Eden planted; Eden stretched her line -From Auran eastward to the royal towers -Of great Seleucia, built by Grecian kings, -Of where the sons of Eden long before -Dwelt in Telassar: In this pleasant soil -His far more pleasant garden God ordained; -Out of the fertile ground he caused to grow -All trees of noblest kind for sight, smell, taste; -And all amid them stood the tree of life, -High eminent, blooming ambrosial fruit -Of vegetable gold; and next to life, -Our death, the tree of knowledge, grew fast by, -Knowledge of good bought dear by knowing ill. -Southward through Eden went a river large, -Nor changed his course, but through the shaggy hill -Passed underneath ingulfed; for God had thrown -That mountain as his garden-mould high raised -Upon the rapid current, which, through veins -Of porous earth with kindly thirst up-drawn, -Rose a fresh fountain, and with many a rill -Watered the garden; thence united fell -Down the steep glade, and met the nether flood, -Which from his darksome passage now appears, -And now, divided into four main streams, -Runs diverse, wandering many a famous realm -And country, whereof here needs no account; -But rather to tell how, if Art could tell, -How from that sapphire fount the crisped brooks, -Rolling on orient pearl and sands of gold, -With mazy errour under pendant shades -Ran nectar, visiting each plant, and fed -Flowers worthy of Paradise, which not nice Art -In beds and curious knots, but Nature boon -Poured forth profuse on hill, and dale, and plain, -Both where the morning sun first warmly smote -The open field, and where the unpierced shade -Imbrowned the noontide bowers: Thus was this place -A happy rural seat of various view; -Groves whose rich trees wept odorous gums and balm, -Others whose fruit, burnished with golden rind, -Hung amiable, Hesperian fables true, -If true, here only, and of delicious taste: -Betwixt them lawns, or level downs, and flocks -Grazing the tender herb, were interposed, -Or palmy hillock; or the flowery lap -Of some irriguous valley spread her store, -Flowers of all hue, and without thorn the rose: -Another side, umbrageous grots and caves -Of cool recess, o'er which the mantling vine -Lays forth her purple grape, and gently creeps -Luxuriant; mean while murmuring waters fall -Down the slope hills, dispersed, or in a lake, -That to the fringed bank with myrtle crowned -Her crystal mirrour holds, unite their streams. -The birds their quire apply; airs, vernal airs, -Breathing the smell of field and grove, attune -The trembling leaves, while universal Pan, -Knit with the Graces and the Hours in dance, -Led on the eternal Spring. Not that fair field -Of Enna, where Proserpine gathering flowers, -Herself a fairer flower by gloomy Dis -Was gathered, which cost Ceres all that pain -To seek her through the world; nor that sweet grove -Of Daphne by Orontes, and the inspired -Castalian spring, might with this Paradise -Of Eden strive; nor that Nyseian isle -Girt with the river Triton, where old Cham, -Whom Gentiles Ammon call and Libyan Jove, -Hid Amalthea, and her florid son -Young Bacchus, from his stepdame Rhea's eye; -Nor where Abassin kings their issue guard, -Mount Amara, though this by some supposed -True Paradise under the Ethiop line -By Nilus' head, enclosed with shining rock, -A whole day's journey high, but wide remote -From this Assyrian garden, where the Fiend -Saw, undelighted, all delight, all kind -Of living creatures, new to sight, and strange -Two of far nobler shape, erect and tall, -Godlike erect, with native honour clad -In naked majesty seemed lords of all: -And worthy seemed; for in their looks divine -The image of their glorious Maker shone, -Truth, wisdom, sanctitude severe and pure, -(Severe, but in true filial freedom placed,) -Whence true authority in men; though both -Not equal, as their sex not equal seemed; -For contemplation he and valour formed; -For softness she and sweet attractive grace; -He for God only, she for God in him: -His fair large front and eye sublime declared -Absolute rule; and hyacinthine locks -Round from his parted forelock manly hung -Clustering, but not beneath his shoulders broad: -She, as a veil, down to the slender waist -Her unadorned golden tresses wore -Dishevelled, but in wanton ringlets waved -As the vine curls her tendrils, which implied -Subjection, but required with gentle sway, -And by her yielded, by him best received, -Yielded with coy submission, modest pride, -And sweet, reluctant, amorous delay. -Nor those mysterious parts were then concealed; -Then was not guilty shame, dishonest shame -Of nature's works, honour dishonourable, -Sin-bred, how have ye troubled all mankind -With shows instead, mere shows of seeming pure, -And banished from man's life his happiest life, -Simplicity and spotless innocence! -So passed they naked on, nor shunned the sight -Of God or Angel; for they thought no ill: -So hand in hand they passed, the loveliest pair, -That ever since in love's embraces met; -Adam the goodliest man of men since born -His sons, the fairest of her daughters Eve. -Under a tuft of shade that on a green -Stood whispering soft, by a fresh fountain side -They sat them down; and, after no more toil -Of their sweet gardening labour than sufficed -To recommend cool Zephyr, and made ease -More easy, wholesome thirst and appetite -More grateful, to their supper-fruits they fell, -Nectarine fruits which the compliant boughs -Yielded them, side-long as they sat recline -On the soft downy bank damasked with flowers: -The savoury pulp they chew, and in the rind, -Still as they thirsted, scoop the brimming stream; -Nor gentle purpose, nor endearing smiles -Wanted, nor youthful dalliance, as beseems -Fair couple, linked in happy nuptial league, -Alone as they. About them frisking played -All beasts of the earth, since wild, and of all chase -In wood or wilderness, forest or den; -Sporting the lion ramped, and in his paw -Dandled the kid; bears, tigers, ounces, pards, -Gambolled before them; the unwieldy elephant, -To make them mirth, used all his might, and wreathed -His?kithetmroboscis; close the serpent sly, -Insinuating, wove with Gordian twine -His braided train, and of his fatal guile -Gave proof unheeded; others on the grass -Couched, and now filled with pasture gazing sat, -Or bedward ruminating; for the sun, -Declined, was hasting now with prone career -To the ocean isles, and in the ascending scale -Of Heaven the stars that usher evening rose: -When Satan still in gaze, as first he stood, -Scarce thus at length failed speech recovered sad. -O Hell! what do mine eyes with grief behold! -Into our room of bliss thus high advanced -Creatures of other mould, earth-born perhaps, -Not Spirits, yet to heavenly Spirits bright -Little inferiour; whom my thoughts pursue -With wonder, and could love, so lively shines -In them divine resemblance, and such grace -The hand that formed them on their shape hath poured. -Ah! gentle pair, ye little think how nigh -Your change approaches, when all these delights -Will vanish, and deliver ye to woe; -More woe, the more your taste is now of joy; -Happy, but for so happy ill secured -Long to continue, and this high seat your Heaven -Ill fenced for Heaven to keep out such a foe -As now is entered; yet no purposed foe -To you, whom I could pity thus forlorn, -Though I unpitied: League with you I seek, -And mutual amity, so strait, so close, -That I with you must dwell, or you with me -Henceforth; my dwelling haply may not please, -Like this fair Paradise, your sense; yet such -Accept your Maker's work; he gave it me, -Which I as freely give: Hell shall unfold, -To entertain you two, her widest gates, -And send forth all her kings; there will be room, -Not like these narrow limits, to receive -Your numerous offspring; if no better place, -Thank him who puts me loth to this revenge -On you who wrong me not for him who wronged. -And should I at your harmless innocence -Melt, as I do, yet publick reason just, -Honour and empire with revenge enlarged, -By conquering this new world, compels me now -To do what else, though damned, I should abhor. -So spake the Fiend, and with necessity, -The tyrant's plea, excused his devilish deeds. -Then from his lofty stand on that high tree -Down he alights among the sportful herd -Of those four-footed kinds, himself now one, -Now other, as their shape served best his end -Nearer to view his prey, and, unespied, -To mark what of their state he more might learn, -By word or action marked. About them round -A lion now he stalks with fiery glare; -Then as a tiger, who by chance hath spied -In some purlieu two gentle fawns at play, -Straight couches close, then, rising, changes oft -His couchant watch, as one who chose his ground, -Whence rushing, he might surest seize them both, -Griped in each paw: when, Adam first of men -To first of women Eve thus moving speech, -Turned him, all ear to hear new utterance flow. -Sole partner, and sole part, of all these joys, -Dearer thyself than all; needs must the Power -That made us, and for us this ample world, -Be infinitely good, and of his good -As liberal and free as infinite; -That raised us from the dust, and placed us here -In all this happiness, who at his hand -Have nothing merited, nor can perform -Aught whereof he hath need; he who requires -From us no other service than to keep -This one, this easy charge, of all the trees -In Paradise that bear delicious fruit -So various, not to taste that only tree -Of knowledge, planted by the tree of life; -So near grows death to life, whate'er death is, -Some dreadful thing no doubt; for well thou knowest -God hath pronounced it death to taste that tree, -The only sign of our obedience left, -Among so many signs of power and rule -Conferred upon us, and dominion given -Over all other creatures that possess -Earth, air, and sea. Then let us not think hard -One easy prohibition, who enjoy -Free leave so large to all things else, and choice -Unlimited of manifold delights: -But let us ever praise him, and extol -His bounty, following our delightful task, -To prune these growing plants, and tend these flowers, -Which were it toilsome, yet with thee were sweet. -To whom thus Eve replied. O thou for whom -And from whom I was formed, flesh of thy flesh, -And without whom am to no end, my guide -And head! what thou hast said is just and right. -For we to him indeed all praises owe, -And daily thanks; I chiefly, who enjoy -So far the happier lot, enjoying thee -Pre-eminent by so much odds, while thou -Like consort to thyself canst no where find. -That day I oft remember, when from sleep -I first awaked, and found myself reposed -Under a shade on flowers, much wondering where -And what I was, whence thither brought, and how. -Not distant far from thence a murmuring sound -Of waters issued from a cave, and spread -Into a liquid plain, then stood unmoved -Pure as the expanse of Heaven; I thither went -With unexperienced thought, and laid me down -On the green bank, to look into the clear -Smooth lake, that to me seemed another sky. -As I bent down to look, just opposite -A shape within the watery gleam appeared, -Bending to look on me: I started back, -It started back; but pleased I soon returned, -Pleased it returned as soon with answering looks -Of sympathy and love: There I had fixed -Mine eyes till now, and pined with vain desire, -Had not a voice thus warned me; 'What thou seest, -'What there thou seest, fair Creature, is thyself; -'With thee it came and goes: but follow me, -'And I will bring thee where no shadow stays -'Thy coming, and thy soft embraces, he -'Whose image thou art; him thou shalt enjoy -'Inseparably thine, to him shalt bear -'Multitudes like thyself, and thence be called -'Mother of human race.' What could I do, -But follow straight, invisibly thus led? -Till I espied thee, fair indeed and tall, -Under a platane; yet methought less fair, -Less winning soft, less amiably mild, -Than that smooth watery image: Back I turned; -Thou following cryedst aloud, 'Return, fair Eve; -'Whom flyest thou? whom thou flyest, of him thou art, -'His flesh, his bone; to give thee being I lent -'Out of my side to thee, nearest my heart, -'Substantial life, to have thee by my side -'Henceforth an individual solace dear; -'Part of my soul I seek thee, and thee claim -'My other half:' With that thy gentle hand -Seised mine: I yielded;and from that time see -How beauty is excelled by manly grace, -And wisdom, which alone is truly fair. -So spake our general mother, and with eyes -Of conjugal attraction unreproved, -And meek surrender, half-embracing leaned -On our first father; half her swelling breast -Naked met his, under the flowing gold -Of her loose tresses hid: he in delight -Both of her beauty, and submissive charms, -Smiled with superiour love, as Jupiter -On Juno smiles, when he impregns the clouds -That shed Mayflowers; and pressed her matron lip -With kisses pure: Aside the Devil turned -For envy; yet with jealous leer malign -Eyed them askance, and to himself thus plained. -Sight hateful, sight tormenting! thus these two, -Imparadised in one another's arms, -The happier Eden, shall enjoy their fill -Of bliss on bliss; while I to Hell am thrust, -Where neither joy nor love, but fierce desire, -Among our other torments not the least, -Still unfulfilled with pain of longing pines. -Yet let me not forget what I have gained -From their own mouths: All is not theirs, it seems; -One fatal tree there stands, of knowledge called, -Forbidden them to taste: Knowledge forbidden -Suspicious, reasonless. Why should their Lord -Envy them that? Can it be sin to know? -Can it be death? And do they only stand -By ignorance? Is that their happy state, -The proof of their obedience and their faith? -O fair foundation laid whereon to build -Their ruin! hence I will excite their minds -With more desire to know, and to reject -Envious commands, invented with design -To keep them low, whom knowledge might exalt -Equal with Gods: aspiring to be such, -They taste and die: What likelier can ensue -But first with narrow search I must walk round -This garden, and no corner leave unspied; -A chance but chance may lead where I may meet -Some wandering Spirit of Heaven by fountain side, -Or in thick shade retired, from him to draw -What further would be learned. Live while ye may, -Yet happy pair; enjoy, till I return, -Short pleasures, for long woes are to succeed! -So saying, his proud step he scornful turned, -But with sly circumspection, and began -Through wood, through waste, o'er hill, o'er dale, his roam -Mean while in utmost longitude, where Heaven -With earth and ocean meets, the setting sun -Slowly descended, and with right aspect -Against the eastern gate of Paradise -Levelled his evening rays: It was a rock -Of alabaster, piled up to the clouds, -Conspicuous far, winding with one ascent -Accessible from earth, one entrance high; -The rest was craggy cliff, that overhung -Still as it rose, impossible to climb. -Betwixt these rocky pillars Gabriel sat, -Chief of the angelick guards, awaiting night; -About him exercised heroick games -The unarmed youth of Heaven, but nigh at hand -Celestial armoury, shields, helms, and spears, -Hung high with diamond flaming, and with gold. -Thither came Uriel, gliding through the even -On a sun-beam, swift as a shooting star -In autumn thwarts the night, when vapours fired -Impress the air, and shows the mariner -From what point of his compass to beware -Impetuous winds: He thus began in haste. -Gabriel, to thee thy course by lot hath given -Charge and strict watch, that to this happy place -No evil thing approach or enter in. -This day at highth of noon came to my sphere -A Spirit, zealous, as he seemed, to know -More of the Almighty's works, and chiefly Man, -God's latest image: I described his way -Bent all on speed, and marked his aery gait; -But in the mount that lies from Eden north, -Where he first lighted, soon discerned his looks -Alien from Heaven, with passions foul obscured: -Mine eye pursued him still, but under shade -Lost sight of him: One of the banished crew, -I fear, hath ventured from the deep, to raise -New troubles; him thy care must be to find. -To whom the winged warriour thus returned. -Uriel, no wonder if thy perfect sight, -Amid the sun's bright circle where thou sitst, -See far and wide: In at this gate none pass -The vigilance here placed, but such as come -Well known from Heaven; and since meridian hour -No creature thence: If Spirit of other sort, -So minded, have o'er-leaped these earthly bounds -On purpose, hard thou knowest it to exclude -Spiritual substance with corporeal bar. -But if within the circuit of these walks, -In whatsoever shape he lurk, of whom -Thou tellest, by morrow dawning I shall know. -So promised he; and Uriel to his charge -Returned on that bright beam, whose point now raised -Bore him slope downward to the sun now fallen -Beneath the Azores; whether the prime orb, -Incredible how swift, had thither rolled -Diurnal, or this less volubil earth, -By shorter flight to the east, had left him there -Arraying with reflected purple and gold -The clouds that on his western throne attend. -Now came still Evening on, and Twilight gray -Had in her sober livery all things clad; -Silence accompanied; for beast and bird, -They to their grassy couch, these to their nests -Were slunk, all but the wakeful nightingale; -She all night long her amorous descant sung; -Silence was pleased: Now glowed the firmament -With living sapphires: Hesperus, that led -The starry host, rode brightest, till the moon, -Rising in clouded majesty, at length -Apparent queen unveiled her peerless light, -And o'er the dark her silver mantle threw. -When Adam thus to Eve. Fair Consort, the hour -Of night, and all things now retired to rest, -Mind us of like repose; since God hath set -Labour and rest, as day and night, to men -Successive; and the timely dew of sleep, -Now falling with soft slumbrous weight, inclines -Our eye-lids: Other creatures all day long -Rove idle, unemployed, and less need rest; -Man hath his daily work of body or mind -Appointed, which declares his dignity, -And the regard of Heaven on all his ways; -While other animals unactive range, -And of their doings God takes no account. -To-morrow, ere fresh morning streak the east -With first approach of light, we must be risen, -And at our pleasant labour, to reform -Yon flowery arbours, yonder alleys green, -Our walk at noon, with branches overgrown, -That mock our scant manuring, and require -More hands than ours to lop their wanton growth: -Those blossoms also, and those dropping gums, -That lie bestrown, unsightly and unsmooth, -Ask riddance, if we mean to tread with ease; -Mean while, as Nature wills, night bids us rest. -To whom thus Eve, with perfect beauty adorned -My Author and Disposer, what thou bidst -Unargued I obey: So God ordains; -God is thy law, thou mine: To know no more -Is woman's happiest knowledge, and her praise. -With thee conversing I forget all time; -All seasons, and their change, all please alike. -Sweet is the breath of Morn, her rising sweet, -With charm of earliest birds: pleasant the sun, -When first on this delightful land he spreads -His orient beams, on herb, tree, fruit, and flower, -Glistering with dew; fragrant the fertile earth -After soft showers; and sweet the coming on -Of grateful Evening mild; then silent Night, -With this her solemn bird, and this fair moon, -And these the gems of Heaven, her starry train: -But neither breath of Morn, when she ascends -With charm of earliest birds; nor rising sun -On this delightful land; nor herb, fruit, flower, -Glistering with dew; nor fragrance after showers; -Nor grateful Evening mild; nor silent Night, -With this her solemn bird, nor walk by moon, -Or glittering star-light, without thee is sweet. -But wherefore all night long shine these? for whom -This glorious sight, when sleep hath shut all eyes? -To whom our general ancestor replied. -Daughter of God and Man, accomplished Eve, -These have their course to finish round the earth, -By morrow evening, and from land to land -In order, though to nations yet unborn, -Ministring light prepared, they set and rise; -Lest total Darkness should by night regain -Her old possession, and extinguish life -In Nature and all things; which these soft fires -Not only enlighten, but with kindly heat -Of various influence foment and warm, -Temper or nourish, or in part shed down -Their stellar virtue on all kinds that grow -On earth, made hereby apter to receive -Perfection from the sun's more potent ray. -These then, though unbeheld in deep of night, -Shine not in vain; nor think, though men were none, -That Heaven would want spectators, God want praise: -Millions of spiritual creatures walk the earth -Unseen, both when we wake, and when we sleep: -All these with ceaseless praise his works behold -Both day and night: How often from the steep -Of echoing hill or thicket have we heard -Celestial voices to the midnight air, -Sole, or responsive each to others note, -Singing their great Creator? oft in bands -While they keep watch, or nightly rounding walk, -With heavenly touch of instrumental sounds -In full harmonick number joined, their songs -Divide the night, and lift our thoughts to Heaven. -Thus talking, hand in hand alone they passed -On to their blissful bower: it was a place -Chosen by the sovran Planter, when he framed -All things to Man's delightful use; the roof -Of thickest covert was inwoven shade -Laurel and myrtle, and what higher grew -Of firm and fragrant leaf; on either side -Acanthus, and each odorous bushy shrub, -Fenced up the verdant wall; each beauteous flower, -Iris all hues, roses, and jessamin, -Reared high their flourished heads between, and wrought -Mosaick; underfoot the violet, -Crocus, and hyacinth, with rich inlay -Broidered the ground, more coloured than with stone -Of costliest emblem: Other creature here, -Bird, beast, insect, or worm, durst enter none, -Such was their awe of Man. In shadier bower -More sacred and sequestered, though but feigned, -Pan or Sylvanus never slept, nor Nymph -Nor Faunus haunted. Here, in close recess, -With flowers, garlands, and sweet-smelling herbs, -Espoused Eve decked first her nuptial bed; -And heavenly quires the hymenaean sung, -What day the genial Angel to our sire -Brought her in naked beauty more adorned, -More lovely, than Pandora, whom the Gods -Endowed with all their gifts, and O! too like -In sad event, when to the unwiser son -Of Japhet brought by Hermes, she ensnared -Mankind with her fair looks, to be avenged -On him who had stole Jove's authentick fire. -Thus, at their shady lodge arrived, both stood, -Both turned, and under open sky adored -The God that made both sky, air, earth, and heaven, -Which they beheld, the moon's resplendent globe, -And starry pole: Thou also madest the night, -Maker Omnipotent, and thou the day, -Which we, in our appointed work employed, -Have finished, happy in our mutual help -And mutual love, the crown of all our bliss -Ordained by thee; and this delicious place -For us too large, where thy abundance wants -Partakers, and uncropt falls to the ground. -But thou hast promised from us two a race -To fill the earth, who shall with us extol -Thy goodness infinite, both when we wake, -And when we seek, as now, thy gift of sleep. -This said unanimous, and other rites -Observing none, but adoration pure -Which God likes best, into their inmost bower -Handed they went; and, eased the putting off -These troublesome disguises which we wear, -Straight side by side were laid; nor turned, I ween, -Adam from his fair spouse, nor Eve the rites -Mysterious of connubial love refused: -Whatever hypocrites austerely talk -Of purity, and place, and innocence, -Defaming as impure what God declares -Pure, and commands to some, leaves free to all. -Our Maker bids encrease; who bids abstain -But our Destroyer, foe to God and Man? -Hail, wedded Love, mysterious law, true source -Of human offspring, sole propriety -In Paradise of all things common else! -By thee adulterous Lust was driven from men -Among the bestial herds to range; by thee -Founded in reason, loyal, just, and pure, -Relations dear, and all the charities -Of father, son, and brother, first were known. -Far be it, that I should write thee sin or blame, -Or think thee unbefitting holiest place, -Perpetual fountain of domestick sweets, -Whose bed is undefiled and chaste pronounced, -Present, or past, as saints and patriarchs used. -Here Love his golden shafts employs, here lights -His constant lamp, and waves his purple wings, -Reigns here and revels; not in the bought smile -Of harlots, loveless, joyless, unendeared, -Casual fruition; nor in court-amours, -Mixed dance, or wanton mask, or midnight ball, -Or serenate, which the starved lover sings -To his proud fair, best quitted with disdain. -These, lulled by nightingales, embracing slept, -And on their naked limbs the flowery roof -Showered roses, which the morn repaired. Sleep on, -Blest pair; and O!yet happiest, if ye seek -No happier state, and know to know no more. -Now had night measured with her shadowy cone -Half way up hill this vast sublunar vault, -And from their ivory port the Cherubim, -Forth issuing at the accustomed hour, stood armed -To their night watches in warlike parade; -When Gabriel to his next in power thus spake. -Uzziel, half these draw off, and coast the south -With strictest watch; these other wheel the north; -Our circuit meets full west. As flame they part, -Half wheeling to the shield, half to the spear. -From these, two strong and subtle Spirits he called -That near him stood, and gave them thus in charge. -Ithuriel and Zephon, with winged speed -Search through this garden, leave unsearched no nook; -But chiefly where those two fair creatures lodge, -Now laid perhaps asleep, secure of harm. -This evening from the sun's decline arrived, -Who tells of some infernal Spirit seen -Hitherward bent (who could have thought?) escaped -The bars of Hell, on errand bad no doubt: -Such, where ye find, seise fast, and hither bring. -So saying, on he led his radiant files, -Dazzling the moon; these to the bower direct -In search of whom they sought: Him there they found -Squat like a toad, close at the ear of Eve, -Assaying by his devilish art to reach -The organs of her fancy, and with them forge -Illusions, as he list, phantasms and dreams; -Or if, inspiring venom, he might taint -The animal spirits, that from pure blood arise -Like gentle breaths from rivers pure, thence raise -At least distempered, discontented thoughts, -Vain hopes, vain aims, inordinate desires, -Blown up with high conceits ingendering pride. -Him thus intent Ithuriel with his spear -Touched lightly; for no falshood can endure -Touch of celestial temper, but returns -Of force to its own likeness: Up he starts -Discovered and surprised. As when a spark -Lights on a heap of nitrous powder, laid -Fit for the tun some magazine to store -Against a rumoured war, the smutty grain, -With sudden blaze diffused, inflames the air; -So started up in his own shape the Fiend. -Back stept those two fair Angels, half amazed -So sudden to behold the grisly king; -Yet thus, unmoved with fear, accost him soon. -Which of those rebel Spirits adjudged to Hell -Comest thou, escaped thy prison? and, transformed, -Why sat'st thou like an enemy in wait, -Here watching at the head of these that sleep? -Know ye not then said Satan, filled with scorn, -Know ye not me? ye knew me once no mate -For you, there sitting where ye durst not soar: -Not to know me argues yourselves unknown, -The lowest of your throng; or, if ye know, -Why ask ye, and superfluous begin -Your message, like to end as much in vain? -To whom thus Zephon, answering scorn with scorn. -Think not, revolted Spirit, thy shape the same, -Or undiminished brightness to be known, -As when thou stoodest in Heaven upright and pure; -That glory then, when thou no more wast good, -Departed from thee; and thou resemblest now -Thy sin and place of doom obscure and foul. -But come, for thou, be sure, shalt give account -To him who sent us, whose charge is to keep -This place inviolable, and these from harm. -So spake the Cherub; and his grave rebuke, -Severe in youthful beauty, added grace -Invincible: Abashed the Devil stood, -And felt how awful goodness is, and saw -Virtue in her shape how lovely; saw, and pined -His loss; but chiefly to find here observed -His lustre visibly impaired; yet seemed -Undaunted. If I must contend, said he, -Best with the best, the sender, not the sent, -Or all at once; more glory will be won, -Or less be lost. Thy fear, said Zephon bold, -Will save us trial what the least can do -Single against thee wicked, and thence weak. -The Fiend replied not, overcome with rage; -But, like a proud steed reined, went haughty on, -Champing his iron curb: To strive or fly -He held it vain; awe from above had quelled -His heart, not else dismayed. Now drew they nigh -The western point, where those half-rounding guards -Just met, and closing stood in squadron joined, -A waiting next command. To whom their Chief, -Gabriel, from the front thus called aloud. -O friends! I hear the tread of nimble feet -Hasting this way, and now by glimpse discern -Ithuriel and Zephon through the shade; -And with them comes a third of regal port, -But faded splendour wan; who by his gait -And fierce demeanour seems the Prince of Hell, -Not likely to part hence without contest; -Stand firm, for in his look defiance lours. -He scarce had ended, when those two approached, -And brief related whom they brought, where found, -How busied, in what form and posture couched. -To whom with stern regard thus Gabriel spake. -Why hast thou, Satan, broke the bounds prescribed -To thy transgressions, and disturbed the charge -Of others, who approve not to transgress -By thy example, but have power and right -To question thy bold entrance on this place; -Employed, it seems, to violate sleep, and those -Whose dwelling God hath planted here in bliss! -To whom thus Satan with contemptuous brow. -Gabriel? thou hadst in Heaven the esteem of wise, -And such I held thee; but this question asked -Puts me in doubt. Lives there who loves his pain! -Who would not, finding way, break loose from Hell, -Though thither doomed! Thou wouldst thyself, no doubt -And boldly venture to whatever place -Farthest from pain, where thou mightst hope to change -Torment with ease, and soonest recompense -Dole with delight, which in this place I sought; -To thee no reason, who knowest only good, -But evil hast not tried: and wilt object -His will who bounds us! Let him surer bar -His iron gates, if he intends our stay -In that dark durance: Thus much what was asked. -The rest is true, they found me where they say; -But that implies not violence or harm. -Thus he in scorn. The warlike Angel moved, -Disdainfully half smiling, thus replied. -O loss of one in Heaven to judge of wise -Since Satan fell, whom folly overthrew, -And now returns him from his prison 'scaped, -Gravely in doubt whether to hold them wise -Or not, who ask what boldness brought him hither -Unlicensed from his bounds in Hell prescribed; -So wise he judges it to fly from pain -However, and to 'scape his punishment! -So judge thou still, presumptuous! till the wrath, -Which thou incurrest by flying, meet thy flight -Sevenfold, and scourge that wisdom back to Hell, -Which taught thee yet no better, that no pain -Can equal anger infinite provoked. -But wherefore thou alone? wherefore with thee -Came not all hell broke loose? or thou than they -Less hardy to endure? Courageous Chief! -The first in flight from pain! hadst thou alleged -To thy deserted host this cause of flight, -Thou surely hadst not come sole fugitive. -To which the Fiend thus answered, frowning stern. -Not that I less endure, or shrink from pain, -Insulting Angel! well thou knowest I stood -Thy fiercest, when in battle to thy aid -The blasting vollied thunder made all speed, -And seconded thy else not dreaded spear. -But still thy words at random, as before, -Argue thy inexperience what behoves -From hard assays and ill successes past -A faithful leader, not to hazard all -Through ways of danger by himself untried: -I, therefore, I alone first undertook -To wing the desolate abyss, and spy -This new created world, whereof in Hell -Fame is not silent, here in hope to find -Better abode, and my afflicted Powers -To settle here on earth, or in mid air; -Though for possession put to try once more -What thou and thy gay legions dare against; -Whose easier business were to serve their Lord -High up in Heaven, with songs to hymn his throne, -And practised distances to cringe, not fight, -To whom the warriour Angel soon replied. -To say and straight unsay, pretending first -Wise to fly pain, professing next the spy, -Argues no leader but a liear traced, -Satan, and couldst thou faithful add? O name, -O sacred name of faithfulness profaned! -Faithful to whom? to thy rebellious crew? -Army of Fiends, fit body to fit head. -Was this your discipline and faith engaged, -Your military obedience, to dissolve -Allegiance to the acknowledged Power supreme? -And thou, sly hypocrite, who now wouldst seem -Patron of liberty, who more than thou -Once fawned, and cringed, and servily adored -Heaven's awful Monarch? wherefore, but in hope -To dispossess him, and thyself to reign? -But mark what I arreed thee now, Avant; -Fly neither whence thou fledst! If from this hour -Within these hallowed limits thou appear, -Back to the infernal pit I drag thee chained, -And seal thee so, as henceforth not to scorn -The facile gates of Hell too slightly barred. -So threatened he; but Satan to no threats -Gave heed, but waxing more in rage replied. -Then when I am thy captive talk of chains, -Proud limitary Cherub! but ere then -Far heavier load thyself expect to feel -From my prevailing arm, though Heaven's King -Ride on thy wings, and thou with thy compeers, -Us'd to the yoke, drawest his triumphant wheels -In progress through the road of Heaven star-paved. -While thus he spake, the angelick squadron bright -Turned fiery red, sharpening in mooned horns -Their phalanx, and began to hem him round -With ported spears, as thick as when a field -Of Ceres ripe for harvest waving bends -Her bearded grove of ears, which way the wind -Sways them; the careful plowman doubting stands, -Left on the threshing floor his hopeless sheaves -Prove chaff. On the other side, Satan, alarmed, -Collecting all his might, dilated stood, -Like Teneriff or Atlas, unremoved: -His stature reached the sky, and on his crest -Sat Horrour plumed; nor wanted in his grasp -What seemed both spear and shield: Now dreadful deeds -Might have ensued, nor only Paradise -In this commotion, but the starry cope -Of Heaven perhaps, or all the elements -At least had gone to wrack, disturbed and torn -With violence of this conflict, had not soon -The Eternal, to prevent such horrid fray, -Hung forth in Heaven his golden scales, yet seen -Betwixt Astrea and the Scorpion sign, -Wherein all things created first he weighed, -The pendulous round earth with balanced air -In counterpoise, now ponders all events, -Battles and realms: In these he put two weights, -The sequel each of parting and of fight: -The latter quick up flew, and kicked the beam, -Which Gabriel spying, thus bespake the Fiend. -Satan, I know thy strength, and thou knowest mine; -Neither our own, but given: What folly then -To boast what arms can do? since thine no more -Than Heaven permits, nor mine, though doubled now -To trample thee as mire: For proof look up, -And read thy lot in yon celestial sign; -Where thou art weighed, and shown how light, how weak, -If thou resist. The Fiend looked up, and knew -His mounted scale aloft: Nor more;but fled -Murmuring, and with him fled the shades of night. - - - -Book V - - -Now Morn, her rosy steps in the eastern clime -Advancing, sowed the earth with orient pearl, -When Adam waked, so customed; for his sleep -Was aery-light, from pure digestion bred, -And temperate vapours bland, which the only sound -Of leaves and fuming rills, Aurora's fan, -Lightly dispersed, and the shrill matin song -Of birds on every bough; so much the more -His wonder was to find unwakened Eve -With tresses discomposed, and glowing cheek, -As through unquiet rest: He, on his side -Leaning half raised, with looks of cordial love -Hung over her enamoured, and beheld -Beauty, which, whether waking or asleep, -Shot forth peculiar graces; then with voice -Mild, as when Zephyrus on Flora breathes, -Her hand soft touching, whispered thus. Awake, -My fairest, my espoused, my latest found, -Heaven's last best gift, my ever new delight! -Awake: The morning shines, and the fresh field -Calls us; we lose the prime, to mark how spring -Our tender plants, how blows the citron grove, -What drops the myrrh, and what the balmy reed, -How nature paints her colours, how the bee -Sits on the bloom extracting liquid sweet. -Such whispering waked her, but with startled eye -On Adam, whom embracing, thus she spake. -O sole in whom my thoughts find all repose, -My glory, my perfection! glad I see -Thy face, and morn returned; for I this night -(Such night till this I never passed) have dreamed, -If dreamed, not, as I oft am wont, of thee, -Works of day past, or morrow's next design, -But of offence and trouble, which my mind -Knew never till this irksome night: Methought, -Close at mine ear one called me forth to walk -With gentle voice; I thought it thine: It said, -'Why sleepest thou, Eve? now is the pleasant time, -'The cool, the silent, save where silence yields -'To the night-warbling bird, that now awake -'Tunes sweetest his love-laboured song; now reigns -'Full-orbed the moon, and with more pleasing light -'Shadowy sets off the face of things; in vain, -'If none regard; Heaven wakes with all his eyes, -'Whom to behold but thee, Nature's desire? -'In whose sight all things joy, with ravishment -'Attracted by thy beauty still to gaze.' -I rose as at thy call, but found thee not; -To find thee I directed then my walk; -And on, methought, alone I passed through ways -That brought me on a sudden to the tree -Of interdicted knowledge: fair it seemed, -Much fairer to my fancy than by day: -And, as I wondering looked, beside it stood -One shaped and winged like one of those from Heaven -By us oft seen; his dewy locks distilled -Ambrosia; on that tree he also gazed; -And 'O fair plant,' said he, 'with fruit surcharged, -'Deigns none to ease thy load, and taste thy sweet, -'Nor God, nor Man? Is knowledge so despised? -'Or envy, or what reserve forbids to taste? -'Forbid who will, none shall from me withhold -'Longer thy offered good; why else set here? -This said, he paused not, but with venturous arm -He plucked, he tasted; me damp horrour chilled -At such bold words vouched with a deed so bold: -But he thus, overjoyed; 'O fruit divine, -'Sweet of thyself, but much more sweet thus cropt, -'Forbidden here, it seems, as only fit -'For Gods, yet able to make Gods of Men: -'And why not Gods of Men; since good, the more -'Communicated, more abundant grows, -'The author not impaired, but honoured more? -'Here, happy creature, fair angelick Eve! -'Partake thou also; happy though thou art, -'Happier thou mayest be, worthier canst not be: -'Taste this, and be henceforth among the Gods -'Thyself a Goddess, not to earth confined, -'But sometimes in the air, as we, sometimes -'Ascend to Heaven, by merit thine, and see -'What life the Gods live there, and such live thou!' -So saying, he drew nigh, and to me held, -Even to my mouth of that same fruit held part -Which he had plucked; the pleasant savoury smell -So quickened appetite, that I, methought, -Could not but taste. Forthwith up to the clouds -With him I flew, and underneath beheld -The earth outstretched immense, a prospect wide -And various: Wondering at my flight and change -To this high exaltation; suddenly -My guide was gone, and I, methought, sunk down, -And fell asleep; but O, how glad I waked -To find this but a dream! Thus Eve her night -Related, and thus Adam answered sad. -Best image of myself, and dearer half, -The trouble of thy thoughts this night in sleep -Affects me equally; nor can I like -This uncouth dream, of evil sprung, I fear; -Yet evil whence? in thee can harbour none, -Created pure. But know that in the soul -Are many lesser faculties, that serve -Reason as chief; among these Fancy next -Her office holds; of all external things -Which the five watchful senses represent, -She forms imaginations, aery shapes, -Which Reason, joining or disjoining, frames -All what we affirm or what deny, and call -Our knowledge or opinion; then retires -Into her private cell, when nature rests. -Oft in her absence mimick Fancy wakes -To imitate her; but, misjoining shapes, -Wild work produces oft, and most in dreams; -Ill matching words and deeds long past or late. -Some such resemblances, methinks, I find -Of our last evening's talk, in this thy dream, -But with addition strange; yet be not sad. -Evil into the mind of God or Man -May come and go, so unreproved, and leave -No spot or blame behind: Which gives me hope -That what in sleep thou didst abhor to dream, -Waking thou never will consent to do. -Be not disheartened then, nor cloud those looks, -That wont to be more cheerful and serene, -Than when fair morning first smiles on the world; -And let us to our fresh employments rise -Among the groves, the fountains, and the flowers -That open now their choisest bosomed smells, -Reserved from night, and kept for thee in store. -So cheered he his fair spouse, and she was cheered; -But silently a gentle tear let fall -From either eye, and wiped them with her hair; -Two other precious drops that ready stood, -Each in their crystal sluice, he ere they fell -Kissed, as the gracious signs of sweet remorse -And pious awe, that feared to have offended. -So all was cleared, and to the field they haste. -But first, from under shady arborous roof -Soon as they forth were come to open sight -Of day-spring, and the sun, who, scarce up-risen, -With wheels yet hovering o'er the ocean-brim, -Shot parallel to the earth his dewy ray, -Discovering in wide landskip all the east -Of Paradise and Eden's happy plains, -Lowly they bowed adoring, and began -Their orisons, each morning duly paid -In various style; for neither various style -Nor holy rapture wanted they to praise -Their Maker, in fit strains pronounced, or sung -Unmeditated; such prompt eloquence -Flowed from their lips, in prose or numerous verse, -More tuneable than needed lute or harp -To add more sweetness; and they thus began. -These are thy glorious works, Parent of good, -Almighty! Thine this universal frame, -Thus wonderous fair; Thyself how wonderous then! -Unspeakable, who sitst above these heavens -To us invisible, or dimly seen -In these thy lowest works; yet these declare -Thy goodness beyond thought, and power divine. -Speak, ye who best can tell, ye sons of light, -Angels; for ye behold him, and with songs -And choral symphonies, day without night, -Circle his throne rejoicing; ye in Heaven -On Earth join all ye Creatures to extol -Him first, him last, him midst, and without end. -Fairest of stars, last in the train of night, -If better thou belong not to the dawn, -Sure pledge of day, that crownest the smiling morn -With thy bright circlet, praise him in thy sphere, -While day arises, that sweet hour of prime. -Thou Sun, of this great world both eye and soul, -Acknowledge him thy greater; sound his praise -In thy eternal course, both when thou climbest, -And when high noon hast gained, and when thou fallest. -Moon, that now meetest the orient sun, now flyest, -With the fixed Stars, fixed in their orb that flies; -And ye five other wandering Fires, that move -In mystick dance not without song, resound -His praise, who out of darkness called up light. -Air, and ye Elements, the eldest birth -Of Nature's womb, that in quaternion run -Perpetual circle, multiform; and mix -And nourish all things; let your ceaseless change -Vary to our great Maker still new praise. -Ye Mists and Exhalations, that now rise -From hill or steaming lake, dusky or gray, -Till the sun paint your fleecy skirts with gold, -In honour to the world's great Author rise; -Whether to deck with clouds the uncoloured sky, -Or wet the thirsty earth with falling showers, -Rising or falling still advance his praise. -His praise, ye Winds, that from four quarters blow, -Breathe soft or loud; and, wave your tops, ye Pines, -With every plant, in sign of worship wave. -Fountains, and ye that warble, as ye flow, -Melodious murmurs, warbling tune his praise. -Join voices, all ye living Souls: Ye Birds, -That singing up to Heaven-gate ascend, -Bear on your wings and in your notes his praise. -Ye that in waters glide, and ye that walk -The earth, and stately tread, or lowly creep; -Witness if I be silent, morn or even, -To hill, or valley, fountain, or fresh shade, -Made vocal by my song, and taught his praise. -Hail, universal Lord, be bounteous still -To give us only good; and if the night -Have gathered aught of evil, or concealed, -Disperse it, as now light dispels the dark! -So prayed they innocent, and to their thoughts -Firm peace recovered soon, and wonted calm. -On to their morning's rural work they haste, -Among sweet dews and flowers; where any row -Of fruit-trees over-woody reached too far -Their pampered boughs, and needed hands to check -Fruitless embraces: or they led the vine -To wed her elm; she, spoused, about him twines -Her marriageable arms, and with him brings -Her dower, the adopted clusters, to adorn -His barren leaves. Them thus employed beheld -With pity Heaven's high King, and to him called -Raphael, the sociable Spirit, that deigned -To travel with Tobias, and secured -His marriage with the seventimes-wedded maid. -Raphael, said he, thou hearest what stir on Earth -Satan, from Hell 'scaped through the darksome gulf, -Hath raised in Paradise; and how disturbed -This night the human pair; how he designs -In them at once to ruin all mankind. -Go therefore, half this day as friend with friend -Converse with Adam, in what bower or shade -Thou findest him from the heat of noon retired, -To respite his day-labour with repast, -Or with repose; and such discourse bring on, -As may advise him of his happy state, -Happiness in his power left free to will, -Left to his own free will, his will though free, -Yet mutable; whence warn him to beware -He swerve not, too secure: Tell him withal -His danger, and from whom; what enemy, -Late fallen himself from Heaven, is plotting now -The fall of others from like state of bliss; -By violence? no, for that shall be withstood; -But by deceit and lies: This let him know, -Lest, wilfully transgressing, he pretend -Surprisal, unadmonished, unforewarned. -So spake the Eternal Father, and fulfilled -All justice: Nor delayed the winged Saint -After his charge received; but from among -Thousand celestial Ardours, where he stood -Veiled with his gorgeous wings, up springing light, -Flew through the midst of Heaven; the angelick quires, -On each hand parting, to his speed gave way -Through all the empyreal road; till, at the gate -Of Heaven arrived, the gate self-opened wide -On golden hinges turning, as by work -Divine the sovran Architect had framed. -From hence no cloud, or, to obstruct his sight, -Star interposed, however small he sees, -Not unconformed to other shining globes, -Earth, and the garden of God, with cedars crowned -Above all hills. As when by night the glass -Of Galileo, less assured, observes -Imagined lands and regions in the moon: -Or pilot, from amidst the Cyclades -Delos or Samos first appearing, kens -A cloudy spot. Down thither prone in flight -He speeds, and through the vast ethereal sky -Sails between worlds and worlds, with steady wing -Now on the polar winds, then with quick fan -Winnows the buxom air; till, within soar -Of towering eagles, to all the fowls he seems -A phoenix, gazed by all as that sole bird, -When, to enshrine his reliques in the Sun's -Bright temple, to Egyptian Thebes he flies. -At once on the eastern cliff of Paradise -He lights, and to his proper shape returns -A Seraph winged: Six wings he wore, to shade -His lineaments divine; the pair that clad -Each shoulder broad, came mantling o'er his breast -With regal ornament; the middle pair -Girt like a starry zone his waist, and round -Skirted his loins and thighs with downy gold -And colours dipt in Heaven; the third his feet -Shadowed from either heel with feathered mail, -Sky-tinctured grain. Like Maia's son he stood, -And shook his plumes, that heavenly fragrance filled -The circuit wide. Straight knew him all the bands -Of Angels under watch; and to his state, -And to his message high, in honour rise; -For on some message high they guessed him bound. -Their glittering tents he passed, and now is come -Into the blissful field, through groves of myrrh, -And flowering odours, cassia, nard, and balm; -A wilderness of sweets; for Nature here -Wantoned as in her prime, and played at will -Her virgin fancies pouring forth more sweet, -Wild above rule or art, enormous bliss. -Him through the spicy forest onward come -Adam discerned, as in the door he sat -Of his cool bower, while now the mounted sun -Shot down direct his fervid rays to warm -Earth's inmost womb, more warmth than Adam needs: -And Eve within, due at her hour prepared -For dinner savoury fruits, of taste to please -True appetite, and not disrelish thirst -Of nectarous draughts between, from milky stream, -Berry or grape: To whom thus Adam called. -Haste hither, Eve, and worth thy sight behold -Eastward among those trees, what glorious shape -Comes this way moving; seems another morn -Risen on mid-noon; some great behest from Heaven -To us perhaps he brings, and will vouchsafe -This day to be our guest. But go with speed, -And, what thy stores contain, bring forth, and pour -Abundance, fit to honour and receive -Our heavenly stranger: Well we may afford -Our givers their own gifts, and large bestow -From large bestowed, where Nature multiplies -Her fertile growth, and by disburthening grows -More fruitful, which instructs us not to spare. -To whom thus Eve. Adam, earth's hallowed mould, -Of God inspired! small store will serve, where store, -All seasons, ripe for use hangs on the stalk; -Save what by frugal storing firmness gains -To nourish, and superfluous moist consumes: -But I will haste, and from each bough and brake, -Each plant and juciest gourd, will pluck such choice -To entertain our Angel-guest, as he -Beholding shall confess, that here on Earth -God hath dispensed his bounties as in Heaven. -So saying, with dispatchful looks in haste -She turns, on hospitable thoughts intent -What choice to choose for delicacy best, -What order, so contrived as not to mix -Tastes, not well joined, inelegant, but bring -Taste after taste upheld with kindliest change; -Bestirs her then, and from each tender stalk -Whatever Earth, all-bearing mother, yields -In India East or West, or middle shore -In Pontus or the Punick coast, or where -Alcinous reigned, fruit of all kinds, in coat -Rough, or smooth rind, or bearded husk, or shell, -She gathers, tribute large, and on the board -Heaps with unsparing hand; for drink the grape -She crushes, inoffensive must, and meaths -From many a berry, and from sweet kernels pressed -She tempers dulcet creams; nor these to hold -Wants her fit vessels pure; then strows the ground -With rose and odours from the shrub unfumed. -Mean while our primitive great sire, to meet -His God-like guest, walks forth, without more train -Accompanied than with his own complete -Perfections; in himself was all his state, -More solemn than the tedious pomp that waits -On princes, when their rich retinue long -Of horses led, and grooms besmeared with gold, -Dazzles the croud, and sets them all agape. -Nearer his presence Adam, though not awed, -Yet with submiss approach and reverence meek, -As to a superiour nature bowing low, -Thus said. Native of Heaven, for other place -None can than Heaven such glorious shape contain; -Since, by descending from the thrones above, -Those happy places thou hast deigned a while -To want, and honour these, vouchsafe with us -Two only, who yet by sovran gift possess -This spacious ground, in yonder shady bower -To rest; and what the garden choicest bears -To sit and taste, till this meridian heat -Be over, and the sun more cool decline. -Whom thus the angelick Virtue answered mild. -Adam, I therefore came; nor art thou such -Created, or such place hast here to dwell, -As may not oft invite, though Spirits of Heaven, -To visit thee; lead on then where thy bower -O'ershades; for these mid-hours, till evening rise, -I have at will. So to the sylvan lodge -They came, that like Pomona's arbour smiled, -With flowerets decked, and fragrant smells; but Eve, -Undecked save with herself, more lovely fair -Than Wood-Nymph, or the fairest Goddess feigned -Of three that in mount Ida naked strove, -Stood to entertain her guest from Heaven; no veil -She needed, virtue-proof; no thought infirm -Altered her cheek. On whom the Angel Hail -Bestowed, the holy salutation used -Long after to blest Mary, second Eve. -Hail, Mother of Mankind, whose fruitful womb -Shall fill the world more numerous with thy sons, -Than with these various fruits the trees of God -Have heaped this table!--Raised of grassy turf -Their table was, and mossy seats had round, -And on her ample square from side to side -All autumn piled, though spring and autumn here -Danced hand in hand. A while discourse they hold; -No fear lest dinner cool; when thus began -Our author. Heavenly stranger, please to taste -These bounties, which our Nourisher, from whom -All perfect good, unmeasured out, descends, -To us for food and for delight hath caused -The earth to yield; unsavoury food perhaps -To spiritual natures; only this I know, -That one celestial Father gives to all. -To whom the Angel. Therefore what he gives -(Whose praise be ever sung) to Man in part -Spiritual, may of purest Spirits be found -No ingrateful food: And food alike those pure -Intelligential substances require, -As doth your rational; and both contain -Within them every lower faculty -Of sense, whereby they hear, see, smell, touch, taste, -Tasting concoct, digest, assimilate, -And corporeal to incorporeal turn. -For know, whatever was created, needs -To be sustained and fed: Of elements -The grosser feeds the purer, earth the sea, -Earth and the sea feed air, the air those fires -Ethereal, and as lowest first the moon; -Whence in her visage round those spots, unpurged -Vapours not yet into her substance turned. -Nor doth the moon no nourishment exhale -From her moist continent to higher orbs. -The sun that light imparts to all, receives -From all his alimental recompence -In humid exhalations, and at even -Sups with the ocean. Though in Heaven the trees -Of life ambrosial fruitage bear, and vines -Yield nectar; though from off the boughs each morn -We brush mellifluous dews, and find the ground -Covered with pearly grain: Yet God hath here -Varied his bounty so with new delights, -As may compare with Heaven; and to taste -Think not I shall be nice. So down they sat, -And to their viands fell; nor seemingly -The Angel, nor in mist, the common gloss -Of Theologians; but with keen dispatch -Of real hunger, and concoctive heat -To transubstantiate: What redounds, transpires -Through Spirits with ease; nor wonder;if by fire -Of sooty coal the empirick alchemist -Can turn, or holds it possible to turn, -Metals of drossiest ore to perfect gold, -As from the mine. Mean while at table Eve -Ministered naked, and their flowing cups -With pleasant liquours crowned: O innocence -Deserving Paradise! if ever, then, -Then had the sons of God excuse to have been -Enamoured at that sight; but in those hearts -Love unlibidinous reigned, nor jealousy -Was understood, the injured lover's hell. -Thus when with meats and drinks they had sufficed, -Not burdened nature, sudden mind arose -In Adam, not to let the occasion pass -Given him by this great conference to know -Of things above his world, and of their being -Who dwell in Heaven, whose excellence he saw -Transcend his own so far; whose radiant forms, -Divine effulgence, whose high power, so far -Exceeded human; and his wary speech -Thus to the empyreal minister he framed. -Inhabitant with God, now know I well -Thy favour, in this honour done to Man; -Under whose lowly roof thou hast vouchsafed -To enter, and these earthly fruits to taste, -Food not of Angels, yet accepted so, -As that more willingly thou couldst not seem -At Heaven's high feasts to have fed: yet what compare -To whom the winged Hierarch replied. -O Adam, One Almighty is, from whom -All things proceed, and up to him return, -If not depraved from good, created all -Such to perfection, one first matter all, -Endued with various forms, various degrees -Of substance, and, in things that live, of life; -But more refined, more spiritous, and pure, -As nearer to him placed, or nearer tending -Each in their several active spheres assigned, -Till body up to spirit work, in bounds -Proportioned to each kind. So from the root -Springs lighter the green stalk, from thence the leaves -More aery, last the bright consummate flower -Spirits odorous breathes: flowers and their fruit, -Man's nourishment, by gradual scale sublimed, -To vital spirits aspire, to animal, -To intellectual; give both life and sense, -Fancy and understanding; whence the soul -Reason receives, and reason is her being, -Discursive, or intuitive; discourse -Is oftest yours, the latter most is ours, -Differing but in degree, of kind the same. -Wonder not then, what God for you saw good -If I refuse not, but convert, as you -To proper substance. Time may come, when Men -With Angels may participate, and find -No inconvenient diet, nor too light fare; -And from these corporal nutriments perhaps -Your bodies may at last turn all to spirit, -Improved by tract of time, and, winged, ascend -Ethereal, as we; or may, at choice, -Here or in heavenly Paradises dwell; -If ye be found obedient, and retain -Unalterably firm his love entire, -Whose progeny you are. Mean while enjoy -Your fill what happiness this happy state -Can comprehend, incapable of more. -To whom the patriarch of mankind replied. -O favourable Spirit, propitious guest, -Well hast thou taught the way that might direct -Our knowledge, and the scale of nature set -From center to circumference; whereon, -In contemplation of created things, -By steps we may ascend to God. But say, -What meant that caution joined, If ye be found -Obedient? Can we want obedience then -To him, or possibly his love desert, -Who formed us from the dust and placed us here -Full to the utmost measure of what bliss -Human desires can seek or apprehend? -To whom the Angel. Son of Heaven and Earth, -Attend! That thou art happy, owe to God; -That thou continuest such, owe to thyself, -That is, to thy obedience; therein stand. -This was that caution given thee; be advised. -God made thee perfect, not immutable; -And good he made thee, but to persevere -He left it in thy power; ordained thy will -By nature free, not over-ruled by fate -Inextricable, or strict necessity: -Our voluntary service he requires, -Not our necessitated; such with him -Finds no acceptance, nor can find; for how -Can hearts, not free, be tried whether they serve -Willing or no, who will but what they must -By destiny, and can no other choose? -Myself, and all the angelick host, that stand -In sight of God, enthroned, our happy state -Hold, as you yours, while our obedience holds; -On other surety none: Freely we serve, -Because we freely love, as in our will -To love or not; in this we stand or fall: -And some are fallen, to disobedience fallen, -And so from Heaven to deepest Hell; O fall -From what high state of bliss, into what woe! -To whom our great progenitor. Thy words -Attentive, and with more delighted ear, -Divine instructer, I have heard, than when -Cherubick songs by night from neighbouring hills -Aereal musick send: Nor knew I not -To be both will and deed created free; -Yet that we never shall forget to love -Our Maker, and obey him whose command -Single is yet so just, my constant thoughts -Assured me, and still assure: Though what thou tellest -Hath passed in Heaven, some doubt within me move, -But more desire to hear, if thou consent, -The full relation, which must needs be strange, -Worthy of sacred silence to be heard; -And we have yet large day, for scarce the sun -Hath finished half his journey, and scarce begins -His other half in the great zone of Heaven. -Thus Adam made request; and Raphael, -After short pause assenting, thus began. -High matter thou enjoinest me, O prime of men, -Sad task and hard: For how shall I relate -To human sense the invisible exploits -Of warring Spirits? how, without remorse, -The ruin of so many glorious once -And perfect while they stood? how last unfold -The secrets of another world, perhaps -Not lawful to reveal? yet for thy good -This is dispensed; and what surmounts the reach -Of human sense, I shall delineate so, -By likening spiritual to corporal forms, -As may express them best; though what if Earth -Be but a shadow of Heaven, and things therein -Each to other like, more than on earth is thought? -As yet this world was not, and Chaos wild -Reigned where these Heavens now roll, where Earth now rests -Upon her center poised; when on a day -(For time, though in eternity, applied -To motion, measures all things durable -By present, past, and future,) on such day -As Heaven's great year brings forth, the empyreal host -Of Angels by imperial summons called, -Innumerable before the Almighty's throne -Forthwith, from all the ends of Heaven, appeared -Under their Hierarchs in orders bright: -Ten thousand thousand ensigns high advanced, -Standards and gonfalons 'twixt van and rear -Stream in the air, and for distinction serve -Of hierarchies, of orders, and degrees; -Or in their glittering tissues bear imblazed -Holy memorials, acts of zeal and love -Recorded eminent. Thus when in orbs -Of circuit inexpressible they stood, -Orb within orb, the Father Infinite, -By whom in bliss imbosomed sat the Son, -Amidst as from a flaming mount, whose top -Brightness had made invisible, thus spake. -Hear, all ye Angels, progeny of light, -Thrones, Dominations, Princedoms, Virtues, Powers; -Hear my decree, which unrevoked shall stand. -This day I have begot whom I declare -My only Son, and on this holy hill -Him have anointed, whom ye now behold -At my right hand; your head I him appoint; -And by myself have sworn, to him shall bow -All knees in Heaven, and shall confess him Lord: -Under his great vice-gerent reign abide -United, as one individual soul, -For ever happy: Him who disobeys, -Me disobeys, breaks union, and that day, -Cast out from God and blessed vision, falls -Into utter darkness, deep ingulfed, his place -Ordained without redemption, without end. -So spake the Omnipotent, and with his words -All seemed well pleased; all seemed, but were not all. -That day, as other solemn days, they spent -In song and dance about the sacred hill; -Mystical dance, which yonder starry sphere -Of planets, and of fixed, in all her wheels -Resembles nearest, mazes intricate, -Eccentrick, intervolved, yet regular -Then most, when most irregular they seem; -And in their motions harmony divine -So smooths her charming tones, that God's own ear -Listens delighted. Evening now approached, -(For we have also our evening and our morn, -We ours for change delectable, not need;) -Forthwith from dance to sweet repast they turn -Desirous; all in circles as they stood, -Tables are set, and on a sudden piled -With Angels food, and rubied nectar flows -In pearl, in diamond, and massy gold, -Fruit of delicious vines, the growth of Heaven. -On flowers reposed, and with fresh flowerets crowned, -They eat, they drink, and in communion sweet -Quaff immortality and joy, secure -Of surfeit, where full measure only bounds -Excess, before the all-bounteous King, who showered -With copious hand, rejoicing in their joy. -Now when ambrosial night with clouds exhaled -From that high mount of God, whence light and shade -Spring both, the face of brightest Heaven had changed -To grateful twilight, (for night comes not there -In darker veil,) and roseat dews disposed -All but the unsleeping eyes of God to rest; -Wide over all the plain, and wider far -Than all this globous earth in plain outspread, -(Such are the courts of God) the angelick throng, -Dispersed in bands and files, their camp extend -By living streams among the trees of life, -Pavilions numberless, and sudden reared, -Celestial tabernacles, where they slept -Fanned with cool winds; save those, who, in their course, -Melodious hymns about the sovran throne -Alternate all night long: but not so waked -Satan; so call him now, his former name -Is heard no more in Heaven; he of the first, -If not the first Arch-Angel, great in power, -In favour and pre-eminence, yet fraught -With envy against the Son of God, that day -Honoured by his great Father, and proclaimed -Messiah King anointed, could not bear -Through pride that sight, and thought himself impaired. -Deep malice thence conceiving and disdain, -Soon as midnight brought on the dusky hour -Friendliest to sleep and silence, he resolved -With all his legions to dislodge, and leave -Unworshipt, unobeyed, the throne supreme, -Contemptuous; and his next subordinate -Awakening, thus to him in secret spake. -Sleepest thou, Companion dear? What sleep can close -Thy eye-lids? and rememberest what decree -Of yesterday, so late hath passed the lips -Of Heaven's Almighty. Thou to me thy thoughts -Wast wont, I mine to thee was wont to impart; -Both waking we were one; how then can now -Thy sleep dissent? New laws thou seest imposed; -New laws from him who reigns, new minds may raise -In us who serve, new counsels to debate -What doubtful may ensue: More in this place -To utter is not safe. Assemble thou -Of all those myriads which we lead the chief; -Tell them, that by command, ere yet dim night -Her shadowy cloud withdraws, I am to haste, -And all who under me their banners wave, -Homeward, with flying march, where we possess -The quarters of the north; there to prepare -Fit entertainment to receive our King, -The great Messiah, and his new commands, -Who speedily through all the hierarchies -Intends to pass triumphant, and give laws. -So spake the false Arch-Angel, and infused -Bad influence into the unwary breast -Of his associate: He together calls, -Or several one by one, the regent Powers, -Under him Regent; tells, as he was taught, -That the Most High commanding, now ere night, -Now ere dim night had disincumbered Heaven, -The great hierarchal standard was to move; -Tells the suggested cause, and casts between -Ambiguous words and jealousies, to sound -Or taint integrity: But all obeyed -The wonted signal, and superiour voice -Of their great Potentate; for great indeed -His name, and high was his degree in Heaven; -His countenance, as the morning-star that guides -The starry flock, allured them, and with lies -Drew after him the third part of Heaven's host. -Mean while the Eternal eye, whose sight discerns -Abstrusest thoughts, from forth his holy mount, -And from within the golden lamps that burn -Nightly before him, saw without their light -Rebellion rising; saw in whom, how spread -Among the sons of morn, what multitudes -Were banded to oppose his high decree; -And, smiling, to his only Son thus said. -Son, thou in whom my glory I behold -In full resplendence, Heir of all my might, -Nearly it now concerns us to be sure -Of our Omnipotence, and with what arms -We mean to hold what anciently we claim -Of deity or empire: Such a foe -Is rising, who intends to erect his throne -Equal to ours, throughout the spacious north; -Nor so content, hath in his thought to try -In battle, what our power is, or our right. -Let us advise, and to this hazard draw -With speed what force is left, and all employ -In our defence; lest unawares we lose -This our high place, our sanctuary, our hill. -To whom the Son with calm aspect and clear, -Lightning divine, ineffable, serene, -Made answer. Mighty Father, thou thy foes -Justly hast in derision, and, secure, -Laughest at their vain designs and tumults vain, -Matter to me of glory, whom their hate -Illustrates, when they see all regal power -Given me to quell their pride, and in event -Know whether I be dextrous to subdue -Thy rebels, or be found the worst in Heaven. -So spake the Son; but Satan, with his Powers, -Far was advanced on winged speed; an host -Innumerable as the stars of night, -Or stars of morning, dew-drops, which the sun -Impearls on every leaf and every flower. -Regions they passed, the mighty regencies -Of Seraphim, and Potentates, and Thrones, -In their triple degrees; regions to which -All thy dominion, Adam, is no more -Than what this garden is to all the earth, -And all the sea, from one entire globose -Stretched into longitude; which having passed, -At length into the limits of the north -They came; and Satan to his royal seat -High on a hill, far blazing, as a mount -Raised on a mount, with pyramids and towers -From diamond quarries hewn, and rocks of gold; -The palace of great Lucifer, (so call -That structure in the dialect of men -Interpreted,) which not long after, he -Affecting all equality with God, -In imitation of that mount whereon -Messiah was declared in sight of Heaven, -The Mountain of the Congregation called; -For thither he assembled all his train, -Pretending so commanded to consult -About the great reception of their King, -Thither to come, and with calumnious art -Of counterfeited truth thus held their ears. -Thrones, Dominations, Princedoms, Virtues, Powers; -If these magnifick titles yet remain -Not merely titular, since by decree -Another now hath to himself engrossed -All power, and us eclipsed under the name -Of King anointed, for whom all this haste -Of midnight-march, and hurried meeting here, -This only to consult how we may best, -With what may be devised of honours new, -Receive him coming to receive from us -Knee-tribute yet unpaid, prostration vile! -Too much to one! but double how endured, -To one, and to his image now proclaimed? -But what if better counsels might erect -Our minds, and teach us to cast off this yoke? -Will ye submit your necks, and choose to bend -The supple knee? Ye will not, if I trust -To know ye right, or if ye know yourselves -Natives and sons of Heaven possessed before -By none; and if not equal all, yet free, -Equally free; for orders and degrees -Jar not with liberty, but well consist. -Who can in reason then, or right, assume -Monarchy over such as live by right -His equals, if in power and splendour less, -In freedom equal? or can introduce -Law and edict on us, who without law -Err not? much less for this to be our Lord, -And look for adoration, to the abuse -Of those imperial titles, which assert -Our being ordained to govern, not to serve. -Thus far his bold discourse without controul -Had audience; when among the Seraphim -Abdiel, than whom none with more zeal adored -The Deity, and divine commands obeyed, -Stood up, and in a flame of zeal severe -The current of his fury thus opposed. -O argument blasphemous, false, and proud! -Words which no ear ever to hear in Heaven -Expected, least of all from thee, Ingrate, -In place thyself so high above thy peers. -Canst thou with impious obloquy condemn -The just decree of God, pronounced and sworn, -That to his only Son, by right endued -With regal scepter, every soul in Heaven -Shall bend the knee, and in that honour due -Confess him rightful King? unjust, thou sayest, -Flatly unjust, to bind with laws the free, -And equal over equals to let reign, -One over all with unsucceeded power. -Shalt thou give law to God? shalt thou dispute -With him the points of liberty, who made -Thee what thou art, and formed the Powers of Heaven -Such as he pleased, and circumscribed their being? -Yet, by experience taught, we know how good, -And of our good and of our dignity -How provident he is; how far from thought -To make us less, bent rather to exalt -Our happy state, under one head more near -United. But to grant it thee unjust, -That equal over equals monarch reign: -Thyself, though great and glorious, dost thou count, -Or all angelick nature joined in one, -Equal to him begotten Son? by whom, -As by his Word, the Mighty Father made -All things, even thee; and all the Spirits of Heaven -By him created in their bright degrees, -Crowned them with glory, and to their glory named -Thrones, Dominations, Princedoms, Virtues, Powers, -Essential Powers; nor by his reign obscured, -But more illustrious made; since he the head -One of our number thus reduced becomes; -His laws our laws; all honour to him done -Returns our own. Cease then this impious rage, -And tempt not these; but hasten to appease -The incensed Father, and the incensed Son, -While pardon may be found in time besought. -So spake the fervent Angel; but his zeal -None seconded, as out of season judged, -Or singular and rash: Whereat rejoiced -The Apostate, and, more haughty, thus replied. -That we were formed then sayest thou? and the work -Of secondary hands, by task transferred -From Father to his Son? strange point and new! -Doctrine which we would know whence learned: who saw -When this creation was? rememberest thou -Thy making, while the Maker gave thee being? -We know no time when we were not as now; -Know none before us, self-begot, self-raised -By our own quickening power, when fatal course -Had circled his full orb, the birth mature -Of this our native Heaven, ethereal sons. -Our puissance is our own; our own right hand -Shall teach us highest deeds, by proof to try -Who is our equal: Then thou shalt behold -Whether by supplication we intend -Address, and to begirt the almighty throne -Beseeching or besieging. This report, -These tidings carry to the anointed King; -And fly, ere evil intercept thy flight. -He said; and, as the sound of waters deep, -Hoarse murmur echoed to his words applause -Through the infinite host; nor less for that -The flaming Seraph fearless, though alone -Encompassed round with foes, thus answered bold. -O alienate from God, O Spirit accursed, -Forsaken of all good! I see thy fall -Determined, and thy hapless crew involved -In this perfidious fraud, contagion spread -Both of thy crime and punishment: Henceforth -No more be troubled how to quit the yoke -Of God's Messiah; those indulgent laws -Will not be now vouchsafed; other decrees -Against thee are gone forth without recall; -That golden scepter, which thou didst reject, -Is now an iron rod to bruise and break -Thy disobedience. Well thou didst advise; -Yet not for thy advice or threats I fly -These wicked tents devoted, lest the wrath -Impendent, raging into sudden flame, -Distinguish not: For soon expect to feel -His thunder on thy head, devouring fire. -Then who created thee lamenting learn, -When who can uncreate thee thou shalt know. -So spake the Seraph Abdiel, faithful found -Among the faithless, faithful only he; -Among innumerable false, unmoved, -Unshaken, unseduced, unterrified, -His loyalty he kept, his love, his zeal; -Nor number, nor example, with him wrought -To swerve from truth, or change his constant mind, -Though single. From amidst them forth he passed, -Long way through hostile scorn, which he sustained -Superiour, nor of violence feared aught; -And, with retorted scorn, his back he turned -On those proud towers to swift destruction doomed. - - - -Book VI - - -All night the dreadless Angel, unpursued, -Through Heaven's wide champain held his way; till Morn, -Waked by the circling Hours, with rosy hand -Unbarred the gates of light. There is a cave -Within the mount of God, fast by his throne, -Where light and darkness in perpetual round -Lodge and dislodge by turns, which makes through Heaven -Grateful vicissitude, like day and night; -Light issues forth, and at the other door -Obsequious darkness enters, till her hour -To veil the Heaven, though darkness there might well -Seem twilight here: And now went forth the Morn -Such as in highest Heaven arrayed in gold -Empyreal; from before her vanished Night, -Shot through with orient beams; when all the plain -Covered with thick embattled squadrons bright, -Chariots, and flaming arms, and fiery steeds, -Reflecting blaze on blaze, first met his view: -War he perceived, war in procinct; and found -Already known what he for news had thought -To have reported: Gladly then he mixed -Among those friendly Powers, who him received -With joy and acclamations loud, that one, -That of so many myriads fallen, yet one -Returned not lost. On to the sacred hill -They led him high applauded, and present -Before the seat supreme; from whence a voice, -From midst a golden cloud, thus mild was heard. -Servant of God. Well done; well hast thou fought -The better fight, who single hast maintained -Against revolted multitudes the cause -Of truth, in word mightier than they in arms; -And for the testimony of truth hast borne -Universal reproach, far worse to bear -Than violence; for this was all thy care -To stand approved in sight of God, though worlds -Judged thee perverse: The easier conquest now -Remains thee, aided by this host of friends, -Back on thy foes more glorious to return, -Than scorned thou didst depart; and to subdue -By force, who reason for their law refuse, -Right reason for their law, and for their King -Messiah, who by right of merit reigns. -Go, Michael, of celestial armies prince, -And thou, in military prowess next, -Gabriel, lead forth to battle these my sons -Invincible; lead forth my armed Saints, -By thousands and by millions, ranged for fight, -Equal in number to that Godless crew -Rebellious: Them with fire and hostile arms -Fearless assault; and, to the brow of Heaven -Pursuing, drive them out from God and bliss, -Into their place of punishment, the gulf -Of Tartarus, which ready opens wide -His fiery Chaos to receive their fall. -So spake the Sovran Voice, and clouds began -To darken all the hill, and smoke to roll -In dusky wreaths, reluctant flames, the sign -Of wrath awaked; nor with less dread the loud -Ethereal trumpet from on high 'gan blow: -At which command the Powers militant, -That stood for Heaven, in mighty quadrate joined -Of union irresistible, moved on -In silence their bright legions, to the sound -Of instrumental harmony, that breathed -Heroick ardour to adventurous deeds -Under their God-like leaders, in the cause -Of God and his Messiah. On they move -Indissolubly firm; nor obvious hill, -Nor straitening vale, nor wood, nor stream, divides -Their perfect ranks; for high above the ground -Their march was, and the passive air upbore -Their nimble tread; as when the total kind -Of birds, in orderly array on wing, -Came summoned over Eden to receive -Their names of thee; so over many a tract -Of Heaven they marched, and many a province wide, -Tenfold the length of this terrene: At last, -Far in the horizon to the north appeared -From skirt to skirt a fiery region, stretched -In battailous aspect, and nearer view -Bristled with upright beams innumerable -Of rigid spears, and helmets thronged, and shields -Various, with boastful argument portrayed, -The banded Powers of Satan hasting on -With furious expedition; for they weened -That self-same day, by fight or by surprise, -To win the mount of God, and on his throne -To set the Envier of his state, the proud -Aspirer; but their thoughts proved fond and vain -In the mid way: Though strange to us it seemed -At first, that Angel should with Angel war, -And in fierce hosting meet, who wont to meet -So oft in festivals of joy and love -Unanimous, as sons of one great Sire, -Hymning the Eternal Father: But the shout -Of battle now began, and rushing sound -Of onset ended soon each milder thought. -High in the midst, exalted as a God, -The Apostate in his sun-bright chariot sat, -Idol of majesty divine, enclosed -With flaming Cherubim, and golden shields; -Then lighted from his gorgeous throne, for now -"twixt host and host but narrow space was left, -A dreadful interval, and front to front -Presented stood in terrible array -Of hideous length: Before the cloudy van, -On the rough edge of battle ere it joined, -Satan, with vast and haughty strides advanced, -Came towering, armed in adamant and gold; -Abdiel that sight endured not, where he stood -Among the mightiest, bent on highest deeds, -And thus his own undaunted heart explores. -O Heaven! that such resemblance of the Highest -Should yet remain, where faith and realty -Remain not: Wherefore should not strength and might -There fail where virtue fails, or weakest prove -Where boldest, though to fight unconquerable? -His puissance, trusting in the Almighty's aid, -I mean to try, whose reason I have tried -Unsound and false; nor is it aught but just, -That he, who in debate of truth hath won, -Should win in arms, in both disputes alike -Victor; though brutish that contest and foul, -When reason hath to deal with force, yet so -Most reason is that reason overcome. -So pondering, and from his armed peers -Forth stepping opposite, half-way he met -His daring foe, at this prevention more -Incensed, and thus securely him defied. -Proud, art thou met? thy hope was to have reached -The highth of thy aspiring unopposed, -The throne of God unguarded, and his side -Abandoned, at the terrour of thy power -Or potent tongue: Fool!not to think how vain -Against the Omnipotent to rise in arms; -Who out of smallest things could, without end, -Have raised incessant armies to defeat -Thy folly; or with solitary hand -Reaching beyond all limit, at one blow, -Unaided, could have finished thee, and whelmed -Thy legions under darkness: But thou seest -All are not of thy train; there be, who faith -Prefer, and piety to God, though then -To thee not visible, when I alone -Seemed in thy world erroneous to dissent -From all: My sect thou seest;now learn too late -How few sometimes may know, when thousands err. -Whom the grand foe, with scornful eye askance, -Thus answered. Ill for thee, but in wished hour -Of my revenge, first sought for, thou returnest -From flight, seditious Angel! to receive -Thy merited reward, the first assay -Of this right hand provoked, since first that tongue, -Inspired with contradiction, durst oppose -A third part of the Gods, in synod met -Their deities to assert; who, while they feel -Vigour divine within them, can allow -Omnipotence to none. But well thou comest -Before thy fellows, ambitious to win -From me some plume, that thy success may show -Destruction to the rest: This pause between, -(Unanswered lest thou boast) to let thee know, -At first I thought that Liberty and Heaven -To heavenly souls had been all one; but now -I see that most through sloth had rather serve, -Ministring Spirits, trained up in feast and song! -Such hast thou armed, the minstrelsy of Heaven, -Servility with freedom to contend, -As both their deeds compared this day shall prove. -To whom in brief thus Abdiel stern replied. -Apostate! still thou errest, nor end wilt find -Of erring, from the path of truth remote: -Unjustly thou depravest it with the name -Of servitude, to serve whom God ordains, -Or Nature: God and Nature bid the same, -When he who rules is worthiest, and excels -Them whom he governs. This is servitude, -To serve the unwise, or him who hath rebelled -Against his worthier, as thine now serve thee, -Thyself not free, but to thyself enthralled; -Yet lewdly darest our ministring upbraid. -Reign thou in Hell, thy kingdom; let me serve -In Heaven God ever blest, and his divine -Behests obey, worthiest to be obeyed; -Yet chains in Hell, not realms, expect: Mean while -From me returned, as erst thou saidst, from flight, -This greeting on thy impious crest receive. -So saying, a noble stroke he lifted high, -Which hung not, but so swift with tempest fell -On the proud crest of Satan, that no sight, -Nor motion of swift thought, less could his shield, -Such ruin intercept: Ten paces huge -He back recoiled; the tenth on bended knee -His massy spear upstaid; as if on earth -Winds under ground, or waters forcing way, -Sidelong had pushed a mountain from his seat, -Half sunk with all his pines. Amazement seised -The rebel Thrones, but greater rage, to see -Thus foiled their mightiest; ours joy filled, and shout, -Presage of victory, and fierce desire -Of battle: Whereat Michael bid sound -The Arch-Angel trumpet; through the vast of Heaven -It sounded, and the faithful armies rung -Hosanna to the Highest: Nor stood at gaze -The adverse legions, nor less hideous joined -The horrid shock. Now storming fury rose, -And clamour such as heard in Heaven till now -Was never; arms on armour clashing brayed -Horrible discord, and the madding wheels -Of brazen chariots raged; dire was the noise -Of conflict; over head the dismal hiss -Of fiery darts in flaming vollies flew, -And flying vaulted either host with fire. -So under fiery cope together rushed -Both battles main, with ruinous assault -And inextinguishable rage. All Heaven -Resounded; and had Earth been then, all Earth -Had to her center shook. What wonder? when -Millions of fierce encountering Angels fought -On either side, the least of whom could wield -These elements, and arm him with the force -Of all their regions: How much more of power -Army against army numberless to raise -Dreadful combustion warring, and disturb, -Though not destroy, their happy native seat; -Had not the Eternal King Omnipotent, -From his strong hold of Heaven, high over-ruled -And limited their might; though numbered such -As each divided legion might have seemed -A numerous host; in strength each armed hand -A legion; led in fight, yet leader seemed -Each warriour single as in chief, expert -When to advance, or stand, or turn the sway -Of battle, open when, and when to close -The ridges of grim war: No thought of flight, -None of retreat, no unbecoming deed -That argued fear; each on himself relied, -As only in his arm the moment lay -Of victory: Deeds of eternal fame -Were done, but infinite; for wide was spread -That war and various; sometimes on firm ground -A standing fight, then, soaring on main wing, -Tormented all the air; all air seemed then -Conflicting fire. Long time in even scale -The battle hung; till Satan, who that day -Prodigious power had shown, and met in arms -No equal, ranging through the dire attack -Of fighting Seraphim confused, at length -Saw where the sword of Michael smote, and felled -Squadrons at once; with huge two-handed sway -Brandished aloft, the horrid edge came down -Wide-wasting; such destruction to withstand -He hasted, and opposed the rocky orb -Of tenfold adamant, his ample shield, -A vast circumference. At his approach -The great Arch-Angel from his warlike toil -Surceased, and glad, as hoping here to end -Intestine war in Heaven, the arch-foe subdued -Or captive dragged in chains, with hostile frown -And visage all inflamed first thus began. -Author of evil, unknown till thy revolt, -Unnamed in Heaven, now plenteous as thou seest -These acts of hateful strife, hateful to all, -Though heaviest by just measure on thyself, -And thy adherents: How hast thou disturbed -Heaven's blessed peace, and into nature brought -Misery, uncreated till the crime -Of thy rebellion! how hast thou instilled -Thy malice into thousands, once upright -And faithful, now proved false! But think not here -To trouble holy rest; Heaven casts thee out -From all her confines. Heaven, the seat of bliss, -Brooks not the works of violence and war. -Hence then, and evil go with thee along, -Thy offspring, to the place of evil, Hell; -Thou and thy wicked crew! there mingle broils, -Ere this avenging sword begin thy doom, -Or some more sudden vengeance, winged from God, -Precipitate thee with augmented pain. -So spake the Prince of Angels; to whom thus -The Adversary. Nor think thou with wind -Of aery threats to awe whom yet with deeds -Thou canst not. Hast thou turned the least of these -To flight, or if to fall, but that they rise -Unvanquished, easier to transact with me -That thou shouldst hope, imperious, and with threats -To chase me hence? err not, that so shall end -The strife which thou callest evil, but we style -The strife of glory; which we mean to win, -Or turn this Heaven itself into the Hell -Thou fablest; here however to dwell free, -If not to reign: Mean while thy utmost force, -And join him named Almighty to thy aid, -I fly not, but have sought thee far and nigh. -They ended parle, and both addressed for fight -Unspeakable; for who, though with the tongue -Of Angels, can relate, or to what things -Liken on earth conspicuous, that may lift -Human imagination to such highth -Of Godlike power? for likest Gods they seemed, -Stood they or moved, in stature, motion, arms, -Fit to decide the empire of great Heaven. -Now waved their fiery swords, and in the air -Made horrid circles; two broad suns their shields -Blazed opposite, while Expectation stood -In horrour: From each hand with speed retired, -Where erst was thickest fight, the angelick throng, -And left large field, unsafe within the wind -Of such commotion; such as, to set forth -Great things by small, if, nature's concord broke, -Among the constellations war were sprung, -Two planets, rushing from aspect malign -Of fiercest opposition, in mid sky -Should combat, and their jarring spheres confound. -Together both with next to almighty arm -Up-lifted imminent, one stroke they aimed -That might determine, and not need repeat, -As not of power at once; nor odds appeared -In might or swift prevention: But the sword -Of Michael from the armoury of God -Was given him tempered so, that neither keen -Nor solid might resist that edge: it met -The sword of Satan, with steep force to smite -Descending, and in half cut sheer; nor staid, -But with swift wheel reverse, deep entering, shared -All his right side: Then Satan first knew pain, -And writhed him to and fro convolved; so sore -The griding sword with discontinuous wound -Passed through him: But the ethereal substance closed, -Not long divisible; and from the gash -A stream of necturous humour issuing flowed -Sanguine, such as celestial Spirits may bleed, -And all his armour stained, ere while so bright. -Forthwith on all sides to his aid was run -By Angels many and strong, who interposed -Defence, while others bore him on their shields -Back to his chariot, where it stood retired -From off the files of war: There they him laid -Gnashing for anguish, and despite, and shame, -To find himself not matchless, and his pride -Humbled by such rebuke, so far beneath -His confidence to equal God in power. -Yet soon he healed; for Spirits that live throughout -Vital in every part, not as frail man -In entrails, heart of head, liver or reins, -Cannot but by annihilating die; -Nor in their liquid texture mortal wound -Receive, no more than can the fluid air: -All heart they live, all head, all eye, all ear, -All intellect, all sense; and, as they please, -They limb themselves, and colour, shape, or size -Assume, as?kikes them best, condense or rare. -Mean while in other parts like deeds deserved -Memorial, where the might of Gabriel fought, -And with fierce ensigns pierced the deep array -Of Moloch, furious king; who him defied, -And at his chariot-wheels to drag him bound -Threatened, nor from the Holy One of Heaven -Refrained his tongue blasphemous; but anon -Down cloven to the waist, with shattered arms -And uncouth pain fled bellowing. On each wing -Uriel, and Raphael, his vaunting foe, -Though huge, and in a rock of diamond armed, -Vanquished Adramelech, and Asmadai, -Two potent Thrones, that to be less than Gods -Disdained, but meaner thoughts learned in their flight, -Mangled with ghastly wounds through plate and mail. -Nor stood unmindful Abdiel to annoy -The atheist crew, but with redoubled blow -Ariel, and Arioch, and the violence -Of Ramiel scorched and blasted, overthrew. -I might relate of thousands, and their names -Eternize here on earth; but those elect -Angels, contented with their fame in Heaven, -Seek not the praise of men: The other sort, -In might though wonderous and in acts of war, -Nor of renown less eager, yet by doom -Cancelled from Heaven and sacred memory, -Nameless in dark oblivion let them dwell. -For strength from truth divided, and from just, -Illaudable, nought merits but dispraise -And ignominy; yet to glory aspires -Vain-glorious, and through infamy seeks fame: -Therefore eternal silence be their doom. -And now, their mightiest quelled, the battle swerved, -With many an inroad gored; deformed rout -Entered, and foul disorder; all the ground -With shivered armour strown, and on a heap -Chariot and charioteer lay overturned, -And fiery-foaming steeds; what stood, recoiled -O'er-wearied, through the faint Satanick host -Defensive scarce, or with pale fear surprised, -Then first with fear surprised, and sense of pain, -Fled ignominious, to such evil brought -By sin of disobedience; till that hour -Not liable to fear, or flight, or pain. -Far otherwise the inviolable Saints, -In cubick phalanx firm, advanced entire, -Invulnerable, impenetrably armed; -Such high advantages their innocence -Gave them above their foes; not to have sinned, -Not to have disobeyed; in fight they stood -Unwearied, unobnoxious to be pained -By wound, though from their place by violence moved, -Now Night her course began, and, over Heaven -Inducing darkness, grateful truce imposed, -And silence on the odious din of war: -Under her cloudy covert both retired, -Victor and vanquished: On the foughten field -Michael and his Angels prevalent -Encamping, placed in guard their watches round, -Cherubick waving fires: On the other part, -Satan with his rebellious disappeared, -Far in the dark dislodged; and, void of rest, -His potentates to council called by night; -And in the midst thus undismayed began. -O now in danger tried, now known in arms -Not to be overpowered, Companions dear, -Found worthy not of liberty alone, -Too mean pretence! but what we more affect, -Honour, dominion, glory, and renown; -Who have sustained one day in doubtful fight, -(And if one day, why not eternal days?) -What Heaven's Lord had powerfullest to send -Against us from about his throne, and judged -Sufficient to subdue us to his will, -But proves not so: Then fallible, it seems, -Of future we may deem him, though till now -Omniscient thought. True is, less firmly armed, -Some disadvantage we endured and pain, -Till now not known, but, known, as soon contemned; -Since now we find this our empyreal form -Incapable of mortal injury, -Imperishable, and, though pierced with wound, -Soon closing, and by native vigour healed. -Of evil then so small as easy think -The remedy; perhaps more valid arms, -Weapons more violent, when next we meet, -May serve to better us, and worse our foes, -Or equal what between us made the odds, -In nature none: If other hidden cause -Left them superiour, while we can preserve -Unhurt our minds, and understanding sound, -Due search and consultation will disclose. -He sat; and in the assembly next upstood -Nisroch, of Principalities the prime; -As one he stood escaped from cruel fight, -Sore toiled, his riven arms to havock hewn, -And cloudy in aspect thus answering spake. -Deliverer from new Lords, leader to free -Enjoyment of our right as Gods; yet hard -For Gods, and too unequal work we find, -Against unequal arms to fight in pain, -Against unpained, impassive; from which evil -Ruin must needs ensue; for what avails -Valour or strength, though matchless, quelled with pain -Which all subdues, and makes remiss the hands -Of mightiest? Sense of pleasure we may well -Spare out of life perhaps, and not repine, -But live content, which is the calmest life: -But pain is perfect misery, the worst -Of evils, and, excessive, overturns -All patience. He, who therefore can invent -With what more forcible we may offend -Our yet unwounded enemies, or arm -Ourselves with like defence, to me deserves -No less than for deliverance what we owe. -Whereto with look composed Satan replied. -Not uninvented that, which thou aright -Believest so main to our success, I bring. -Which of us who beholds the bright surface -Of this ethereous mould whereon we stand, -This continent of spacious Heaven, adorned -With plant, fruit, flower ambrosial, gems, and gold; -Whose eye so superficially surveys -These things, as not to mind from whence they grow -Deep under ground, materials dark and crude, -Of spiritous and fiery spume, till touched -With Heaven's ray, and tempered, they shoot forth -So beauteous, opening to the ambient light? -These in their dark nativity the deep -Shall yield us, pregnant with infernal flame; -Which, into hollow engines, long and round, -Thick rammed, at the other bore with touch of fire -Dilated and infuriate, shall send forth -From far, with thundering noise, among our foes -Such implements of mischief, as shall dash -To pieces, and o'erwhelm whatever stands -Adverse, that they shall fear we have disarmed -The Thunderer of his only dreaded bolt. -Nor long shall be our labour; yet ere dawn, -Effect shall end our wish. Mean while revive; -Abandon fear; to strength and counsel joined -Think nothing hard, much less to be despaired. -He ended, and his words their drooping cheer -Enlightened, and their languished hope revived. -The invention all admired, and each, how he -To be the inventer missed; so easy it seemed -Once found, which yet unfound most would have thought -Impossible: Yet, haply, of thy race -In future days, if malice should abound, -Some one intent on mischief, or inspired -With devilish machination, might devise -Like instrument to plague the sons of men -For sin, on war and mutual slaughter bent. -Forthwith from council to the work they flew; -None arguing stood; innumerable hands -Were ready; in a moment up they turned -Wide the celestial soil, and saw beneath -The originals of nature in their crude -Conception; sulphurous and nitrous foam -They found, they mingled, and, with subtle art, -Concocted and adusted they reduced -To blackest grain, and into store conveyed: -Part hidden veins digged up (nor hath this earth -Entrails unlike) of mineral and stone, -Whereof to found their engines and their balls -Of missive ruin; part incentive reed -Provide, pernicious with one touch to fire. -So all ere day-spring, under conscious night, -Secret they finished, and in order set, -With silent circumspection, unespied. -Now when fair morn orient in Heaven appeared, -Up rose the victor-Angels, and to arms -The matin trumpet sung: In arms they stood -Of golden panoply, refulgent host, -Soon banded; others from the dawning hills -Look round, and scouts each coast light-armed scour, -Each quarter to descry the distant foe, -Where lodged, or whither fled, or if for fight, -In motion or in halt: Him soon they met -Under spread ensigns moving nigh, in slow -But firm battalion; back with speediest sail -Zophiel, of Cherubim the swiftest wing, -Came flying, and in mid air aloud thus cried. -Arm, Warriours, arm for fight; the foe at hand, -Whom fled we thought, will save us long pursuit -This day; fear not his flight;so thick a cloud -He comes, and settled in his face I see -Sad resolution, and secure: Let each -His adamantine coat gird well, and each -Fit well his helm, gripe fast his orbed shield, -Borne even or high; for this day will pour down, -If I conjecture aught, no drizzling shower, -But rattling storm of arrows barbed with fire. -So warned he them, aware themselves, and soon -In order, quit of all impediment; -Instant without disturb they took alarm, -And onward moved embattled: When behold! -Not distant far with heavy pace the foe -Approaching gross and huge, in hollow cube -Training his devilish enginery, impaled -On every side with shadowing squadrons deep, -To hide the fraud. At interview both stood -A while; but suddenly at head appeared -Satan, and thus was heard commanding loud. -Vanguard, to right and left the front unfold; -That all may see who hate us, how we seek -Peace and composure, and with open breast -Stand ready to receive them, if they like -Our overture; and turn not back perverse: -But that I doubt; however witness, Heaven! -Heaven, witness thou anon! while we discharge -Freely our part: ye, who appointed stand -Do as you have in charge, and briefly touch -What we propound, and loud that all may hear! -So scoffing in ambiguous words, he scarce -Had ended; when to right and left the front -Divided, and to either flank retired: -Which to our eyes discovered, new and strange, -A triple mounted row of pillars laid -On wheels (for like to pillars most they seemed, -Or hollowed bodies made of oak or fir, -With branches lopt, in wood or mountain felled,) -Brass, iron, stony mould, had not their mouths -With hideous orifice gaped on us wide, -Portending hollow truce: At each behind -A Seraph stood, and in his hand a reed -Stood waving tipt with fire; while we, suspense, -Collected stood within our thoughts amused, -Not long; for sudden all at once their reeds -Put forth, and to a narrow vent applied -With nicest touch. Immediate in a flame, -But soon obscured with smoke, all Heaven appeared, -From those deep-throated engines belched, whose roar -Embowelled with outrageous noise the air, -And all her entrails tore, disgorging foul -Their devilish glut, chained thunderbolts and hail -Of iron globes; which, on the victor host -Levelled, with such impetuous fury smote, -That, whom they hit, none on their feet might stand, -Though standing else as rocks, but down they fell -By thousands, Angel on Arch-Angel rolled; -The sooner for their arms; unarmed, they might -Have easily, as Spirits, evaded swift -By quick contraction or remove; but now -Foul dissipation followed, and forced rout; -Nor served it to relax their serried files. -What should they do? if on they rushed, repulse -Repeated, and indecent overthrow -Doubled, would render them yet more despised, -And to their foes a laughter; for in view -Stood ranked of Seraphim another row, -In posture to displode their second tire -Of thunder: Back defeated to return -They worse abhorred. Satan beheld their plight, -And to his mates thus in derision called. -O Friends! why come not on these victors proud -Ere while they fierce were coming; and when we, -To entertain them fair with open front -And breast, (what could we more?) propounded terms -Of composition, straight they changed their minds, -Flew off, and into strange vagaries fell, -As they would dance; yet for a dance they seemed -Somewhat extravagant and wild; perhaps -For joy of offered peace: But I suppose, -If our proposals once again were heard, -We should compel them to a quick result. -To whom thus Belial, in like gamesome mood. -Leader! the terms we sent were terms of weight, -Of hard contents, and full of force urged home; -Such as we might perceive amused them all, -And stumbled many: Who receives them right, -Had need from head to foot well understand; -Not understood, this gift they have besides, -They show us when our foes walk not upright. -So they among themselves in pleasant vein -Stood scoffing, hightened in their thoughts beyond -All doubt of victory: Eternal Might -To match with their inventions they presumed -So easy, and of his thunder made a scorn, -And all his host derided, while they stood -A while in trouble: But they stood not long; -Rage prompted them at length, and found them arms -Against such hellish mischief fit to oppose. -Forthwith (behold the excellence, the power, -Which God hath in his mighty Angels placed!) -Their arms away they threw, and to the hills -(For Earth hath this variety from Heaven -Of pleasure situate in hill and dale,) -Light as the lightning glimpse they ran, they flew; -From their foundations loosening to and fro, -They plucked the seated hills, with all their load, -Rocks, waters, woods, and by the shaggy tops -Up-lifting bore them in their hands: Amaze, -Be sure, and terrour, seized the rebel host, -When coming towards them so dread they saw -The bottom of the mountains upward turned; -Till on those cursed engines' triple-row -They saw them whelmed, and all their confidence -Under the weight of mountains buried deep; -Themselves invaded next, and on their heads -Main promontories flung, which in the air -Came shadowing, and oppressed whole legions armed; -Their armour helped their harm, crushed in and bruised -Into their substance pent, which wrought them pain -Implacable, and many a dolorous groan; -Long struggling underneath, ere they could wind -Out of such prison, though Spirits of purest light, -Purest at first, now gross by sinning grown. -The rest, in imitation, to like arms -Betook them, and the neighbouring hills uptore: -So hills amid the air encountered hills, -Hurled to and fro with jaculation dire; -That under ground they fought in dismal shade; -Infernal noise! war seemed a civil game -To this uproar; horrid confusion heaped -Upon confusion rose: And now all Heaven -Had gone to wrack, with ruin overspread; -Had not the Almighty Father, where he sits -Shrined in his sanctuary of Heaven secure, -Consulting on the sum of things, foreseen -This tumult, and permitted all, advised: -That his great purpose he might so fulfil, -To honour his anointed Son avenged -Upon his enemies, and to declare -All power on him transferred: Whence to his Son, -The Assessour of his throne, he thus began. -Effulgence of my glory, Son beloved, -Son, in whose face invisible is beheld -Visibly, what by Deity I am; -And in whose hand what by decree I do, -Second Omnipotence! two days are past, -Two days, as we compute the days of Heaven, -Since Michael and his Powers went forth to tame -These disobedient: Sore hath been their fight, -As likeliest was, when two such foes met armed; -For to themselves I left them; and thou knowest, -Equal in their creation they were formed, -Save what sin hath impaired; which yet hath wrought -Insensibly, for I suspend their doom; -Whence in perpetual fight they needs must last -Endless, and no solution will be found: -War wearied hath performed what war can do, -And to disordered rage let loose the reins -With mountains, as with weapons, armed; which makes -Wild work in Heaven, and dangerous to the main. -Two days are therefore past, the third is thine; -For thee I have ordained it; and thus far -Have suffered, that the glory may be thine -Of ending this great war, since none but Thou -Can end it. Into thee such virtue and grace -Immense I have transfused, that all may know -In Heaven and Hell thy power above compare; -And, this perverse commotion governed thus, -To manifest thee worthiest to be Heir -Of all things; to be Heir, and to be King -By sacred unction, thy deserved right. -Go then, Thou Mightiest, in thy Father's might; -Ascend my chariot, guide the rapid wheels -That shake Heaven's basis, bring forth all my war, -My bow and thunder, my almighty arms -Gird on, and sword upon thy puissant thigh; -Pursue these sons of darkness, drive them out -From all Heaven's bounds into the utter deep: -There let them learn, as likes them, to despise -God, and Messiah his anointed King. -He said, and on his Son with rays direct -Shone full; he all his Father full expressed -Ineffably into his face received; -And thus the Filial Godhead answering spake. -O Father, O Supreme of heavenly Thrones, -First, Highest, Holiest, Best; thou always seek'st -To glorify thy Son, I always thee, -As is most just: This I my glory account, -My exaltation, and my whole delight, -That thou, in me well pleased, declarest thy will -Fulfilled, which to fulfil is all my bliss. -Scepter and power, thy giving, I assume, -And gladlier shall resign, when in the end -Thou shalt be all in all, and I in thee -For ever; and in me all whom thou lovest: -But whom thou hatest, I hate, and can put on -Thy terrours, as I put thy mildness on, -Image of thee in all things; and shall soon, -Armed with thy might, rid Heaven of these rebelled; -To their prepared ill mansion driven down, -To chains of darkness, and the undying worm; -That from thy just obedience could revolt, -Whom to obey is happiness entire. -Then shall thy Saints unmixed, and from the impure -Far separate, circling thy holy mount, -Unfeigned Halleluiahs to thee sing, -Hymns of high praise, and I among them Chief. -So said, he, o'er his scepter bowing, rose -From the right hand of Glory where he sat; -And the third sacred morn began to shine, -Dawning through Heaven. Forth rushed with whirlwind sound -The chariot of Paternal Deity, -Flashing thick flames, wheel within wheel undrawn, -Itself instinct with Spirit, but convoyed -By four Cherubick shapes; four faces each -Had wonderous; as with stars, their bodies all -And wings were set with eyes; with eyes the wheels -Of beryl, and careering fires between; -Over their heads a crystal firmament, -Whereon a sapphire throne, inlaid with pure -Amber, and colours of the showery arch. -He, in celestial panoply all armed -Of radiant Urim, work divinely wrought, -Ascended; at his right hand Victory -Sat eagle-winged; beside him hung his bow -And quiver with three-bolted thunder stored; -And from about him fierce effusion rolled -Of smoke, and bickering flame, and sparkles dire: -Attended with ten thousand thousand Saints, -He onward came; far off his coming shone; -And twenty thousand (I their number heard) -Chariots of God, half on each hand, were seen; -He on the wings of Cherub rode sublime -On the crystalline sky, in sapphire throned, -Illustrious far and wide; but by his own -First seen: Them unexpected joy surprised, -When the great ensign of Messiah blazed -Aloft by Angels borne, his sign in Heaven; -Under whose conduct Michael soon reduced -His army, circumfused on either wing, -Under their Head imbodied all in one. -Before him Power Divine his way prepared; -At his command the uprooted hills retired -Each to his place; they heard his voice, and went -Obsequious; Heaven his wonted face renewed, -And with fresh flowerets hill and valley smiled. -This saw his hapless foes, but stood obdured, -And to rebellious fight rallied their Powers, -Insensate, hope conceiving from despair. -In heavenly Spirits could such perverseness dwell? -But to convince the proud what signs avail, -Or wonders move the obdurate to relent? -They, hardened more by what might most reclaim, -Grieving to see his glory, at the sight -Took envy; and, aspiring to his highth, -Stood re-embattled fierce, by force or fraud -Weening to prosper, and at length prevail -Against God and Messiah, or to fall -In universal ruin last; and now -To final battle drew, disdaining flight, -Or faint retreat; when the great Son of God -To all his host on either hand thus spake. -Stand still in bright array, ye Saints; here stand, -Ye Angels armed; this day from battle rest: -Faithful hath been your warfare, and of God -Accepted, fearless in his righteous cause; -And as ye have received, so have ye done, -Invincibly: But of this cursed crew -The punishment to other hand belongs; -Vengeance is his, or whose he sole appoints: -Number to this day's work is not ordained, -Nor multitude; stand only, and behold -God's indignation on these godless poured -By me; not you, but me, they have despised, -Yet envied; against me is all their rage, -Because the Father, to whom in Heaven s'preme -Kingdom, and power, and glory appertains, -Hath honoured me, according to his will. -Therefore to me their doom he hath assigned; -That they may have their wish, to try with me -In battle which the stronger proves; they all, -Or I alone against them; since by strength -They measure all, of other excellence -Not emulous, nor care who them excels; -Nor other strife with them do I vouchsafe. -So spake the Son, and into terrour changed -His countenance too severe to be beheld, -And full of wrath bent on his enemies. -At once the Four spread out their starry wings -With dreadful shade contiguous, and the orbs -Of his fierce chariot rolled, as with the sound -Of torrent floods, or of a numerous host. -He on his impious foes right onward drove, -Gloomy as night; under his burning wheels -The stedfast empyrean shook throughout, -All but the throne itself of God. Full soon -Among them he arrived; in his right hand -Grasping ten thousand thunders, which he sent -Before him, such as in their souls infixed -Plagues: They, astonished, all resistance lost, -All courage; down their idle weapons dropt: -O'er shields, and helms, and helmed heads he rode -Of Thrones and mighty Seraphim prostrate, -That wished the mountains now might be again -Thrown on them, as a shelter from his ire. -Nor less on either side tempestuous fell -His arrows, from the fourfold-visaged Four -Distinct with eyes, and from the living wheels -Distinct alike with multitude of eyes; -One Spirit in them ruled; and every eye -Glared lightning, and shot forth pernicious fire -Among the accursed, that withered all their strength, -And of their wonted vigour left them drained, -Exhausted, spiritless, afflicted, fallen. -Yet half his strength he put not forth, but checked -His thunder in mid volley; for he meant -Not to destroy, but root them out of Heaven: -The overthrown he raised, and as a herd -Of goats or timorous flock together thronged -Drove them before him thunder-struck, pursued -With terrours, and with furies, to the bounds -And crystal wall of Heaven; which, opening wide, -Rolled inward, and a spacious gap disclosed -Into the wasteful deep: The monstrous sight -Struck them with horrour backward, but far worse -Urged them behind: Headlong themselves they threw -Down from the verge of Heaven; eternal wrath -Burnt after them to the bottomless pit. -Hell heard the unsufferable noise, Hell saw -Heaven ruining from Heaven, and would have fled -Affrighted; but strict Fate had cast too deep -Her dark foundations, and too fast had bound. -Nine days they fell: Confounded Chaos roared, -And felt tenfold confusion in their fall -Through his wild anarchy, so huge a rout -Incumbered him with ruin: Hell at last -Yawning received them whole, and on them closed; -Hell, their fit habitation, fraught with fire -Unquenchable, the house of woe and pain. -Disburdened Heaven rejoiced, and soon repaired -Her mural breach, returning whence it rolled. -Sole victor, from the expulsion of his foes, -Messiah his triumphal chariot turned: -To meet him all his Saints, who silent stood -Eye-witnesses of his almighty acts, -With jubilee advanced; and, as they went, -Shaded with branching palm, each Order bright, -Sung triumph, and him sung victorious King, -Son, Heir, and Lord, to him dominion given, -Worthiest to reign: He, celebrated, rode -Triumphant through mid Heaven, into the courts -And temple of his Mighty Father throned -On high; who into glory him received, -Where now he sits at the right hand of bliss. -Thus, measuring things in Heaven by things on Earth, -At thy request, and that thou mayest beware -By what is past, to thee I have revealed -What might have else to human race been hid; -The discord which befel, and war in Heaven -Among the angelick Powers, and the deep fall -Of those too high aspiring, who rebelled -With Satan; he who envies now thy state, -Who now is plotting how he may seduce -Thee also from obedience, that, with him -Bereaved of happiness, thou mayest partake -His punishment, eternal misery; -Which would be all his solace and revenge, -As a despite done against the Most High, -Thee once to gain companion of his woe. -But listen not to his temptations, warn -Thy weaker; let it profit thee to have heard, -By terrible example, the reward -Of disobedience; firm they might have stood, -Yet fell; remember, and fear to transgress. - - - -Book VII - - -Descend from Heaven, Urania, by that name -If rightly thou art called, whose voice divine -Following, above the Olympian hill I soar, -Above the flight of Pegasean wing! -The meaning, not the name, I call: for thou -Nor of the Muses nine, nor on the top -Of old Olympus dwellest; but, heavenly-born, -Before the hills appeared, or fountain flowed, -Thou with eternal Wisdom didst converse, -Wisdom thy sister, and with her didst play -In presence of the Almighty Father, pleased -With thy celestial song. Up led by thee -Into the Heaven of Heavens I have presumed, -An earthly guest, and drawn empyreal air, -Thy tempering: with like safety guided down -Return me to my native element: -Lest from this flying steed unreined, (as once -Bellerophon, though from a lower clime,) -Dismounted, on the Aleian field I fall, -Erroneous there to wander, and forlorn. -Half yet remains unsung, but narrower bound -Within the visible diurnal sphere; -Standing on earth, not rapt above the pole, -More safe I sing with mortal voice, unchanged -To hoarse or mute, though fallen on evil days, -On evil days though fallen, and evil tongues; -In darkness, and with dangers compassed round, -And solitude; yet not alone, while thou -Visitest my slumbers nightly, or when morn -Purples the east: still govern thou my song, -Urania, and fit audience find, though few. -But drive far off the barbarous dissonance -Of Bacchus and his revellers, the race -Of that wild rout that tore the Thracian bard -In Rhodope, where woods and rocks had ears -To rapture, till the savage clamour drowned -Both harp and voice; nor could the Muse defend -Her son. So fail not thou, who thee implores: -For thou art heavenly, she an empty dream. -Say, Goddess, what ensued when Raphael, -The affable Arch-Angel, had forewarned -Adam, by dire example, to beware -Apostasy, by what befel in Heaven -To those apostates; lest the like befall -In Paradise to Adam or his race, -Charged not to touch the interdicted tree, -If they transgress, and slight that sole command, -So easily obeyed amid the choice -Of all tastes else to please their appetite, -Though wandering. He, with his consorted Eve, -The story heard attentive, and was filled -With admiration and deep muse, to hear -Of things so high and strange; things, to their thought -So unimaginable, as hate in Heaven, -And war so near the peace of God in bliss, -With such confusion: but the evil, soon -Driven back, redounded as a flood on those -From whom it sprung; impossible to mix -With blessedness. Whence Adam soon repealed -The doubts that in his heart arose: and now -Led on, yet sinless, with desire to know -What nearer might concern him, how this world -Of Heaven and Earth conspicuous first began; -When, and whereof created; for what cause; -What within Eden, or without, was done -Before his memory; as one whose drouth -Yet scarce allayed still eyes the current stream, -Whose liquid murmur heard new thirst excites, -Proceeded thus to ask his heavenly guest. -Great things, and full of wonder in our ears, -Far differing from this world, thou hast revealed, -Divine interpreter! by favour sent -Down from the empyrean, to forewarn -Us timely of what might else have been our loss, -Unknown, which human knowledge could not reach; -For which to the infinitely Good we owe -Immortal thanks, and his admonishment -Receive, with solemn purpose to observe -Immutably his sovran will, the end -Of what we are. But since thou hast vouchsafed -Gently, for our instruction, to impart -Things above earthly thought, which yet concerned -Our knowing, as to highest wisdom seemed, -Deign to descend now lower, and relate -What may no less perhaps avail us known, -How first began this Heaven which we behold -Distant so high, with moving fires adorned -Innumerable; and this which yields or fills -All space, the ambient air wide interfused -Embracing round this floried Earth; what cause -Moved the Creator, in his holy rest -Through all eternity, so late to build -In Chaos; and the work begun, how soon -Absolved; if unforbid thou mayest unfold -What we, not to explore the secrets ask -Of his eternal empire, but the more -To magnify his works, the more we know. -And the great light of day yet wants to run -Much of his race though steep; suspense in Heaven, -Held by thy voice, thy potent voice, he hears, -And longer will delay to hear thee tell -His generation, and the rising birth -Of Nature from the unapparent Deep: -Or if the star of evening and the moon -Haste to thy audience, Night with her will bring, -Silence; and Sleep, listening to thee, will watch; -Or we can bid his absence, till thy song -End, and dismiss thee ere the morning shine. -Thus Adam his illustrious guest besought: -And thus the Godlike Angel answered mild. -This also thy request, with caution asked, -Obtain; though to recount almighty works -What words or tongue of Seraph can suffice, -Or heart of man suffice to comprehend? -Yet what thou canst attain, which best may serve -To glorify the Maker, and infer -Thee also happier, shall not be withheld -Thy hearing; such commission from above -I have received, to answer thy desire -Of knowledge within bounds; beyond, abstain -To ask; nor let thine own inventions hope -Things not revealed, which the invisible King, -Only Omniscient, hath suppressed in night; -To none communicable in Earth or Heaven: -Enough is left besides to search and know. -But knowledge is as food, and needs no less -Her temperance over appetite, to know -In measure what the mind may well contain; -Oppresses else with surfeit, and soon turns -Wisdom to folly, as nourishment to wind. -Know then, that, after Lucifer from Heaven -(So call him, brighter once amidst the host -Of Angels, than that star the stars among,) -Fell with his flaming legions through the deep -Into his place, and the great Son returned -Victorious with his Saints, the Omnipotent -Eternal Father from his throne beheld -Their multitude, and to his Son thus spake. -At least our envious Foe hath failed, who thought -All like himself rebellious, by whose aid -This inaccessible high strength, the seat -Of Deity supreme, us dispossessed, -He trusted to have seised, and into fraud -Drew many, whom their place knows here no more: -Yet far the greater part have kept, I see, -Their station; Heaven, yet populous, retains -Number sufficient to possess her realms -Though wide, and this high temple to frequent -With ministeries due, and solemn rites: -But, lest his heart exalt him in the harm -Already done, to have dispeopled Heaven, -My damage fondly deemed, I can repair -That detriment, if such it be to lose -Self-lost; and in a moment will create -Another world, out of one man a race -Of men innumerable, there to dwell, -Not here; till, by degrees of merit raised, -They open to themselves at length the way -Up hither, under long obedience tried; -And Earth be changed to Heaven, and Heaven to Earth, -One kingdom, joy and union without end. -Mean while inhabit lax, ye Powers of Heaven; -And thou my Word, begotten Son, by thee -This I perform; speak thou, and be it done! -My overshadowing Spirit and Might with thee -I send along; ride forth, and bid the Deep -Within appointed bounds be Heaven and Earth; -Boundless the Deep, because I Am who fill -Infinitude, nor vacuous the space. -Though I, uncircumscribed myself, retire, -And put not forth my goodness, which is free -To act or not, Necessity and Chance -Approach not me, and what I will is Fate. -So spake the Almighty, and to what he spake -His Word, the Filial Godhead, gave effect. -Immediate are the acts of God, more swift -Than time or motion, but to human ears -Cannot without process of speech be told, -So told as earthly notion can receive. -Great triumph and rejoicing was in Heaven, -When such was heard declared the Almighty's will; -Glory they sung to the Most High, good will -To future men, and in their dwellings peace; -Glory to Him, whose just avenging ire -Had driven out the ungodly from his sight -And the habitations of the just; to Him -Glory and praise, whose wisdom had ordained -Good out of evil to create; instead -Of Spirits malign, a better race to bring -Into their vacant room, and thence diffuse -His good to worlds and ages infinite. -So sang the Hierarchies: Mean while the Son -On his great expedition now appeared, -Girt with Omnipotence, with radiance crowned -Of Majesty Divine; sapience and love -Immense, and all his Father in him shone. -About his chariot numberless were poured -Cherub, and Seraph, Potentates, and Thrones, -And Virtues, winged Spirits, and chariots winged -From the armoury of God; where stand of old -Myriads, between two brazen mountains lodged -Against a solemn day, harnessed at hand, -Celestial equipage; and now came forth -Spontaneous, for within them Spirit lived, -Attendant on their Lord: Heaven opened wide -Her ever-during gates, harmonious sound -On golden hinges moving, to let forth -The King of Glory, in his powerful Word -And Spirit, coming to create new worlds. -On heavenly ground they stood; and from the shore -They viewed the vast immeasurable abyss -Outrageous as a sea, dark, wasteful, wild, -Up from the bottom turned by furious winds -And surging waves, as mountains, to assault -Heaven's highth, and with the center mix the pole. -Silence, ye troubled Waves, and thou Deep, peace, -Said then the Omnifick Word; your discord end! -Nor staid; but, on the wings of Cherubim -Uplifted, in paternal glory rode -Far into Chaos, and the world unborn; -For Chaos heard his voice: Him all his train -Followed in bright procession, to behold -Creation, and the wonders of his might. -Then staid the fervid wheels, and in his hand -He took the golden compasses, prepared -In God's eternal store, to circumscribe -This universe, and all created things: -One foot he centered, and the other turned -Round through the vast profundity obscure; -And said, Thus far extend, thus far thy bounds, -This be thy just circumference, O World! -Thus God the Heaven created, thus the Earth, -Matter unformed and void: Darkness profound -Covered the abyss: but on the watery calm -His brooding wings the Spirit of God outspread, -And vital virtue infused, and vital warmth -Throughout the fluid mass; but downward purged -The black tartareous cold infernal dregs, -Adverse to life: then founded, then conglobed -Like things to like; the rest to several place -Disparted, and between spun out the air; -And Earth self-balanced on her center hung. -Let there be light, said God; and forthwith Light -Ethereal, first of things, quintessence pure, -Sprung from the deep; and from her native east -To journey through the aery gloom began, -Sphered in a radiant cloud, for yet the sun -Was not; she in a cloudy tabernacle -Sojourned the while. God saw the light was good; -And light from darkness by the hemisphere -Divided: light the Day, and darkness Night, -He named. Thus was the first day even and morn: -Nor past uncelebrated, nor unsung -By the celestial quires, when orient light -Exhaling first from darkness they beheld; -Birth-day of Heaven and Earth; with joy and shout -The hollow universal orb they filled, -And touched their golden harps, and hymning praised -God and his works; Creator him they sung, -Both when first evening was, and when first morn. -Again, God said, Let there be firmament -Amid the waters, and let it divide -The waters from the waters; and God made -The firmament, expanse of liquid, pure, -Transparent, elemental air, diffused -In circuit to the uttermost convex -Of this great round; partition firm and sure, -The waters underneath from those above -Dividing: for as earth, so he the world -Built on circumfluous waters calm, in wide -Crystalline ocean, and the loud misrule -Of Chaos far removed; lest fierce extremes -Contiguous might distemper the whole frame: -And Heaven he named the Firmament: So even -And morning chorus sung the second day. -The Earth was formed, but in the womb as yet -Of waters, embryon immature involved, -Appeared not: over all the face of Earth -Main ocean flowed, not idle; but, with warm -Prolifick humour softening all her globe, -Fermented the great mother to conceive, -Satiate with genial moisture; when God said, -Be gathered now ye waters under Heaven -Into one place, and let dry land appear. -Immediately the mountains huge appear -Emergent, and their broad bare backs upheave -Into the clouds; their tops ascend the sky: -So high as heaved the tumid hills, so low -Down sunk a hollow bottom broad and deep, -Capacious bed of waters: Thither they -Hasted with glad precipitance, uprolled, -As drops on dust conglobing from the dry: -Part rise in crystal wall, or ridge direct, -For haste; such flight the great command impressed -On the swift floods: As armies at the call -Of trumpet (for of armies thou hast heard) -Troop to their standard; so the watery throng, -Wave rolling after wave, where way they found, -If steep, with torrent rapture, if through plain, -Soft-ebbing; nor withstood them rock or hill; -But they, or under ground, or circuit wide -With serpent errour wandering, found their way, -And on the washy oose deep channels wore; -Easy, ere God had bid the ground be dry, -All but within those banks, where rivers now -Stream, and perpetual draw their humid train. -The dry land, Earth; and the great receptacle -Of congregated waters, he called Seas: -And saw that it was good; and said, Let the Earth -Put forth the verdant grass, herb yielding seed, -And fruit-tree yielding fruit after her kind, -Whose seed is in herself upon the Earth. -He scarce had said, when the bare Earth, till then -Desart and bare, unsightly, unadorned, -Brought forth the tender grass, whose verdure clad -Her universal face with pleasant green; -Then herbs of every leaf, that sudden flowered -Opening their various colours, and made gay -Her bosom, smelling sweet: and, these scarce blown, -Forth flourished thick the clustering vine, forth crept -The swelling gourd, up stood the corny reed -Embattled in her field, and the humble shrub, -And bush with frizzled hair implicit: Last -Rose, as in dance, the stately trees, and spread -Their branches hung with copious fruit, or gemmed -Their blossoms: With high woods the hills were crowned; -With tufts the valleys, and each fountain side; -With borders long the rivers: that Earth now -Seemed like to Heaven, a seat where Gods might dwell, -Or wander with delight, and love to haunt -Her sacred shades: though God had yet not rained -Upon the Earth, and man to till the ground -None was; but from the Earth a dewy mist -Went up, and watered all the ground, and each -Plant of the field; which, ere it was in the Earth, -God made, and every herb, before it grew -On the green stem: God saw that it was good: -So even and morn recorded the third day. -Again the Almighty spake, Let there be lights -High in the expanse of Heaven, to divide -The day from night; and let them be for signs, -For seasons, and for days, and circling years; -And let them be for lights, as I ordain -Their office in the firmament of Heaven, -To give light on the Earth; and it was so. -And God made two great lights, great for their use -To Man, the greater to have rule by day, -The less by night, altern; and made the stars, -And set them in the firmament of Heaven -To illuminate the Earth, and rule the day -In their vicissitude, and rule the night, -And light from darkness to divide. God saw, -Surveying his great work, that it was good: -For of celestial bodies first the sun -A mighty sphere he framed, unlightsome first, -Though of ethereal mould: then formed the moon -Globose, and every magnitude of stars, -And sowed with stars the Heaven, thick as a field: -Of light by far the greater part he took, -Transplanted from her cloudy shrine, and placed -In the sun's orb, made porous to receive -And drink the liquid light; firm to retain -Her gathered beams, great palace now of light. -Hither, as to their fountain, other stars -Repairing, in their golden urns draw light, -And hence the morning-planet gilds her horns; -By tincture or reflection they augment -Their small peculiar, though from human sight -So far remote, with diminution seen, -First in his east the glorious lamp was seen, -Regent of day, and all the horizon round -Invested with bright rays, jocund to run -His longitude through Heaven's high road; the gray -Dawn, and the Pleiades, before him danced, -Shedding sweet influence: Less bright the moon, -But opposite in levelled west was set, -His mirrour, with full face borrowing her light -From him; for other light she needed none -In that aspect, and still that distance keeps -Till night; then in the east her turn she shines, -Revolved on Heaven's great axle, and her reign -With thousand lesser lights dividual holds, -With thousand thousand stars, that then appeared -Spangling the hemisphere: Then first adorned -With their bright luminaries that set and rose, -Glad evening and glad morn crowned the fourth day. -And God said, Let the waters generate -Reptile with spawn abundant, living soul: -And let fowl fly above the Earth, with wings -Displayed on the open firmament of Heaven. -And God created the great whales, and each -Soul living, each that crept, which plenteously -The waters generated by their kinds; -And every bird of wing after his kind; -And saw that it was good, and blessed them, saying. -Be fruitful, multiply, and in the seas, -And lakes, and running streams, the waters fill; -And let the fowl be multiplied, on the Earth. -Forthwith the sounds and seas, each creek and bay, -With fry innumerable swarm, and shoals -Of fish that with their fins, and shining scales, -Glide under the green wave, in sculls that oft -Bank the mid sea: part single, or with mate, -Graze the sea-weed their pasture, and through groves -Of coral stray; or, sporting with quick glance, -Show to the sun their waved coats dropt with gold; -Or, in their pearly shells at ease, attend -Moist nutriment; or under rocks their food -In jointed armour watch: on smooth the seal -And bended dolphins play: part huge of bulk -Wallowing unwieldy, enormous in their gait, -Tempest the ocean: there leviathan, -Hugest of living creatures, on the deep -Stretched like a promontory sleeps or swims, -And seems a moving land; and at his gills -Draws in, and at his trunk spouts out, a sea. -Mean while the tepid caves, and fens, and shores, -Their brood as numerous hatch, from the egg that soon -Bursting with kindly rupture forth disclosed -Their callow young; but feathered soon and fledge -They summed their pens; and, soaring the air sublime, -With clang despised the ground, under a cloud -In prospect; there the eagle and the stork -On cliffs and cedar tops their eyries build: -Part loosely wing the region, part more wise -In common, ranged in figure, wedge their way, -Intelligent of seasons, and set forth -Their aery caravan, high over seas -Flying, and over lands, with mutual wing -Easing their flight; so steers the prudent crane -Her annual voyage, borne on winds; the air -Floats as they pass, fanned with unnumbered plumes: -From branch to branch the smaller birds with song -Solaced the woods, and spread their painted wings -Till even; nor then the solemn nightingale -Ceased warbling, but all night tun'd her soft lays: -Others, on silver lakes and rivers, bathed -Their downy breast; the swan with arched neck, -Between her white wings mantling proudly, rows -Her state with oary feet; yet oft they quit -The dank, and, rising on stiff pennons, tower -The mid aereal sky: Others on ground -Walked firm; the crested cock whose clarion sounds -The silent hours, and the other whose gay train -Adorns him, coloured with the florid hue -Of rainbows and starry eyes. The waters thus -With fish replenished, and the air with fowl, -Evening and morn solemnized the fifth day. -The sixth, and of creation last, arose -With evening harps and matin; when God said, -Let the Earth bring forth soul living in her kind, -Cattle, and creeping things, and beast of the Earth, -Each in their kind. The Earth obeyed, and straight -Opening her fertile womb teemed at a birth -Innumerous living creatures, perfect forms, -Limbed and full grown: Out of the ground up rose, -As from his lair, the wild beast where he wons -In forest wild, in thicket, brake, or den; -Among the trees in pairs they rose, they walked: -The cattle in the fields and meadows green: -Those rare and solitary, these in flocks -Pasturing at once, and in broad herds upsprung. -The grassy clods now calved; now half appeared -The tawny lion, pawing to get free -His hinder parts, then springs as broke from bonds, -And rampant shakes his brinded mane; the ounce, -The libbard, and the tiger, as the mole -Rising, the crumbled earth above them threw -In hillocks: The swift stag from under ground -Bore up his branching head: Scarce from his mould -Behemoth biggest born of earth upheaved -His vastness: Fleeced the flocks and bleating rose, -As plants: Ambiguous between sea and land -The river-horse, and scaly crocodile. -At once came forth whatever creeps the ground, -Insect or worm: those waved their limber fans -For wings, and smallest lineaments exact -In all the liveries decked of summer's pride -With spots of gold and purple, azure and green: -These, as a line, their long dimension drew, -Streaking the ground with sinuous trace; not all -Minims of nature; some of serpent-kind, -Wonderous in length and corpulence, involved -Their snaky folds, and added wings. First crept -The parsimonious emmet, provident -Of future; in small room large heart enclosed; -Pattern of just equality perhaps -Hereafter, joined in her popular tribes -Of commonalty: Swarming next appeared -The female bee, that feeds her husband drone -Deliciously, and builds her waxen cells -With honey stored: The rest are numberless, -And thou their natures knowest, and gavest them names, -Needless to thee repeated; nor unknown -The serpent, subtlest beast of all the field, -Of huge extent sometimes, with brazen eyes -And hairy mane terrifick, though to thee -Not noxious, but obedient at thy call. -Now Heaven in all her glory shone, and rolled -Her motions, as the great first Mover's hand -First wheeled their course: Earth in her rich attire -Consummate lovely smiled; air, water, earth, -By fowl, fish, beast, was flown, was swum, was walked, -Frequent; and of the sixth day yet remained: -There wanted yet the master-work, the end -Of all yet done; a creature, who, not prone -And brute as other creatures, but endued -With sanctity of reason, might erect -His stature, and upright with front serene -Govern the rest, self-knowing; and from thence -Magnanimous to correspond with Heaven, -But grateful to acknowledge whence his good -Descends, thither with heart, and voice, and eyes -Directed in devotion, to adore -And worship God Supreme, who made him chief -Of all his works: therefore the Omnipotent -Eternal Father (for where is not he -Present?) thus to his Son audibly spake. -Let us make now Man in our image, Man -In our similitude, and let them rule -Over the fish and fowl of sea and air, -Beast of the field, and over all the Earth, -And every creeping thing that creeps the ground. -This said, he formed thee, Adam, thee, O Man, -Dust of the ground, and in thy nostrils breathed -The breath of life; in his own image he -Created thee, in the image of God -Express; and thou becamest a living soul. -Male he created thee; but thy consort -Female, for race; then blessed mankind, and said, -Be fruitful, multiply, and fill the Earth; -Subdue it, and throughout dominion hold -Over fish of the sea, and fowl of the air, -And every living thing that moves on the Earth. -Wherever thus created, for no place -Is yet distinct by name, thence, as thou knowest, -He brought thee into this delicious grove, -This garden, planted with the trees of God, -Delectable both to behold and taste; -And freely all their pleasant fruit for food -Gave thee; all sorts are here that all the Earth yields, -Variety without end; but of the tree, -Which, tasted, works knowledge of good and evil, -Thou mayest not; in the day thou eatest, thou diest; -Death is the penalty imposed; beware, -And govern well thy appetite; lest Sin -Surprise thee, and her black attendant Death. -Here finished he, and all that he had made -Viewed, and behold all was entirely good; -So even and morn accomplished the sixth day: -Yet not till the Creator from his work -Desisting, though unwearied, up returned, -Up to the Heaven of Heavens, his high abode; -Thence to behold this new created world, -The addition of his empire, how it showed -In prospect from his throne, how good, how fair, -Answering his great idea. Up he rode -Followed with acclamation, and the sound -Symphonious of ten thousand harps, that tuned -Angelick harmonies: The earth, the air -Resounded, (thou rememberest, for thou heardst,) -The heavens and all the constellations rung, -The planets in their station listening stood, -While the bright pomp ascended jubilant. -Open, ye everlasting gates! they sung, -Open, ye Heavens! your living doors;let in -The great Creator from his work returned -Magnificent, his six days work, a World; -Open, and henceforth oft; for God will deign -To visit oft the dwellings of just men, -Delighted; and with frequent intercourse -Thither will send his winged messengers -On errands of supernal grace. So sung -The glorious train ascending: He through Heaven, -That opened wide her blazing portals, led -To God's eternal house direct the way; -A broad and ample road, whose dust is gold -And pavement stars, as stars to thee appear, -Seen in the galaxy, that milky way, -Which nightly, as a circling zone, thou seest -Powdered with stars. And now on Earth the seventh -Evening arose in Eden, for the sun -Was set, and twilight from the east came on, -Forerunning night; when at the holy mount -Of Heaven's high-seated top, the imperial throne -Of Godhead, fixed for ever firm and sure, -The Filial Power arrived, and sat him down -With his great Father; for he also went -Invisible, yet staid, (such privilege -Hath Omnipresence) and the work ordained, -Author and End of all things; and, from work -Now resting, blessed and hallowed the seventh day, -As resting on that day from all his work, -But not in silence holy kept: the harp -Had work and rested not; the solemn pipe, -And dulcimer, all organs of sweet stop, -All sounds on fret by string or golden wire, -Tempered soft tunings, intermixed with voice -Choral or unison: of incense clouds, -Fuming from golden censers, hid the mount. -Creation and the six days acts they sung: -Great are thy works, Jehovah! infinite -Thy power! what thought can measure thee, or tongue -Relate thee! Greater now in thy return -Than from the giant Angels: Thee that day -Thy thunders magnified; but to create -Is greater than created to destroy. -Who can impair thee, Mighty King, or bound -Thy empire! Easily the proud attempt -Of Spirits apostate, and their counsels vain, -Thou hast repelled; while impiously they thought -Thee to diminish, and from thee withdraw -The number of thy worshippers. Who seeks -To lessen thee, against his purpose serves -To manifest the more thy might: his evil -Thou usest, and from thence createst more good. -Witness this new-made world, another Heaven -From Heaven-gate not far, founded in view -On the clear hyaline, the glassy sea; -Of amplitude almost immense, with stars -Numerous, and every star perhaps a world -Of destined habitation; but thou knowest -Their seasons: among these the seat of Men, -Earth, with her nether ocean circumfused, -Their pleasant dwelling-place. Thrice happy Men, -And sons of Men, whom God hath thus advanced! -Created in his image, there to dwell -And worship him; and in reward to rule -Over his works, on earth, in sea, or air, -And multiply a race of worshippers -Holy and just: Thrice happy, if they know -Their happiness, and persevere upright! -So sung they, and the empyrean rung -With halleluiahs: Thus was sabbath kept. -And thy request think now fulfilled, that asked -How first this world and face of things began, -And what before thy memory was done -From the beginning; that posterity, -Informed by thee, might know: If else thou seekest -Aught, not surpassing human measure, say. - - - -Book VIII - - -The Angel ended, and in Adam's ear -So charming left his voice, that he a while -Thought him still speaking, still stood fixed to hear; -Then, as new waked, thus gratefully replied. -What thanks sufficient, or what recompence -Equal, have I to render thee, divine -Historian, who thus largely hast allayed -The thirst I had of knowledge, and vouchsafed -This friendly condescension to relate -Things, else by me unsearchable; now heard -With wonder, but delight, and, as is due, -With glory attributed to the high -Creator! Something yet of doubt remains, -Which only thy solution can resolve. -When I behold this goodly frame, this world, -Of Heaven and Earth consisting; and compute -Their magnitudes; this Earth, a spot, a grain, -An atom, with the firmament compared -And all her numbered stars, that seem to roll -Spaces incomprehensible, (for such -Their distance argues, and their swift return -Diurnal,) merely to officiate light -Round this opacous Earth, this punctual spot, -One day and night; in all her vast survey -Useless besides; reasoning I oft admire, -How Nature wise and frugal could commit -Such disproportions, with superfluous hand -So many nobler bodies to create, -Greater so manifold, to this one use, -For aught appears, and on their orbs impose -Such restless revolution day by day -Repeated; while the sedentary Earth, -That better might with far less compass move, -Served by more noble than herself, attains -Her end without least motion, and receives, -As tribute, such a sumless journey brought -Of incorporeal speed, her warmth and light; -Speed, to describe whose swiftness number fails. -So spake our sire, and by his countenance seemed -Entering on studious thoughts abstruse; which Eve -Perceiving, where she sat retired in sight, -With lowliness majestick from her seat, -And grace that won who saw to wish her stay, -Rose, and went forth among her fruits and flowers, -To visit how they prospered, bud and bloom, -Her nursery; they at her coming sprung, -And, touched by her fair tendance, gladlier grew. -Yet went she not, as not with such discourse -Delighted, or not capable her ear -Of what was high: such pleasure she reserved, -Adam relating, she sole auditress; -Her husband the relater she preferred -Before the Angel, and of him to ask -Chose rather; he, she knew, would intermix -Grateful digressions, and solve high dispute -With conjugal caresses: from his lip -Not words alone pleased her. O! when meet now -Such pairs, in love and mutual honour joined? -With Goddess-like demeanour forth she went, -Not unattended; for on her, as Queen, -A pomp of winning Graces waited still, -And from about her shot darts of desire -Into all eyes, to wish her still in sight. -And Raphael now, to Adam's doubt proposed, -Benevolent and facile thus replied. -To ask or search, I blame thee not; for Heaven -Is as the book of God before thee set, -Wherein to read his wonderous works, and learn -His seasons, hours, or days, or months, or years: -This to attain, whether Heaven move or Earth, -Imports not, if thou reckon right; the rest -From Man or Angel the great Architect -Did wisely to conceal, and not divulge -His secrets to be scanned by them who ought -Rather admire; or, if they list to try -Conjecture, he his fabrick of the Heavens -Hath left to their disputes, perhaps to move -His laughter at their quaint opinions wide -Hereafter; when they come to model Heaven -And calculate the stars, how they will wield -The mighty frame; how build, unbuild, contrive -To save appearances; how gird the sphere -With centrick and eccentrick scribbled o'er, -Cycle and epicycle, orb in orb: -Already by thy reasoning this I guess, -Who art to lead thy offspring, and supposest -That bodies bright and greater should not serve -The less not bright, nor Heaven such journeys run, -Earth sitting still, when she alone receives -The benefit: Consider first, that great -Or bright infers not excellence: the Earth -Though, in comparison of Heaven, so small, -Nor glistering, may of solid good contain -More plenty than the sun that barren shines; -Whose virtue on itself works no effect, -But in the fruitful Earth; there first received, -His beams, unactive else, their vigour find. -Yet not to Earth are those bright luminaries -Officious; but to thee, Earth's habitant. -And for the Heaven's wide circuit, let it speak -The Maker's high magnificence, who built -So spacious, and his line stretched out so far; -That Man may know he dwells not in his own; -An edifice too large for him to fill, -Lodged in a small partition; and the rest -Ordained for uses to his Lord best known. -The swiftness of those circles attribute, -Though numberless, to his Omnipotence, -That to corporeal substances could add -Speed almost spiritual: Me thou thinkest not slow, -Who since the morning-hour set out from Heaven -Where God resides, and ere mid-day arrived -In Eden; distance inexpressible -By numbers that have name. But this I urge, -Admitting motion in the Heavens, to show -Invalid that which thee to doubt it moved; -Not that I so affirm, though so it seem -To thee who hast thy dwelling here on Earth. -God, to remove his ways from human sense, -Placed Heaven from Earth so far, that earthly sight, -If it presume, might err in things too high, -And no advantage gain. What if the sun -Be center to the world; and other stars, -By his attractive virtue and their own -Incited, dance about him various rounds? -Their wandering course now high, now low, then hid, -Progressive, retrograde, or standing still, -In six thou seest; and what if seventh to these -The planet earth, so stedfast though she seem, -Insensibly three different motions move? -Which else to several spheres thou must ascribe, -Moved contrary with thwart obliquities; -Or save the sun his labour, and that swift -Nocturnal and diurnal rhomb supposed, -Invisible else above all stars, the wheel -Of day and night; which needs not thy belief, -If earth, industrious of herself, fetch day -Travelling east, and with her part averse -From the sun's beam meet night, her other part -Still luminous by his ray. What if that light, -Sent from her through the wide transpicuous air, -To the terrestrial moon be as a star, -Enlightening her by day, as she by night -This earth? reciprocal, if land be there, -Fields and inhabitants: Her spots thou seest -As clouds, and clouds may rain, and rain produce -Fruits in her softened soil for some to eat -Allotted there; and other suns perhaps, -With their attendant moons, thou wilt descry, -Communicating male and female light; -Which two great sexes animate the world, -Stored in each orb perhaps with some that live. -For such vast room in Nature unpossessed -By living soul, desart and desolate, -Only to shine, yet scarce to contribute -Each orb a glimpse of light, conveyed so far -Down to this habitable, which returns -Light back to them, is obvious to dispute. -But whether thus these things, or whether not; -But whether the sun, predominant in Heaven, -Rise on the earth; or earth rise on the sun; -He from the east his flaming road begin; -Or she from west her silent course advance, -With inoffensive pace that spinning sleeps -On her soft axle, while she paces even, -And bears thee soft with the smooth hair along; -Sollicit not thy thoughts with matters hid; -Leave them to God above; him serve, and fear! -Of other creatures, as him pleases best, -Wherever placed, let him dispose; joy thou -In what he gives to thee, this Paradise -And thy fair Eve; Heaven is for thee too high -To know what passes there; be lowly wise: -Think only what concerns thee, and thy being; -Dream not of other worlds, what creatures there -Live, in what state, condition, or degree; -Contented that thus far hath been revealed -Not of Earth only, but of highest Heaven. -To whom thus Adam, cleared of doubt, replied. -How fully hast thou satisfied me, pure -Intelligence of Heaven, Angel serene! -And, freed from intricacies, taught to live -The easiest way; nor with perplexing thoughts -To interrupt the sweet of life, from which -God hath bid dwell far off all anxious cares, -And not molest us; unless we ourselves -Seek them with wandering thoughts, and notions vain. -But apt the mind or fancy is to rove -Unchecked, and of her roving is no end; -Till warned, or by experience taught, she learn, -That, not to know at large of things remote -From use, obscure and subtle; but, to know -That which before us lies in daily life, -Is the prime wisdom: What is more, is fume, -Or emptiness, or fond impertinence: -And renders us, in things that most concern, -Unpractised, unprepared, and still to seek. -Therefore from this high pitch let us descend -A lower flight, and speak of things at hand -Useful; whence, haply, mention may arise -Of something not unseasonable to ask, -By sufferance, and thy wonted favour, deigned. -Thee I have heard relating what was done -Ere my remembrance: now, hear me relate -My story, which perhaps thou hast not heard; -And day is not yet spent; till then thou seest -How subtly to detain thee I devise; -Inviting thee to hear while I relate; -Fond! were it not in hope of thy reply: -For, while I sit with thee, I seem in Heaven; -And sweeter thy discourse is to my ear -Than fruits of palm-tree pleasantest to thirst -And hunger both, from labour, at the hour -Of sweet repast; they satiate, and soon fill, -Though pleasant; but thy words, with grace divine -Imbued, bring to their sweetness no satiety. -To whom thus Raphael answered heavenly meek. -Nor are thy lips ungraceful, Sire of men, -Nor tongue ineloquent; for God on thee -Abundantly his gifts hath also poured -Inward and outward both, his image fair: -Speaking, or mute, all comeliness and grace -Attends thee; and each word, each motion, forms; -Nor less think we in Heaven of thee on Earth -Than of our fellow-servant, and inquire -Gladly into the ways of God with Man: -For God, we see, hath honoured thee, and set -On Man his equal love: Say therefore on; -For I that day was absent, as befel, -Bound on a voyage uncouth and obscure, -Far on excursion toward the gates of Hell; -Squared in full legion (such command we had) -To see that none thence issued forth a spy, -Or enemy, while God was in his work; -Lest he, incensed at such eruption bold, -Destruction with creation might have mixed. -Not that they durst without his leave attempt; -But us he sends upon his high behests -For state, as Sovran King; and to inure -Our prompt obedience. Fast we found, fast shut, -The dismal gates, and barricadoed strong; -But long ere our approaching heard within -Noise, other than the sound of dance or song, -Torment, and loud lament, and furious rage. -Glad we returned up to the coasts of light -Ere sabbath-evening: so we had in charge. -But thy relation now; for I attend, -Pleased with thy words no less than thou with mine. -So spake the Godlike Power, and thus our Sire. -For Man to tell how human life began -Is hard; for who himself beginning knew -Desire with thee still longer to converse -Induced me. As new waked from soundest sleep, -Soft on the flowery herb I found me laid, -In balmy sweat; which with his beams the sun -Soon dried, and on the reeking moisture fed. -Straight toward Heaven my wondering eyes I turned, -And gazed a while the ample sky; till, raised -By quick instinctive motion, up I sprung, -As thitherward endeavouring, and upright -Stood on my feet: about me round I saw -Hill, dale, and shady woods, and sunny plains, -And liquid lapse of murmuring streams; by these, -Creatures that lived and moved, and walked, or flew; -Birds on the branches warbling; all things smiled; -With fragrance and with joy my heart o'erflowed. -Myself I then perused, and limb by limb -Surveyed, and sometimes went, and sometimes ran -With supple joints, as lively vigour led: -But who I was, or where, or from what cause, -Knew not; to speak I tried, and forthwith spake; -My tongue obeyed, and readily could name -Whate'er I saw. Thou Sun, said I, fair light, -And thou enlightened Earth, so fresh and gay, -Ye Hills, and Dales, ye Rivers, Woods, and Plains, -And ye that live and move, fair Creatures, tell, -Tell, if ye saw, how I came thus, how here?-- -Not of myself;--by some great Maker then, -In goodness and in power pre-eminent: -Tell me, how may I know him, how adore, -From whom I have that thus I move and live, -And feel that I am happier than I know.-- -While thus I called, and strayed I knew not whither, -From where I first drew air, and first beheld -This happy light; when, answer none returned, -On a green shady bank, profuse of flowers, -Pensive I sat me down: There gentle sleep -First found me, and with soft oppression seised -My droused sense, untroubled, though I thought -I then was passing to my former state -Insensible, and forthwith to dissolve: -When suddenly stood at my head a dream, -Whose inward apparition gently moved -My fancy to believe I yet had being, -And lived: One came, methought, of shape divine, -And said, 'Thy mansion wants thee, Adam; rise, -'First Man, of men innumerable ordained -'First Father! called by thee, I come thy guide -'To the garden of bliss, thy seat prepared.' -So saying, by the hand he took me raised, -And over fields and waters, as in air -Smooth-sliding without step, last led me up -A woody mountain; whose high top was plain, -A circuit wide, enclosed, with goodliest trees -Planted, with walks, and bowers; that what I saw -Of Earth before scarce pleasant seemed. Each tree, -Loaden with fairest fruit that hung to the eye -Tempting, stirred in me sudden appetite -To pluck and eat; whereat I waked, and found -Before mine eyes all real, as the dream -Had lively shadowed: Here had new begun -My wandering, had not he, who was my guide -Up hither, from among the trees appeared, -Presence Divine. Rejoicing, but with awe, -In adoration at his feet I fell -Submiss: He reared me, and 'Whom thou soughtest I am,' -Said mildly, 'Author of all this thou seest -'Above, or round about thee, or beneath. -'This Paradise I give thee, count it thine -'To till and keep, and of the fruit to eat: -'Of every tree that in the garden grows -'Eat freely with glad heart; fear here no dearth: -'But of the tree whose operation brings -'Knowledge of good and ill, which I have set -'The pledge of thy obedience and thy faith, -'Amid the garden by the tree of life, -'Remember what I warn thee, shun to taste, -'And shun the bitter consequence: for know, -'The day thou eatest thereof, my sole command -'Transgressed, inevitably thou shalt die, -'From that day mortal; and this happy state -'Shalt lose, expelled from hence into a world -'Of woe and sorrow.' Sternly he pronounced -The rigid interdiction, which resounds -Yet dreadful in mine ear, though in my choice -Not to incur; but soon his clear aspect -Returned, and gracious purpose thus renewed. -'Not only these fair bounds, but all the Earth -'To thee and to thy race I give; as lords -'Possess it, and all things that therein live, -'Or live in sea, or air; beast, fish, and fowl. -'In sign whereof, each bird and beast behold -'After their kinds; I bring them to receive -'From thee their names, and pay thee fealty -'With low subjection; understand the same -'Of fish within their watery residence, -'Not hither summoned, since they cannot change -'Their element, to draw the thinner air.' -As thus he spake, each bird and beast behold -Approaching two and two; these cowering low -With blandishment; each bird stooped on his wing. -I named them, as they passed, and understood -Their nature, with such knowledge God endued -My sudden apprehension: But in these -I found not what methought I wanted still; -And to the heavenly Vision thus presumed. -O, by what name, for thou above all these, -Above mankind, or aught than mankind higher, -Surpassest far my naming; how may I -Adore thee, Author of this universe, -And all this good to man? for whose well being -So amply, and with hands so liberal, -Thou hast provided all things: But with me -I see not who partakes. In solitude -What happiness, who can enjoy alone, -Or, all enjoying, what contentment find? -Thus I presumptuous; and the Vision bright, -As with a smile more brightened, thus replied. -What callest thou solitude? Is not the Earth -With various living creatures, and the air -Replenished, and all these at thy command -To come and play before thee? Knowest thou not -Their language and their ways? They also know, -And reason not contemptibly: With these -Find pastime, and bear rule; thy realm is large. -So spake the Universal Lord, and seemed -So ordering: I, with leave of speech implored, -And humble deprecation, thus replied. -Let not my words offend thee, Heavenly Power; -My Maker, be propitious while I speak. -Hast thou not made me here thy substitute, -And these inferiour far beneath me set? -Among unequals what society -Can sort, what harmony, or true delight? -Which must be mutual, in proportion due -Given and received; but, in disparity -The one intense, the other still remiss, -Cannot well suit with either, but soon prove -Tedious alike: Of fellowship I speak -Such as I seek, fit to participate -All rational delight: wherein the brute -Cannot be human consort: They rejoice -Each with their kind, lion with lioness; -So fitly them in pairs thou hast combined: -Much less can bird with beast, or fish with fowl -So well converse, nor with the ox the ape; -Worse then can man with beast, and least of all. -Whereto the Almighty answered, not displeased. -A nice and subtle happiness, I see, -Thou to thyself proposest, in the choice -Of thy associates, Adam! and wilt taste -No pleasure, though in pleasure, solitary. -What thinkest thou then of me, and this my state? -Seem I to thee sufficiently possessed -Of happiness, or not? who am alone -From all eternity; for none I know -Second to me or like, equal much less. -How have I then with whom to hold converse, -Save with the creatures which I made, and those -To me inferiour, infinite descents -Beneath what other creatures are to thee? -He ceased; I lowly answered. To attain -The highth and depth of thy eternal ways -All human thoughts come short, Supreme of things! -Thou in thyself art perfect, and in thee -Is no deficience found: Not so is Man, -But in degree; the cause of his desire -By conversation with his like to help -Or solace his defects. No need that thou -Shouldst propagate, already Infinite; -And through all numbers absolute, though One: -But Man by number is to manifest -His single imperfection, and beget -Like of his like, his image multiplied, -In unity defective; which requires -Collateral love, and dearest amity. -Thou in thy secresy although alone, -Best with thyself accompanied, seekest not -Social communication; yet, so pleased, -Canst raise thy creature to what highth thou wilt -Of union or communion, deified: -I, by conversing, cannot these erect -From prone; nor in their ways complacence find. -Thus I emboldened spake, and freedom used -Permissive, and acceptance found; which gained -This answer from the gracious Voice Divine. -Thus far to try thee, Adam, I was pleased; -And find thee knowing, not of beasts alone, -Which thou hast rightly named, but of thyself; -Expressing well the spirit within thee free, -My image, not imparted to the brute; -Whose fellowship therefore unmeet for thee -Good reason was thou freely shouldst dislike; -And be so minded still: I, ere thou spakest, -Knew it not good for Man to be alone; -And no such company as then thou sawest -Intended thee; for trial only brought, -To see how thou couldest judge of fit and meet: -What next I bring shall please thee, be assured, -Thy likeness, thy fit help, thy other self, -Thy wish exactly to thy heart's desire. -He ended, or I heard no more; for now -My earthly by his heavenly overpowered, -Which it had long stood under, strained to the highth -In that celestial colloquy sublime, -As with an object that excels the sense -Dazzled and spent, sunk down; and sought repair -Of sleep, which instantly fell on me, called -By Nature as in aid, and closed mine eyes. -Mine eyes he closed, but open left the cell -Of fancy, my internal sight; by which, -Abstract as in a trance, methought I saw, -Though sleeping, where I lay, and saw the shape -Still glorious before whom awake I stood: -Who stooping opened my left side, and took -From thence a rib, with cordial spirits warm, -And life-blood streaming fresh; wide was the wound, -But suddenly with flesh filled up and healed: -The rib he formed and fashioned with his hands; -Under his forming hands a creature grew, -Man-like, but different sex; so lovely fair, -That what seemed fair in all the world, seemed now -Mean, or in her summed up, in her contained -And in her looks; which from that time infused -Sweetness into my heart, unfelt before, -And into all things from her air inspired -The spirit of love and amorous delight. -She disappeared, and left me dark; I waked -To find her, or for ever to deplore -Her loss, and other pleasures all abjure: -When out of hope, behold her, not far off, -Such as I saw her in my dream, adorned -With what all Earth or Heaven could bestow -To make her amiable: On she came, -Led by her heavenly Maker, though unseen, -And guided by his voice; nor uninformed -Of nuptial sanctity, and marriage rites: -Grace was in all her steps, Heaven in her eye, -In every gesture dignity and love. -I, overjoyed, could not forbear aloud. -This turn hath made amends; thou hast fulfilled -Thy words, Creator bounteous and benign, -Giver of all things fair! but fairest this -Of all thy gifts! nor enviest. I now see -Bone of my bone, flesh of my flesh, myself -Before me: Woman is her name;of Man -Extracted: for this cause he shall forego -Father and mother, and to his wife adhere; -And they shall be one flesh, one heart, one soul. -She heard me thus; and though divinely brought, -Yet innocence, and virgin modesty, -Her virtue, and the conscience of her worth, -That would be wooed, and not unsought be won, -Not obvious, not obtrusive, but, retired, -The more desirable; or, to say all, -Nature herself, though pure of sinful thought, -Wrought in her so, that, seeing me, she turned: -I followed her; she what was honour knew, -And with obsequious majesty approved -My pleaded reason. To the nuptial bower -I led her blushing like the morn: All Heaven, -And happy constellations, on that hour -Shed their selectest influence; the Earth -Gave sign of gratulation, and each hill; -Joyous the birds; fresh gales and gentle airs -Whispered it to the woods, and from their wings -Flung rose, flung odours from the spicy shrub, -Disporting, till the amorous bird of night -Sung spousal, and bid haste the evening-star -On his hill top, to light the bridal lamp. -Thus have I told thee all my state, and brought -My story to the sum of earthly bliss, -Which I enjoy; and must confess to find -In all things else delight indeed, but such -As, used or not, works in the mind no change, -Nor vehement desire; these delicacies -I mean of taste, sight, smell, herbs, fruits, and flowers, -Walks, and the melody of birds: but here -Far otherwise, transported I behold, -Transported touch; here passion first I felt, -Commotion strange! in all enjoyments else -Superiour and unmoved; here only weak -Against the charm of Beauty's powerful glance. -Or Nature failed in me, and left some part -Not proof enough such object to sustain; -Or, from my side subducting, took perhaps -More than enough; at least on her bestowed -Too much of ornament, in outward show -Elaborate, of inward less exact. -For well I understand in the prime end -Of Nature her the inferiour, in the mind -And inward faculties, which most excel; -In outward also her resembling less -His image who made both, and less expressing -The character of that dominion given -O'er other creatures: Yet when I approach -Her loveliness, so absolute she seems -And in herself complete, so well to know -Her own, that what she wills to do or say, -Seems wisest, virtuousest, discreetest, best: -All higher knowledge in her presence falls -Degraded; Wisdom in discourse with her -Loses discountenanced, and like Folly shows; -Authority and Reason on her wait, -As one intended first, not after made -Occasionally; and, to consummate all, -Greatness of mind and Nobleness their seat -Build in her loveliest, and create an awe -About her, as a guard angelick placed. -To whom the Angel with contracted brow. -Accuse not Nature, she hath done her part; -Do thou but thine; and be not diffident -Of Wisdom; she deserts thee not, if thou -Dismiss not her, when most thou needest her nigh, -By attributing overmuch to things -Less excellent, as thou thyself perceivest. -For, what admirest thou, what transports thee so, -An outside? fair, no doubt, and worthy well -Thy cherishing, thy honouring, and thy love; -Not thy subjection: Weigh with her thyself; -Then value: Oft-times nothing profits more -Than self-esteem, grounded on just and right -Well managed; of that skill the more thou knowest, -The more she will acknowledge thee her head, -And to realities yield all her shows: -Made so adorn for thy delight the more, -So awful, that with honour thou mayest love -Thy mate, who sees when thou art seen least wise. -But if the sense of touch, whereby mankind -Is propagated, seem such dear delight -Beyond all other; think the same vouchsafed -To cattle and each beast; which would not be -To them made common and divulged, if aught -Therein enjoyed were worthy to subdue -The soul of man, or passion in him move. -What higher in her society thou findest -Attractive, human, rational, love still; -In loving thou dost well, in passion not, -Wherein true love consists not: Love refines -The thoughts, and heart enlarges; hath his seat -In reason, and is judicious; is the scale -By which to heavenly love thou mayest ascend, -Not sunk in carnal pleasure; for which cause, -Among the beasts no mate for thee was found. -To whom thus, half abashed, Adam replied. -Neither her outside formed so fair, nor aught -In procreation common to all kinds, -(Though higher of the genial bed by far, -And with mysterious reverence I deem,) -So much delights me, as those graceful acts, -Those thousand decencies, that daily flow -From all her words and actions mixed with love -And sweet compliance, which declare unfeigned -Union of mind, or in us both one soul; -Harmony to behold in wedded pair -More grateful than harmonious sound to the ear. -Yet these subject not; I to thee disclose -What inward thence I feel, not therefore foiled, -Who meet with various objects, from the sense -Variously representing; yet, still free, -Approve the best, and follow what I approve. -To love, thou blamest me not; for Love, thou sayest, -Leads up to Heaven, is both the way and guide; -Bear with me then, if lawful what I ask: -Love not the heavenly Spirits, and how their love -Express they? by looks only? or do they mix -Irradiance, virtual or immediate touch? -To whom the Angel, with a smile that glowed -Celestial rosy red, Love's proper hue, -Answered. Let it suffice thee that thou knowest -Us happy, and without love no happiness. -Whatever pure thou in the body enjoyest, -(And pure thou wert created) we enjoy -In eminence; and obstacle find none -Of membrane, joint, or limb, exclusive bars; -Easier than air with air, if Spirits embrace, -Total they mix, union of pure with pure -Desiring, nor restrained conveyance need, -As flesh to mix with flesh, or soul with soul. -But I can now no more; the parting sun -Beyond the Earth's green Cape and verdant Isles -Hesperian sets, my signal to depart. -Be strong, live happy, and love! But, first of all, -Him, whom to love is to obey, and keep -His great command; take heed lest passion sway -Thy judgement to do aught, which else free will -Would not admit: thine, and of all thy sons, -The weal or woe in thee is placed; beware! -I in thy persevering shall rejoice, -And all the Blest: Stand fast;to stand or fall -Free in thine own arbitrement it lies. -Perfect within, no outward aid require; -And all temptation to transgress repel. -So saying, he arose; whom Adam thus -Followed with benediction. Since to part, -Go, heavenly guest, ethereal Messenger, -Sent from whose sovran goodness I adore! -Gentle to me and affable hath been -Thy condescension, and shall be honoured ever -With grateful memory: Thou to mankind -Be good and friendly still, and oft return! -So parted they; the Angel up to Heaven -From the thick shade, and Adam to his bower. - - - -Book IX - - -No more of talk where God or Angel guest -With Man, as with his friend, familiar us'd, -To sit indulgent, and with him partake -Rural repast; permitting him the while -Venial discourse unblam'd. I now must change -Those notes to tragick; foul distrust, and breach -Disloyal on the part of Man, revolt, -And disobedience: on the part of Heaven -Now alienated, distance and distaste, -Anger and just rebuke, and judgement given, -That brought into this world a world of woe, -Sin and her shadow Death, and Misery -Death's harbinger: Sad talk!yet argument -Not less but more heroick than the wrath -Of stern Achilles on his foe pursued -Thrice fugitive about Troy wall; or rage -Of Turnus for Lavinia disespous'd; -Or Neptune's ire, or Juno's, that so long -Perplexed the Greek, and Cytherea's son: - - 00482129 -If answerable style I can obtain -Of my celestial patroness, who deigns -Her nightly visitation unimplor'd, -And dictates to me slumbering; or inspires -Easy my unpremeditated verse: -Since first this subject for heroick song -Pleas'd me long choosing, and beginning late; -Not sedulous by nature to indite -Wars, hitherto the only argument -Heroick deem'd chief mastery to dissect -With long and tedious havock fabled knights -In battles feign'd; the better fortitude -Of patience and heroick martyrdom -Unsung; or to describe races and games, -Or tilting furniture, imblazon'd shields, -Impresses quaint, caparisons and steeds, -Bases and tinsel trappings, gorgeous knights -At joust and tournament; then marshall'd feast -Serv'd up in hall with sewers and seneshals; -The skill of artifice or office mean, -Not that which justly gives heroick name -To person, or to poem. Me, of these -Nor skill'd nor studious, higher argument -Remains; sufficient of itself to raise -That name, unless an age too late, or cold -Climate, or years, damp my intended wing -Depress'd; and much they may, if all be mine, -Not hers, who brings it nightly to my ear. -The sun was sunk, and after him the star -Of Hesperus, whose office is to bring -Twilight upon the earth, short arbiter -"twixt day and night, and now from end to end -Night's hemisphere had veil'd the horizon round: -When satan, who late fled before the threats -Of Gabriel out of Eden, now improv'd -In meditated fraud and malice, bent -On Man's destruction, maugre what might hap -Of heavier on himself, fearless returned -From compassing the earth; cautious of day, -Since Uriel, regent of the sun, descried -His entrance, and foreworned the Cherubim -That kept their watch; thence full of anguish driven, -The space of seven continued nights he rode -With darkness; thrice the equinoctial line -He circled; four times crossed the car of night -From pole to pole, traversing each colure; -On the eighth returned; and, on the coast averse -From entrance or Cherubick watch, by stealth -Found unsuspected way. There was a place, -Now not, though sin, not time, first wrought the change, -Where Tigris, at the foot of Paradise, -Into a gulf shot under ground, till part -Rose up a fountain by the tree of life: -In with the river sunk, and with it rose -Satan, involved in rising mist; then sought -Where to lie hid; sea he had searched, and land, -From Eden over Pontus and the pool -Maeotis, up beyond the river Ob; -Downward as far antarctick; and in length, -West from Orontes to the ocean barred -At Darien ; thence to the land where flows -Ganges and Indus: Thus the orb he roamed -With narrow search; and with inspection deep -Considered every creature, which of all -Most opportune might serve his wiles; and found -The Serpent subtlest beast of all the field. -Him after long debate, irresolute -Of thoughts revolved, his final sentence chose -Fit vessel, fittest imp of fraud, in whom -To enter, and his dark suggestions hide -From sharpest sight: for, in the wily snake -Whatever sleights, none would suspicious mark, -As from his wit and native subtlety -Proceeding; which, in other beasts observed, -Doubt might beget of diabolick power -Active within, beyond the sense of brute. -Thus he resolved, but first from inward grief -His bursting passion into plaints thus poured. -More justly, seat worthier of Gods, as built -With second thoughts, reforming what was old! -O Earth, how like to Heaven, if not preferred -For what God, after better, worse would build? -Terrestrial Heaven, danced round by other Heavens -That shine, yet bear their bright officious lamps, -Light above light, for thee alone, as seems, -In thee concentring all their precious beams -Of sacred influence! As God in Heaven -Is center, yet extends to all; so thou, -Centring, receivest from all those orbs: in thee, -Not in themselves, all their known virtue appears -Productive in herb, plant, and nobler birth -Of creatures animate with gradual life -Of growth, sense, reason, all summed up in Man. -With what delight could I have walked thee round, -If I could joy in aught, sweet interchange -Of hill, and valley, rivers, woods, and plains, -Now land, now sea and shores with forest crowned, -Rocks, dens, and caves! But I in none of these -Find place or refuge; and the more I see -Pleasures about me, so much more I feel -Torment within me, as from the hateful siege -Of contraries: all good to me becomes -Bane, and in Heaven much worse would be my state. -But neither here seek I, no nor in Heaven -To dwell, unless by mastering Heaven's Supreme; -Nor hope to be myself less miserable -By what I seek, but others to make such -As I, though thereby worse to me redound: -For only in destroying I find ease -To my relentless thoughts; and, him destroyed, -Or won to what may work his utter loss, -For whom all this was made, all this will soon -Follow, as to him linked in weal or woe; -In woe then; that destruction wide may range: -To me shall be the glory sole among -The infernal Powers, in one day to have marred -What he, Almighty styled, six nights and days -Continued making; and who knows how long -Before had been contriving? though perhaps -Not longer than since I, in one night, freed -From servitude inglorious well nigh half -The angelick name, and thinner left the throng -Of his adorers: He, to be avenged, -And to repair his numbers thus impaired, -Whether such virtue spent of old now failed -More Angels to create, if they at least -Are his created, or, to spite us more, -Determined to advance into our room -A creature formed of earth, and him endow, -Exalted from so base original, -With heavenly spoils, our spoils: What he decreed, -He effected; Man he made, and for him built -Magnificent this world, and earth his seat, -Him lord pronounced; and, O indignity! -Subjected to his service angel-wings, -And flaming ministers to watch and tend -Their earthly charge: Of these the vigilance -I dread; and, to elude, thus wrapt in mist -Of midnight vapour glide obscure, and pry -In every bush and brake, where hap may find -The serpent sleeping; in whose mazy folds -To hide me, and the dark intent I bring. -O foul descent! that I, who erst contended -With Gods to sit the highest, am now constrained -Into a beast; and, mixed with bestial slime, -This essence to incarnate and imbrute, -That to the highth of Deity aspired! -But what will not ambition and revenge -Descend to? Who aspires, must down as low -As high he soared; obnoxious, first or last, -To basest things. Revenge, at first though sweet, -Bitter ere long, back on itself recoils: -Let it; I reck not, so it light well aimed, -Since higher I fall short, on him who next -Provokes my envy, this new favourite -Of Heaven, this man of clay, son of despite, -Whom, us the more to spite, his Maker raised -From dust: Spite then with spite is best repaid. -So saying, through each thicket dank or dry, -Like a black mist low-creeping, he held on -His midnight-search, where soonest he might find -The serpent; him fast-sleeping soon he found -In labyrinth of many a round self-rolled, -His head the midst, well stored with subtile wiles: -Not yet in horrid shade or dismal den, -Nor nocent yet; but, on the grassy herb, -Fearless unfeared he slept: in at his mouth -The Devil entered; and his brutal sense, -In heart or head, possessing, soon inspired -With act intelligential; but his sleep -Disturbed not, waiting close the approach of morn. -Now, when as sacred light began to dawn -In Eden on the humid flowers, that breathed -Their morning incense, when all things, that breathe, -From the Earth's great altar send up silent praise -To the Creator, and his nostrils fill -With grateful smell, forth came the human pair, -And joined their vocal worship to the quire -Of creatures wanting voice; that done, partake -The season prime for sweetest scents and airs: -Then commune, how that day they best may ply -Their growing work: for much their work out-grew -The hands' dispatch of two gardening so wide, -And Eve first to her husband thus began. -Adam, well may we labour still to dress -This garden, still to tend plant, herb, and flower, -Our pleasant task enjoined; but, till more hands -Aid us, the work under our labour grows, -Luxurious by restraint; what we by day -Lop overgrown, or prune, or prop, or bind, -One night or two with wanton growth derides -Tending to wild. Thou therefore now advise, -Or bear what to my mind first thoughts present: -Let us divide our labours; thou, where choice -Leads thee, or where most needs, whether to wind -The woodbine round this arbour, or direct -The clasping ivy where to climb; while I, -In yonder spring of roses intermixed -With myrtle, find what to redress till noon: -For, while so near each other thus all day -Our task we choose, what wonder if so near -Looks intervene and smiles, or object new -Casual discourse draw on; which intermits -Our day's work, brought to little, though begun -Early, and the hour of supper comes unearned? -To whom mild answer Adam thus returned. -Sole Eve, associate sole, to me beyond -Compare above all living creatures dear! -Well hast thou motioned, well thy thoughts employed, -How we might best fulfil the work which here -God hath assigned us; nor of me shalt pass -Unpraised: for nothing lovelier can be found -In woman, than to study houshold good, -And good works in her husband to promote. -Yet not so strictly hath our Lord imposed -Labour, as to debar us when we need -Refreshment, whether food, or talk between, -Food of the mind, or this sweet intercourse -Of looks and smiles; for smiles from reason flow, -To brute denied, and are of love the food; -Love, not the lowest end of human life. -For not to irksome toil, but to delight, -He made us, and delight to reason joined. -These paths and bowers doubt not but our joint hands -Will keep from wilderness with ease, as wide -As we need walk, till younger hands ere long -Assist us; But, if much converse perhaps -Thee satiate, to short absence I could yield: -For solitude sometimes is best society, -And short retirement urges sweet return. -But other doubt possesses me, lest harm -Befall thee severed from me; for thou knowest -What hath been warned us, what malicious foe -Envying our happiness, and of his own -Despairing, seeks to work us woe and shame -By sly assault; and somewhere nigh at hand -Watches, no doubt, with greedy hope to find -His wish and best advantage, us asunder; -Hopeless to circumvent us joined, where each -To other speedy aid might lend at need: -Whether his first design be to withdraw -Our fealty from God, or to disturb -Conjugal love, than which perhaps no bliss -Enjoyed by us excites his envy more; -Or this, or worse, leave not the faithful side -That gave thee being, still shades thee, and protects. -The wife, where danger or dishonour lurks, -Safest and seemliest by her husband stays, -Who guards her, or with her the worst endures. -To whom the virgin majesty of Eve, -As one who loves, and some unkindness meets, -With sweet austere composure thus replied. -Offspring of Heaven and Earth, and all Earth's Lord! -That such an enemy we have, who seeks -Our ruin, both by thee informed I learn, -And from the parting Angel over-heard, -As in a shady nook I stood behind, -Just then returned at shut of evening flowers. -But, that thou shouldst my firmness therefore doubt -To God or thee, because we have a foe -May tempt it, I expected not to hear. -His violence thou fearest not, being such -As we, not capable of death or pain, -Can either not receive, or can repel. -His fraud is then thy fear; which plain infers -Thy equal fear, that my firm faith and love -Can by his fraud be shaken or seduced; -Thoughts, which how found they harbour in thy breast, -Adam, mis-thought of her to thee so dear? -To whom with healing words Adam replied. -Daughter of God and Man, immortal Eve! -For such thou art; from sin and blame entire: -Not diffident of thee do I dissuade -Thy absence from my sight, but to avoid -The attempt itself, intended by our foe. -For he who tempts, though in vain, at least asperses -The tempted with dishonour foul; supposed -Not incorruptible of faith, not proof -Against temptation: Thou thyself with scorn -And anger wouldst resent the offered wrong, -Though ineffectual found: misdeem not then, -If such affront I labour to avert -From thee alone, which on us both at once -The enemy, though bold, will hardly dare; -Or daring, first on me the assault shall light. -Nor thou his malice and false guile contemn; -Subtle he needs must be, who could seduce -Angels; nor think superfluous other's aid. -I, from the influence of thy looks, receive -Access in every virtue; in thy sight -More wise, more watchful, stronger, if need were -Of outward strength; while shame, thou looking on, -Shame to be overcome or over-reached, -Would utmost vigour raise, and raised unite. -Why shouldst not thou like sense within thee feel -When I am present, and thy trial choose -With me, best witness of thy virtue tried? -So spake domestick Adam in his care -And matrimonial love; but Eve, who thought -Less attributed to her faith sincere, -Thus her reply with accent sweet renewed. -If this be our condition, thus to dwell -In narrow circuit straitened by a foe, -Subtle or violent, we not endued -Single with like defence, wherever met; -How are we happy, still in fear of harm? -But harm precedes not sin: only our foe, -Tempting, affronts us with his foul esteem -Of our integrity: his foul esteem -Sticks no dishonour on our front, but turns -Foul on himself; then wherefore shunned or feared -By us? who rather double honour gain -From his surmise proved false; find peace within, -Favour from Heaven, our witness, from the event. -And what is faith, love, virtue, unassayed -Alone, without exteriour help sustained? -Let us not then suspect our happy state -Left so imperfect by the Maker wise, -As not secure to single or combined. -Frail is our happiness, if this be so, -And Eden were no Eden, thus exposed. -To whom thus Adam fervently replied. -O Woman, best are all things as the will -Of God ordained them: His creating hand -Nothing imperfect or deficient left -Of all that he created, much less Man, -Or aught that might his happy state secure, -Secure from outward force; within himself -The danger lies, yet lies within his power: -Against his will he can receive no harm. -But God left free the will; for what obeys -Reason, is free; and Reason he made right, -But bid her well be ware, and still erect; -Lest, by some fair-appearing good surprised, -She dictate false; and mis-inform the will -To do what God expressly hath forbid. -Not then mistrust, but tender love, enjoins, -That I should mind thee oft; and mind thou me. -Firm we subsist, yet possible to swerve; -Since Reason not impossibly may meet -Some specious object by the foe suborned, -And fall into deception unaware, -Not keeping strictest watch, as she was warned. -Seek not temptation then, which to avoid -Were better, and most likely if from me -Thou sever not: Trial will come unsought. -Wouldst thou approve thy constancy, approve -First thy obedience; the other who can know, -Not seeing thee attempted, who attest? -But, if thou think, trial unsought may find -Us both securer than thus warned thou seemest, -Go; for thy stay, not free, absents thee more; -Go in thy native innocence, rely -On what thou hast of virtue; summon all! -For God towards thee hath done his part, do thine. -So spake the patriarch of mankind; but Eve -Persisted; yet submiss, though last, replied. -With thy permission then, and thus forewarned -Chiefly by what thy own last reasoning words -Touched only; that our trial, when least sought, -May find us both perhaps far less prepared, -The willinger I go, nor much expect -A foe so proud will first the weaker seek; -So bent, the more shall shame him his repulse. -Thus saying, from her husband's hand her hand -Soft she withdrew; and, like a Wood-Nymph light, -Oread or Dryad, or of Delia's train, -Betook her to the groves; but Delia's self -In gait surpassed, and Goddess-like deport, -Though not as she with bow and quiver armed, -But with such gardening tools as Art yet rude, -Guiltless of fire, had formed, or Angels brought. -To Pales, or Pomona, thus adorned, -Likest she seemed, Pomona when she fled -Vertumnus, or to Ceres in her prime, -Yet virgin of Proserpina from Jove. -Her long with ardent look his eye pursued -Delighted, but desiring more her stay. -Oft he to her his charge of quick return -Repeated; she to him as oft engaged -To be returned by noon amid the bower, -And all things in best order to invite -Noontide repast, or afternoon's repose. -O much deceived, much failing, hapless Eve, -Of thy presumed return! event perverse! -Thou never from that hour in Paradise -Foundst either sweet repast, or sound repose; -Such ambush, hid among sweet flowers and shades, -Waited with hellish rancour imminent -To intercept thy way, or send thee back -Despoiled of innocence, of faith, of bliss! -For now, and since first break of dawn, the Fiend, -Mere serpent in appearance, forth was come; -And on his quest, where likeliest he might find -The only two of mankind, but in them -The whole included race, his purposed prey. -In bower and field he sought, where any tuft -Of grove or garden-plot more pleasant lay, -Their tendance, or plantation for delight; -By fountain or by shady rivulet -He sought them both, but wished his hap might find -Eve separate; he wished, but not with hope -Of what so seldom chanced; when to his wish, -Beyond his hope, Eve separate he spies, -Veiled in a cloud of fragrance, where she stood, -Half spied, so thick the roses blushing round -About her glowed, oft stooping to support -Each flower of slender stalk, whose head, though gay -Carnation, purple, azure, or specked with gold, -Hung drooping unsustained; them she upstays -Gently with myrtle band, mindless the while -Herself, though fairest unsupported flower, -From her best prop so far, and storm so nigh. -Nearer he drew, and many a walk traversed -Of stateliest covert, cedar, pine, or palm; -Then voluble and bold, now hid, now seen, -Among thick-woven arborets, and flowers -Imbordered on each bank, the hand of Eve: -Spot more delicious than those gardens feigned -Or of revived Adonis, or renowned -Alcinous, host of old Laertes' son; -Or that, not mystick, where the sapient king -Held dalliance with his fair Egyptian spouse. -Much he the place admired, the person more. -As one who long in populous city pent, -Where houses thick and sewers annoy the air, -Forth issuing on a summer's morn, to breathe -Among the pleasant villages and farms -Adjoined, from each thing met conceives delight; -The smell of grain, or tedded grass, or kine, -Or dairy, each rural sight, each rural sound; -If chance, with nymph-like step, fair virgin pass, -What pleasing seemed, for her now pleases more; -She most, and in her look sums all delight: -Such pleasure took the Serpent to behold -This flowery plat, the sweet recess of Eve -Thus early, thus alone: Her heavenly form -Angelick, but more soft, and feminine, -Her graceful innocence, her every air -Of gesture, or least action, overawed -His malice, and with rapine sweet bereaved -His fierceness of the fierce intent it brought: -That space the Evil-one abstracted stood -From his own evil, and for the time remained -Stupidly good; of enmity disarmed, -Of guile, of hate, of envy, of revenge: -But the hot Hell that always in him burns, -Though in mid Heaven, soon ended his delight, -And tortures him now more, the more he sees -Of pleasure, not for him ordained: then soon -Fierce hate he recollects, and all his thoughts -Of mischief, gratulating, thus excites. -Thoughts, whither have ye led me! with what sweet -Compulsion thus transported, to forget -What hither brought us! hate, not love;nor hope -Of Paradise for Hell, hope here to taste -Of pleasure; but all pleasure to destroy, -Save what is in destroying; other joy -To me is lost. Then, let me not let pass -Occasion which now smiles; behold alone -The woman, opportune to all attempts, -Her husband, for I view far round, not nigh, -Whose higher intellectual more I shun, -And strength, of courage haughty, and of limb -Heroick built, though of terrestrial mould; -Foe not informidable! exempt from wound, -I not; so much hath Hell debased, and pain -Enfeebled me, to what I was in Heaven. -She fair, divinely fair, fit love for Gods! -Not terrible, though terrour be in love -And beauty, not approached by stronger hate, -Hate stronger, under show of love well feigned; -The way which to her ruin now I tend. -So spake the enemy of mankind, enclosed -In serpent, inmate bad! and toward Eve -Addressed his way: not with indented wave, -Prone on the ground, as since; but on his rear, -Circular base of rising folds, that towered -Fold above fold, a surging maze! his head -Crested aloft, and carbuncle his eyes; -With burnished neck of verdant gold, erect -Amidst his circling spires, that on the grass -Floated redundant: pleasing was his shape -And lovely; never since of serpent-kind -Lovelier, not those that in Illyria changed, -Hermione and Cadmus, or the god -In Epidaurus; nor to which transformed -Ammonian Jove, or Capitoline, was seen; -He with Olympias; this with her who bore -Scipio, the highth of Rome. With tract oblique -At first, as one who sought access, but feared -To interrupt, side-long he works his way. -As when a ship, by skilful steersmen wrought -Nigh river's mouth or foreland, where the wind -Veers oft, as oft so steers, and shifts her sail: -So varied he, and of his tortuous train -Curled many a wanton wreath in sight of Eve, -To lure her eye; she, busied, heard the sound -Of rusling leaves, but minded not, as used -To such disport before her through the field, -From every beast; more duteous at her call, -Than at Circean call the herd disguised. -He, bolder now, uncalled before her stood, -But as in gaze admiring: oft he bowed -His turret crest, and sleek enamelled neck, -Fawning; and licked the ground whereon she trod. -His gentle dumb expression turned at length -The eye of Eve to mark his play; he, glad -Of her attention gained, with serpent-tongue -Organick, or impulse of vocal air, -His fraudulent temptation thus began. -Wonder not, sovran Mistress, if perhaps -Thou canst, who art sole wonder! much less arm -Thy looks, the Heaven of mildness, with disdain, -Displeased that I approach thee thus, and gaze -Insatiate; I thus single;nor have feared -Thy awful brow, more awful thus retired. -Fairest resemblance of thy Maker fair, -Thee all things living gaze on, all things thine -By gift, and thy celestial beauty adore -With ravishment beheld! there best beheld, -Where universally admired; but here -In this enclosure wild, these beasts among, -Beholders rude, and shallow to discern -Half what in thee is fair, one man except, -Who sees thee? and what is one? who should be seen -A Goddess among Gods, adored and served -By Angels numberless, thy daily train. -So glozed the Tempter, and his proem tuned: -Into the heart of Eve his words made way, -Though at the voice much marvelling; at length, -Not unamazed, she thus in answer spake. -What may this mean? language of man pronounced -By tongue of brute, and human sense expressed? -The first, at least, of these I thought denied -To beasts; whom God, on their creation-day, -Created mute to all articulate sound: -The latter I demur; for in their looks -Much reason, and in their actions, oft appears. -Thee, Serpent, subtlest beast of all the field -I knew, but not with human voice endued; -Redouble then this miracle, and say, -How camest thou speakable of mute, and how -To me so friendly grown above the rest -Of brutal kind, that daily are in sight? -Say, for such wonder claims attention due. -To whom the guileful Tempter thus replied. -Empress of this fair world, resplendent Eve! -Easy to me it is to tell thee all -What thou commandest; and right thou shouldst be obeyed: -I was at first as other beasts that graze -The trodden herb, of abject thoughts and low, -As was my food; nor aught but food discerned -Or sex, and apprehended nothing high: -Till, on a day roving the field, I chanced -A goodly tree far distant to behold -Loaden with fruit of fairest colours mixed, -Ruddy and gold: I nearer drew to gaze; -When from the boughs a savoury odour blown, -Grateful to appetite, more pleased my sense -Than smell of sweetest fennel, or the teats -Of ewe or goat dropping with milk at even, -Unsucked of lamb or kid, that tend their play. -To satisfy the sharp desire I had -Of tasting those fair apples, I resolved -Not to defer; hunger and thirst at once, -Powerful persuaders, quickened at the scent -Of that alluring fruit, urged me so keen. -About the mossy trunk I wound me soon; -For, high from ground, the branches would require -Thy utmost reach or Adam's: Round the tree -All other beasts that saw, with like desire -Longing and envying stood, but could not reach. -Amid the tree now got, where plenty hung -Tempting so nigh, to pluck and eat my fill -I spared not; for, such pleasure till that hour, -At feed or fountain, never had I found. -Sated at length, ere long I might perceive -Strange alteration in me, to degree -Of reason in my inward powers; and speech -Wanted not long; though to this shape retained. -Thenceforth to speculations high or deep -I turned my thoughts, and with capacious mind -Considered all things visible in Heaven, -Or Earth, or Middle; all things fair and good: -But all that fair and good in thy divine -Semblance, and in thy beauty's heavenly ray, -United I beheld; no fair to thine -Equivalent or second! which compelled -Me thus, though importune perhaps, to come -And gaze, and worship thee of right declared -Sovran of creatures, universal Dame! -So talked the spirited sly Snake; and Eve, -Yet more amazed, unwary thus replied. -Serpent, thy overpraising leaves in doubt -The virtue of that fruit, in thee first proved: -But say, where grows the tree? from hence how far? -For many are the trees of God that grow -In Paradise, and various, yet unknown -To us; in such abundance lies our choice, -As leaves a greater store of fruit untouched, -Still hanging incorruptible, till men -Grow up to their provision, and more hands -Help to disburden Nature of her birth. -To whom the wily Adder, blithe and glad. -Empress, the way is ready, and not long; -Beyond a row of myrtles, on a flat, -Fast by a fountain, one small thicket past -Of blowing myrrh and balm: if thou accept -My conduct, I can bring thee thither soon -Lead then, said Eve. He, leading, swiftly rolled -In tangles, and made intricate seem straight, -To mischief swift. Hope elevates, and joy -Brightens his crest; as when a wandering fire, -Compact of unctuous vapour, which the night -Condenses, and the cold environs round, -Kindled through agitation to a flame, -Which oft, they say, some evil Spirit attends, -Hovering and blazing with delusive light, -Misleads the amazed night-wanderer from his way -To bogs and mires, and oft through pond or pool; -There swallowed up and lost, from succour far. -So glistered the dire Snake, and into fraud -Led Eve, our credulous mother, to the tree -Of prohibition, root of all our woe; -Which when she saw, thus to her guide she spake. -Serpent, we might have spared our coming hither, -Fruitless to me, though fruit be here to excess, -The credit of whose virtue rest with thee; -Wonderous indeed, if cause of such effects. -But of this tree we may not taste nor touch; -God so commanded, and left that command -Sole daughter of his voice; the rest, we live -Law to ourselves; our reason is our law. -To whom the Tempter guilefully replied. -Indeed! hath God then said that of the fruit -Of all these garden-trees ye shall not eat, -Yet Lords declared of all in earth or air$? -To whom thus Eve, yet sinless. Of the fruit -Of each tree in the garden we may eat; -But of the fruit of this fair tree amidst -The garden, God hath said, Ye shall not eat -Thereof, nor shall ye touch it, lest ye die. -She scarce had said, though brief, when now more bold -The Tempter, but with show of zeal and love -To Man, and indignation at his wrong, -New part puts on; and, as to passion moved, -Fluctuates disturbed, yet comely and in act -Raised, as of some great matter to begin. -As when of old some orator renowned, -In Athens or free Rome, where eloquence -Flourished, since mute! to some great cause addressed, -Stood in himself collected; while each part, -Motion, each act, won audience ere the tongue; -Sometimes in highth began, as no delay -Of preface brooking, through his zeal of right: -So standing, moving, or to highth up grown, -The Tempter, all impassioned, thus began. -O sacred, wise, and wisdom-giving Plant, -Mother of science! now I feel thy power -Within me clear; not only to discern -Things in their causes, but to trace the ways -Of highest agents, deemed however wise. -Queen of this universe! do not believe -Those rigid threats of death: ye shall not die: -How should you? by the fruit? it gives you life -To knowledge; by the threatener? look on me, -Me, who have touched and tasted; yet both live, -And life more perfect have attained than Fate -Meant me, by venturing higher than my lot. -Shall that be shut to Man, which to the Beast -Is open? or will God incense his ire -For such a petty trespass? and not praise -Rather your dauntless virtue, whom the pain -Of death denounced, whatever thing death be, -Deterred not from achieving what might lead -To happier life, knowledge of good and evil; -Of good, how just? of evil, if what is evil -Be real, why not known, since easier shunned? -God therefore cannot hurt ye, and be just; -Not just, not God; not feared then, nor obeyed: -Your fear itself of death removes the fear. -Why then was this forbid? Why, but to awe; -Why, but to keep ye low and ignorant, -His worshippers? He knows that in the day -Ye eat thereof, your eyes that seem so clear, -Yet are but dim, shall perfectly be then -Opened and cleared, and ye shall be as Gods, -Knowing both good and evil, as they know. -That ye shall be as Gods, since I as Man, -Internal Man, is but proportion meet; -I, of brute, human; ye, of human, Gods. -So ye shall die perhaps, by putting off -Human, to put on Gods; death to be wished, -Though threatened, which no worse than this can bring. -And what are Gods, that Man may not become -As they, participating God-like food? -The Gods are first, and that advantage use -On our belief, that all from them proceeds: -I question it; for this fair earth I see, -Warmed by the sun, producing every kind; -Them, nothing: if they all things, who enclosed -Knowledge of good and evil in this tree, -That whoso eats thereof, forthwith attains -Wisdom without their leave? and wherein lies -The offence, that Man should thus attain to know? -What can your knowledge hurt him, or this tree -Impart against his will, if all be his? -Or is it envy? and can envy dwell -In heavenly breasts? These, these, and many more -Causes import your need of this fair fruit. -Goddess humane, reach then, and freely taste! -He ended; and his words, replete with guile, -Into her heart too easy entrance won: -Fixed on the fruit she gazed, which to behold -Might tempt alone; and in her ears the sound -Yet rung of his persuasive words, impregned -With reason, to her seeming, and with truth: -Mean while the hour of noon drew on, and waked -An eager appetite, raised by the smell -So savoury of that fruit, which with desire, -Inclinable now grown to touch or taste, -Solicited her longing eye; yet first -Pausing a while, thus to herself she mused. -Great are thy virtues, doubtless, best of fruits, -Though kept from man, and worthy to be admired; -Whose taste, too long forborn, at first assay -Gave elocution to the mute, and taught -The tongue not made for speech to speak thy praise: -Thy praise he also, who forbids thy use, -Conceals not from us, naming thee the tree -Of knowledge, knowledge both of good and evil; -Forbids us then to taste! but his forbidding -Commends thee more, while it infers the good -By thee communicated, and our want: -For good unknown sure is not had; or, had -And yet unknown, is as not had at all. -In plain then, what forbids he but to know, -Forbids us good, forbids us to be wise? -Such prohibitions bind not. But, if death -Bind us with after-bands, what profits then -Our inward freedom? In the day we eat -Of this fair fruit, our doom is, we shall die! -How dies the Serpent? he hath eaten and lives, -And knows, and speaks, and reasons, and discerns, -Irrational till then. For us alone -Was death invented? or to us denied -This intellectual food, for beasts reserved? -For beasts it seems: yet that one beast which first -Hath tasted envies not, but brings with joy -The good befallen him, author unsuspect, -Friendly to man, far from deceit or guile. -What fear I then? rather, what know to fear -Under this ignorance of good and evil, -Of God or death, of law or penalty? -Here grows the cure of all, this fruit divine, -Fair to the eye, inviting to the taste, -Of virtue to make wise: What hinders then -To reach, and feed at once both body and mind? -So saying, her rash hand in evil hour -Forth reaching to the fruit, she plucked, she eat! -Earth felt the wound; and Nature from her seat, -Sighing through all her works, gave signs of woe, -That all was lost. Back to the thicket slunk -The guilty Serpent; and well might;for Eve, -Intent now wholly on her taste, nought else -Regarded; such delight till then, as seemed, -In fruit she never tasted, whether true -Or fancied so, through expectation high -Of knowledge; not was Godhead from her thought. -Greedily she ingorged without restraint, -And knew not eating death: Satiate at length, -And hightened as with wine, jocund and boon, -Thus to herself she pleasingly began. -O sovran, virtuous, precious of all trees -In Paradise! of operation blest -To sapience, hitherto obscured, infamed. -And thy fair fruit let hang, as to no end -Created; but henceforth my early care, -Not without song, each morning, and due praise, -Shall tend thee, and the fertile burden ease -Of thy full branches offered free to all; -Till, dieted by thee, I grow mature -In knowledge, as the Gods, who all things know; -Though others envy what they cannot give: -For, had the gift been theirs, it had not here -Thus grown. Experience, next, to thee I owe, -Best guide; not following thee, I had remained -In ignorance; thou openest wisdom's way, -And givest access, though secret she retire. -And I perhaps am secret: Heaven is high, -High, and remote to see from thence distinct -Each thing on Earth; and other care perhaps -May have diverted from continual watch -Our great Forbidder, safe with all his spies -About him. But to Adam in what sort -Shall I appear? shall I to him make known -As yet my change, and give him to partake -Full happiness with me, or rather not, -But keeps the odds of knowledge in my power -Without copartner? so to add what wants -In female sex, the more to draw his love, -And render me more equal; and perhaps, -A thing not undesirable, sometime -Superiour; for, inferiour, who is free -This may be well: But what if God have seen, -And death ensue? then I shall be no more! -And Adam, wedded to another Eve, -Shall live with her enjoying, I extinct; -A death to think! Confirmed then I resolve, -Adam shall share with me in bliss or woe: -So dear I love him, that with him all deaths -I could endure, without him live no life. -So saying, from the tree her step she turned; -But first low reverence done, as to the Power -That dwelt within, whose presence had infused -Into the plant sciential sap, derived -From nectar, drink of Gods. Adam the while, -Waiting desirous her return, had wove -Of choicest flowers a garland, to adorn -Her tresses, and her rural labours crown; -As reapers oft are wont their harvest-queen. -Great joy he promised to his thoughts, and new -Solace in her return, so long delayed: -Yet oft his heart, divine of something ill, -Misgave him; he the faltering measure felt; -And forth to meet her went, the way she took -That morn when first they parted: by the tree -Of knowledge he must pass; there he her met, -Scarce from the tree returning; in her hand -A bough of fairest fruit, that downy smiled, -New gathered, and ambrosial smell diffused. -To him she hasted; in her face excuse -Came prologue, and apology too prompt; -Which, with bland words at will, she thus addressed. -Hast thou not wondered, Adam, at my stay? -Thee I have missed, and thought it long, deprived -Thy presence; agony of love till now -Not felt, nor shall be twice; for never more -Mean I to try, what rash untried I sought, -The pain of absence from thy sight. But strange -Hath been the cause, and wonderful to hear: -This tree is not, as we are told, a tree -Of danger tasted, nor to evil unknown -Opening the way, but of divine effect -To open eyes, and make them Gods who taste; -And hath been tasted such: The serpent wise, -Or not restrained as we, or not obeying, -Hath eaten of the fruit; and is become, -Not dead, as we are threatened, but thenceforth -Endued with human voice and human sense, -Reasoning to admiration; and with me -Persuasively hath so prevailed, that I -Have also tasted, and have also found -The effects to correspond; opener mine eyes, -Dim erst, dilated spirits, ampler heart, -And growing up to Godhead; which for thee -Chiefly I sought, without thee can despise. -For bliss, as thou hast part, to me is bliss; -Tedious, unshared with thee, and odious soon. -Thou therefore also taste, that equal lot -May join us, equal joy, as equal love; -Lest, thou not tasting, different degree -Disjoin us, and I then too late renounce -Deity for thee, when Fate will not permit. -Thus Eve with countenance blithe her story told; -But in her cheek distemper flushing glowed. -On the other side Adam, soon as he heard -The fatal trespass done by Eve, amazed, -Astonied stood and blank, while horrour chill -Ran through his veins, and all his joints relaxed; -From his slack hand the garland wreathed for Eve -Down dropt, and all the faded roses shed: -Speechless he stood and pale, till thus at length -First to himself he inward silence broke. -O fairest of Creation, last and best -Of all God's works, Creature in whom excelled -Whatever can to sight or thought be formed, -Holy, divine, good, amiable, or sweet! -How art thou lost! how on a sudden lost, -Defaced, deflowered, and now to death devote! -Rather, how hast thou yielded to transgress -The strict forbiddance, how to violate -The sacred fruit forbidden! Some cursed fraud -Of enemy hath beguiled thee, yet unknown, -And me with thee hath ruined; for with thee -Certain my resolution is to die: -How can I live without thee! how forego -Thy sweet converse, and love so dearly joined, -To live again in these wild woods forlorn! -Should God create another Eve, and I -Another rib afford, yet loss of thee -Would never from my heart: no, no!I feel -The link of Nature draw me: flesh of flesh, -Bone of my bone thou art, and from thy state -Mine never shall be parted, bliss or woe. -So having said, as one from sad dismay -Recomforted, and after thoughts disturbed -Submitting to what seemed remediless, -Thus in calm mood his words to Eve he turned. -Bold deed thou hast presumed, adventurous Eve, -And peril great provoked, who thus hast dared, -Had it been only coveting to eye -That sacred fruit, sacred to abstinence, -Much more to taste it under ban to touch. -But past who can recall, or done undo? -Not God Omnipotent, nor Fate; yet so -Perhaps thou shalt not die, perhaps the fact -Is not so heinous now, foretasted fruit, -Profaned first by the serpent, by him first -Made common, and unhallowed, ere our taste; -Nor yet on him found deadly; yet he lives; -Lives, as thou saidst, and gains to live, as Man, -Higher degree of life; inducement strong -To us, as likely tasting to attain -Proportional ascent; which cannot be -But to be Gods, or Angels, demi-Gods. -Nor can I think that God, Creator wise, -Though threatening, will in earnest so destroy -Us his prime creatures, dignified so high, -Set over all his works; which in our fall, -For us created, needs with us must fail, -Dependant made; so God shall uncreate, -Be frustrate, do, undo, and labour lose; -Not well conceived of God, who, though his power -Creation could repeat, yet would be loth -Us to abolish, lest the Adversary -Triumph, and say; "Fickle their state whom God -"Most favours; who can please him long? Me first -"He ruined, now Mankind; whom will he next?" -Matter of scorn, not to be given the Foe. -However I with thee have fixed my lot, -Certain to undergo like doom: If death -Consort with thee, death is to me as life; -So forcible within my heart I feel -The bond of Nature draw me to my own; -My own in thee, for what thou art is mine; -Our state cannot be severed; we are one, -One flesh; to lose thee were to lose myself. -So Adam; and thus Eve to him replied. -O glorious trial of exceeding love, -Illustrious evidence, example high! -Engaging me to emulate; but, short -Of thy perfection, how shall I attain, -Adam, from whose dear side I boast me sprung, -And gladly of our union hear thee speak, -One heart, one soul in both; whereof good proof -This day affords, declaring thee resolved, -Rather than death, or aught than death more dread, -Shall separate us, linked in love so dear, -To undergo with me one guilt, one crime, -If any be, of tasting this fair fruit; -Whose virtue for of good still good proceeds, -Direct, or by occasion, hath presented -This happy trial of thy love, which else -So eminently never had been known? -Were it I thought death menaced would ensue -This my attempt, I would sustain alone -The worst, and not persuade thee, rather die -Deserted, than oblige thee with a fact -Pernicious to thy peace; chiefly assured -Remarkably so late of thy so true, -So faithful, love unequalled: but I feel -Far otherwise the event; not death, but life -Augmented, opened eyes, new hopes, new joys, -Taste so divine, that what of sweet before -Hath touched my sense, flat seems to this, and harsh. -On my experience, Adam, freely taste, -And fear of death deliver to the winds. -So saying, she embraced him, and for joy -Tenderly wept; much won, that he his love -Had so ennobled, as of choice to incur -Divine displeasure for her sake, or death. -In recompence for such compliance bad -Such recompence best merits from the bough -She gave him of that fair enticing fruit -With liberal hand: he scrupled not to eat, -Against his better knowledge; not deceived, -But fondly overcome with female charm. -Earth trembled from her entrails, as again -In pangs; and Nature gave a second groan; -Sky loured; and, muttering thunder, some sad drops -Wept at completing of the mortal sin -Original: while Adam took no thought, -Eating his fill; nor Eve to iterate -Her former trespass feared, the more to sooth -Him with her loved society; that now, -As with new wine intoxicated both, -They swim in mirth, and fancy that they feel -Divinity within them breeding wings, -Wherewith to scorn the earth: But that false fruit -Far other operation first displayed, -Carnal desire inflaming; he on Eve -Began to cast lascivious eyes; she him -As wantonly repaid; in lust they burn: -Till Adam thus 'gan Eve to dalliance move. -Eve, now I see thou art exact of taste, -And elegant, of sapience no small part; -Since to each meaning savour we apply, -And palate call judicious; I the praise -Yield thee, so well this day thou hast purveyed. -Much pleasure we have lost, while we abstained -From this delightful fruit, nor known till now -True relish, tasting; if such pleasure be -In things to us forbidden, it might be wished, -For this one tree had been forbidden ten. -But come, so well refreshed, now let us play, -As meet is, after such delicious fare; -For never did thy beauty, since the day -I saw thee first and wedded thee, adorned -With all perfections, so inflame my sense -With ardour to enjoy thee, fairer now -Than ever; bounty of this virtuous tree! -So said he, and forbore not glance or toy -Of amorous intent; well understood -Of Eve, whose eye darted contagious fire. -Her hand he seised; and to a shady bank, -Thick over-head with verdant roof imbowered, -He led her nothing loth; flowers were the couch, -Pansies, and violets, and asphodel, -And hyacinth; Earth's freshest softest lap. -There they their fill of love and love's disport -Took largely, of their mutual guilt the seal, -The solace of their sin; till dewy sleep -Oppressed them, wearied with their amorous play, -Soon as the force of that fallacious fruit, -That with exhilarating vapour bland -About their spirits had played, and inmost powers -Made err, was now exhaled; and grosser sleep, -Bred of unkindly fumes, with conscious dreams -Incumbered, now had left them; up they rose -As from unrest; and, each the other viewing, -Soon found their eyes how opened, and their minds -How darkened; innocence, that as a veil -Had shadowed them from knowing ill, was gone; -Just confidence, and native righteousness, -And honour, from about them, naked left -To guilty Shame; he covered, but his robe -Uncovered more. So rose the Danite strong, -Herculean Samson, from the harlot-lap -Of Philistean Dalilah, and waked -Shorn of his strength. They destitute and bare -Of all their virtue: Silent, and in face -Confounded, long they sat, as strucken mute: -Till Adam, though not less than Eve abashed, -At length gave utterance to these words constrained. -O Eve, in evil hour thou didst give ear -To that false worm, of whomsoever taught -To counterfeit Man's voice; true in our fall, -False in our promised rising; since our eyes -Opened we find indeed, and find we know -Both good and evil; good lost, and evil got; -Bad fruit of knowledge, if this be to know; -Which leaves us naked thus, of honour void, -Of innocence, of faith, of purity, -Our wonted ornaments now soiled and stained, -And in our faces evident the signs -Of foul concupiscence; whence evil store; -Even shame, the last of evils; of the first -Be sure then.--How shall I behold the face -Henceforth of God or Angel, erst with joy -And rapture so oft beheld? Those heavenly shapes -Will dazzle now this earthly with their blaze -Insufferably bright. O! might I here -In solitude live savage; in some glade -Obscured, where highest woods, impenetrable -To star or sun-light, spread their umbrage broad -And brown as evening: Cover me, ye Pines! -Ye Cedars, with innumerable boughs -Hide me, where I may never see them more!-- -But let us now, as in bad plight, devise -What best may for the present serve to hide -The parts of each from other, that seem most -To shame obnoxious, and unseemliest seen; -Some tree, whose broad smooth leaves together sewed, -And girded on our loins, may cover round -Those middle parts; that this new comer, Shame, -There sit not, and reproach us as unclean. -So counselled he, and both together went -Into the thickest wood; there soon they chose -The fig-tree; not that kind for fruit renowned, -But such as at this day, to Indians known, -In Malabar or Decan spreads her arms -Branching so broad and long, that in the ground -The bended twigs take root, and daughters grow -About the mother tree, a pillared shade -High over-arched, and echoing walks between: -There oft the Indian herdsman, shunning heat, -Shelters in cool, and tends his pasturing herds -At loop-holes cut through thickest shade: Those leaves -They gathered, broad as Amazonian targe; -And, with what skill they had, together sewed, -To gird their waist; vain covering, if to hide -Their guilt and dreaded shame! O, how unlike -To that first naked glory! Such of late -Columbus found the American, so girt -With feathered cincture; naked else, and wild -Among the trees on isles and woody shores. -Thus fenced, and, as they thought, their shame in part -Covered, but not at rest or ease of mind, -They sat them down to weep; nor only tears -Rained at their eyes, but high winds worse within -Began to rise, high passions, anger, hate, -Mistrust, suspicion, discord; and shook sore -Their inward state of mind, calm region once -And full of peace, now tost and turbulent: -For Understanding ruled not, and the Will -Heard not her lore; both in subjection now -To sensual Appetite, who from beneath -Usurping over sovran Reason claimed -Superiour sway: From thus distempered breast, -Adam, estranged in look and altered style, -Speech intermitted thus to Eve renewed. -Would thou hadst hearkened to my words, and staid -With me, as I besought thee, when that strange -Desire of wandering, this unhappy morn, -I know not whence possessed thee; we had then -Remained still happy; not, as now, despoiled -Of all our good; shamed, naked, miserable! -Let none henceforth seek needless cause to approve -The faith they owe; when earnestly they seek -Such proof, conclude, they then begin to fail. -To whom, soon moved with touch of blame, thus Eve. -What words have passed thy lips, Adam severe! -Imputest thou that to my default, or will -Of wandering, as thou callest it, which who knows -But might as ill have happened thou being by, -Or to thyself perhaps? Hadst thou been there, -Or here the attempt, thou couldst not have discerned -Fraud in the Serpent, speaking as he spake; -No ground of enmity between us known, -Why he should mean me ill, or seek to harm. -Was I to have never parted from thy side? -As good have grown there still a lifeless rib. -Being as I am, why didst not thou, the head, -Command me absolutely not to go, -Going into such danger, as thou saidst? -Too facile then, thou didst not much gainsay; -Nay, didst permit, approve, and fair dismiss. -Hadst thou been firm and fixed in thy dissent, -Neither had I transgressed, nor thou with me. -To whom, then first incensed, Adam replied. -Is this the love, is this the recompence -Of mine to thee, ingrateful Eve! expressed -Immutable, when thou wert lost, not I; -Who might have lived, and joyed immortal bliss, -Yet willingly chose rather death with thee? -And am I now upbraided as the cause -Of thy transgressing? Not enough severe, -It seems, in thy restraint: What could I more -I warned thee, I admonished thee, foretold -The danger, and the lurking enemy -That lay in wait; beyond this, had been force; -And force upon free will hath here no place. -But confidence then bore thee on; secure -Either to meet no danger, or to find -Matter of glorious trial; and perhaps -I also erred, in overmuch admiring -What seemed in thee so perfect, that I thought -No evil durst attempt thee; but I rue -The errour now, which is become my crime, -And thou the accuser. Thus it shall befall -Him, who, to worth in women overtrusting, -Lets her will rule: restraint she will not brook; -And, left to herself, if evil thence ensue, -She first his weak indulgence will accuse. -Thus they in mutual accusation spent -The fruitless hours, but neither self-condemning; -And of their vain contest appeared no end. - - - -Book X - - -Mean while the heinous and despiteful act -Of Satan, done in Paradise; and how -He, in the serpent, had perverted Eve, -Her husband she, to taste the fatal fruit, -Was known in Heaven; for what can 'scape the eye -Of God all-seeing, or deceive his heart -Omniscient? who, in all things wise and just, -Hindered not Satan to attempt the mind -Of Man, with strength entire and free will armed, -Complete to have discovered and repulsed -Whatever wiles of foe or seeming friend. -For still they knew, and ought to have still remembered, -The high injunction, not to taste that fruit, -Whoever tempted; which they not obeying, -(Incurred what could they less?) the penalty; -And, manifold in sin, deserved to fall. -Up into Heaven from Paradise in haste -The angelick guards ascended, mute, and sad, -For Man; for of his state by this they knew, -Much wondering how the subtle Fiend had stolen -Entrance unseen. Soon as the unwelcome news -From Earth arrived at Heaven-gate, displeased -All were who heard; dim sadness did not spare -That time celestial visages, yet, mixed -With pity, violated not their bliss. -About the new-arrived, in multitudes -The ethereal people ran, to hear and know -How all befel: They towards the throne supreme, -Accountable, made haste, to make appear, -With righteous plea, their utmost vigilance -And easily approved; when the Most High -Eternal Father, from his secret cloud, -Amidst in thunder uttered thus his voice. -Assembled Angels, and ye Powers returned -From unsuccessful charge; be not dismayed, -Nor troubled at these tidings from the earth, -Which your sincerest care could not prevent; -Foretold so lately what would come to pass, -When first this tempter crossed the gulf from Hell. -I told ye then he should prevail, and speed -On his bad errand; Man should be seduced, -And flattered out of all, believing lies -Against his Maker; no decree of mine -Concurring to necessitate his fall, -Or touch with lightest moment of impulse -His free will, to her own inclining left -In even scale. But fallen he is; and now -What rests, but that the mortal sentence pass -On his transgression,--death denounced that day? -Which he presumes already vain and void, -Because not yet inflicted, as he feared, -By some immediate stroke; but soon shall find -Forbearance no acquittance, ere day end. -Justice shall not return as bounty scorned. -But whom send I to judge them? whom but thee, -Vicegerent Son? To thee I have transferred -All judgement, whether in Heaven, or Earth, or Hell. -Easy it may be seen that I intend -Mercy colleague with justice, sending thee -Man's friend, his Mediator, his designed -Both ransom and Redeemer voluntary, -And destined Man himself to judge Man fallen. -So spake the Father; and, unfolding bright -Toward the right hand his glory, on the Son -Blazed forth unclouded Deity: He full -Resplendent all his Father manifest -Expressed, and thus divinely answered mild. -Father Eternal, thine is to decree; -Mine, both in Heaven and Earth, to do thy will -Supreme; that thou in me, thy Son beloved, -Mayest ever rest well pleased. I go to judge -On earth these thy transgressours; but thou knowest, -Whoever judged, the worst on me must light, -When time shall be; for so I undertook -Before thee; and, not repenting, this obtain -Of right, that I may mitigate their doom -On me derived; yet I shall temper so -Justice with mercy, as may illustrate most -Them fully satisfied, and thee appease. -Attendance none shall need, nor train, where none -Are to behold the judgement, but the judged, -Those two; the third best absent is condemned, -Convict by flight, and rebel to all law: -Conviction to the serpent none belongs. -Thus saying, from his radiant seat he rose -Of high collateral glory: Him Thrones, and Powers, -Princedoms, and Dominations ministrant, -Accompanied to Heaven-gate; from whence -Eden, and all the coast, in prospect lay. -Down he descended straight; the speed of Gods -Time counts not, though with swiftest minutes winged. -Now was the sun in western cadence low -From noon, and gentle airs, due at their hour, -To fan the earth now waked, and usher in -The evening cool; when he, from wrath more cool, -Came the mild Judge, and Intercessour both, -To sentence Man: The voice of God they heard -Now walking in the garden, by soft winds -Brought to their ears, while day declined; they heard, -And from his presence hid themselves among -The thickest trees, both man and wife; till God, -Approaching, thus to Adam called aloud. -Where art thou, Adam, wont with joy to meet -My coming seen far off? I miss thee here, -Not pleased, thus entertained with solitude, -Where obvious duty ere while appeared unsought: -Or come I less conspicuous, or what change -Absents thee, or what chance detains?--Come forth! -He came; and with him Eve, more loth, though first -To offend; discountenanced both, and discomposed; -Love was not in their looks, either to God, -Or to each other; but apparent guilt, -And shame, and perturbation, and despair, -Anger, and obstinacy, and hate, and guile. -Whence Adam, faltering long, thus answered brief. -I heard thee in the garden, and of thy voice -Afraid, being naked, hid myself. To whom -The gracious Judge without revile replied. -My voice thou oft hast heard, and hast not feared, -But still rejoiced; how is it now become -So dreadful to thee? That thou art naked, who -Hath told thee? Hast thou eaten of the tree, -Whereof I gave thee charge thou shouldst not eat? -To whom thus Adam sore beset replied. -O Heaven! in evil strait this day I stand -Before my Judge; either to undergo -Myself the total crime, or to accuse -My other self, the partner of my life; -Whose failing, while her faith to me remains, -I should conceal, and not expose to blame -By my complaint: but strict necessity -Subdues me, and calamitous constraint; -Lest on my head both sin and punishment, -However insupportable, be all -Devolved; though should I hold my peace, yet thou -Wouldst easily detect what I conceal.-- -This Woman, whom thou madest to be my help, -And gavest me as thy perfect gift, so good, -So fit, so acceptable, so divine, -That from her hand I could suspect no ill, -And what she did, whatever in itself, -Her doing seemed to justify the deed; -She gave me of the tree, and I did eat. -To whom the Sovran Presence thus replied. -Was she thy God, that her thou didst obey -Before his voice? or was she made thy guide, -Superiour, or but equal, that to her -Thou didst resign thy manhood, and the place -Wherein God set thee above her made of thee, -And for thee, whose perfection far excelled -Hers in all real dignity? Adorned -She was indeed, and lovely, to attract -Thy love, not thy subjection; and her gifts -Were such, as under government well seemed; -Unseemly to bear rule; which was thy part -And person, hadst thou known thyself aright. -So having said, he thus to Eve in few. -Say, Woman, what is this which thou hast done? -To whom sad Eve, with shame nigh overwhelmed, -Confessing soon, yet not before her Judge -Bold or loquacious, thus abashed replied. -The Serpent me beguiled, and I did eat. -Which when the Lord God heard, without delay -To judgement he proceeded on the accused -Serpent, though brute; unable to transfer -The guilt on him, who made him instrument -Of mischief, and polluted from the end -Of his creation; justly then accursed, -As vitiated in nature: More to know -Concerned not Man, (since he no further knew) -Nor altered his offence; yet God at last -To Satan first in sin his doom applied, -Though in mysterious terms, judged as then best: -And on the Serpent thus his curse let fall. -Because thou hast done this, thou art accursed -Above all cattle, each beast of the field; -Upon thy belly groveling thou shalt go, -And dust shalt eat all the days of thy life. -Between thee and the woman I will put -Enmity, and between thine and her seed; -Her seed shall bruise thy head, thou bruise his heel. -So spake this oracle, then verified -When Jesus, Son of Mary, second Eve, -Saw Satan fall, like lightning, down from Heaven, -Prince of the air; then, rising from his grave -Spoiled Principalities and Powers, triumphed -In open show; and, with ascension bright, -Captivity led captive through the air, -The realm itself of Satan, long usurped; -Whom he shall tread at last under our feet; -Even he, who now foretold his fatal bruise; -And to the Woman thus his sentence turned. -Thy sorrow I will greatly multiply -By thy conception; children thou shalt bring -In sorrow forth; and to thy husband's will -Thine shall submit; he over thee shall rule. -On Adam last thus judgement he pronounced. -Because thou hast hearkened to the voice of thy wife, -And eaten of the tree, concerning which -I charged thee, saying, Thou shalt not eat thereof: -Cursed is the ground for thy sake; thou in sorrow -Shalt eat thereof, all the days of thy life; -Thorns also and thistles it shall bring thee forth -Unbid; and thou shalt eat the herb of the field; -In the sweat of thy face shalt thou eat bread, -Till thou return unto the ground; for thou -Out of the ground wast taken, know thy birth, -For dust thou art, and shalt to dust return. -So judged he Man, both Judge and Saviour sent; -And the instant stroke of death, denounced that day, -Removed far off; then, pitying how they stood -Before him naked to the air, that now -Must suffer change, disdained not to begin -Thenceforth the form of servant to assume; -As when he washed his servants feet; so now, -As father of his family, he clad -Their nakedness with skins of beasts, or slain, -Or as the snake with youthful coat repaid; -And thought not much to clothe his enemies; -Nor he their outward only with the skins -Of beasts, but inward nakedness, much more. -Opprobrious, with his robe of righteousness, -Arraying, covered from his Father's sight. -To him with swift ascent he up returned, -Into his blissful bosom reassumed -In glory, as of old; to him appeased -All, though all-knowing, what had passed with Man -Recounted, mixing intercession sweet. -Mean while, ere thus was sinned and judged on Earth, -Within the gates of Hell sat Sin and Death, -In counterview within the gates, that now -Stood open wide, belching outrageous flame -Far into Chaos, since the Fiend passed through, -Sin opening; who thus now to Death began. -O Son, why sit we here each other viewing -Idly, while Satan, our great author, thrives -In other worlds, and happier seat provides -For us, his offspring dear? It cannot be -But that success attends him; if mishap, -Ere this he had returned, with fury driven -By his avengers; since no place like this -Can fit his punishment, or their revenge. -Methinks I feel new strength within me rise, -Wings growing, and dominion given me large -Beyond this deep; whatever draws me on, -Or sympathy, or some connatural force, -Powerful at greatest distance to unite, -With secret amity, things of like kind, -By secretest conveyance. Thou, my shade -Inseparable, must with me along; -For Death from Sin no power can separate. -But, lest the difficulty of passing back -Stay his return perhaps over this gulf -Impassable, impervious; let us try -Adventurous work, yet to thy power and mine -Not unagreeable, to found a path -Over this main from Hell to that new world, -Where Satan now prevails; a monument -Of merit high to all the infernal host, -Easing their passage hence, for intercourse, -Or transmigration, as their lot shall lead. -Nor can I miss the way, so strongly drawn -By this new-felt attraction and instinct. -Whom thus the meager Shadow answered soon. -Go, whither Fate, and inclination strong, -Leads thee; I shall not lag behind, nor err -The way, thou leading; such a scent I draw -Of carnage, prey innumerable, and taste -The savour of death from all things there that live: -Nor shall I to the work thou enterprisest -Be wanting, but afford thee equal aid. -So saying, with delight he snuffed the smell -Of mortal change on earth. As when a flock -Of ravenous fowl, though many a league remote, -Against the day of battle, to a field, -Where armies lie encamped, come flying, lured -With scent of living carcasses designed -For death, the following day, in bloody fight: -So scented the grim Feature, and upturned -His nostril wide into the murky air; -Sagacious of his quarry from so far. -Then both from out Hell-gates, into the waste -Wide anarchy of Chaos, damp and dark, -Flew diverse; and with power (their power was great) -Hovering upon the waters, what they met -Solid or slimy, as in raging sea -Tost up and down, together crouded drove, -From each side shoaling towards the mouth of Hell; -As when two polar winds, blowing adverse -Upon the Cronian sea, together drive -Mountains of ice, that stop the imagined way -Beyond Petsora eastward, to the rich -Cathaian coast. The aggregated soil -Death with his mace petrifick, cold and dry, -As with a trident, smote; and fixed as firm -As Delos, floating once; the rest his look -Bound with Gorgonian rigour not to move; -And with Asphaltick slime, broad as the gate, -Deep to the roots of Hell the gathered beach -They fastened, and the mole immense wrought on -Over the foaming deep high-arched, a bridge -Of length prodigious, joining to the wall -Immoveable of this now fenceless world, -Forfeit to Death; from hence a passage broad, -Smooth, easy, inoffensive, down to Hell. -So, if great things to small may be compared, -Xerxes, the liberty of Greece to yoke, -From Susa, his Memnonian palace high, -Came to the sea: and, over Hellespont -Bridging his way, Europe with Asia joined, -And scourged with many a stroke the indignant waves. -Now had they brought the work by wonderous art -Pontifical, a ridge of pendant rock, -Over the vexed abyss, following the track -Of Satan to the self-same place where he -First lighted from his wing, and landed safe -From out of Chaos, to the outside bare -Of this round world: With pins of adamant -And chains they made all fast, too fast they made -And durable! And now in little space -The confines met of empyrean Heaven, -And of this World; and, on the left hand, Hell -With long reach interposed; three several ways -In sight, to each of these three places led. -And now their way to Earth they had descried, -To Paradise first tending; when, behold! -Satan, in likeness of an Angel bright, -Betwixt the Centaur and the Scorpion steering -His zenith, while the sun in Aries rose: -Disguised he came; but those his children dear -Their parent soon discerned, though in disguise. -He, after Eve seduced, unminded slunk -Into the wood fast by; and, changing shape, -To observe the sequel, saw his guileful act -By Eve, though all unweeting, seconded -Upon her husband; saw their shame that sought -Vain covertures; but when he saw descend -The Son of God to judge them, terrified -He fled; not hoping to escape, but shun -The present; fearing, guilty, what his wrath -Might suddenly inflict; that past, returned -By night, and listening where the hapless pair -Sat in their sad discourse, and various plaint, -Thence gathered his own doom; which understood -Not instant, but of future time, with joy -And tidings fraught, to Hell he now returned; -And at the brink of Chaos, near the foot -Of this new wonderous pontifice, unhoped -Met, who to meet him came, his offspring dear. -Great joy was at their meeting, and at sight -Of that stupendious bridge his joy encreased. -Long he admiring stood, till Sin, his fair -Enchanting daughter, thus the silence broke. -O Parent, these are thy magnifick deeds, -Thy trophies! which thou viewest as not thine own; -Thou art their author, and prime architect: -For I no sooner in my heart divined, -My heart, which by a secret harmony -Still moves with thine, joined in connexion sweet, -That thou on earth hadst prospered, which thy looks -Now also evidence, but straight I felt, -Though distant from thee worlds between, yet felt, -That I must after thee, with this thy son; -Such fatal consequence unites us three! -Hell could no longer hold us in our bounds, -Nor this unvoyageable gulf obscure -Detain from following thy illustrious track. -Thou hast achieved our liberty, confined -Within Hell-gates till now; thou us impowered -To fortify thus far, and overlay, -With this portentous bridge, the dark abyss. -Thine now is all this world; thy virtue hath won -What thy hands builded not; thy wisdom gained -With odds what war hath lost, and fully avenged -Our foil in Heaven; here thou shalt monarch reign, -There didst not; there let him still victor sway, -As battle hath adjudged; from this new world -Retiring, by his own doom alienated; -And henceforth monarchy with thee divide -Of all things, parted by the empyreal bounds, -His quadrature, from thy orbicular world; -Or try thee now more dangerous to his throne. -Whom thus the Prince of darkness answered glad. -Fair Daughter, and thou Son and Grandchild both; -High proof ye now have given to be the race -Of Satan (for I glory in the name, -Antagonist of Heaven's Almighty King,) -Amply have merited of me, of all -The infernal empire, that so near Heaven's door -Triumphal with triumphal act have met, -Mine, with this glorious work; and made one realm, -Hell and this world, one realm, one continent -Of easy thorough-fare. Therefore, while I -Descend through darkness, on your road with ease, -To my associate Powers, them to acquaint -With these successes, and with them rejoice; -You two this way, among these numerous orbs, -All yours, right down to Paradise descend; -There dwell, and reign in bliss; thence on the earth -Dominion exercise and in the air, -Chiefly on Man, sole lord of all declared; -Him first make sure your thrall, and lastly kill. -My substitutes I send ye, and create -Plenipotent on earth, of matchless might -Issuing from me: on your joint vigour now -My hold of this new kingdom all depends, -Through Sin to Death exposed by my exploit. -If your joint power prevail, the affairs of Hell -No detriment need fear; go, and be strong! -So saying he dismissed them; they with speed -Their course through thickest constellations held, -Spreading their bane; the blasted stars looked wan, -And planets, planet-struck, real eclipse -Then suffered. The other way Satan went down -The causey to Hell-gate: On either side -Disparted Chaos overbuilt exclaimed, -And with rebounding surge the bars assailed, -That scorned his indignation: Through the gate, -Wide open and unguarded, Satan passed, -And all about found desolate; for those, -Appointed to sit there, had left their charge, -Flown to the upper world; the rest were all -Far to the inland retired, about the walls -Of Pandemonium; city and proud seat -Of Lucifer, so by allusion called -Of that bright star to Satan paragoned; -There kept their watch the legions, while the Grand -In council sat, solicitous what chance -Might intercept their emperour sent; so he -Departing gave command, and they observed. -As when the Tartar from his Russian foe, -By Astracan, over the snowy plains, -Retires; or Bactrin Sophi, from the horns -Of Turkish crescent, leaves all waste beyond -The realm of Aladule, in his retreat -To Tauris or Casbeen: So these, the late -Heaven-banished host, left desart utmost Hell -Many a dark league, reduced in careful watch -Round their metropolis; and now expecting -Each hour their great adventurer, from the search -Of foreign worlds: He through the midst unmarked, -In show plebeian Angel militant -Of lowest order, passed; and from the door -Of that Plutonian hall, invisible -Ascended his high throne; which, under state -Of richest texture spread, at the upper end -Was placed in regal lustre. Down a while -He sat, and round about him saw unseen: -At last, as from a cloud, his fulgent head -And shape star-bright appeared, or brighter; clad -With what permissive glory since his fall -Was left him, or false glitter: All amazed -At that so sudden blaze the Stygian throng -Bent their aspect, and whom they wished beheld, -Their mighty Chief returned: loud was the acclaim: -Forth rushed in haste the great consulting peers, -Raised from their dark Divan, and with like joy -Congratulant approached him; who with hand -Silence, and with these words attention, won. -Thrones, Dominations, Princedoms, Virtues, Powers; -For in possession such, not only of right, -I call ye, and declare ye now; returned -Successful beyond hope, to lead ye forth -Triumphant out of this infernal pit -Abominable, accursed, the house of woe, -And dungeon of our tyrant: Now possess, -As Lords, a spacious world, to our native Heaven -Little inferiour, by my adventure hard -With peril great achieved. Long were to tell -What I have done; what suffered;with what pain -Voyaged th' unreal, vast, unbounded deep -Of horrible confusion; over which -By Sin and Death a broad way now is paved, -To expedite your glorious march; but I -Toiled out my uncouth passage, forced to ride -The untractable abyss, plunged in the womb -Of unoriginal Night and Chaos wild; -That, jealous of their secrets, fiercely opposed -My journey strange, with clamorous uproar -Protesting Fate supreme; thence how I found -The new created world, which fame in Heaven -Long had foretold, a fabrick wonderful -Of absolute perfection! therein Man -Placed in a Paradise, by our exile -Made happy: Him by fraud I have seduced -From his Creator; and, the more to encrease -Your wonder, with an apple; he, thereat -Offended, worth your laughter! hath given up -Both his beloved Man, and all his world, -To Sin and Death a prey, and so to us, -Without our hazard, labour, or alarm; -To range in, and to dwell, and over Man -To rule, as over all he should have ruled. -True is, me also he hath judged, or rather -Me not, but the brute serpent in whose shape -Man I deceived: that which to me belongs, -Is enmity which he will put between -Me and mankind; I am to bruise his heel; -His seed, when is not set, shall bruise my head: -A world who would not purchase with a bruise, -Or much more grievous pain?--Ye have the account -Of my performance: What remains, ye Gods, -But up, and enter now into full bliss? -So having said, a while he stood, expecting -Their universal shout, and high applause, -To fill his ear; when, contrary, he hears -On all sides, from innumerable tongues, -A dismal universal hiss, the sound -Of publick scorn; he wondered, but not long -Had leisure, wondering at himself now more, -His visage drawn he felt to sharp and spare; -His arms clung to his ribs; his legs entwining -Each other, till supplanted down he fell -A monstrous serpent on his belly prone, -Reluctant, but in vain; a greater power -Now ruled him, punished in the shape he sinned, -According to his doom: he would have spoke, -But hiss for hiss returned with forked tongue -To forked tongue; for now were all transformed -Alike, to serpents all, as accessories -To his bold riot: Dreadful was the din -Of hissing through the hall, thick swarming now -With complicated monsters head and tail, -Scorpion, and Asp, and Amphisbaena dire, -Cerastes horned, Hydrus, and Elops drear, -And Dipsas; (not so thick swarmed once the soil -Bedropt with blood of Gorgon, or the isle -Ophiusa,) but still greatest he the midst, -Now Dragon grown, larger than whom the sun -Ingendered in the Pythian vale or slime, -Huge Python, and his power no less he seemed -Above the rest still to retain; they all -Him followed, issuing forth to the open field, -Where all yet left of that revolted rout, -Heaven-fallen, in station stood or just array; -Sublime with expectation when to see -In triumph issuing forth their glorious Chief; -They saw, but other sight instead! a croud -Of ugly serpents; horrour on them fell, -And horrid sympathy; for, what they saw, -They felt themselves, now changing; down their arms, -Down fell both spear and shield; down they as fast; -And the dire hiss renewed, and the dire form -Catched, by contagion; like in punishment, -As in their crime. Thus was the applause they meant, -Turned to exploding hiss, triumph to shame -Cast on themselves from their own mouths. There stood -A grove hard by, sprung up with this their change, -His will who reigns above, to aggravate -Their penance, laden with fair fruit, like that -Which grew in Paradise, the bait of Eve -Used by the Tempter: on that prospect strange -Their earnest eyes they fixed, imagining -For one forbidden tree a multitude -Now risen, to work them further woe or shame; -Yet, parched with scalding thirst and hunger fierce, -Though to delude them sent, could not abstain; -But on they rolled in heaps, and, up the trees -Climbing, sat thicker than the snaky locks -That curled Megaera: greedily they plucked -The fruitage fair to sight, like that which grew -Near that bituminous lake where Sodom flamed; -This more delusive, not the touch, but taste -Deceived; they, fondly thinking to allay -Their appetite with gust, instead of fruit -Chewed bitter ashes, which the offended taste -With spattering noise rejected: oft they assayed, -Hunger and thirst constraining; drugged as oft, -With hatefullest disrelish writhed their jaws, -With soot and cinders filled; so oft they fell -Into the same illusion, not as Man -Whom they triumphed once lapsed. Thus were they plagued -And worn with famine, long and ceaseless hiss, -Till their lost shape, permitted, they resumed; -Yearly enjoined, some say, to undergo, -This annual humbling certain numbered days, -To dash their pride, and joy, for Man seduced. -However, some tradition they dispersed -Among the Heathen, of their purchase got, -And fabled how the Serpent, whom they called -Ophion, with Eurynome, the wide-- -Encroaching Eve perhaps, had first the rule -Of high Olympus; thence by Saturn driven -And Ops, ere yet Dictaean Jove was born. -Mean while in Paradise the hellish pair -Too soon arrived; Sin, there in power before, -Once actual; now in body, and to dwell -Habitual habitant; behind her Death, -Close following pace for pace, not mounted yet -On his pale horse: to whom Sin thus began. -Second of Satan sprung, all-conquering Death! -What thinkest thou of our empire now, though earned -With travel difficult, not better far -Than still at Hell's dark threshold to have sat watch, -Unnamed, undreaded, and thyself half starved? -Whom thus the Sin-born monster answered soon. -To me, who with eternal famine pine, -Alike is Hell, or Paradise, or Heaven; -There best, where most with ravine I may meet; -Which here, though plenteous, all too little seems -To stuff this maw, this vast unhide-bound corps. -To whom the incestuous mother thus replied. -Thou therefore on these herbs, and fruits, and flowers, -Feed first; on each beast next, and fish, and fowl; -No homely morsels! and, whatever thing -The sithe of Time mows down, devour unspared; -Till I, in Man residing, through the race, -His thoughts, his looks, words, actions, all infect; -And season him thy last and sweetest prey. -This said, they both betook them several ways, -Both to destroy, or unimmortal make -All kinds, and for destruction to mature -Sooner or later; which the Almighty seeing, -From his transcendent seat the Saints among, -To those bright Orders uttered thus his voice. -See, with what heat these dogs of Hell advance -To waste and havock yonder world, which I -So fair and good created; and had still -Kept in that state, had not the folly of Man -Let in these wasteful furies, who impute -Folly to me; so doth the Prince of Hell -And his adherents, that with so much ease -I suffer them to enter and possess -A place so heavenly; and, conniving, seem -To gratify my scornful enemies, -That laugh, as if, transported with some fit -Of passion, I to them had quitted all, -At random yielded up to their misrule; -And know not that I called, and drew them thither, -My Hell-hounds, to lick up the draff and filth -Which Man's polluting sin with taint hath shed -On what was pure; til, crammed and gorged, nigh burst -With sucked and glutted offal, at one sling -Of thy victorious arm, well-pleasing Son, -Both Sin, and Death, and yawning Grave, at last, -Through Chaos hurled, obstruct the mouth of Hell -For ever, and seal up his ravenous jaws. -Then Heaven and Earth renewed shall be made pure -To sanctity, that shall receive no stain: -Till then, the curse pronounced on both precedes. -He ended, and the heavenly audience loud -Sung Halleluiah, as the sound of seas, -Through multitude that sung: Just are thy ways, -Righteous are thy decrees on all thy works; -Who can extenuate thee? Next, to the Son, -Destined Restorer of mankind, by whom -New Heaven and Earth shall to the ages rise, -Or down from Heaven descend.--Such was their song; -While the Creator, calling forth by name -His mighty Angels, gave them several charge, -As sorted best with present things. The sun -Had first his precept so to move, so shine, -As might affect the earth with cold and heat -Scarce tolerable; and from the north to call -Decrepit winter; from the south to bring -Solstitial summer's heat. To the blanc moon -Her office they prescribed; to the other five -Their planetary motions, and aspects, -In sextile, square, and trine, and opposite, -Of noxious efficacy, and when to join -In synod unbenign; and taught the fixed -Their influence malignant when to shower, -Which of them rising with the sun, or falling, -Should prove tempestuous: To the winds they set -Their corners, when with bluster to confound -Sea, air, and shore; the thunder when to roll -With terrour through the dark aereal hall. -Some say, he bid his Angels turn ascanse -The poles of earth, twice ten degrees and more, -From the sun's axle; they with labour pushed -Oblique the centrick globe: Some say, the sun -Was bid turn reins from the equinoctial road -Like distant breadth to Taurus with the seven -Atlantick Sisters, and the Spartan Twins, -Up to the Tropick Crab: thence down amain -By Leo, and the Virgin, and the Scales, -As deep as Capricorn; to bring in change -Of seasons to each clime; else had the spring -Perpetual smiled on earth with vernant flowers, -Equal in days and nights, except to those -Beyond the polar circles; to them day -Had unbenighted shone, while the low sun, -To recompense his distance, in their sight -Had rounded still the horizon, and not known -Or east or west; which had forbid the snow -From cold Estotiland, and south as far -Beneath Magellan. At that tasted fruit -The sun, as from Thyestean banquet, turned -His course intended; else, how had the world -Inhabited, though sinless, more than now, -Avoided pinching cold and scorching heat? -These changes in the Heavens, though slow, produced -Like change on sea and land; sideral blast, -Vapour, and mist, and exhalation hot, -Corrupt and pestilent: Now from the north -Of Norumbega, and the Samoed shore, -Bursting their brazen dungeon, armed with ice, -And snow, and hail, and stormy gust and flaw, -Boreas, and Caecias, and Argestes loud, -And Thrascias, rend the woods, and seas upturn; -With adverse blast upturns them from the south -Notus, and Afer black with thunderous clouds -From Serraliona; thwart of these, as fierce, -Forth rush the Levant and the Ponent winds, -Eurus and Zephyr, with their lateral noise, -Sirocco and Libecchio. Thus began -Outrage from lifeless things; but Discord first, -Daughter of Sin, among the irrational -Death introduced, through fierce antipathy: -Beast now with beast 'gan war, and fowl with fowl, -And fish with fish; to graze the herb all leaving, -Devoured each other; nor stood much in awe -Of Man, but fled him; or, with countenance grim, -Glared on him passing. These were from without -The growing miseries, which Adam saw -Already in part, though hid in gloomiest shade, -To sorrow abandoned, but worse felt within; -And, in a troubled sea of passion tost, -Thus to disburden sought with sad complaint. -O miserable of happy! Is this the end -Of this new glorious world, and me so late -The glory of that glory, who now become -Accursed, of blessed? hide me from the face -Of God, whom to behold was then my highth -Of happiness!--Yet well, if here would end -The misery; I deserved it, and would bear -My own deservings; but this will not serve: -All that I eat or drink, or shall beget, -Is propagated curse. O voice, once heard -Delightfully, Encrease and multiply; -Now death to hear! for what can I encrease, -Or multiply, but curses on my head? -Who of all ages to succeed, but, feeling -The evil on him brought by me, will curse -My head? Ill fare our ancestor impure, -For this we may thank Adam! but his thanks -Shall be the execration: so, besides -Mine own that bide upon me, all from me -Shall with a fierce reflux on me rebound; -On me, as on their natural center, light -Heavy, though in their place. O fleeting joys -Of Paradise, dear bought with lasting woes! -Did I request thee, Maker, from my clay -To mould me Man? did I solicit thee -From darkness to promote me, or here place -In this delicious garden? As my will -Concurred not to my being, it were but right -And equal to reduce me to my dust; -Desirous to resign and render back -All I received; unable to perform -Thy terms too hard, by which I was to hold -The good I sought not. To the loss of that, -Sufficient penalty, why hast thou added -The sense of endless woes? Inexplicable -Why am I mocked with death, and lengthened out -To deathless pain? How gladly would I meet -Mortality my sentence, and be earth -Insensible! How glad would lay me down -As in my mother's lap! There I should rest, -And sleep secure; his dreadful voice no more -Would thunder in my ears; no fear of worse -To me, and to my offspring, would torment me -With cruel expectation. Yet one doubt -Pursues me still, lest all I cannot die; -Lest that pure breath of life, the spirit of Man -Which God inspired, cannot together perish -With this corporeal clod; then, in the grave, -Or in some other dismal place, who knows -But I shall die a living death? O thought -Horrid, if true! Yet why? It was but breath -Of life that sinned; what dies but what had life -And sin? The body properly had neither, -All of me then shall die: let this appease -The doubt, since human reach no further knows. -For though the Lord of all be infinite, -Is his wrath also? Be it, Man is not so, -But mortal doomed. How can he exercise -Wrath without end on Man, whom death must end? -Can he make deathless death? That were to make -Strange contradiction, which to God himself -Impossible is held; as argument -Of weakness, not of power. Will he draw out, -For anger's sake, finite to infinite, -In punished Man, to satisfy his rigour, -Satisfied never? That were to extend -His sentence beyond dust and Nature's law; -By which all causes else, according still -To the reception of their matter, act; -Not to the extent of their own sphere. But say -That death be not one stroke, as I supposed, -Bereaving sense, but endless misery -From this day onward; which I feel begun -Both in me, and without me; and so last -To perpetuity;--Ay me!that fear -Comes thundering back with dreadful revolution -On my defenceless head; both Death and I -Am found eternal, and incorporate both; -Nor I on my part single; in me all -Posterity stands cursed: Fair patrimony -That I must leave ye, Sons! O, were I able -To waste it all myself, and leave ye none! -So disinherited, how would you bless -Me, now your curse! Ah, why should all mankind, -For one man's fault, thus guiltless be condemned, -It guiltless? But from me what can proceed, -But all corrupt; both mind and will depraved -Not to do only, but to will the same -With me? How can they then acquitted stand -In sight of God? Him, after all disputes, -Forced I absolve: all my evasions vain, -And reasonings, though through mazes, lead me still -But to my own conviction: first and last -On me, me only, as the source and spring -Of all corruption, all the blame lights due; -So might the wrath! Fond wish!couldst thou support -That burden, heavier than the earth to bear; -Than all the world much heavier, though divided -With that bad Woman? Thus, what thou desirest, -And what thou fearest, alike destroys all hope -Of refuge, and concludes thee miserable -Beyond all past example and future; -To Satan only like both crime and doom. -O Conscience! into what abyss of fears -And horrours hast thou driven me; out of which -I find no way, from deep to deeper plunged! -Thus Adam to himself lamented loud, -Through the still night; not now, as ere Man fell, -Wholesome, and cool, and mild, but with black air -Accompanied; with damps, and dreadful gloom; -Which to his evil conscience represented -All things with double terrour: On the ground -Outstretched he lay, on the cold ground; and oft -Cursed his creation; Death as oft accused -Of tardy execution, since denounced -The day of his offence. Why comes not Death, -Said he, with one thrice-acceptable stroke -To end me? Shall Truth fail to keep her word, -Justice Divine not hasten to be just? -But Death comes not at call; Justice Divine -Mends not her slowest pace for prayers or cries, -O woods, O fountains, hillocks, dales, and bowers! -With other echo late I taught your shades -To answer, and resound far other song.-- -Whom thus afflicted when sad Eve beheld, -Desolate where she sat, approaching nigh, -Soft words to his fierce passion she assayed: -But her with stern regard he thus repelled. -Out of my sight, thou Serpent! That name best -Befits thee with him leagued, thyself as false -And hateful; nothing wants, but that thy shape, -Like his, and colour serpentine, may show -Thy inward fraud; to warn all creatures from thee -Henceforth; lest that too heavenly form, pretended -To hellish falshood, snare them! But for thee -I had persisted happy; had not thy pride -And wandering vanity, when least was safe, -Rejected my forewarning, and disdained -Not to be trusted; longing to be seen, -Though by the Devil himself; him overweening -To over-reach; but, with the serpent meeting, -Fooled and beguiled; by him thou, I by thee -To trust thee from my side; imagined wise, -Constant, mature, proof against all assaults; -And understood not all was but a show, -Rather than solid virtue; all but a rib -Crooked by nature, bent, as now appears, -More to the part sinister, from me drawn; -Well if thrown out, as supernumerary -To my just number found. O! why did God, -Creator wise, that peopled highest Heaven -With Spirits masculine, create at last -This novelty on earth, this fair defect -Of nature, and not fill the world at once -With Men, as Angels, without feminine; -Or find some other way to generate -Mankind? This mischief had not been befallen, -And more that shall befall; innumerable -Disturbances on earth through female snares, -And strait conjunction with this sex: for either -He never shall find out fit mate, but such -As some misfortune brings him, or mistake; -Or whom he wishes most shall seldom gain -Through her perverseness, but shall see her gained -By a far worse; or, if she love, withheld -By parents; or his happiest choice too late -Shall meet, already linked and wedlock-bound -To a fell adversary, his hate or shame: -Which infinite calamity shall cause -To human life, and houshold peace confound. -He added not, and from her turned; but Eve, -Not so repulsed, with tears that ceased not flowing -And tresses all disordered, at his feet -Fell humble; and, embracing them, besought -His peace, and thus proceeded in her plaint. -Forsake me not thus, Adam! witness Heaven -What love sincere, and reverence in my heart -I bear thee, and unweeting have offended, -Unhappily deceived! Thy suppliant -I beg, and clasp thy knees; bereave me not, -Whereon I live, thy gentle looks, thy aid, -Thy counsel, in this uttermost distress, -My only strength and stay: Forlorn of thee, -Whither shall I betake me, where subsist? -While yet we live, scarce one short hour perhaps, -Between us two let there be peace; both joining, -As joined in injuries, one enmity -Against a foe by doom express assigned us, -That cruel Serpent: On me exercise not -Thy hatred for this misery befallen; -On me already lost, me than thyself -More miserable! Both have sinned;but thou -Against God only; I against God and thee; -And to the place of judgement will return, -There with my cries importune Heaven; that all -The sentence, from thy head removed, may light -On me, sole cause to thee of all this woe; -Me, me only, just object of his ire! -She ended weeping; and her lowly plight, -Immoveable, till peace obtained from fault -Acknowledged and deplored, in Adam wrought -Commiseration: Soon his heart relented -Towards her, his life so late, and sole delight, -Now at his feet submissive in distress; -Creature so fair his reconcilement seeking, -His counsel, whom she had displeased, his aid: -As one disarmed, his anger all he lost, -And thus with peaceful words upraised her soon. -Unwary, and too desirous, as before, -So now of what thou knowest not, who desirest -The punishment all on thyself; alas! -Bear thine own first, ill able to sustain -His full wrath, whose thou feelest as yet least part, -And my displeasure bearest so ill. If prayers -Could alter high decrees, I to that place -Would speed before thee, and be louder heard, -That on my head all might be visited; -Thy frailty and infirmer sex forgiven, -To me committed, and by me exposed. -But rise;--let us no more contend, nor blame -Each other, blamed enough elsewhere; but strive -In offices of love, how we may lighten -Each other's burden, in our share of woe; -Since this day's death denounced, if aught I see, -Will prove no sudden, but a slow-paced evil; -A long day's dying, to augment our pain; -And to our seed (O hapless seed!) derived. -To whom thus Eve, recovering heart, replied. -Adam, by sad experiment I know -How little weight my words with thee can find, -Found so erroneous; thence by just event -Found so unfortunate: Nevertheless, -Restored by thee, vile as I am, to place -Of new acceptance, hopeful to regain -Thy love, the sole contentment of my heart -Living or dying, from thee I will not hide -What thoughts in my unquiet breast are risen, -Tending to some relief of our extremes, -Or end; though sharp and sad, yet tolerable, -As in our evils, and of easier choice. -If care of our descent perplex us most, -Which must be born to certain woe, devoured -By Death at last; and miserable it is -To be to others cause of misery, -Our own begotten, and of our loins to bring -Into this cursed world a woeful race, -That after wretched life must be at last -Food for so foul a monster; in thy power -It lies, yet ere conception to prevent -The race unblest, to being yet unbegot. -Childless thou art, childless remain: so Death -Shall be deceived his glut, and with us two -Be forced to satisfy his ravenous maw. -But if thou judge it hard and difficult, -Conversing, looking, loving, to abstain -From love's due rights, nuptial embraces sweet; -And with desire to languish without hope, -Before the present object languishing -With like desire; which would be misery -And torment less than none of what we dread; -Then, both ourselves and seed at once to free -From what we fear for both, let us make short, -- -Let us seek Death; -- or, he not found, supply -With our own hands his office on ourselves: -Why stand we longer shivering under fears, -That show no end but death, and have the power, -Of many ways to die the shortest choosing, -Destruction with destruction to destroy? -- -She ended here, or vehement despair -Broke off the rest: so much of death her thoughts -Had entertained, as dyed her cheeks with pale. -But Adam, with such counsel nothing swayed, -To better hopes his more attentive mind -Labouring had raised; and thus to Eve replied. -Eve, thy contempt of life and pleasure seems -To argue in thee something more sublime -And excellent, than what thy mind contemns; -But self-destruction therefore sought, refutes -That excellence thought in thee; and implies, -Not thy contempt, but anguish and regret -For loss of life and pleasure overloved. -Or if thou covet death, as utmost end -Of misery, so thinking to evade -The penalty pronounced; doubt not but God -Hath wiselier armed his vengeful ire, than so -To be forestalled; much more I fear lest death, -So snatched, will not exempt us from the pain -We are by doom to pay; rather, such acts -Of contumacy will provoke the Highest -To make death in us live: Then let us seek -Some safer resolution, which methinks -I have in view, calling to mind with heed -Part of our sentence, that thy seed shall bruise -The Serpent's head; piteous amends! unless -Be meant, whom I conjecture, our grand foe, -Satan; who, in the serpent, hath contrived -Against us this deceit: To crush his head -Would be revenge indeed! which will be lost -By death brought on ourselves, or childless days -Resolved, as thou proposest; so our foe -Shal 'scape his punishment ordained, and we -Instead shall double ours upon our heads. -No more be mentioned then of violence -Against ourselves; and wilful barrenness, -That cuts us off from hope; and savours only -Rancour and pride, impatience and despite, -Reluctance against God and his just yoke -Laid on our necks. Remember with what mild -And gracious temper he both heard, and judged, -Without wrath or reviling; we expected -Immediate dissolution, which we thought -Was meant by death that day; when lo!to thee -Pains only in child-bearing were foretold, -And bringing forth; soon recompensed with joy, -Fruit of thy womb: On me the curse aslope -Glanced on the ground; with labour I must earn -My bread; what harm? Idleness had been worse; -My labour will sustain me; and, lest cold -Or heat should injure us, his timely care -Hath, unbesought, provided; and his hands -Clothed us unworthy, pitying while he judged; -How much more, if we pray him, will his ear -Be open, and his heart to pity incline, -And teach us further by what means to shun -The inclement seasons, rain, ice, hail, and snow! -Which now the sky, with various face, begins -To show us in this mountain; while the winds -Blow moist and keen, shattering the graceful locks -Of these fair spreading trees; which bids us seek -Some better shroud, some better warmth to cherish -Our limbs benummed, ere this diurnal star -Leave cold the night, how we his gathered beams -Reflected may with matter sere foment; -Or, by collision of two bodies, grind -The air attrite to fire; as late the clouds -Justling, or pushed with winds, rude in their shock, -Tine the slant lightning; whose thwart flame, driven down -Kindles the gummy bark of fir or pine; -And sends a comfortable heat from far, -Which might supply the sun: Such fire to use, -And what may else be remedy or cure -To evils which our own misdeeds have wrought, -He will instruct us praying, and of grace -Beseeching him; so as we need not fear -To pass commodiously this life, sustained -By him with many comforts, till we end -In dust, our final rest and native home. -What better can we do, than, to the place -Repairing where he judged us, prostrate fall -Before him reverent; and there confess -Humbly our faults, and pardon beg; with tears -Watering the ground, and with our sighs the air -Frequenting, sent from hearts contrite, in sign -Of sorrow unfeigned, and humiliation meek - - - -Book XI - - -Undoubtedly he will relent, and turn -From his displeasure; in whose look serene, -When angry most he seemed and most severe, -What else but favour, grace, and mercy, shone? -So spake our father penitent; nor Eve -Felt less remorse: they, forthwith to the place -Repairing where he judged them, prostrate fell -Before him reverent; and both confessed -Humbly their faults, and pardon begged; with tears -Watering the ground, and with their sighs the air -Frequenting, sent from hearts contrite, in sign -Of sorrow unfeigned, and humiliation meek. -Thus they, in lowliest plight, repentant stood -Praying; for from the mercy-seat above -Prevenient grace descending had removed -The stony from their hearts, and made new flesh -Regenerate grow instead; that sighs now breathed -Unutterable; which the Spirit of prayer -Inspired, and winged for Heaven with speedier flight -Than loudest oratory: Yet their port -Not of mean suitors; nor important less -Seemed their petition, than when the ancient pair -In fables old, less ancient yet than these, -Deucalion and chaste Pyrrha, to restore -The race of mankind drowned, before the shrine -Of Themis stood devout. To Heaven their prayers -Flew up, nor missed the way, by envious winds -Blown vagabond or frustrate: in they passed -Dimensionless through heavenly doors; then clad -With incense, where the golden altar fumed, -By their great intercessour, came in sight -Before the Father's throne: them the glad Son -Presenting, thus to intercede began. -See$ Father, what first-fruits on earth are sprung -From thy implanted grace in Man; these sighs -And prayers, which in this golden censer mixed -With incense, I thy priest before thee bring; -Fruits of more pleasing savour, from thy seed -Sown with contrition in his heart, than those -Which, his own hand manuring, all the trees -Of Paradise could have produced, ere fallen -From innocence. Now therefore, bend thine ear -To supplication; hear his sighs, though mute; -Unskilful with what words to pray, let me -Interpret for him; me, his advocate -And propitiation; all his works on me, -Good, or not good, ingraft; my merit those -Shall perfect, and for these my death shall pay. -Accept me; and, in me, from these receive -The smell of peace toward mankind: let him live -Before thee reconciled, at least his days -Numbered, though sad; till death, his doom, (which I -To mitigate thus plead, not to reverse,) -To better life shall yield him: where with me -All my redeemed may dwell in joy and bliss; -Made one with me, as I with thee am one. -To whom the Father, without cloud, serene. -All thy request for Man, accepted Son, -Obtain; all thy request was my decree: -But, longer in that Paradise to dwell, -The law I gave to Nature him forbids: -Those pure immortal elements, that know, -No gross, no unharmonious mixture foul, -Eject him, tainted now; and purge him off, -As a distemper, gross, to air as gross, -And mortal food; as may dispose him best -For dissolution wrought by sin, that first -Distempered all things, and of incorrupt -Corrupted. I, at first, with two fair gifts -Created him endowed; with happiness, -And immortality: that fondly lost, -This other served but to eternize woe; -Till I provided death: so death becomes -His final remedy; and, after life, -Tried in sharp tribulation, and refined -By faith and faithful works, to second life, -Waked in the renovation of the just, -Resigns him up with Heaven and Earth renewed. -But let us call to synod all the Blest, -Through Heaven's wide bounds: from them I will not hide -My judgements; how with mankind I proceed, -As how with peccant Angels late they saw, -And in their state, though firm, stood more confirmed. -He ended, and the Son gave signal high -To the bright minister that watched; he blew -His trumpet, heard in Oreb since perhaps -When God descended, and perhaps once more -To sound at general doom. The angelick blast -Filled all the regions: from their blisful bowers -Of amarantine shade, fountain or spring, -By the waters of life, where'er they sat -In fellowships of joy, the sons of light -Hasted, resorting to the summons high; -And took their seats; till from his throne supreme -The Almighty thus pronounced his sovran will. -O Sons, like one of us Man is become -To know both good and evil, since his taste -Of that defended fruit; but let him boast -His knowledge of good lost, and evil got; -Happier! had it sufficed him to have known -Good by itself, and evil not at all. -He sorrows now, repents, and prays contrite, -My motions in him; longer than they move, -His heart I know, how variable and vain, -Self-left. Lest therefore his now bolder hand -Reach also of the tree of life, and eat, -And live for ever, dream at least to live -For ever, to remove him I decree, -And send him from the garden forth to till -The ground whence he was taken, fitter soil. -Michael, this my behest have thou in charge; -Take to thee from among the Cherubim -Thy choice of flaming warriours, lest the Fiend, -Or in behalf of Man, or to invade -Vacant possession, some new trouble raise: -Haste thee, and from the Paradise of God -Without remorse drive out the sinful pair; -From hallowed ground the unholy; and denounce -To them, and to their progeny, from thence -Perpetual banishment. Yet, lest they faint -At the sad sentence rigorously urged, -(For I behold them softened, and with tears -Bewailing their excess,) all terrour hide. -If patiently thy bidding they obey, -Dismiss them not disconsolate; reveal -To Adam what shall come in future days, -As I shall thee enlighten; intermix -My covenant in the Woman's seed renewed; -So send them forth, though sorrowing, yet in peace: -And on the east side of the garden place, -Where entrance up from Eden easiest climbs, -Cherubick watch; and of a sword the flame -Wide-waving; all approach far off to fright, -And guard all passage to the tree of life: -Lest Paradise a receptacle prove -To Spirits foul, and all my trees their prey; -With whose stolen fruit Man once more to delude. -He ceased; and the arch-angelick Power prepared -For swift descent; with him the cohort bright -Of watchful Cherubim: four faces each -Had, like a double Janus; all their shape -Spangled with eyes more numerous than those -Of Argus, and more wakeful than to drouse, -Charmed with Arcadian pipe, the pastoral reed -Of Hermes, or his opiate rod. Mean while, -To re-salute the world with sacred light, -Leucothea waked; and with fresh dews imbalmed -The earth; when Adam and first matron Eve -Had ended now their orisons, and found -Strength added from above; new hope to spring -Out of despair; joy, but with fear yet linked; -Which thus to Eve his welcome words renewed. -Eve, easily my faith admit, that all -The good which we enjoy from Heaven descends; -But, that from us aught should ascend to Heaven -So prevalent as to concern the mind -Of God high-blest, or to incline his will, -Hard to belief may seem; yet this will prayer -Or one short sigh of human breath, upborne -Even to the seat of God. For since I sought -By prayer the offended Deity to appease; -Kneeled, and before him humbled all my heart; -Methought I saw him placable and mild, -Bending his ear; persuasion in me grew -That I was heard with favour; peace returned -Home to my breast, and to my memory -His promise, that thy seed shall bruise our foe; -Which, then not minded in dismay, yet now -Assures me that the bitterness of death -Is past, and we shall live. Whence hail to thee, -Eve rightly called, mother of all mankind, -Mother of all things living, since by thee -Man is to live; and all things live for Man. -To whom thus Eve with sad demeanour meek. -Ill-worthy I such title should belong -To me transgressour; who, for thee ordained -A help, became thy snare; to me reproach -Rather belongs, distrust, and all dispraise: -But infinite in pardon was my Judge, -That I, who first brought death on all, am graced -The source of life; next favourable thou, -Who highly thus to entitle me vouchsaf'st, -Far other name deserving. But the field -To labour calls us, now with sweat imposed, -Though after sleepless night; for see!the morn, -All unconcerned with our unrest, begins -Her rosy progress smiling: let us forth; -I never from thy side henceforth to stray, -Where'er our day's work lies, though now enjoined -Laborious, till day droop; while here we dwell, -What can be toilsome in these pleasant walks? -Here let us live, though in fallen state, content. -So spake, so wished much humbled Eve; but Fate -Subscribed not: Nature first gave signs, impressed -On bird, beast, air; air suddenly eclipsed, -After short blush of morn; nigh in her sight -The bird of Jove, stooped from his aery tour, -Two birds of gayest plume before him drove; -Down from a hill the beast that reigns in woods, -First hunter then, pursued a gentle brace, -Goodliest of all the forest, hart and hind; -Direct to the eastern gate was bent their flight. -Adam observed, and with his eye the chase -Pursuing, not unmoved, to Eve thus spake. -O Eve, some further change awaits us nigh, -Which Heaven, by these mute signs in Nature, shows -Forerunners of his purpose; or to warn -Us, haply too secure, of our discharge -From penalty, because from death released -Some days: how long, and what till then our life, -Who knows? or more than this, that we are dust, -And thither must return, and be no more? -Why else this double object in our sight -Of flight pursued in the air, and o'er the ground, -One way the self-same hour? why in the east -Darkness ere day's mid-course, and morning-light -More orient in yon western cloud, that draws -O'er the blue firmament a radiant white, -And slow descends with something heavenly fraught? -He erred not; for by this the heavenly bands -Down from a sky of jasper lighted now -In Paradise, and on a hill made halt; -A glorious apparition, had not doubt -And carnal fear that day dimmed Adam's eye. -Not that more glorious, when the Angels met -Jacob in Mahanaim, where he saw -The field pavilioned with his guardians bright; -Nor that, which on the flaming mount appeared -In Dothan, covered with a camp of fire, -Against the Syrian king, who to surprise -One man, assassin-like, had levied war, -War unproclaimed. The princely Hierarch -In their bright stand there left his Powers, to seise -Possession of the garden; he alone, -To find where Adam sheltered, took his way, -Not unperceived of Adam; who to Eve, -While the great visitant approached, thus spake. -Eve$ now expect great tidings, which perhaps -Of us will soon determine, or impose -New laws to be observed; for I descry, -From yonder blazing cloud that veils the hill, -One of the heavenly host; and, by his gait, -None of the meanest; some great Potentate -Or of the Thrones above; such majesty -Invests him coming! yet not terrible, -That I should fear; nor sociably mild, -As Raphael, that I should much confide; -But solemn and sublime; whom not to offend, -With reverence I must meet, and thou retire. -He ended: and the Arch-Angel soon drew nigh, -Not in his shape celestial, but as man -Clad to meet man; over his lucid arms -A military vest of purple flowed, -Livelier than Meliboean, or the grain -Of Sarra, worn by kings and heroes old -In time of truce; Iris had dipt the woof; -His starry helm unbuckled showed him prime -In manhood where youth ended; by his side, -As in a glistering zodiack, hung the sword, -Satan's dire dread; and in his hand the spear. -Adam bowed low; he, kingly, from his state -Inclined not, but his coming thus declared. -Adam, Heaven's high behest no preface needs: -Sufficient that thy prayers are heard; and Death, -Then due by sentence when thou didst transgress, -Defeated of his seisure many days -Given thee of grace; wherein thou mayest repent, -And one bad act with many deeds well done -Mayest cover: Well may then thy Lord, appeased, -Redeem thee quite from Death's rapacious claim; -But longer in this Paradise to dwell -Permits not: to remove thee I am come, -And send thee from the garden forth to till -The ground whence thou wast taken, fitter soil. -He added not; for Adam at the news -Heart-struck with chilling gripe of sorrow stood, -That all his senses bound; Eve, who unseen -Yet all had heard, with audible lament -Discovered soon the place of her retire. -O unexpected stroke, worse than of Death! -Must I thus leave thee$ Paradise? thus leave -Thee, native soil! these happy walks and shades, -Fit haunt of Gods? where I had hope to spend, -Quiet though sad, the respite of that day -That must be mortal to us both. O flowers, -That never will in other climate grow, -My early visitation, and my last - ;t even, which I bred up with tender hand -From the first opening bud, and gave ye names! -Who now shall rear ye to the sun, or rank -Your tribes, and water from the ambrosial fount? -Thee lastly, nuptial bower! by me adorned -With what to sight or smell was sweet! from thee -How shall I part, and whither wander down -Into a lower world; to this obscure -And wild? how shall we breathe in other air -Less pure, accustomed to immortal fruits? -Whom thus the Angel interrupted mild. -Lament not, Eve, but patiently resign -What justly thou hast lost, nor set thy heart, -Thus over-fond, on that which is not thine: -Thy going is not lonely; with thee goes -Thy husband; whom to follow thou art bound; -Where he abides, think there thy native soil. -Adam, by this from the cold sudden damp -Recovering, and his scattered spirits returned, -To Michael thus his humble words addressed. -Celestial, whether among the Thrones, or named -Of them the highest; for such of shape may seem -Prince above princes! gently hast thou told -Thy message, which might else in telling wound, -And in performing end us; what besides -Of sorrow, and dejection, and despair, -Our frailty can sustain, thy tidings bring, -Departure from this happy place, our sweet -Recess, and only consolation left -Familiar to our eyes! all places else -Inhospitable appear, and desolate; -Nor knowing us, nor known: And, if by prayer -Incessant I could hope to change the will -Of Him who all things can, I would not cease -To weary him with my assiduous cries: -But prayer against his absolute decree -No more avails than breath against the wind, -Blown stifling back on him that breathes it forth: -Therefore to his great bidding I submit. -This most afflicts me, that, departing hence, -As from his face I shall be hid, deprived -His blessed countenance: Here I could frequent -With worship place by place where he vouchsafed -Presence Divine; and to my sons relate, -'On this mount he appeared; under this tree -'Stood visible; among these pines his voice -'I heard; here with him at this fountain talked: -So many grateful altars I would rear -Of grassy turf, and pile up every stone -Of lustre from the brook, in memory, -Or monument to ages; and theron -Offer sweet-smelling gums, and fruits, and flowers: -In yonder nether world where shall I seek -His bright appearances, or foot-step trace? -For though I fled him angry, yet recalled -To life prolonged and promised race, I now -Gladly behold though but his utmost skirts -Of glory; and far off his steps adore. -To whom thus Michael with regard benign. -Adam, thou knowest Heaven his, and all the Earth; -Not this rock only; his Omnipresence fills -Land, sea, and air, and every kind that lives, -Fomented by his virtual power and warmed: -All the earth he gave thee to possess and rule, -No despicable gift; surmise not then -His presence to these narrow bounds confined -Of Paradise, or Eden: this had been -Perhaps thy capital seat, from whence had spread -All generations; and had hither come -From all the ends of the earth, to celebrate -And reverence thee, their great progenitor. -But this pre-eminence thou hast lost, brought down -To dwell on even ground now with thy sons: -Yet doubt not but in valley, and in plain, -God is, as here; and will be found alike -Present; and of his presence many a sign -Still following thee, still compassing thee round -With goodness and paternal love, his face -Express, and of his steps the track divine. -Which that thou mayest believe, and be confirmed -Ere thou from hence depart; know, I am sent -To show thee what shall come in future days -To thee, and to thy offspring: good with bad -Expect to hear; supernal grace contending -With sinfulness of men; thereby to learn -True patience, and to temper joy with fear -And pious sorrow; equally inured -By moderation either state to bear, -Prosperous or adverse: so shalt thou lead -Safest thy life, and best prepared endure -Thy mortal passage when it comes.--Ascend -This hill; let Eve (for I have drenched her eyes) -Here sleep below; while thou to foresight wakest; -As once thou sleptst, while she to life was formed. -To whom thus Adam gratefully replied. -Ascend, I follow thee, safe Guide, the path -Thou leadest me; and to the hand of Heaven submit, -However chastening; to the evil turn -My obvious breast; arming to overcome -By suffering, and earn rest from labour won, -If so I may attain. -- So both ascend -In the visions of God. It was a hill, -Of Paradise the highest; from whose top -The hemisphere of earth, in clearest ken, -Stretched out to the amplest reach of prospect lay. -Not higher that hill, nor wider looking round, -Whereon, for different cause, the Tempter set -Our second Adam, in the wilderness; -To show him all Earth's kingdoms, and their glory. -His eye might there command wherever stood -City of old or modern fame, the seat -Of mightiest empire, from the destined walls -Of Cambalu, seat of Cathaian Can, -And Samarchand by Oxus, Temir's throne, -To Paquin of Sinaean kings; and thence -To Agra and Lahor of great Mogul, -Down to the golden Chersonese; or where -The Persian in Ecbatan sat, or since -In Hispahan; or where the Russian Ksar -In Mosco; or the Sultan in Bizance, -Turchestan-born; nor could his eye not ken -The empire of Negus to his utmost port -Ercoco, and the less maritim kings -Mombaza, and Quiloa, and Melind, -And Sofala, thought Ophir, to the realm -Of Congo, and Angola farthest south; -Or thence from Niger flood to Atlas mount -The kingdoms of Almansor, Fez and Sus, -Morocco, and Algiers, and Tremisen; -On Europe thence, and where Rome was to sway -The world: in spirit perhaps he also saw -Rich Mexico, the seat of Montezume, -And Cusco in Peru, the richer seat -Of Atabalipa; and yet unspoiled -Guiana, whose great city Geryon's sons -Call El Dorado. But to nobler sights -Michael from Adam's eyes the film removed, -Which that false fruit that promised clearer sight -Had bred; then purged with euphrasy and rue -The visual nerve, for he had much to see; -And from the well of life three drops instilled. -So deep the power of these ingredients pierced, -Even to the inmost seat of mental sight, -That Adam, now enforced to close his eyes, -Sunk down, and all his spirits became entranced; -But him the gentle Angel by the hand -Soon raised, and his attention thus recalled. -Adam, now ope thine eyes; and first behold -The effects, which thy original crime hath wrought -In some to spring from thee; who never touched -The excepted tree; nor with the snake conspired; -Nor sinned thy sin; yet from that sin derive -Corruption, to bring forth more violent deeds. -His eyes he opened, and beheld a field, -Part arable and tilth, whereon were sheaves -New reaped; the other part sheep-walks and folds; -I' the midst an altar as the land-mark stood, -Rustick, of grassy sord; thither anon -A sweaty reaper from his tillage brought -First fruits, the green ear, and the yellow sheaf, -Unculled, as came to hand; a shepherd next, -More meek, came with the firstlings of his flock, -Choicest and best; then, sacrificing, laid -The inwards and their fat, with incense strowed, -On the cleft wood, and all due rights performed: -His offering soon propitious fire from Heaven -Consumed with nimble glance, and grateful steam; -The other's not, for his was not sincere; -Whereat he inly raged, and, as they talked, -Smote him into the midriff with a stone -That beat out life; he fell;and, deadly pale, -Groaned out his soul with gushing blood effused. -Much at that sight was Adam in his heart -Dismayed, and thus in haste to the Angel cried. -O Teacher, some great mischief hath befallen -To that meek man, who well had sacrificed; -Is piety thus and pure devotion paid? -To whom Michael thus, he also moved, replied. -These two are brethren, Adam, and to come -Out of thy loins; the unjust the just hath slain, -For envy that his brother's offering found -From Heaven acceptance; but the bloody fact -Will be avenged; and the other's faith, approved, -Lose no reward; though here thou see him die, -Rolling in dust and gore. To which our sire. -Alas! both for the deed, and for the cause! -But have I now seen Death? Is this the way -I must return to native dust? O sight -Of terrour, foul and ugly to behold, -Horrid to think, how horrible to feel! -To whom thus Michael. Death thou hast seen -In his first shape on Man; but many shapes -Of Death, and many are the ways that lead -To his grim cave, all dismal; yet to sense -More terrible at the entrance, than within. -Some, as thou sawest, by violent stroke shall die; -By fire, flood, famine, by intemperance more -In meats and drinks, which on the earth shall bring -Diseases dire, of which a monstrous crew -Before thee shall appear; that thou mayest know -What misery the inabstinence of Eve -Shall bring on Men. Immediately a place -Before his eyes appeared, sad, noisome, dark; -A lazar-house it seemed; wherein were laid -Numbers of all diseased; all maladies -Of ghastly spasm, or racking torture, qualms -Of heart-sick agony, all feverous kinds, -Convulsions, epilepsies, fierce catarrhs, -Intestine stone and ulcer, colick-pangs, -Demoniack phrenzy, moaping melancholy, -And moon-struck madness, pining atrophy, -Marasmus, and wide-wasting pestilence, -Dropsies, and asthmas, and joint-racking rheums. -Dire was the tossing, deep the groans; Despair -Tended the sick busiest from couch to couch; -And over them triumphant Death his dart -Shook, but delayed to strike, though oft invoked -With vows, as their chief good, and final hope. -Sight so deform what heart of rock could long -Dry-eyed behold? Adam could not, but wept, -Though not of woman born; compassion quelled -His best of man, and gave him up to tears -A space, till firmer thoughts restrained excess; -And, scarce recovering words, his plaint renewed. -O miserable mankind, to what fall -Degraded, to what wretched state reserved! -Better end here unborn. Why is life given -To be thus wrested from us? rather, why -Obtruded on us thus? who, if we knew -What we receive, would either no accept -Life offered, or soon beg to lay it down; -Glad to be so dismissed in peace. Can thus -The image of God in Man, created once -So goodly and erect, though faulty since, -To such unsightly sufferings be debased -Under inhuman pains? Why should not Man, -Retaining still divine similitude -In part, from such deformities be free, -And, for his Maker's image sake, exempt? -Their Maker's image, answered Michael, then -Forsook them, when themselves they vilified -To serve ungoverned Appetite; and took -His image whom they served, a brutish vice, -Inductive mainly to the sin of Eve. -Therefore so abject is their punishment, -Disfiguring not God's likeness, but their own; -Or if his likeness, by themselves defaced; -While they pervert pure Nature's healthful rules -To loathsome sickness; worthily, since they -God's image did not reverence in themselves. -I yield it just, said Adam, and submit. -But is there yet no other way, besides -These painful passages, how we may come -To death, and mix with our connatural dust? -There is, said Michael, if thou well observe -The rule of Not too much; by temperance taught, -In what thou eatest and drinkest; seeking from thence -Due nourishment, not gluttonous delight, -Till many years over thy head return: -So mayest thou live; till, like ripe fruit, thou drop -Into thy mother's lap; or be with ease -Gathered, nor harshly plucked; for death mature: -This is Old Age; but then, thou must outlive -Thy youth, thy strength, thy beauty; which will change -To withered, weak, and gray; thy senses then, -Obtuse, all taste of pleasure must forego, -To what thou hast; and, for the air of youth, -Hopeful and cheerful, in thy blood will reign -A melancholy damp of cold and dry -To weigh thy spirits down, and last consume -The balm of life. To whom our ancestor. -Henceforth I fly not death, nor would prolong -Life much; bent rather, how I may be quit, -Fairest and easiest, of this cumbrous charge; -Which I must keep till my appointed day -Of rendering up, and patiently attend -My dissolution. Michael replied. -Nor love thy life, nor hate; but what thou livest -Live well; how long, or short, permit to Heaven: -And now prepare thee for another sight. -He looked, and saw a spacious plain, whereon -Were tents of various hue; by some, were herds -Of cattle grazing; others, whence the sound -Of instruments, that made melodious chime, -Was heard, of harp and organ; and, who moved -Their stops and chords, was seen; his volant touch, -Instinct through all proportions, low and high, -Fled and pursued transverse the resonant fugue. -In other part stood one who, at the forge -Labouring, two massy clods of iron and brass -Had melted, (whether found where casual fire -Had wasted woods on mountain or in vale, -Down to the veins of earth; thence gliding hot -To some cave's mouth; or whether washed by stream -From underground;) the liquid ore he drained -Into fit moulds prepared; from which he formed -First his own tools; then, what might else be wrought -Fusil or graven in metal. After these, -But on the hither side, a different sort -From the high neighbouring hills, which was their seat, -Down to the plain descended; by their guise -Just men they seemed, and all their study bent -To worship God aright, and know his works -Not hid; nor those things last, which might preserve -Freedom and peace to Men; they on the plain -Long had not walked, when from the tents, behold! -A bevy of fair women, richly gay -In gems and wanton dress; to the harp they sung -Soft amorous ditties, and in dance came on: -The men, though grave, eyed them; and let their eyes -Rove without rein; till, in the amorous net -Fast caught, they liked; and each his liking chose; -And now of love they treat, till the evening-star, -Love's harbinger, appeared; then, all in heat -They light the nuptial torch, and bid invoke -Hymen, then first to marriage rites invoked: -With feast and musick all the tents resound. -Such happy interview, and fair event -Of love and youth not lost, songs, garlands, flowers, -And charming symphonies, attached the heart -Of Adam, soon inclined to admit delight, -The bent of nature; which he thus expressed. -True opener of mine eyes, prime Angel blest; -Much better seems this vision, and more hope -Of peaceful days portends, than those two past; -Those were of hate and death, or pain much worse; -Here Nature seems fulfilled in all her ends. -To whom thus Michael. Judge not what is best -By pleasure, though to nature seeming meet; -Created, as thou art, to nobler end -Holy and pure, conformity divine. -Those tents thou sawest so pleasant, were the tents -Of wickedness, wherein shall dwell his race -Who slew his brother; studious they appear -Of arts that polish life, inventers rare; -Unmindful of their Maker, though his Spirit -Taught them; but they his gifts acknowledged none. -Yet they a beauteous offspring shall beget; -For that fair female troop thou sawest, that seemed -Of Goddesses, so blithe, so smooth, so gay, -Yet empty of all good wherein consists -Woman's domestick honour and chief praise; -Bred only and completed to the taste -Of lustful appetence, to sing, to dance, -To dress, and troll the tongue, and roll the eye: -To these that sober race of men, whose lives -Religious titled them the sons of God, -Shall yield up all their virtue, all their fame -Ignobly, to the trains and to the smiles -Of these fair atheists; and now swim in joy, -Erelong to swim at large; and laugh, for which -The world erelong a world of tears must weep. -To whom thus Adam, of short joy bereft. -O pity and shame, that they, who to live well -Entered so fair, should turn aside to tread -Paths indirect, or in the mid way faint! -But still I see the tenour of Man's woe -Holds on the same, from Woman to begin. -From Man's effeminate slackness it begins, -Said the Angel, who should better hold his place -By wisdom, and superiour gifts received. -But now prepare thee for another scene. -He looked, and saw wide territory spread -Before him, towns, and rural works between; -Cities of men with lofty gates and towers, -Concourse in arms, fierce faces threatening war, -Giants of mighty bone and bold emprise; -Part wield their arms, part curb the foaming steed, -Single or in array of battle ranged -Both horse and foot, nor idly mustering stood; -One way a band select from forage drives -A herd of beeves, fair oxen and fair kine, -From a fat meadow ground; or fleecy flock, -Ewes and their bleating lambs over the plain, -Their booty; scarce with life the shepherds fly, -But call in aid, which makes a bloody fray; -With cruel tournament the squadrons join; -Where cattle pastured late, now scattered lies -With carcasses and arms the ensanguined field, -Deserted: Others to a city strong -Lay siege, encamped; by battery, scale, and mine, -Assaulting; others from the wall defend -With dart and javelin, stones, and sulphurous fire; -On each hand slaughter, and gigantick deeds. -In other part the sceptered heralds call -To council, in the city-gates; anon -Gray-headed men and grave, with warriours mixed, -Assemble, and harangues are heard; but soon, -In factious opposition; till at last, -Of middle age one rising, eminent -In wise deport, spake much of right and wrong, -Of justice, or religion, truth, and peace, -And judgement from above: him old and young -Exploded, and had seized with violent hands, -Had not a cloud descending snatched him thence -Unseen amid the throng: so violence -Proceeded, and oppression, and sword-law, -Through all the plain, and refuge none was found. -Adam was all in tears, and to his guide -Lamenting turned full sad; O!what are these, -Death's ministers, not men? who thus deal death -Inhumanly to men, and multiply -Ten thousandfold the sin of him who slew -His brother: for of whom such massacre -Make they, but of their brethren; men of men -But who was that just man, whom had not Heaven -Rescued, had in his righteousness been lost? -To whom thus Michael. These are the product -Of those ill-mated marriages thou sawest; -Where good with bad were matched, who of themselves -Abhor to join; and, by imprudence mixed, -Produce prodigious births of body or mind. -Such were these giants, men of high renown; -For in those days might only shall be admired, -And valour and heroick virtue called; -To overcome in battle, and subdue -Nations, and bring home spoils with infinite -Man-slaughter, shall be held the highest pitch -Of human glory; and for glory done -Of triumph, to be styled great conquerours -Patrons of mankind, Gods, and sons of Gods; -Destroyers rightlier called, and plagues of men. -Thus fame shall be achieved, renown on earth; -And what most merits fame, in silence hid. -But he, the seventh from thee, whom thou beheldst -The only righteous in a world preverse, -And therefore hated, therefore so beset -With foes, for daring single to be just, -And utter odious truth, that God would come -To judge them with his Saints; him the Most High -Rapt in a balmy cloud with winged steeds -Did, as thou sawest, receive, to walk with God -High in salvation and the climes of bliss, -Exempt from death; to show thee what reward -Awaits the good; the rest what punishment; -Which now direct thine eyes and soon behold. -He looked, and saw the face of things quite changed; -The brazen throat of war had ceased to roar; -All now was turned to jollity and game, -To luxury and riot, feast and dance; -Marrying or prostituting, as befel, -Rape or adultery, where passing fair -Allured them; thence from cups to civil broils. -At length a reverend sire among them came, -And of their doings great dislike declared, -And testified against their ways; he oft -Frequented their assemblies, whereso met, -Triumphs or festivals; and to them preached -Conversion and repentance, as to souls -In prison, under judgements imminent: -But all in vain: which when he saw, he ceased -Contending, and removed his tents far off; -Then, from the mountain hewing timber tall, -Began to build a vessel of huge bulk; -Measured by cubit, length, and breadth, and highth; -Smeared round with pitch; and in the side a door -Contrived; and of provisions laid in large, -For man and beast: when lo, a wonder strange! -Of every beast, and bird, and insect small, -Came sevens, and pairs; and entered in as taught -Their order: last the sire and his three sons, -With their four wives; and God made fast the door. -Mean while the south-wind rose, and, with black wings -Wide-hovering, all the clouds together drove -From under Heaven; the hills to their supply -Vapour, and exhalation dusk and moist, -Sent up amain; and now the thickened sky -Like a dark cieling stood; down rushed the rain -Impetuous; and continued, till the earth -No more was seen: the floating vessel swum -Uplifted, and secure with beaked prow -Rode tilting o'er the waves; all dwellings else -Flood overwhelmed, and them with all their pomp -Deep under water rolled; sea covered sea, -Sea without shore; and in their palaces, -Where luxury late reigned, sea-monsters whelped -And stabled; of mankind, so numerous late, -All left, in one small bottom swum imbarked. -How didst thou grieve then, Adam, to behold -The end of all thy offspring, end so sad, -Depopulation! Thee another flood, -Of tears and sorrow a flood, thee also drowned, -And sunk thee as thy sons; till, gently reared -By the Angel, on thy feet thou stoodest at last, -Though comfortless; as when a father mourns -His children, all in view destroyed at once; -And scarce to the Angel utter'dst thus thy plaint. -O visions ill foreseen! Better had I -Lived ignorant of future! so had borne -My part of evil only, each day's lot -Enough to bear; those now, that were dispensed -The burden of many ages, on me light -At once, by my foreknowledge gaining birth -Abortive, to torment me ere their being, -With thought that they must be. Let no man seek -Henceforth to be foretold, what shall befall -Him or his children; evil he may be sure, -Which neither his foreknowing can prevent; -And he the future evil shall no less -In apprehension than in substance feel, -Grievous to bear: but that care now is past, -Man is not whom to warn: those few escaped -Famine and anguish will at last consume, -Wandering that watery desart: I had hope, -When violence was ceased, and war on earth, -All would have then gone well; peace would have crowned -With length of happy days the race of Man; -But I was far deceived; for now I see -Peace to corrupt no less than war to waste. -How comes it thus? unfold, celestial Guide, -And whether here the race of Man will end. -To whom thus Michael. Those, whom last thou sawest -In triumph and luxurious wealth, are they -First seen in acts of prowess eminent -And great exploits, but of true virtue void; -Who, having spilt much blood, and done much wast -Subduing nations, and achieved thereby -Fame in the world, high titles, and rich prey; -Shall change their course to pleasure, ease, and sloth, -Surfeit, and lust; till wantonness and pride -Raise out of friendship hostile deeds in peace. -The conquered also, and enslaved by war, -Shall, with their freedom lost, all virtue lose -And fear of God; from whom their piety feigned -In sharp contest of battle found no aid -Against invaders; therefore, cooled in zeal, -Thenceforth shall practice how to live secure, -Worldly or dissolute, on what their lords -Shall leave them to enjoy; for the earth shall bear -More than enough, that temperance may be tried: -So all shall turn degenerate, all depraved; -Justice and temperance, truth and faith, forgot; -One man except, the only son of light -In a dark age, against example good, -Against allurement, custom, and a world -Offended: fearless of reproach and scorn, -The grand-child, with twelve sons encreased, departs -From Canaan, to a land hereafter called -Egypt, divided by the river Nile; -See where it flows, disgorging at seven mouths -Into the sea: To sojourn in that land -He comes, invited by a younger son -In time of dearth; a son, whose worthy deeds -Raise him to be the second in that realm -Of Pharaoh: There he dies, and leaves his race -Growing into a nation, and now grown -Suspected to a sequent king, who seeks -To stop their overgrowth, as inmate guests -Or violence, he of their wicked ways -Shall them admonish; and before them set -The paths of righteousness, how much more safe -And full of peace; denouncing wrath to come -On their impenitence; and shall return -Of them derided, but of God observed -The one just man alive; by his command -Shall build a wonderous ark, as thou beheldst, -To save himself, and houshold, from amidst -A world devote to universal wrack. -No sooner he, with them of man and beast -Select for life, shall in the ark be lodged, -And sheltered round; but all the cataracts -Of Heaven set open on the Earth shall pour -Rain, day and night; all fountains of the deep, -Broke up, shall heave the ocean to usurp -Beyond all bounds; till inundation rise -Above the highest hills: Then shall this mount -Of Paradise by might of waves be moved -Out of his place, pushed by the horned flood, -With all his verdure spoiled, and trees adrift, -Down the great river to the opening gulf, -And there take root an island salt and bare, -The haunt of seals, and orcs, and sea-mews' clang: -To teach thee that God attributes to place -No sanctity, if none be thither brought -By men who there frequent, or therein dwell. -And now, what further shall ensue, behold. -He looked, and saw the ark hull on the flood, -Which now abated; for the clouds were fled, -Driven by a keen north-wind, that, blowing dry, -Wrinkled the face of deluge, as decayed; -And the clear sun on his wide watery glass -Gazed hot, and of the fresh wave largely drew, -As after thirst; which made their flowing shrink -From standing lake to tripping ebb, that stole -With soft foot towards the deep; who now had stopt -His sluces, as the Heaven his windows shut. -The ark no more now floats, but seems on ground, -Fast on the top of some high mountain fixed. -And now the tops of hills, as rocks, appear; -With clamour thence the rapid currents drive, -Towards the retreating sea, their furious tide. -Forthwith from out the ark a raven flies, -And after him, the surer messenger, -A dove sent forth once and again to spy -Green tree or ground, whereon his foot may light: -The second time returning, in his bill -An olive-leaf he brings, pacifick sign: -Anon dry ground appears, and from his ark -The ancient sire descends, with all his train; -Then with uplifted hands, and eyes devout, -Grateful to Heaven, over his head beholds -A dewy cloud, and in the cloud a bow -Conspicuous with three lifted colours gay, -Betokening peace from God, and covenant new. -Whereat the heart of Adam, erst so sad, -Greatly rejoiced; and thus his joy broke forth. -O thou, who future things canst represent -As present, heavenly Instructer! I revive -At this last sight; assured that Man shall live, -With all the creatures, and their seed preserve. -Far less I now lament for one whole world -Of wicked sons destroyed, than I rejoice -For one man found so perfect, and so just, -That God vouchsafes to raise another world -From him, and all his anger to forget. -But say, what mean those coloured streaks in Heaven -Distended, as the brow of God appeased? -Or serve they, as a flowery verge, to bind -The fluid skirts of that same watery cloud, -Lest it again dissolve, and shower the earth? -To whom the Arch-Angel. Dextrously thou aimest; -So willingly doth God remit his ire, -Though late repenting him of Man depraved; -Grieved at his heart, when looking down he saw -The whole earth filled with violence, and all flesh -Corrupting each their way; yet, those removed, -Such grace shall one just man find in his sight, -That he relents, not to blot out mankind; -And makes a covenant never to destroy -The earth again by flood; nor let the sea -Surpass his bounds; nor rain to drown the world, -With man therein or beast; but, when he brings -Over the earth a cloud, will therein set -His triple-coloured bow, whereon to look, -And call to mind his covenant: Day and night, -Seed-time and harvest, heat and hoary frost, -Shall hold their course; till fire purge all things new, -Both Heaven and Earth, wherein the just shall dwell. - - - -Book XII - - -As one who in his journey bates at noon, -Though bent on speed; so here the Arch-Angel paused -Betwixt the world destroyed and world restored, -If Adam aught perhaps might interpose; -Then, with transition sweet, new speech resumes. -Thus thou hast seen one world begin, and end; -And Man, as from a second stock, proceed. -Much thou hast yet to see; but I perceive -Thy mortal sight to fail; objects divine -Must needs impair and weary human sense: -Henceforth what is to come I will relate; -Thou therefore give due audience, and attend. -This second source of Men, while yet but few, -And while the dread of judgement past remains -Fresh in their minds, fearing the Deity, -With some regard to what is just and right -Shall lead their lives, and multiply apace; -Labouring the soil, and reaping plenteous crop, -Corn, wine, and oil; and, from the herd or flock, -Oft sacrificing bullock, lamb, or kid, -With large wine-offerings poured, and sacred feast, -Shall spend their days in joy unblamed; and dwell -Long time in peace, by families and tribes, -Under paternal rule: till one shall rise -Of proud ambitious heart; who, not content -With fair equality, fraternal state, -Will arrogate dominion undeserved -Over his brethren, and quite dispossess -Concord and law of nature from the earth; -Hunting (and men not beasts shall be his game) -With war, and hostile snare, such as refuse -Subjection to his empire tyrannous: -A mighty hunter thence he shall be styled -Before the Lord; as in despite of Heaven, -Or from Heaven, claiming second sovranty; -And from rebellion shall derive his name, -Though of rebellion others he accuse. -He with a crew, whom like ambition joins -With him or under him to tyrannize, -Marching from Eden towards the west, shall find -The plain, wherein a black bituminous gurge -Boils out from under ground, the mouth of Hell: -Of brick, and of that stuff, they cast to build -A city and tower, whose top may reach to Heaven; -And get themselves a name; lest, far dispersed -In foreign lands, their memory be lost; -Regardless whether good or evil fame. -But God, who oft descends to visit men -Unseen, and through their habitations walks -To mark their doings, them beholding soon, -Comes down to see their city, ere the tower -Obstruct Heaven-towers, and in derision sets -Upon their tongues a various spirit, to rase -Quite out their native language; and, instead, -To sow a jangling noise of words unknown: -Forthwith a hideous gabble rises loud, -Among the builders; each to other calls -Not understood; till hoarse, and all in rage, -As mocked they storm: great laughter was in Heaven, -And looking down, to see the hubbub strange, -And hear the din: Thus was the building left -Ridiculous, and the work Confusion named. -Whereto thus Adam, fatherly displeased. -O execrable son! so to aspire -Above his brethren; to himself assuming -Authority usurped, from God not given: -He gave us only over beast, fish, fowl, -Dominion absolute; that right we hold -By his donation; but man over men -He made not lord; such title to himself -Reserving, human left from human free. -But this usurper his encroachment proud -Stays not on Man; to God his tower intends -Siege and defiance: Wretched man!what food -Will he convey up thither, to sustain -Himself and his rash army; where thin air -Above the clouds will pine his entrails gross, -And famish him of breath, if not of bread? -To whom thus Michael. Justly thou abhorrest -That son, who on the quiet state of men -Such trouble brought, affecting to subdue -Rational liberty; yet know withal, -Since thy original lapse, true liberty -Is lost, which always with right reason dwells -Twinned, and from her hath no dividual being: -Reason in man obscured, or not obeyed, -Immediately inordinate desires, -And upstart passions, catch the government -From reason; and to servitude reduce -Man, till then free. Therefore, since he permits -Within himself unworthy powers to reign -Over free reason, God, in judgement just, -Subjects him from without to violent lords; -Who oft as undeservedly enthrall -His outward freedom: Tyranny must be; -Though to the tyrant thereby no excuse. -Yet sometimes nations will decline so low -From virtue, which is reason, that no wrong, -But justice, and some fatal curse annexed, -Deprives them of their outward liberty; -Their inward lost: Witness the irreverent son -Of him who built the ark; who, for the shame -Done to his father, heard this heavy curse, -Servant of servants, on his vicious race. -Thus will this latter, as the former world, -Still tend from bad to worse; till God at last, -Wearied with their iniquities, withdraw -His presence from among them, and avert -His holy eyes; resolving from thenceforth -To leave them to their own polluted ways; -And one peculiar nation to select -From all the rest, of whom to be invoked, -A nation from one faithful man to spring: -Him on this side Euphrates yet residing, -Bred up in idol-worship: O, that men -(Canst thou believe?) should be so stupid grown, -While yet the patriarch lived, who 'scaped the flood, -As to forsake the living God, and fall -To worship their own work in wood and stone -For Gods! Yet him God the Most High vouchsafes -To call by vision, from his father's house, -His kindred, and false Gods, into a land -Which he will show him; and from him will raise -A mighty nation; and upon him shower -His benediction so, that in his seed -All nations shall be blest: he straight obeys; -Not knowing to what land, yet firm believes: -I see him, but thou canst not, with what faith -He leaves his Gods, his friends, and native soil, -Ur of Chaldaea, passing now the ford -To Haran; after him a cumbrous train -Of herds and flocks, and numerous servitude; -Not wandering poor, but trusting all his wealth -With God, who called him, in a land unknown. -Canaan he now attains; I see his tents -Pitched about Sechem, and the neighbouring plain -Of Moreh; there by promise he receives -Gift to his progeny of all that land, -From Hameth northward to the Desart south; -(Things by their names I call, though yet unnamed;) -From Hermon east to the great western Sea; -Mount Hermon, yonder sea; each place behold -In prospect, as I point them; on the shore -Mount Carmel; here, the double-founted stream, -Jordan, true limit eastward; but his sons -Shall dwell to Senir, that long ridge of hills. -This ponder, that all nations of the earth -Shall in his seed be blessed: By that seed -Is meant thy great Deliverer, who shall bruise -The Serpent's head; whereof to thee anon -Plainlier shall be revealed. This patriarch blest, -Whom faithful Abraham due time shall call, -A son, and of his son a grand-child, leaves; -Like him in faith, in wisdom, and renown: -The grandchild, with twelve sons increased, departs -From Canaan to a land hereafter called -Egypt, divided by the river Nile -See where it flows, disgorging at seven mouths -Into the sea. To sojourn in that land -He comes, invited by a younger son -In time of dearth, a son whose worthy deeds -Raise him to be the second in that realm -Of Pharaoh. There he dies, and leaves his race -Growing into a nation, and now grown -Suspected to a sequent king, who seeks -To stop their overgrowth, as inmate guests -Too numerous; whence of guests he makes them slaves -Inhospitably, and kills their infant males: -Till by two brethren (these two brethren call -Moses and Aaron) sent from God to claim -His people from enthralment, they return, -With glory and spoil, back to their promised land. -But first, the lawless tyrant, who denies -To know their God, or message to regard, -Must be compelled by signs and judgements dire; -To blood unshed the rivers must be turned; -Frogs, lice, and flies, must all his palace fill -With loathed intrusion, and fill all the land; -His cattle must of rot and murren die; -Botches and blains must all his flesh emboss, -And all his people; thunder mixed with hail, -Hail mixed with fire, must rend the Egyptians sky, -And wheel on the earth, devouring where it rolls; -What it devours not, herb, or fruit, or grain, -A darksome cloud of locusts swarming down -Must eat, and on the ground leave nothing green; -Darkness must overshadow all his bounds, -Palpable darkness, and blot out three days; -Last, with one midnight stroke, all the first-born -Of Egypt must lie dead. Thus with ten wounds -The river-dragon tamed at length submits -To let his sojourners depart, and oft -Humbles his stubborn heart; but still, as ice -More hardened after thaw; till, in his rage -Pursuing whom he late dismissed, the sea -Swallows him with his host; but them lets pass, -As on dry land, between two crystal walls; -Awed by the rod of Moses so to stand -Divided, till his rescued gain their shore: -Such wondrous power God to his saint will lend, -Though present in his Angel; who shall go -Before them in a cloud, and pillar of fire; -By day a cloud, by night a pillar of fire; -To guide them in their journey, and remove -Behind them, while the obdurate king pursues: -All night he will pursue; but his approach -Darkness defends between till morning watch; -Then through the fiery pillar, and the cloud, -God looking forth will trouble all his host, -And craze their chariot-wheels: when by command -Moses once more his potent rod extends -Over the sea; the sea his rod obeys; -On their embattled ranks the waves return, -And overwhelm their war: The race elect -Safe toward Canaan from the shore advance -Through the wild Desart, not the readiest way; -Lest, entering on the Canaanite alarmed, -War terrify them inexpert, and fear -Return them back to Egypt, choosing rather -Inglorious life with servitude; for life -To noble and ignoble is more sweet -Untrained in arms, where rashness leads not on. -This also shall they gain by their delay -In the wide wilderness; there they shall found -Their government, and their great senate choose -Through the twelve tribes, to rule by laws ordained: -God from the mount of Sinai, whose gray top -Shall tremble, he descending, will himself -In thunder, lightning, and loud trumpets' sound, -Ordain them laws; part, such as appertain -To civil justice; part, religious rites -Of sacrifice; informing them, by types -And shadows, of that destined Seed to bruise -The Serpent, by what means he shall achieve -Mankind's deliverance. But the voice of God -To mortal ear is dreadful: They beseech -That Moses might report to them his will, -And terrour cease; he grants what they besought, -Instructed that to God is no access -Without Mediator, whose high office now -Moses in figure bears; to introduce -One greater, of whose day he shall foretel, -And all the Prophets in their age the times -Of great Messiah shall sing. Thus, laws and rites -Established, such delight hath God in Men -Obedient to his will, that he vouchsafes -Among them to set up his tabernacle; -The Holy One with mortal Men to dwell: -By his prescript a sanctuary is framed -Of cedar, overlaid with gold; therein -An ark, and in the ark his testimony, -The records of his covenant; over these -A mercy-seat of gold, between the wings -Of two bright Cherubim; before him burn -Seven lamps as in a zodiack representing -The heavenly fires; over the tent a cloud -Shall rest by day, a fiery gleam by night; -Save when they journey, and at length they come, -Conducted by his Angel, to the land -Promised to Abraham and his seed:--The rest -Were long to tell; how many battles fought -How many kings destroyed; and kingdoms won; -Or how the sun shall in mid Heaven stand still -A day entire, and night's due course adjourn, -Man's voice commanding, 'Sun, in Gibeon stand, -'And thou moon in the vale of Aialon, -'Till Israel overcome! so call the third -From Abraham, son of Isaac; and from him -His whole descent, who thus shall Canaan win. -Here Adam interposed. O sent from Heaven, -Enlightener of my darkness, gracious things -Thou hast revealed; those chiefly, which concern -Just Abraham and his seed: now first I find -Mine eyes true-opening, and my heart much eased; -Erewhile perplexed with thoughts, what would become -Of me and all mankind: But now I see -His day, in whom all nations shall be blest; -Favour unmerited by me, who sought -Forbidden knowledge by forbidden means. -This yet I apprehend not, why to those -Among whom God will deign to dwell on earth -So many and so various laws are given; -So many laws argue so many sins -Among them; how can God with such reside? -To whom thus Michael. Doubt not but that sin -Will reign among them, as of thee begot; -And therefore was law given them, to evince -Their natural pravity, by stirring up -Sin against law to fight: that when they see -Law can discover sin, but not remove, -Save by those shadowy expiations weak, -The blood of bulls and goats, they may conclude -Some blood more precious must be paid for Man; -Just for unjust; that, in such righteousness -To them by faith imputed, they may find -Justification towards God, and peace -Of conscience; which the law by ceremonies -Cannot appease; nor Man the mortal part -Perform; and, not performing, cannot live. -So law appears imperfect; and but given -With purpose to resign them, in full time, -Up to a better covenant; disciplined -From shadowy types to truth; from flesh to spirit; -From imposition of strict laws to free -Acceptance of large grace; from servile fear -To filial; works of law to works of faith. -And therefore shall not Moses, though of God -Highly beloved, being but the minister -Of law, his people into Canaan lead; -But Joshua, whom the Gentiles Jesus call, -His name and office bearing, who shall quell -The adversary-Serpent, and bring back -Through the world's wilderness long-wandered Man -Safe to eternal Paradise of rest. -Mean while they, in their earthly Canaan placed, -Long time shall dwell and prosper, but when sins -National interrupt their publick peace, -Provoking God to raise them enemies; -From whom as oft he saves them penitent -By Judges first, then under Kings; of whom -The second, both for piety renowned -And puissant deeds, a promise shall receive -Irrevocable, that his regal throne -For ever shall endure; the like shall sing -All Prophecy, that of the royal stock -Of David (so I name this king) shall rise -A Son, the Woman's seed to thee foretold, -Foretold to Abraham, as in whom shall trust -All nations; and to kings foretold, of kings -The last; for of his reign shall be no end. -But first, a long succession must ensue; -And his next son, for wealth and wisdom famed, -The clouded ark of God, till then in tents -Wandering, shall in a glorious temple enshrine. -Such follow him, as shall be registered -Part good, part bad; of bad the longer scroll; -Whose foul idolatries, and other faults -Heaped to the popular sum, will so incense -God, as to leave them, and expose their land, -Their city, his temple, and his holy ark, -With all his sacred things, a scorn and prey -To that proud city, whose high walls thou sawest -Left in confusion; Babylon thence called. -There in captivity he lets them dwell -The space of seventy years; then brings them back, -Remembering mercy, and his covenant sworn -To David, stablished as the days of Heaven. -Returned from Babylon by leave of kings -Their lords, whom God disposed, the house of God -They first re-edify; and for a while -In mean estate live moderate; till, grown -In wealth and multitude, factious they grow; -But first among the priests dissention springs, -Men who attend the altar, and should most -Endeavour peace: their strife pollution brings -Upon the temple itself: at last they seise -The scepter, and regard not David's sons; -Then lose it to a stranger, that the true -Anointed King Messiah might be born -Barred of his right; yet at his birth a star, -Unseen before in Heaven, proclaims him come; -And guides the eastern sages, who inquire -His place, to offer incense, myrrh, and gold: -His place of birth a solemn Angel tells -To simple shepherds, keeping watch by night; -They gladly thither haste, and by a quire -Of squadroned Angels hear his carol sung. -A virgin is his mother, but his sire -The power of the Most High: He shall ascend -The throne hereditary, and bound his reign -With Earth's wide bounds, his glory with the Heavens. -He ceased, discerning Adam with such joy -Surcharged, as had like grief been dewed in tears, -Without the vent of words; which these he breathed. -O prophet of glad tidings, finisher -Of utmost hope! now clear I understand -What oft my steadiest thoughts have searched in vain; -Why our great Expectation should be called -The seed of Woman: Virgin Mother, hail, -High in the love of Heaven; yet from my loins -Thou shalt proceed, and from thy womb the Son -Of God Most High: so God with Man unites! -Needs must the Serpent now his capital bruise -Expect with mortal pain: Say where and when -Their fight, what stroke shall bruise the victor's heel. -To whom thus Michael. Dream not of their fight, -As of a duel, or the local wounds -Of head or heel: Not therefore joins the Son -Manhood to Godhead, with more strength to foil -Thy enemy; nor so is overcome -Satan, whose fall from Heaven, a deadlier bruise, -Disabled, not to give thee thy death's wound: -Which he, who comes thy Saviour, shall recure, -Not by destroying Satan, but his works -In thee, and in thy seed: Nor can this be, -But by fulfilling that which thou didst want, -Obedience to the law of God, imposed -On penalty of death, and suffering death; -The penalty to thy transgression due, -And due to theirs which out of thine will grow: -So only can high Justice rest appaid. -The law of God exact he shall fulfil -Both by obedience and by love, though love -Alone fulfil the law; thy punishment -He shall endure, by coming in the flesh -To a reproachful life, and cursed death; -Proclaiming life to all who shall believe -In his redemption; and that his obedience, -Imputed, becomes theirs by faith; his merits -To save them, not their own, though legal, works. -For this he shall live hated, be blasphemed, -Seised on by force, judged, and to death condemned -A shameful and accursed, nailed to the cross -By his own nation; slain for bringing life: -But to the cross he nails thy enemies, -The law that is against thee, and the sins -Of all mankind, with him there crucified, -Never to hurt them more who rightly trust -In this his satisfaction; so he dies, -But soon revives; Death over him no power -Shall long usurp; ere the third dawning light -Return, the stars of morn shall see him rise -Out of his grave, fresh as the dawning light, -Thy ransom paid, which Man from death redeems, -His death for Man, as many as offered life -Neglect not, and the benefit embrace -By faith not void of works: This God-like act -Annuls thy doom, the death thou shouldest have died, -In sin for ever lost from life; this act -Shall bruise the head of Satan, crush his strength, -Defeating Sin and Death, his two main arms; -And fix far deeper in his head their stings -Than temporal death shall bruise the victor's heel, -Or theirs whom he redeems; a death, like sleep, -A gentle wafting to immortal life. -Nor after resurrection shall he stay -Longer on earth, than certain times to appear -To his disciples, men who in his life -Still followed him; to them shall leave in charge -To teach all nations what of him they learned -And his salvation; them who shall believe -Baptizing in the profluent stream, the sign -Of washing them from guilt of sin to life -Pure, and in mind prepared, if so befall, -For death, like that which the Redeemer died. -All nations they shall teach; for, from that day, -Not only to the sons of Abraham's loins -Salvation shall be preached, but to the sons -Of Abraham's faith wherever through the world; -So in his seed all nations shall be blest. -Then to the Heaven of Heavens he shall ascend -With victory, triumphing through the air -Over his foes and thine; there shall surprise -The Serpent, prince of air, and drag in chains -Through all his realm, and there confounded leave; -Then enter into glory, and resume -His seat at God's right hand, exalted high -Above all names in Heaven; and thence shall come, -When this world's dissolution shall be ripe, -With glory and power to judge both quick and dead; -To judge the unfaithful dead, but to reward -His faithful, and receive them into bliss, -Whether in Heaven or Earth; for then the Earth -Shall all be Paradise, far happier place -Than this of Eden, and far happier days. -So spake the Arch-Angel Michael; then paused, -As at the world's great period; and our sire, -Replete with joy and wonder, thus replied. -O Goodness infinite, Goodness immense! -That all this good of evil shall produce, -And evil turn to good; more wonderful -Than that which by creation first brought forth -Light out of darkness! Full of doubt I stand, -Whether I should repent me now of sin -By me done, and occasioned; or rejoice -Much more, that much more good thereof shall spring; -To God more glory, more good-will to Men -From God, and over wrath grace shall abound. -But say, if our Deliverer up to Heaven -Must re-ascend, what will betide the few -His faithful, left among the unfaithful herd, -The enemies of truth? Who then shall guide -His people, who defend? Will they not deal -Worse with his followers than with him they dealt? -Be sure they will, said the Angel; but from Heaven -He to his own a Comforter will send, -The promise of the Father, who shall dwell -His Spirit within them; and the law of faith, -Working through love, upon their hearts shall write, -To guide them in all truth; and also arm -With spiritual armour, able to resist -Satan's assaults, and quench his fiery darts; -What man can do against them, not afraid, -Though to the death; against such cruelties -With inward consolations recompensed, -And oft supported so as shall amaze -Their proudest persecutors: For the Spirit, -Poured first on his Apostles, whom he sends -To evangelize the nations, then on all -Baptized, shall them with wonderous gifts endue -To speak all tongues, and do all miracles, -As did their Lord before them. Thus they win -Great numbers of each nation to receive -With joy the tidings brought from Heaven: At length -Their ministry performed, and race well run, -Their doctrine and their story written left, -They die; but in their room, as they forewarn, -Wolves shall succeed for teachers, grievous wolves, -Who all the sacred mysteries of Heaven -To their own vile advantages shall turn -Of lucre and ambition; and the truth -With superstitions and traditions taint, -Left only in those written records pure, -Though not but by the Spirit understood. -Then shall they seek to avail themselves of names, -Places, and titles, and with these to join -Secular power; though feigning still to act -By spiritual, to themselves appropriating -The Spirit of God, promised alike and given -To all believers; and, from that pretence, -Spiritual laws by carnal power shall force -On every conscience; laws which none shall find -Left them inrolled, or what the Spirit within -Shall on the heart engrave. What will they then -But force the Spirit of Grace itself, and bind -His consort Liberty? what, but unbuild -His living temples, built by faith to stand, -Their own faith, not another's? for, on earth, -Who against faith and conscience can be heard -Infallible? yet many will presume: -Whence heavy persecution shall arise -On all, who in the worship persevere -Of spirit and truth; the rest, far greater part, -Will deem in outward rites and specious forms -Religion satisfied; Truth shall retire -Bestuck with slanderous darts, and works of faith -Rarely be found: So shall the world go on, -To good malignant, to bad men benign; -Under her own weight groaning; till the day -Appear of respiration to the just, -And vengeance to the wicked, at return -Of him so lately promised to thy aid, -The Woman's Seed; obscurely then foretold, -Now ampler known thy Saviour and thy Lord; -Last, in the clouds, from Heaven to be revealed -In glory of the Father, to dissolve -Satan with his perverted world; then raise -From the conflagrant mass, purged and refined, -New Heavens, new Earth, ages of endless date, -Founded in righteousness, and peace, and love; -To bring forth fruits, joy and eternal bliss. -He ended; and thus Adam last replied. -How soon hath thy prediction, Seer blest, -Measured this transient world, the race of time, -Till time stand fixed! Beyond is all abyss, -Eternity, whose end no eye can reach. -Greatly-instructed I shall hence depart; -Greatly in peace of thought; and have my fill -Of knowledge, what this vessel can contain; -Beyond which was my folly to aspire. -Henceforth I learn, that to obey is best, -And love with fear the only God; to walk -As in his presence; ever to observe -His providence; and on him sole depend, -Merciful over all his works, with good -Still overcoming evil, and by small -Accomplishing great things, by things deemed weak -Subverting worldly strong, and worldly wise -By simply meek: that suffering for truth's sake -Is fortitude to highest victory, -And, to the faithful, death the gate of life; -Taught this by his example, whom I now -Acknowledge my Redeemer ever blest. -To whom thus also the Angel last replied. -This having learned, thou hast attained the sum -Of wisdom; hope no higher, though all the stars -Thou knewest by name, and all the ethereal powers, -All secrets of the deep, all Nature's works, -Or works of God in Heaven, air, earth, or sea, -And all the riches of this world enjoyedst, -And all the rule, one empire; only add -Deeds to thy knowledge answerable; add faith, -Add virtue, patience, temperance; add love, -By name to come called charity, the soul -Of all the rest: then wilt thou not be loth -To leave this Paradise, but shalt possess -A Paradise within thee, happier far.-- -Let us descend now therefore from this top -Of speculation; for the hour precise -Exacts our parting hence; and see!the guards, -By me encamped on yonder hill, expect -Their motion; at whose front a flaming sword, -In signal of remove, waves fiercely round: -We may no longer stay: go, waken Eve; -Her also I with gentle dreams have calmed -Portending good, and all her spirits composed -To meek submission: thou, at season fit, -Let her with thee partake what thou hast heard; -Chiefly what may concern her faith to know, -The great deliverance by her seed to come -(For by the Woman's seed) on all mankind: -That ye may live, which will be many days, -Both in one faith unanimous, though sad, -With cause, for evils past; yet much more cheered -With meditation on the happy end. -He ended, and they both descend the hill; -Descended, Adam to the bower, where Eve -Lay sleeping, ran before; but found her waked; -And thus with words not sad she him received. -Whence thou returnest, and whither wentest, I know; -For God is also in sleep; and dreams advise, -Which he hath sent propitious, some great good -Presaging, since with sorrow and heart's distress -Wearied I fell asleep: But now lead on; -In me is no delay; with thee to go, -Is to stay here; without thee here to stay, -Is to go hence unwilling; thou to me -Art all things under $Heaven, all places thou, -Who for my wilful crime art banished hence. -This further consolation yet secure -I carry hence; though all by me is lost, -Such favour I unworthy am vouchsafed, -By me the Promised Seed shall all restore. -So spake our mother Eve; and Adam heard -Well pleased, but answered not: For now, too nigh -The Arch-Angel stood; and, from the other hill -To their fixed station, all in bright array -The Cherubim descended; on the ground -Gliding meteorous, as evening-mist -Risen from a river o'er the marish glides, -And gathers ground fast at the labourer's heel -Homeward returning. High in front advanced, -The brandished sword of God before them blazed, -Fierce as a comet; which with torrid heat, -And vapour as the Libyan air adust, -Began to parch that temperate clime; whereat -In either hand the hastening Angel caught -Our lingering parents, and to the eastern gate -Led them direct, and down the cliff as fast -To the subjected plain; then disappeared. -They, looking back, all the eastern side beheld -Of Paradise, so late their happy seat, -Waved over by that flaming brand; the gate -With dreadful faces thronged, and fiery arms: -Some natural tears they dropt, but wiped them soon; -The world was all before them, where to choose -Their place of rest, and Providence their guide: -They, hand in hand, with wandering steps and slow, -Through Eden took their solitary way. - -[The End] diff --git a/src/snappy/snappy/testdata/urls.10K b/src/snappy/snappy/testdata/urls.10K deleted file mode 100644 index eaf0633766..0000000000 --- a/src/snappy/snappy/testdata/urls.10K +++ /dev/null @@ -1,10000 +0,0 @@ -http://ftp.sektornet.dk/tucows/herdwin0904.html -http://209.143.244.16/directory/us/nd/fargo/insurance/automotive.html -http://bellona.itworld.com:8080/cwi/reprint/0,1926,NAV63-128-1357-1367_STO46538,00.html -http://www.legis.state.ia.us/usr/ns-home/docs/GA/76GA/Session.2/SJournal/01600/01644.html -http://www.centc251.org/forums/aca-1/dispatch.cgi/isowg4/showFolder/100001/1211898 -http://www.burstnet.com/ads/ad7826a-map.cgi/271412263 -http://topcu.tucows.com/winme/adnload/137036_30095.html -http://topcu.tucows.com/winme/adnload/145034_49120.html -http://link.fastpartner.com/do/session/600342/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/bitconomy.php -http://www.retrobytes.org/classiccmp/9911/msg01245.html -http://www.localbusiness.com/Story/Print/0,1197,DFW_196102,00.html -http://bbs.kh.edu.tw/treasure/childhood/M.962620586.A/M.966031025.A/M.966031098.A.html -http://www.hig.se/(accessed,clientname,return)/~jackson/roxen/testform.html -http://www.ipclub.ru:8102/cgi-bin/linkmaker/linklist-view.cgi?owner=elvis&Sector=434 -http://www.dulux.co.uk/UKRETAIL:229853034:DFinity.1QJiP4jMofi7bof -http://www.dominionpost.com/cgi-bin/redirect.exe/85288 -http://br.egroups.com/message/anedotas/3988 -http://www.ing.iac.es/~cfg/group_notes/texinfo/spec/file$_must$_exist_$28appendfile$29.html -http://hurweb01.hurriyetim.com.tr/hur/turk/99/06/22/yasam/14yas.htm -http://www3.plala.or.jp/shinchi/niltuki/mai0416.htm -http://www3.plala.or.jp/shinchi/niltuki/mai0420.htm -http://213.36.119.69/do/session/152968/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www3.travelprice.com/voyages/recherche.phtml -http://www.meristation.es/Trucos/s/starcraft_brood.htm -http://www.meristation.es/Trucos/trainer/train_star_war.htm -http://www.askme.com/cat/ShowCategory_3104_an_9.htm -http://mozilla.org/newlayout/testcases/css/sec542cm.htm -http://ampec.ampec.it/ted/box04/page36.htm -http://ampec.ampec.it/ted/box04/page39.htm -http://ampec.ampec.it/ted/box04/page42.htm -http://ampec.ampec.it/ted/box04/page58.htm -http://ampec.ampec.it/ted/box04/page62.htm -http://www.businesswire.com/webbox/bw.080300/202160192.htm -http://www.businesswire.com/webbox/bw.062700/201790580.htm -http://www.businesswire.com/webbox/bw.040300/200940796.htm -http://retailer.gocollect.com/do/session/1912606/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/product_display/top_ten.asp?pagenum=1 -http://retailer.gocollect.com/do/session/1912606/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/clubhouse/suggestions.asp -http://genforum.genealogy.com/cgi-bin/print.cgi?ivy::116.html -http://www.spiral.at/Katalog/Artikel/6150331/ -http://www.spiral.at/Katalog/Artikel/6150390/ -http://www.spiral.at/Katalog/Artikel/6150411/ -http://bbs.msquare.or.kr/list.bbs/writer/Soohah/8.html -http://www.eskimo.com/~wesn/waflyfishers/msg03537.html -http://denniscares.mp2.homes.com/content/glossary.html?Letter=A -http://library.bangor.ac.uk/search/aChandler,+Peter,+1936-/achandler+peter+1936/-5,-1,0,B/bibandlinks&F=achandler+raymond+1888+1959&5,,6 -http://www.kimkihong.pe.kr/ -http://mayu.sourceforge.net/cgi-bin/nph-ml.cgi/000/http/www.geocrawler.com/archives/3/199/1998/6/0/1323673/ -http://musictz.com/user/fernman.html -http://tucows.concepts.nl/winnt/adnload/1381_28803.html -http://www.mirror.kiev.ua:8083/paper/2000/03/1251/text/03-06-6.htm -http://ring.crl.go.jp/pub/linux/debian/debian-jp/dists/stable/non-free/binary-arm/x11/?N=D -http://news.novgorod.ru/news/2000/4/23/2/9 -http://www.egroups.com/dir/World/Deutsch/Gesellschaft/Bildung/Schule?st=167 -http://www.egroups.com/group/abitur98 -http://genforum.genealogy.com/cgi-genforum/forums/casey.cgi?1477 -http://www.tvstore.com/browse/TV/BOXERSHO/s.UtRroVXF -http://www.tvstore.com/browse/TV/COLLECTI/s.UtRroVXF -http://www.tvstore.com/browse/TV/EARRINGS/s.UtRroVXF -http://polygraph.ircache.net:8181/text/m90/http_-2ewp.aliant.com/attivita.htm -http://rosebay.1000pages.com/ceclgt12.htm -http://www02.u-page.so-net.ne.jp/sb3/mizo/home/sub1/link2/?M=A -http://community.webshots.com/photo/5827455/5827535oqdRLPNiek -http://troy.lib.sfu.ca/search/dbiology+periodicals/dbiology+periodicals/19,-1,0,B/frameset&F=dbiology+religious+aspects&1,1 -http://213.36.119.69/do/session/152973/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/FR/special/alitalia.html -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/programs/simple/linux/math/computers/tunes.html -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/programs/simple/linux/math/lit/hasard.html -http://www.elop.de/l0-1011-xx-3006-top.html -http://britanica.com/bcom/eb/article/idxref/0/0,5716,364643,00.html -http://britanica.com/bcom/eb/article/7/0,5716,28557+1+28108,00.html -http://www.geocrawler.com/archives/3/3174/2000/5/50/3724502/ -http://www.geocrawler.com/archives/3/3174/2000/5/50/3699557/ -http://www.geocrawler.com/archives/3/3174/2000/5/50/3689003/ -http://ftp.sunet.se/pub/FreeBSD/ports/ports-stable/net/slirp/files/ -http://www.duluxvalentine.com/FRANCE:219793321:DFinity.1QJiP4jmPgUaedp -http://mundo.ole.es/ocio/articulo/html/oci4270.htm -http://www.maasvlakte-cam.nl/webcams/43/etna__italy/1999/08/29/01:28:02.html -http://www.chinabyte.com/staticpages/builder/builder_course_next/HIPR/builder_course_next_219_HIPR.html -http://www.prospects2.csu.ac.uk/servlet/postgrad.TcAssess?pgid=9634 -http://ftp.sunet.se/pub/lang/perl/CPAN/authors/id/SPP/?N=D -http://www.egroups.com/message/WDT/7751 -http://pub8.ezboard.com/fapricotyarn.unsubscribeUnregisteredToTopic?topicID=4.topic -http://support.tandy.com/support_audio/doc9/9679.htm -http://megalink.tucows.com/winme/preview/74862.html -http://mayu.sourceforge.net/cgi-bin/nph-ml.cgi/000/http/www.geocrawler.com/archives/3/199/1996/2/0/2460450/ -http://www.monaco.gouv.mc/dataweb/gouvmc.nsf/(NewsActu)/d28eaee29b3287d4c1256905004e1ef1!OpenDocument&ExpandSection=10.3,10.4,7,9,4,6 -http://www.fao.org/montes/foda/wforcong/PUBLI/V2/T8S/1-3.HTM -http://library.cuhk.edu.hk/search*chi/a蔡淙霖,+1965-/a%7B215572%7D%7B214758%7D%7B215f60%7D+1965/-5,-1,0,B/browse -http://www.nrk.no/finnmark/x31_12_97/nyh6.htm -http://www.dailyrush.dk/stories/129/comments/pages/1 -http://home.wanadoo.nl/pieter.heres/nedbaskteam/nbt/Web%20Album%20nbt%20spelers/page3.htm -http://members.tripod.co.jp/masa_selfish/?M=A -http://bsd.sinica.edu.tw/cgi-bin/cvsweb.cgi/ports/misc/lile/patches/Attic/?sortby=date -http://www.chaos.dk/sexriddle/z/l/x/y/m/ -http://www.chaos.dk/sexriddle/z/l/x/y/p/ -http://users.sexyboards.com/amandaslut/messages/17.html -http://pub11.ezboard.com/fusscroatiastartrekanimators.showAddTopicScreenFromWeb -http://retailer.gocollect.com/do/session/1912610/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/help/site_tour/index.asp -http://ftp.sunet.se/pub/FreeBSD/ports/ports-current/misc/boxes/pkg-comment -http://www.ce-europe2.philips.com/do/session/80299/vsid/1034/tid/1034/cid/28533/mid/1020/rid/1021/chid/1024/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkZHbjbHrolLmbkKmefLifmLpkZHljlKmoaLl0/url/http://www.eu.microsoft.com/windows/ie_intl/es/ -http://www.peopledaily.co.jp/199904/26/newfiles/col_990426001084_tyxw.html -http://www.peopledaily.co.jp/199904/26/newfiles/col_990426001087_tyxw.html -http://iraustralia.com/listco/hk/swire/profile.htm -http://jefferson.village.virginia.edu/wax/slow/english/3pix/BRight2/1/1a5a15a1.html -http://infoserv2.ita.doc.gov/efm/efm.nsf/Sources!OpenView&Start=35.16&Count=30&Expand=37 -http://www.affiliate.hpstore.hp.co.uk/do/session/380772/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/entry1.asp -http://www.trax.nilex.co.uk/trax.cgi/A1S/B1U/B1R/A3S/A4R/C2U/ -http://www.trax.nilex.co.uk/trax.cgi/A1S/B1U/B1R/A3S/A4R/C2S/ -http://www.quia.com/email.cgi?7106&fc -http://www.mirror.edu.cn/res/sunsite/pub/academic/agriculture/sustainable_agriculture/news+mail-archives/6/ -http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/Beholder/CVSROOT/config?only_with_tag=MAIN -http://collection.nlc-bnc.ca/100/201/300/info_tabac/html/1998/bull21/poumon.html -http://www.erotism.com/sweetlostcherry/g3.htm -http://adex3.flycast.com/server/socket/127.0.0.1:2800/click/SharewareMusicMachine/MusicSoftware1/96457 -http://members.tripod.com/~tonarcos/paginas/Nancy1.html -http://www.gbnf.com/genealog2/stout/html/d0024/I2144.HTM -http://ftp.du.se/disk4/FreeBSD/branches/4.0-stable/ports/deskutils/cbb/ -http://www.hri.org/docs//statedep/95-09-13.std.html -http://ftp.univie.ac.at/packages/tex/macros/latex//contrib/supported/eurofont/adobeuro/readme.txt -http://forum.rai.it/aca-finestre/dispatch.cgi/FORUM/showNextUnseen/fol/100001/1513138 -http://tucows.ipv.pt/winnt/adnload/1891_28712.html -http://www.tucsonweekly.com/tw/02-09-95/danehy.htm -http://message/artefactphil/87?expand=1 -http://www.kiarchive.ru:8091/pub/FreeBSD/FreeBSD-current/src/gnu/Makefile/ -http://retailer.gocollect.com/do/session/1912644/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/index.asp -http://retailer.gocollect.com/do/session/1912644/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/company_info/about.asp -http://park.org:8888/Cdrom/TheNot/Mail/NotPark/msg00070.html -http://citeseer.nj.nec.com/cachedpage/67611/1 -http://citeseer.nj.nec.com/cidcontext/1053642 -http://www.3w-buecher.de/GiacamanGeorge/GiacamanGeorge0745312381.htm -http://au.yahoo.com/Regional/U_S__States/Colorado/Cities/Littleton/Real_Estate/Agencies/ -http://www.power2lead.com/Global/English.nsf/pgWWLocations!OpenPage&ExpandSection=21,28,29,32,22 -http://hem.fyristorg.com/bfo/gagarin/WWW.SAMIRADIO.ORG/svenska/sport-sv.html -http://www.chaos.dk/sexriddle/e/n/q/v/m/ -http://www.hig.se/(formoutput,remove_cookie,sort,sql,sqlquery)/~jackson/roxen/ -http://129.142.8.149/ds/it/isodocs/122400/12240011/12240000117900/ -http://129.142.8.149/ds/it/isodocs/122400/12240011/12240000116400/ -http://129.142.8.149/ds/it/isodocs/122400/12240011/12240000116200/ -http://129.142.8.149/ds/it/isodocs/122400/12240011/12240000113100/ -http://129.142.8.149/ds/it/isodocs/122400/12240011/12240000110800/ -http://koi.www.citycat.ru/funny/fido/2000_10/07.html -http://koi.www.citycat.ru/funny/fido/2000_10/09.html -http://www.hig.se/(countdown,debug,header,if,return)/~jackson/roxen/ -http://www.findtravel.to/search_engine_directory/north_america_usa_canada/united_states/michigan/_travel_guides/ -http://mediate.magicbutton.net/do/session/625534/vsid/3255/tid/3255/cid/87978/mid/2008/rid/2157/chid/2581/url/http://www1.getmapping.com/competition/index.cfm -http://mediate.magicbutton.net/do/session/625534/vsid/3255/tid/3255/cid/87978/mid/2008/rid/2157/chid/2581/url/http://www1.getmapping.com/aboutus/partners2.cfm -http://www.petropages.com/products/p9827.htm -http://www.egroups.com/login.cgi?login_target=%2Fmessage%2Fspynews%2F54 -http://health.sx.zj.cn/Treatment/SuperGuide/2000-3-8/4716.htm -http://www.nease.net/~qin/chardware.htm -http://www.argos.asso.fr/bourges/pratiq/emploi/texte/anpesud.htm -http://ftp.sunet.se/pub/FreeBSD/ports/ports-current/www/p5-Apache-Session/?S=A -http://www.eveclub.com/cgi-bin/eveclub.front/972959425847/Catalog/1000046 -http://retailer.gocollect.com/do/session/1912628/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/product_display/top_ten.asp?pagenum=1 -http://yp.gates96.com/1/10/21/73.html -http://yp.gates96.com/1/10/21/95.html -http://yp.gates96.com/1/10/22/21.html -http://yp.gates96.com/1/10/22/31.html -http://yp.gates96.com/1/10/22/52.html -http://yp.gates96.com/1/10/22/76.html -http://yp.gates96.com/1/10/22/79.html -http://yp.gates96.com/1/10/23/57.html -http://yp.gates96.com/1/10/23/73.html -http://yp.gates96.com/1/10/25/20.html -http://yp.gates96.com/1/10/25/46.html -http://yp.gates96.com/1/10/25/87.html -http://yp.gates96.com/1/10/26/76.html -http://yp.gates96.com/1/10/26/84.html -http://yp.gates96.com/1/10/27/67.html -http://yp.gates96.com/1/10/28/70.html -http://yp.gates96.com/1/10/28/91.html -http://live.excite.com/lifestyle/politics_and_society/countries/asia/uzbekistan/guides_and_reference/ -http://biblioteca.upv.es/bib/doc/doc_fisbd/367/114176//C/1825519/0////25/S/MLTPAI -http://mai.flora.org/forum/5322 -http://mai.flora.org/forum/5318 -http://www.brickshelf.com/scans/0000/0715/0715-03.html -http://www.brickshelf.com/scans/0000/0715/0715-12.html -http://www.brickshelf.com/scans/0000/0715/0715-21.html -http://www.msb.malmo.se/search*swe/dManikyr/dmanikyr/-5,-1,0,B/frameset&F=dmani&1,1 -http://message/cinematik/2441?expand=1 -http://message/cinematik/2447?expand=1 -http://www.jamba.de/KNet/_KNet-Rco8j1-WDd-137sh/showInfo-special1.de/node.0/cde7f1uou -http://www.jamba.de/KNet/_KNet-Rco8j1-WDd-137ss/showInfo-hilfe.de/node.0/cde7f1uou -http://acmepet.petsmart.com/canine/breeds/labrador/bboard/messages/5245.html -http://acmepet.petsmart.com/canine/breeds/labrador/bboard/messages/5226.html -http://config.tucows.com/winnt/adnload/67680_29009.html -http://config.tucows.com/winnt/adnload/55386_29005.html -http://us.mandrakesoft.com/cgi-bin/cvsweb.cgi/kdeutils/knotes/Attic/renamedlg.cpp?r1=1.7&only_with_tag=MAIN -http://www.imagestation.com/member/?name=Twiggy5&c=1 -http://cometweb01.comet.co.uk/do!tid=20&rtid=3&vsid=700&session=131981&mid=1000&rid=1060&cid=37030&chid=1713&url=eqqLmwlGltt5tkZHljbLqkZHlkrHhlZHljbLqleHqjiLlel5jblKqlmLkeq5j1 -http://community.webshots.com/photo/1921549/2334169DWEIWPyCoH -http://www.fogdog.com/cedroID/ssd3040183158605/nav/stores/skateboarding/ -http://www.fogdog.com/cedroID/ssd3040183158605/content/fan/subway_series/ -http://www.fogdog.com/cedroID/ssd3040183158605/boutique/ashworth/ -http://www.fogdog.com/cedroID/ssd3040183158605/customer_service/our_partners.html -http://www.jacksonhewitt.com/ctg/cgi-bin/JacksonHewitt/media_center/AAAksrACwAAACCOAAl -http://www.jacksonhewitt.com/ctg/cgi-bin/JacksonHewitt/talktous/AAAksrACwAAACCOAAl -http://arabia.com/jordan/article/print/1,5130,3048|Life,00.html -http://198.3.99.101/reference/politics_and_govt/humor/games/ -http://www.pocketbible.co.kr/old/Leviticus/Leviticus24/Leviticus24-14.htm -http://www.ozon.ru/detail.cfm/ent=5&id=12&txt=1 -http://www.ozon.ru/detail.cfm/ent=2&id=2141 -http://www.chaos.dk/sexriddle/m/t/i/t/j/ -http://www.outpersonals.com/cgi-bin/w3com/pws/out/5VhIq3rCy0eiHAzs1LOyTswNBIR33Wxc8NtFBCnYVNlrV5p9laRchaQrPWdU7-F739tsfX-p5-IA-j1rTm1YLCRAwn1FAriW9Ps21GP6CvyIL7YFYjLtOcez03i6Q9Xw3LRDtJY2CIzGQuZp-sH_-s_D66j9 -http://www.outpersonals.com/cgi-bin/w3com/pws/out/lKhIoWbn-weE729M1n0JT8Ina4qOfm_FI2ROg8RdrrVu5kq_AK_urPMHafLCMwWCiOLuc8OIIHCFnJaCfz2LSrURBHFjDJP1fBO0X58Y28opSv0qVXWAKYtub7NbCIIWMbE_ldcypBmh -http://www.outpersonals.com/cgi-bin/w3com/pws/out/PbhIoduIKw3faQWbBTWSK5aq7Y-nGqcvK3flLaTRo02t7k7GMY8rPlupJIheD8869wCXUAer4VimzyYa25qUx7ef2l2VdMR9i_p-pJ5gg2S6ZcP-G6RuPfdDS3TEsJNXGVsOTs1rA605 -http://www.linux.com/networking/network/development/web_server/performance/?printable=yes -http://www.linux.com/networking/network/development/web_server/performance/IBM/ -http://sunsite.icm.edu.pl/Linux/Documentation/HOWTO/mini/IP-Subnetworking-3.html -http://dreamcity.gaiax.com/www/dreamcity/m/s/musou/frame.html -http://guardian.co.uk/Widgets/Read_It_Later/TR/1,4694,4043922,00.html -http://www.gpul.org/ftp/os/infinite/?M=A -http://www.gpul.org/ftp/os/infinite/infinite_OS.txt -http://retailer.gocollect.com/do/session/1912666/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/exclusives/exclusives.asp -http://yp.gates96.com/13/77/10/66.html -http://yp.gates96.com/13/77/10/91.html -http://yp.gates96.com/13/77/11/82.html -http://yp.gates96.com/13/77/12/17.html -http://yp.gates96.com/13/77/13/68.html -http://yp.gates96.com/13/77/13/80.html -http://yp.gates96.com/13/77/16/3.html -http://yp.gates96.com/13/77/16/17.html -http://yp.gates96.com/13/77/16/49.html -http://yp.gates96.com/13/77/17/8.html -http://yp.gates96.com/13/77/18/4.html -http://yp.gates96.com/13/77/18/61.html -http://yp.gates96.com/13/77/18/71.html -http://yp.gates96.com/13/77/19/3.html -http://yp.gates96.com/13/77/19/24.html -http://yp.gates96.com/13/77/19/48.html -http://yp.gates96.com/13/77/19/98.html -http://yp.gates96.com/13/77/19/99.html -http://scsinternet.tucows.com/winnt/mail95.html -http://tolm.terrashare.com/45.htm -http://news.dreamwiz.com/news/08/20001030/kukmin/200010301903081903261.html -http://www.tccomputers.com/cgi-bin/bp/1463655603/services/info/tci.htm -http://www.tccomputers.com/cgi-bin/bp/1463655603/services/csc/csc.htm -http://www.2pl.com/b/pl/to/1/01/04/v2/1010400016-6-2r.htm -http://www.2pl.com/b/pl/to/1/01/04/v2/1010400016-3-2r.htm -http://www.2pl.com/b/pl/to/1/01/04/v2/1010400016-18-2r.htm -http://www.2pl.com/b/pl/to/1/01/04/v2/1010400016-1r.htm -http://www.123bestphonerates.com/q/001p/vn/vR85aEOIaY.htm -http://www.thisislancashire.co.uk/lancashire/archive/1997/07/17/SPORTST5VQ.html -http://www.thisislancashire.co.uk/lancashire/archive/1997/07/17/SPORTST7VQ.html -http://www.thisislancashire.co.uk/lancashire/archive/1997/07/17/SPORTST11VQ.html -http://www.elsur.cl/archivo/marzo2000/13marzo2000/elsur/deportes/ind3.php3 -http://home.no.net/fristart/kvasir816/ -http://www.fun7.de/party/cafe_europa/_vti_cnf/?D=A -http://www.users.yun.co.jp/cgi-bin/moriq/pigeon/pigeon.cgi/%C5%E7%BA%AC%B8%A9.%C2%E7%B8%B6%B7%B4%C2%E7%C5%EC%C4%AE?c=e -http://polygraph.ircache.net:8181/http_-2www.whowhere.com/http_-2www.expired.com/html/service.html -http://home.t-online.de/home/mtc.hannover/head1655833.htm -http://moneycentral.msn.com/investor/invsub/insider/Details.asp?Pval=1&Symbol=MKSI -http://www.sohu.com/Regional/hunan/City_County/Yiyang/Firms/Food_Beverage/ -http://www.kulturkreis-rhein-lahn.de/lauer/fax.htm -http://ustlib.ust.hk/search*chi/aporter+bill+1943/aporter+bill+1943/7,-1,0,B/browse -http://www.brio.de/BRIO.catalog/39fe2f3708fb3c8e2740d472aa7806d5/UserTemplate/2 -http://www.brio.de/BRIO.catalog/39fe2f3708fb3c8e2740d472aa7806d5/UserTemplate/6 -http://rcsl.auto.inha.ac.kr/~treeman/Documents/HOWTO/Keyboard-and-Console-HOWTO-19.html -http://www.etoys.com/cat/toy/category/construction/brio_builder_system/1 -http://www.kxmd.com/now/story/0,1597,194790-295,00.shtml -http://www.ferien-immobilien.de/DominikanischeRep/verkauf/GmbH-Kauf-Verkauf-Insolvenz-konkurs/Startseite/Gemeinsam/Gemeinsam/versicherungen/gebaeude/IIM-Teil/Startseite/froben.htm -http://hiv.medscape.com/LWW/SMD/1999/v21.n03/smd2103.01.html -http://www.egroups.com/message/dk-jaws/530 -http://no.egroups.com/message/daemon-news-announce/12 -http://ring.toyama-ix.net/archives/text/elisp/jaist/yamaoka/apel/00_THIS_DIRECTORY_WILL_NOT_BE_UPDATED_UNTIL_2000-10-26 -http://pub12.ezboard.com/ftibesataxg1637tibes.subscribeUnregisteredToTopic?topicID=7.topic -http://ustlib.ust.hk/search*chi/ali+huan+1827+1891/ali+huan+1827+1891/-5,-1,0,E/frameset&F=ali+huan&4,,0 -http://ustlib.ust.hk/search*chi/ali+huan+1827+1891/ali+huan+1827+1891/-5,-1,0,E/frameset&F=ali+huang+1895&1,,0 -http://www.digitalcity.com/cincinnati/sports/log.dci?league=NCF&team=NNF -http://ftp.nacamar.de/pub/debian/dists/potato/main/disks-m68k/2.2.16-2000-07-14/mac/images-1.44/?D=A -http://www.academyfloral.com/state/arboo/flowers/thanksabunchbouquet2.html -http://dante.bdp.it/cgi-bin/poseidon_v2.0/reflect/poseidon/disc/peacelink-scuola/2015003604/view/8 -http://ring.omp.ad.jp/pub/NetBSD/NetBSD-current/pkgsrc/lang/smalltalk/files/?S=A -http://ring.omp.ad.jp/pub/NetBSD/NetBSD-current/pkgsrc/lang/smalltalk/files/patch-sum -http://carriage.de/Schoner/Sammlungen/literature/collections/literature/modelle/ -http://www.buybuddy.com/sleuth/27/1/11001/1692/ -http://193.120.14.241/pub/languages/perl/CPAN/src/5.0/devel/ -http://lastminutetravel.bedandbreakfast.com/bbc/p208900.asp -http://chat.sportsline.com/u/wire/stories/0,1169,2957692_59,00.html -http://acad.uis.edu/sas/qc/q-index.htm -http://acad.uis.edu/sas/qc/s-index.htm -http://library.cuhk.edu.hk/search*chi/aPan,+Zhuonan./apan+zhuonan/-5,1,1,B/frameset&F=apan+zhichang+1956&1,1, -http://www.linux.com/networking/network/install/tools/updates/new/ -http://www.linux.com/networking/network/install/tools/updates/Standards/ -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=13,31,5,11,26 -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=23,31,5,11,26 -http://www.mfa.no/fin/norsk/publ/stprp/006005-991562/index-hov017-b-n-a.html -http://ftp.sunet.se/pub/lang/perl/CPAN/authors/id/DBEAZLEY/?N=D -http://fi.egroups.com/messages/infoespo/6?expand=1 -http://ibc.cn.net/2000/0718/it-1message.html -http://www.shaggysguide.com/conhtml/adnload/51647_1809.html -http://www.shaggysguide.com/conhtml/adnload/51657_5567.html -http://www.shaggysguide.com/conhtml/adnload/74370_17872.html -http://www.shaggysguide.com/conhtml/adnload/78469_19520.html -http://www.shaggysguide.com/conhtml/adnload/78940_19788.html -http://www.backflip.com/members/jhferrara/5171381/page=1/sort=1/linkspp=10 -http://www.amcity.com/philadelphia/stories/1998/08/24/newscolumn3.html?t=printable -http://www.rge.com/pub/tex/biblio/bibtex/ms-dos/demel/?N=D -http://www.v2music.com/Scripts/WebObjects-ISAPI.dll/V2_New_Publisher.woa/67841000005885200000309700000064451/Giveaways.wo/257820000054451/2.0.0.6.0/3/Webobjects1 -http://smb.slac.stanford.edu/cgi-bin/nph-proxy.cgi/000/http/www-gds.desy.de:8080/zeitpl/zpl.htm -http://click-to.tell-a-friend.boardhost.com/tell-a-friend-confirm.cgi?chudtvlogic&msg=1596 -http://retailer.gocollect.com/do/session/1912639/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/clubhouse/suggestions.asp -http://www.jpc-music.com/5590216.htm -http://huntingfishing.tripod.com/sturgeonmain.htm -http://polygraph.ircache.net:8181/wwwboard/prodev/seminar/fast/http_-2www.centennialcc.org/bps.html -http://www.chaos.dk/sexriddle/s/t/c/x/l/ -http://www.chaos.dk/sexriddle/s/t/c/x/z/ -http://es.egroups.com/messages/plato-meno/1285 -http://tonggu-gch.ed.seoul.kr/home/2grade/2-10/981001/hang.htm -http://sjsulib1.sjsu.edu:81/search/dreligion/-5,-1,0,E/exact&dreligion+libraries&1,3 -http://www.generation-formation.fr/chiffrec.htm---o21zAo0UPwo0Ol9A074fo6Td4ezyr6feZJPAPfVbNyqHSezTHkekydMfeZJPdspt6dsSAtdsNhJdspt6dsrvrdjlhkfbd.htm -http://www.generation-formation.fr/dicoguid/diclogin.htm---o21zAo0UPwo0Ol9A074fo6Td4ezyr6feZJPAPfVbNyqureds5cezwhlezMpDeH7vGebI1yoKkfMd4vmMAxaAooKkfMd4u5xdfb7rmdfbT.htm -http://www.hollywoodonline.com/asplocal/mgvideoad.asp?rushhour-video-holdon-mov -http://www.ifg.uni-kiel.de/doc-clients/kdelibs-doc/html/kdeui/full-list-KRestrictedLine.html -http://www.3w-sciencefiction.de/ShapiroLarry/ShapiroLarry0760306729.htm -http://202.96.140.98/js/wenge/ -http://www.great-cyber-mall.com/SelectCompany.asp?CityID=230&CatID=19 -http://www.great-cyber-mall.com/SelectCompany.asp?CityID=230&CatID=34 -http://www.amazon.com.hk/exec/obidos/tg/stores/browse/-/books/13361/ -http://www.hole.kommune.no/hole/journweb.nsf/weboffjournal!OpenView&Start=99&Count=50&Collapse=116 -http://www.pbase.com/image/35702/small -http://www.infoscape.com.cn:8171/nf/0010/21/nfzy2104.htm -http://dell.excite.com/photo/topic/weather/national/19 -http://www.linux.com/networking/network/network/firewall/microsoft/government/ -http://www.gasex.com/gay.photo/gay.penis.pics.html -http://hausarbeiten.de/cgi-bin/superDBinters.pl/archiv/geschichte/gesch-stedinger.shtml -http://polygraph.ircache.net:8181/http_-2www.microsoft.com/frontpage/http_-2www.exploreuw.com/cards/ssoenews.html -http://www.fogdog.com/cedroID/ssd3040183137325/cgi-bin/MyFogdog -http://www.fogdog.com/cedroID/ssd3040183137325/cgi-bin/CedroCommerce?func=EditBasket -http://www.fogdog.com/cedroID/ssd3040183137325/nav/stores/cycling/ -http://www.fogdog.com/cedroID/ssd3040183137325/nav/stores/snowboarding/ -http://tucows.wanadoo.nl/win2k/organ2k_license.html -http://tucows.wanadoo.nl/win2k/preview/59164.html -http://windows.tucows.com/preview/001-009-005-005C.html -http://anekdotwall.boom.ru/car/html/75.htm -http://tucows.concepts.nl/win2k/clipb2k_size.html -http://tucows.concepts.nl/win2k/adnload/37291_29917.html -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=cricrila&l=pt -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=cricrilava&l=pt -http://www.trax.nilex.co.uk/trax.cgi/A1C/1AR/A2S/A3S/A3D/D1S/ -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/12_ngqyjt_ngqyjt.html -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/12_rtnucb_tyciyrg.html -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/12_kiektgt_fpwif.html -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/12_rjdbc_rjdbc.html -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/12_xsygo_xsygo.html -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/12_bovqcy_mkaqta.html -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/12_lgbrnl_psnjjt.html -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/12_lgbrnl_ybvfp.html -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/12_vermn_xmxmm.html -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/12_keojvu_faoex.html -http://info-china.hypermart.net/enterprise/company/messages/25.html -http://ring.yamanashi.ac.jp/pub/linux/debian/debian-jp/dists/potato/non-US/contrib/binary-m68k/Release -http://www.amigos.com/cgi-bin/w3com/pws/ffe/R7RIRASjZ5ATyRjNyXQBbwzK4LLK-rhgzZEBqJsLaR1cdnaeB7LT1xORWRg6aQmLxO7QWLEpsdjuf2ZqAnUO1IKpfrRctaIMYIzMNy1DSb7dp8_5z39WdF7oxbKUAByA -http://indigotrem1.chemie.uni-mainz.de/~manng001/Filme/S/SexLuegenundVideo.html -http://se.egroups.com/message/hur/387 -http://www.ilmessaggero.it/hermes/19990111/07_MARCHE/MARCHE_REGIONE/DUE.htm -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/computers/lit/quizz/misc/colorart/lit/pushkin.html -http://www.amzn.com/exec/obidos/ts/artist-glance/201040/ref=pm_dp_ln_m_6/ -http://tucows.netpower.no/winme/adnload/138674_29970.html -http://www.chaos.dk/sexriddle/z/d/q/p/c/ -http://www.chaos.dk/sexriddle/z/d/q/p/u/ -http://sv.pachinkovillage.co.jp/catalog/DinoVaderB/3.html -http://ww2.comune.fe.it/cgi-win/hiweb.exe/a2/B1,a,1f,6,6,3a,3a,,5,,1f,5, -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=deflazioneranno&l=it -http://polygraph.ircache.net:8181/company/html/http_-2www.io.com/~kinnaman/pchealth/f-agents.html -http://polygraph.ircache.net:8181/company/html/http_-2www.io.com/~kinnaman/pchealth/f-leisureworld.html -http://ftp.univie.ac.at/packages/perl/modules/by-module/Tie/ILYAZ/cperl-mode/rms-emacs-20.2-patch-narrow-buffer+dirfiles -http://www.expressindia.com/ie/daily/19991126/ige26097p.html -http://l-infonet.phkk.fi/fi/TIETOPALVELUT/ELINKEINO-+JA+YRITYSTOIMINTA/yritt%E4jyys/lukio/oppimateriaali/itseopiskelu/ -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=36,23,11,33,18 -http://www.trib.com/scjournal/ARC/1996/MAR/3_24_96/marines.html -http://www.slac.stanford.edu/BFROOT/www/Computing/Programming/QA/QaBetaTools/6.7.5a/SunOS5/?S=D -http://pokemonplant.tripod.com/150yellow.html -http://ftp.debian.org/dists/potato/contrib/binary-all/devel/?N=D -http://sunsite.org.uk/packages/tcl/Collections/ftp.neosoft.com/sorted/packages-8.0/print/frink/1.2p35/ -http://library.bangor.ac.uk/search/m304.6+LIN/m304.6+lin/-5,-1,0,B/frameset&F=m304.6+jos&1,1 -http://members.tripod.lycos.nl/janninksweg145/huis.htm -http://www.uib.no/People/mihtr/PS01/PS01_219.htm -http://www.kfi640.com/shared/mod_perl/looksmart/looksmart/eus1/eus141561/eus174865/eus327367/eus327602/eus329879/ -http://www.kfi640.com/shared/mod_perl/looksmart/looksmart/eus1/eus141561/eus174865/eus327367/eus327602/eus327608/ -http://sound-dist.secured.co.uk/cgi-bin/psShop.cgi/add|39P02|972959512|Communications|user|0|1,0,0,1 -http://www.bluefreds.f9.co.uk/vote2.html -http://www.hri.org/docs//statedep/1999/99-05-07.std.html -http://polygraph.ircache.net:8181/http_-2www.hblinfo.com/f_snowbuddies.html -http://mediate.magicbutton.net/do/session/625565/vsid/3342/tid/3342/cid/88020/mid/2008/rid/2313/chid/2648/url/http://www1.getmapping.com/products.cfm -http://cometweb01.comet.co.uk/do!tid=20&rtid=2&vsid=692&session=131975&mid=1000&rid=1060&cid=37051&chid=1702&url=eqqLmwlGltt5tkZHljbLqkZHlkrHhlZHdfjKYfkLlkZ5ljjLboZLbplG5ubLZDXLZolLl3l5jbqLlci5XqVLkXsLkao4tloHbmlLoq5 -http://digilander.iol.it/net4free/spedia.htm -http://totalsports.aol.com/stats/bbo/mlb/20000425/col.at.mon.prvw.html -http://210.178.135.1/netbbs/Bbs.cgi/nhic32042/qry/pno/0/zka/B2-kB2Zk/qqatt/^ -http://cikkek.lezlisoft.com/kikelet/spiritualitas/spirit3v9.shtml -http://www.wingateinns.com/ctg/cgi-bin/Wingate/aarp/AAAksrACwAAACCPAAl -http://sunsite.berkeley.edu/PhiloBiblon/BITAGAP/BIB/BIB1848.html -http://sunsite.uakom.sk/tucows/adnload/69390_28371.html -http://sunsite.uakom.sk/tucows/preview/77630.html -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=(22,0+9,0-~0,3 -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=(22,0+9,0-~9,6 -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=(22,0+9,0-~21,0 -http://sirac.inrialpes.fr/Infos/Personnes/Christophe.Rippert/ressources/jdk1.2.2/docs/api/java/security/ -http://polygraph.ircache.net:8181/getting_started/http_-2www.microsoft.com/powered/radio/email_pal/email_pal.htm -http://mirror.nucba.ac.jp/mirror/FreeBSD/branches/2.2-stable/ports/net/tund/?M=A -http://mirror.nucba.ac.jp/mirror/FreeBSD/branches/2.2-stable/ports/net/tund/?D=A -http://library.bangor.ac.uk/search/tNursing+times+clinical+monographs+&%2359%3B+no.+51/tnursing+times+clinical+monographs+no+++51/-17,-1,0,B/browse -http://library.bangor.ac.uk/search/tNursing+times+clinical+monographs+&%2359%3B+no.+51/tnursing+times+clinical+monographs+no+++51/-5,-1,0,B/frameset&F=tnursing+times+complementary+therapy&1,1 -http://ftp.chg.ru/pub/FreeBSD/doc/en_US.ISO_8859-1/articles/programming-tools/ -http://polygraph.ircache.net:8181/getting_started/http_-2www.microsoft.com/powered/bomb/bomb.htm -http://linux.tucows.inwind.it/conhtml/adnload/8523_5414.html -http://www.magicvillage.de/magicvillage/KonferenzPlaza/fbs/%2328835852?NextInThread -http://www.shopworks.com/samplers/index.cfm/action/cart/userid/0009CECE-2EE1-19FE-9038010B0A0ADCF2 -http://dailynews.sina.com/newsCenter/taiwan/udn/2000/1021/2051701_b5.html -http://us.mandrakesoft.com/cgi-bin/cvsweb.cgi/kdeutils/khexedit/pics/Attic/?hideattic=1&sortby=date -http://moviestore.zap2it.com/browse/MOVIES/BOWL/s.zchC6lsi -http://moviestore.zap2it.com/browse/MOVIES/MUSIC/s.zchC6lsi -http://ww2.comune.fe.it/cgi-win/hiweb.exe/a2/d13/b12,c,1f,18,18,,13,,1f,13,17,,1f,17, -http://ww2.comune.fe.it/cgi-win/hiweb.exe/a2/d14/b12,c,1f,18,18,,13,,1f,13,17,,1f,17, -http://209.50.251.176/~bb/ -http://tucows.energy.it/winnt/adnload/59163_30035.html -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=circundara&l=pt -http://vishvesha.tripod.com/4/068d.htm -http://www.hot.ee/timbsy/kass_files/pildikogu.html -http://www3.newstimes.com/archive99/jan2599/rga.htm -http://pub11.ezboard.com/fmarjoriesdmboardpostyourdmpedigreeshere.showMessage?topicID=21.topic -http://www.geocities.com/Heartland/Plains/4825/bennyn.html -http://citeseer.nj.nec.com/site/115145 -http://www.techsupplies.com/sleuth/17/1/40406/254200/ -http://ccmnet.xj.cei.gov.cn/10/b10/b1007/99-05-02/a5-02.asp -http://206.251.18.85/FEATURES/home_improvement/1999/10/01/fall_lawncare3.html -http://www.dulux.co.uk/UKRETAIL:1355333640:DFinity.1QJiP4jmPgimjKlA -http://cometweb01.comet.co.uk/do!tid=20&rtid=2&vsid=700&session=131985&mid=1000&rid=1060&cid=37030&chid=1713&url=eqqLmwlGltt5tkZHljbLqkZHlkrHhlZHdfjKYfkLlkZ5ljjLboZLbplG5ubLZDXLZolLl3l5jbqLlci5XqVLkXsLkao4tloHbmlLoq5 -http://cometweb01.comet.co.uk/do!tid=20&rtid=1&vsid=700&session=131985&mid=1000&rid=1060&cid=37030&chid=1713&url=eqqLmwlGltt5tkZHljbLqkZHlkrHhlZHdfjKYfkLlkZ5ljjLboZLbplGGolLarZLq4fLpmiLXv-KmooLckYLoznGmpq0qsc0mojLbkYLozvGotc0ZdoLckYLozvGsmv0qmc0jXfLkVZLdocLkYoLzcj1XfkLVZXLqkXLjbzKcob5qroLkVrLoizKlZd5fjYHfklKkZlLjjbLoZbLpl51ubZLDXZLollK3ljLbqlKjXfLkkaHotl4obmLloqL -http://www.berliner-morgenpost.de/bm/inhalt/990928/berlin/story14.html -http://gb.toget.com.tw/article/printer_tool/19990825_3210_p1.html -http://sbtr42.sbsusa.com/ncsamples/base1.htm -http://halflife02.opasia.dk/cs3stats/players/_AMNeSIA_.html -http://mediate.magicbutton.net/do/session/625570/vsid/3342/tid/3342/cid/88020/mid/2008/rid/2313/chid/2648/url/http://www1.getmapping.com/basket.cfm -http://mediate.magicbutton.net/do/session/625570/vsid/3342/tid/3342/cid/88020/mid/2008/rid/2313/chid/2648/url/http://www1.getmapping.com/viewer.cfm -http://www.citythek.de/erfurt/rheinhyp/fsinhalt.htm -http://my.egroups.com/group/mall-komputer -http://www-bd.cricket.org/link_to_database/ARCHIVE/1997-98/PAK_IN_RSA/PAK_IN_RSA_JAN-APR1998_PAK-SQUAD.html -http://www-bd.cricket.org/link_to_database/GROUNDS/RSA/ST-GEORGE_PARK_PT-ELIZ/ -http://www-bd.cricket.org/link_to_database/ARCHIVE/1997-98/PAK_IN_RSA/PAK_RSA_T3_06-10MAR1998_ET_MR.html -http://www.bemi-immobilien.de/Startseite/www.ferien-immobilien.de/ferien-ib/startseite/Gemeinsam/versicherungen/unfall/Gemeinsam/erreichenPartner/Gemeinsam/MarketingStrategie/Gemeinsam/versicherungen/gebaeude/Gemeinsam/Top-Darlehens-Konditionen/anforderungsformular.htm -http://www.online.kokusai.co.jp/Qa/V0043459/wrd/G800/qa/ -http://iland.tucows.com/win2k/adnload/59229_29990.html -http://iland.tucows.com/win2k/preview/144411.html -http://iland.tucows.com/win2k/adnload/38173_29963.html -http://www.arm.com/sitearchitek/armtech.ns4/8ab0ea422fba51238025691f00399e13/9cb09cb360a967848025691f004e28b2!OpenDocument&ExpandSection=6,13,12,-1 -http://ftp.uni-mannheim.de/languages/perl/CPAN/modules/by-authors/id/JMURPHY/?N=D -http://proam.golfonline.com/tours/2000/hooters/silversprings/scores2.html -http://ftp.du.se/pub/FreeBSD/branches/4.0-stable/src/games/grdc/ -http://ftp.du.se/pub/FreeBSD/branches/4.0-stable/src/games/pom/ -http://ftp.du.se/pub/FreeBSD/branches/4.0-stable/src/games/Makefile -http://www.artex.firenze.it/_qualitart/articoli/zoom/03651.htm -http://www.chaos.dk/sexriddle/m/k/v/b/p/ -http://www.chaos.dk/sexriddle/m/k/v/b/s/ -http://www.chaos.dk/sexriddle/t/j/d/n/n/ -http://www.daysinn.com/ctg/cgi-bin/DaysInn/media_center/AAAksrACwAAACCQAAM -http://tukela.heha.net/ys/ll/boyuan.htm -http://tukela.heha.net/ys/ll/jinciming.htm -http://genforum.genealogy.com/ai/messages/4299.html -http://genforum.genealogy.com/ai/messages/4221.html -http://genforum.genealogy.com/ai/messages/4225.html -http://www.linkclub.or.jp/~sticky/index1/diary/1999/199906.html -http://ww.egroups.com/subscribe/lexingtonkystrapon -http://chita.fi.upm.es/docs/info/en_US/a_doc_lib/motif/motifsg/About.htm -http://chita.fi.upm.es/docs/info/en_US/a_doc_lib/motif/motifsg/motifsg41.htm -http://chita.fi.upm.es/docs/info/en_US/a_doc_lib/motif/motifsg/motifsg43.htm -http://hakuba-net.gr.jp/guide/rest/spa_each/spa_2.html -http://yp.gates96.com/6/16/40/22.html -http://yp.gates96.com/6/16/40/44.html -http://yp.gates96.com/6/16/40/50.html -http://yp.gates96.com/6/16/40/69.html -http://yp.gates96.com/6/16/40/83.html -http://yp.gates96.com/6/16/41/49.html -http://yp.gates96.com/6/16/41/50.html -http://yp.gates96.com/6/16/41/67.html -http://yp.gates96.com/6/16/42/15.html -http://yp.gates96.com/6/16/42/51.html -http://yp.gates96.com/6/16/42/56.html -http://yp.gates96.com/6/16/43/8.html -http://yp.gates96.com/6/16/43/69.html -http://yp.gates96.com/6/16/43/71.html -http://yp.gates96.com/6/16/44/11.html -http://yp.gates96.com/6/16/44/51.html -http://yp.gates96.com/6/16/45/20.html -http://yp.gates96.com/6/16/45/43.html -http://yp.gates96.com/6/16/46/12.html -http://yp.gates96.com/6/16/46/25.html -http://yp.gates96.com/6/16/46/64.html -http://yp.gates96.com/6/16/47/42.html -http://yp.gates96.com/6/16/47/80.html -http://yp.gates96.com/6/16/48/54.html -http://yp.gates96.com/6/16/48/85.html -http://yp.gates96.com/6/16/49/51.html -http://yp.gates96.com/6/16/49/62.html -http://assgay.com/main.html?fuck.cock.gaysex -http://ring.yamanashi.ac.jp/pub/linux/linuxppc/contrib/software/System_Environment/Libraries/?S=A -http://computalynx.tucows.com/winme/adnload/138681_29976.html -http://computalynx.tucows.com/winme/adnload/138706_29992.html -http://computalynx.tucows.com/winme/adnload/138690_29990.html -http://computalynx.tucows.com/winme/adnload/138694_29981.html -http://iceberg.adhomeworld.com/cgi-win/redirect.exe/851857198 -http://link.fastpartner.com/do/session/600337/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/mondosoft.php -http://link.fastpartner.com/do/session/600337/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/nordicliving.php -http://link.fastpartner.com/do/session/600337/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/create/learn.htm -http://www.linux.com/networking/network/applications/hardware/device/development/ -http://www.linux.com/networking/network/applications/hardware/device/Corel/ -http://www.linux.com/networking/network/applications/hardware/device/?kw_offset=50 -http://ftp.gigabell.net/debian/dists/unstable/main/binary-m68k/sound/?M=A -http://no.egroups.com/message/slfxpzur/36 -http://no.egroups.com/message/slfxpzur/38 -http://nuance.dhs.org/lbo-talk/0004/2286.html -http://www.jamba.de/KNet/_KNet-XEk8j1-ADd-136sq/showInfo-datenschutz.de/node.0/cde7f1uou -http://yp.gates96.com/2/37/60/0.html -http://yp.gates96.com/2/37/60/13.html -http://yp.gates96.com/2/37/61/24.html -http://yp.gates96.com/2/37/61/66.html -http://yp.gates96.com/2/37/62/5.html -http://yp.gates96.com/2/37/62/31.html -http://yp.gates96.com/2/37/63/31.html -http://yp.gates96.com/2/37/63/43.html -http://yp.gates96.com/2/37/63/48.html -http://yp.gates96.com/2/37/63/60.html -http://yp.gates96.com/2/37/63/88.html -http://yp.gates96.com/2/37/64/62.html -http://yp.gates96.com/2/37/64/74.html -http://yp.gates96.com/2/37/65/0.html -http://yp.gates96.com/2/37/66/20.html -http://yp.gates96.com/2/37/67/41.html -http://yp.gates96.com/2/37/68/2.html -http://yp.gates96.com/2/37/68/50.html -http://yp.gates96.com/2/37/69/15.html -http://yp.gates96.com/2/37/69/41.html -http://yp.gates96.com/2/37/69/47.html -http://yp.gates96.com/2/37/69/60.html -http://yp.gates96.com/2/37/69/75.html -http://yp.gates96.com/2/37/69/76.html -http://gettosdownloads.subportal.com/sn/Palm_Pilot/Games/12428.html -http://news.novgorod.ru/read/65/2000/10/27/10/49 -http://www.schwan.de/links-biografie.html -http://www.fogdog.com/cedroID/ssd3040183124617/cgi-bin/MyFogdog -http://www.nrk.no/finnmark/x27_6_97/nyh9.htm -http://www.aelita.net/products/news/services/sitemap/~archive/Download_redirect/company/Copyright.htm -http://www.staroriental.net/nav/soeg_c/ihf,aol,n15,149,TVB香港å°å§2000.html -http://members.xoom.com/agent187/politics.htm -http://sunsite.org.uk/public/packages/perl/collections/cis.ufl/comp.lang.perl.announce/1998-03/724 -http://www.thestateofcolorado.com/gcecommercialsales.html -http://ftp.du.se/pub/redhat/rawhide/sparc/RedHat/RPMS/?M=A -http://www.linux.com/networking/network/community/trade_show/magazine/open_source/ -http://www.linux.com/networking/network/community/trade_show/magazine/Slashdot/ -http://www.linux.com/networking/network/community/trade_show/magazine/investors/ -http://scifi.emerchandise.com/browse/TV/PIN/b.TV/s.KkOtzPMn -http://scifi.emerchandise.com/browse/DILBERT/_/b.TV/s.KkOtzPMn -http://scifi.emerchandise.com/browse/DR.KATZ/_/b.TV/s.KkOtzPMn -http://scifi.emerchandise.com/browse/FRIENDS/_/b.TV/s.KkOtzPMn -http://scifi.emerchandise.com/browse/FUTURAMA/_/b.TV/s.KkOtzPMn -http://scifi.emerchandise.com/browse/LOIS-CLARK/_/b.TV/s.KkOtzPMn -http://scifi.emerchandise.com/browse/SPEEDRACER/_/b.TV/s.KkOtzPMn -http://scifi.emerchandise.com/browse/THUNDERCATS/_/b.TV/s.KkOtzPMn -http://scifi.emerchandise.com/browse/WCW/_/b.TV/s.KkOtzPMn -http://www.railion.de/home/db_reise_touristik/region/bremen/db_rt_firmenreisedienst_reisezentrum_hb.shtml -http://pegasus.infor.kanazawa-it.ac.jp/~hara/bsd4.1-release/D/N_GETFLAG_NET.html -http://yp.gates96.com/5/54/20/19.html -http://yp.gates96.com/5/54/21/5.html -http://yp.gates96.com/5/54/21/42.html -http://yp.gates96.com/5/54/21/60.html -http://yp.gates96.com/5/54/21/69.html -http://yp.gates96.com/5/54/21/81.html -http://yp.gates96.com/5/54/21/96.html -http://yp.gates96.com/5/54/22/6.html -http://yp.gates96.com/5/54/22/29.html -http://yp.gates96.com/5/54/22/33.html -http://yp.gates96.com/5/54/22/64.html -http://yp.gates96.com/5/54/22/83.html -http://yp.gates96.com/5/54/22/94.html -http://yp.gates96.com/5/54/22/98.html -http://yp.gates96.com/5/54/23/17.html -http://yp.gates96.com/5/54/23/41.html -http://yp.gates96.com/5/54/24/2.html -http://yp.gates96.com/5/54/24/5.html -http://yp.gates96.com/5/54/24/9.html -http://yp.gates96.com/5/54/24/90.html -http://yp.gates96.com/5/54/25/89.html -http://yp.gates96.com/5/54/26/41.html -http://yp.gates96.com/5/54/27/83.html -http://yp.gates96.com/6/59/21/52.html -http://yp.gates96.com/6/59/22/63.html -http://yp.gates96.com/6/59/23/37.html -http://yp.gates96.com/6/59/23/95.html -http://yp.gates96.com/6/59/24/3.html -http://yp.gates96.com/6/59/24/9.html -http://yp.gates96.com/6/59/25/26.html -http://yp.gates96.com/6/59/25/55.html -http://yp.gates96.com/6/59/25/84.html -http://yp.gates96.com/6/59/25/94.html -http://yp.gates96.com/6/59/26/53.html -http://yp.gates96.com/6/59/26/73.html -http://yp.gates96.com/6/59/27/15.html -http://yp.gates96.com/6/59/27/29.html -http://yp.gates96.com/6/59/27/49.html -http://yp.gates96.com/6/59/27/97.html -http://yp.gates96.com/6/59/28/31.html -http://yp.gates96.com/6/59/28/32.html -http://yp.gates96.com/6/59/28/39.html -http://yp.gates96.com/6/59/28/98.html -http://yp.gates96.com/6/59/29/22.html -http://yp.gates96.com/6/59/29/83.html -http://www.gbnf.com/genealogy/royal92/html/d0016/I1249.HTM -http://www.gbnf.com/genealogy/royal92/html/d0018/I734.HTM -http://hifichoice.co.uk/archive/perl/193_printreview.htm -http://hifichoice.co.uk/archive/perl/313_printreview.htm -http://www.highwired.net/Paper/UniversalNav/Redirect/0,5314,2623-7802,00.html -http://www.mrlinux.notrix.de/ -http://www.ucalgary.ca/UofC/faculties/medicine/CHS/nhrdb/area/anat/fr.htm -http://home.pchome.com.tw/tv/pili0614/xing-sh/capric/capric47.htm -http://home.pchome.com.tw/tv/pili0614/xing-sh/capric/capric21.htm -http://home.pchome.com.tw/tv/pili0614/xing-sh/capric/caf26.htm -http://user.chollian.net/~pleiad7s/josun/3-37.htm -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=233&discrim=81,3,15 -http://mediate.magicbutton.net/do/session/625571/vsid/3342/tid/3342/cid/88020/mid/2008/rid/2313/chid/2648/url/http://www1.getmapping.com/aboutus/index.cfm -http://www.telecombrokers.com/q/001p/atn8/2aS9DLAZRXc.htm -http://www.telecomrefunds.com/q/001p/atn8/4SeFiiXvs2A.htm -http://soho.nascom.nasa.gov/solarsoft/soho/lasco/lasco/data_anal/data/9701/?M=A -http://members.xoom.com/mindnare -http://people.freenet.de/TheChamp/nachhilfe.htm -http://people.freenet.de/TheChamp/cheats.htm -http://www.zinezone.com/movies/1,4003,1040-23080,00.html -http://kulichki-win.rambler.ru/moshkow/TURIZM/kutsajo6.txt_with-icons.html -http://www.linux.com/networking/network/release/availability/hardware/?printable=yes -http://www.linux.com/networking/network/release/availability/hardware/applications/ -http://www.shopworks.com/flmp/index.cfm/action/cart/userid/000D1850-2F00-19FE-9038010B0A0ADCF2 -http://shrike.depaul.edu/~afranz/multimedia/?S=A -http://totalsports.net/news/20001014/bbo/mlb/sea/001014.0024.html -http://totalsports.net/news/20001009/bbo/mlb/sea/001009.0039.html -http://totalsports.net/news/20001006/bbo/mlb/sea/001006.0354.html -http://cometweb01.comet.co.uk/do!session=131986&vsid=700&tid=20&cid=37030&mid=1000&rid=1060&chid=1713&url=eqqLmwlGltt5tkkHbqpLZXmLbkZHljlKaltLkilLXalKfkaLbukKeqjLi1 -http://html.tucows.ciaoweb.it/adnload/berglincondlbind.html -http://www.tiscover.com/1Root/Interessante_Region/127151/sportfreizeit/m_sportfreizeit.wm_sport_freibad..1.html -http://f24.parsimony.net/forum54080/messages/97.htm -http://f24.parsimony.net/forum54080/messages/68.htm -http://www.amulation.com/md-l-archive/199702/msg00210.html -http://netpower.tucows.com/winnt/adnload/2821_29573.html -http://kutschen.de/Schoner/Info-d/literature/collections/collections/Geschichte/ -http://webtools.myschoolonline.com/page/0,1871,0-353-38-44534,00.html -http://www.linux.com/networking/network/help/hardware/open_source/GNOME/ -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=12,25,26,17,24 -http://retailer.gocollect.com/do/session/1912664/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/exclusives/exclusives.asp -http://retailer.gocollect.com/do/session/1912665/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/news/index.asp -http://ring.nihon-u.ac.jp/pub/doc/jpnic/members/WORLDNET/members.txt -http://www.123webagent.com/q/001p/atn8/zImXxARDSm.htm -http://www.tu-chemnitz.de/~jflo/DOSDemos/cost_b.txt -http://yp.gates96.com/5/54/27/97.html -http://yp.gates96.com/5/54/28/23.html -http://yp.gates96.com/5/54/29/33.html -http://yp.gates96.com/5/54/29/64.html -http://rex.skyline.net/html/Medical_Equipment.html?224,software,equipment,agriculture,science -http://adex3.flycast.com/server/socket/127.0.0.1:2800/click/OnlineCitiesSM/OnlineCitiesInteractiveCityGuides/bd434602591 -http://www.dispatch.co.za/1998/05/29/business/BA.HTM -http://www.dispatch.co.za/1998/05/29/business/JSE.HTM -http://retailer.gocollect.com/do/session/1912663/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/help/site_tour/index.asp -http://retailer.gocollect.com/do/session/1912663/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/company_info/about.asp -http://retailer.gocollect.com/do/session/1912663/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/company_info/contact.asp -http://www.hblb.org.uk/hblbweb.nsf/$Pages/NewsArchive1!OpenDocument&ExpandSection=8,9,3,6,1,11,13 -http://retailer.gocollect.com/do/session/1912620/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/product_display/gifts/gift_floor.asp -http://genforum.genealogy.com/ga/messages/4583.html -http://genforum.genealogy.com/ga/messages/4582.html -http://genforum.genealogy.com/ga/messages/4570.html -http://genforum.genealogy.com/ga/messages/4561.html -http://genforum.genealogy.com/ga/messages/5575.html -http://ftp.gnu.org/software/sather/ICSI_Sather/whoswho.html -http://dk.egroups.com/group/GHSBasketball -http://dk.egroups.com/group/lovebasket -http://biblioteca.upv.es/bib/doc/doc_fisbd/10/131276//V/1820145/0////25/S/MLTPAID -http://www.qth.net/archive/packfr/200009/20000921.html -http://213.36.119.69/do/session/152975/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/FR/preparer/sante.htm -http://ftp.lip6.fr/pub8/FreeBSD/FreeBSD-current/ports/emulators/mtools/ -http://ftp.lip6.fr/pub8/FreeBSD/FreeBSD-current/ports/emulators/sim6811/ -http://fyi.cnn.com/ASIANOW/asiaweek/97/0328/aa7.html -http://pub21.ezboard.com/fbeauxbatonfrm32.showMessage?topicID=6.topic -http://www.tente.de/us/produkte/produkteigenschaften/aa000001609.htm -http://www.tente.de/us/produkte/produkteigenschaften/aa000001630.htm -http://ftp.sunet.se/pub/FreeBSD/ports/ports-stable/net/rboot/?N=D -http://www.geocities.co.jp/Technopolis-Mars/3952/link.html -http://saleonall.com/cat/software/reference/5112/969434/advanced-search.html -http://www.jazzbude.de/EddieLockjawDavis/B000026F24.htm -http://www6.freeweb.ne.jp/art/iftaka/art/ -http://www.canit.se/(ftp,irc,k15,www)/support/kontakt.html -http://www.mirror.edu.cn/res/sunsite/pub/academic/chemistry/iupac/Download/publications/pac/special/0199/ -http://cinemabilia.de/details/katnr/234764/ -http://polygraph.ircache.net:8181/services/design/http_-2www.infolane.com/dallas.htm -http://ftp.sunet.se/pub/FreeBSD/ports/ports-stable/games/crafty-open-medium/pkg-comment -http://uk.dir.yahoo.com/Education/Primary_and_Secondary/Schools/Middle_Schools/By_Region/U_S__States/Virginia/Complete_List/ -http://yp.gates96.com/6/2/10/13.html -http://yp.gates96.com/6/2/10/41.html -http://yp.gates96.com/6/2/10/83.html -http://yp.gates96.com/6/2/11/51.html -http://yp.gates96.com/6/2/11/89.html -http://yp.gates96.com/6/2/12/22.html -http://yp.gates96.com/6/2/12/58.html -http://yp.gates96.com/6/2/12/62.html -http://yp.gates96.com/6/2/12/79.html -http://yp.gates96.com/6/2/13/19.html -http://yp.gates96.com/6/2/13/51.html -http://yp.gates96.com/6/2/13/64.html -http://yp.gates96.com/6/2/14/75.html -http://yp.gates96.com/6/2/15/91.html -http://yp.gates96.com/6/2/16/83.html -http://yp.gates96.com/6/2/18/15.html -http://yp.gates96.com/6/2/18/54.html -http://yp.gates96.com/6/2/19/35.html -http://yp.gates96.com/6/2/19/68.html -http://yp.gates96.com/6/2/19/75.html -http://yp.gates96.com/6/2/19/82.html -http://yp.gates96.com/6/2/19/87.html -http://www.chaos.dk/sexriddle/z/w/c/b/v/ -http://itcareers.careercast.com/texis/it/itjs/+bwwBmeg5986wwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewhTwdGpdGwBna5dhBiwGnawppcoqwBodD5amnVncdpMnDBaiw5roDtBdDamwBwaoDqc1moDtamn5otDanLpnGonDqnawDwcO5o5aMFqhTfR20Dzme8hwwwpBmeMWD86etmwww5rmeHdwwwBrmeZpwww/jobpage.html -http://itcareers.careercast.com/texis/it/itjs/+3wwBmeV6D86euhwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewhTwdGpdGwBna5dhBiwGnawppcoqwBodD5amnVncdpMnDBaiw5roDtBdDamwBwaoDqc1moDtamn5otDanLpnGonDqnawDwcO5o5aMFqhTfR20Dzme8hwwwpBmeMWD86etmwww5rmeidwwwBrmeZpwww/jobpage.html -http://itcareers.careercast.com/texis/it/itjs/+iwwBmeiWD86zwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewhTwdGpdGwBna5dhBiwGnawppcoqwBodD5amnVncdpMnDBaiw5roDtBdDamwBwaoDqc1moDtamn5otDanLpnGonDqnawDwcO5o5aMFqhTfR20Dzme8hwwwpBmeMWD86etmwww5rme3dwwwBrmeZpwww/jobpage.html -http://sanming.ebigchina.com/ -http://www.bestinfo.net.cn/bsti_kjxn/gn/guoneifagui/17hebei3.htm -http://www.detroitfreepress.com/photos/umgallery/g8/g8.1.htm -http://www.detroitfreepress.com/photos/umgallery/g8/g8.3.htm -http://xgll.soyou.edu.cn/item/2000-04-07/43733.html43733.html -http://se.egroups.com/message/bunyan/903 -http://l-infonet.phkk.fi/fi/TIETOPALVELUT/KIRJASTO-+JA+TIETOPALVELUT/p%E4ij%E4t-h%E4meen+koulutuskonserni/tietokannat/kirjastot/viitetietokannat/ -http://channel.nytimes.com/2000/05/19/technology/ -http://www.ycwb.com.cn/gb/2000/04/15/jrzk/jrms/5.html -http://no.egroups.com/message/healthdigest/97 -http://no.egroups.com/message/healthdigest/119 -http://www.securitiestimes.com.cn/199909/10/ssgs_19990910007_xw.html -http://javatest.a-net.nl/servlet/pedit.Main/http://www.dohistory.org/interests/i_teaching.html -http://www.buybuddy.com/sleuth/27/1/11009/518452/ -http://www.buybuddy.com/sleuth/27/1/11001/518452/ -http://www.buybuddy.com/sleuth/27/1/11004/518452/ -http://ring.omp.ad.jp/archives/text/CTAN/fonts/metrics/tools/?D=A -http://www.jamba.de/KNet/_KNet-CIq8j1-hEd-138qo/showInfo-special1.de/node.0/cde7f1uou -http://cafe4.daum.net/Cafe-bin/Bbs.cgi/sdfamilypds/qry/zka/B2-kBI7p/qqatt/^ -http://www.insurequotes.com/oh3/1AB2.html -http://www.egroups.com/login.cgi?login_target=%2Fmessage%2FWHKPNews%2F190 -http://www.linux.com/networking/network/performance/reliability/linux/?printable=yes -http://preview.egroups.com/message/tattoos88/32 -http://ring.shibaura-it.ac.jp/archives/NetBSD/packages/1.5/cobalt/math/ -http://ring.shibaura-it.ac.jp/archives/NetBSD/packages/1.5/cobalt/sysutils/ -http://in.us.biz.yahoo.com/z/a/p/prgx/prgx_f0149933.html -http://www.backflip.org/members/robeeena/6484057 -http://www.accesslasvegas.com/shared/health/adam/ency/article/003481res.html -http://library.cuhk.edu.hk/search*chi/dAir+--+Pollution+--+China+--+Hong+Kong./dair+pollution+china+hong+kong/-17,1,1,B/frameset&F=dair+pilots+united+states+biography&7,,7 -http://innopac.lib.tsinghua.edu.cn:2082/search*chi/cTM-62+C288/ctm-62+c288/-5,-1,,B/browse -http://www.nd.edu/~rarebook/coins/bnl-mg/BNL-index-B/BNL-index-BU/BNL-index-bursley.html -http://home.kimo.com.tw/lcl566/布告欄.htm -http://www.northampton.ac.uk/cgi-bin/liberation/betsie/betsie.pl/1005/www.northampton.ac.uk/stu/commdev/chap.htm -http://www.peopledaily.co.jp/199905/11/newfiles/col_990511001040_zyxw.html -http://missuniverse.studiostore.com/browse/PAGEANTS/CAP/s.pJicQfVY -http://ftp.up.pt/Linux/Linus/kernel/v2.1/patch-html/patch-2.2.0-pre6/linux_drivers_misc_parport_procfs.c.html -http://ftp.up.pt/Linux/Linus/kernel/v2.1/patch-html/patch-2.2.0-pre6/linux_drivers_sound_es1370.c.html -http://ftp.up.pt/Linux/Linus/kernel/v2.1/patch-html/patch-2.2.0-pre6/linux_include_asm-arm_arch-vnc_system.h.html -http://ftp.up.pt/Linux/Linus/kernel/v2.1/patch-html/patch-2.2.0-pre6/linux_include_asm-arm_dec21285.h.html -http://www.gbnf.com/genealog2/dezarn/html/d0004/I1071.HTM -http://dogbert.wu-wien.ac.at/UniverCD/cc/td/doc/product/access/acs_mod/cis4000/4000/c4000him/22693/ -http://www.uralweb.ru:8081/stats/who -http://www.rrz.uni-hamburg.de/biologie/b_online/kegg/kegg/db/ligand/cpdhtm/C04881.html -http://www.la.digitalcity.com/fortwaynein/health/conditions.dci?condition=badbreath -http://ibelong.digitalcity.com/uticaarea/guygirlmidwest/main.dci?page=guyssept2000 -http://moviestore.zap2it.com/browse/MOVIES/JACKET/s.jNIqMaLO -http://www.doc.ic.ac.uk/~ace97/whoknows/whoknows.cgi?topic=applescript -http://www.doc.ic.ac.uk/~ace97/whoknows/whoknows.cgi?topic=prolog -http://www.doc.ic.ac.uk/~ace97/whoknows/whoknows.cgi?topic=samba -http://209.52.189.2/discussions.cfm/3031/1757-1776 -http://209.52.189.2/discussions.cfm/3031/757-776 -http://209.52.189.2/discussions.cfm/3031/57-76 -http://itcareers.careercast.com/texis/it/itjs/+DwwBmeOWD86OwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewVtqDhdGMwBodDanDtoDnnGaoDBntGwBodDaMwDwtnMnDBanDBnGpGo5na5nGVnG5anLpnGonDqnaDnBidGAa5O5BnMawppcoqwBodDaMFqhTfR20DzmeitwwwpBme2WD86e1xwww5rmenDwwwBrmeZpwww/morelike.html -http://volunteersolutions.org/austin/volunteer/opp/one_100634_printer_detailed.html -http://www.changeyourhome.net/PropertiesToLet/WithamLet/LOO606/pages/DCP_0421_JPG.htm -http://www.users.qwest.net/~eagletac/ -http://www.motorradversand.de/cgi-bin/bekleidung/integralhelm/NG94G933/beurteilung.htm -http://stol.list.ru/catalog/25440.html -http://stol.list.ru/catalog/25301.html -http://www.eveclub.com/cgi-bin/eveclub.front/972959436300/Club/start/1000000 -http://www.gohamptonroads.com/sportsticker/events/06-12/0447.CWS.FSUTEXCURRENT.html -http://genforum.genealogy.com/merriman/messages/228.html -http://genforum.genealogy.com/merriman/messages/223.html -http://genforum.genealogy.com/merriman/messages/163.html -http://genforum.genealogy.com/merriman/messages/495.html -http://genforum.genealogy.com/merriman/messages/232.html -http://genforum.genealogy.com/merriman/messages/351.html -http://genforum.genealogy.com/merriman/messages/324.html -http://genforum.genealogy.com/merriman/messages/510.html -http://genforum.genealogy.com/merriman/messages/57.html -http://genforum.genealogy.com/merriman/messages/12.html -http://genforum.genealogy.com/merriman/messages/263.html -http://genforum.genealogy.com/merriman/messages/15.html -http://retailer.gocollect.com/do/session/1912656/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/clubhouse/suggestions.asp -http://www.kfi640.com/shared/mod_perl/looksmart/looksmart/eus1/eus53832/eus53833/eus328722/eus129553/eus129564/ -http://cma.arabia.com:8008/jordan/article/print/arabic/0,5195,3750,00.html -http://webhome.ai-lab.fh-furtwangen.de/for_local_use_only/CD-TMFUMV/daten/mathema/01121m/?N=D -http://store1.europe.yahoo.com/brink2/2000000141305.html -http://www.contractorresource.com/Vermont/Westford/Architects.shtml -http://www.bemi-immobilien.de/Startseite/www.ferien-immobilien.de/ferien-ib/startseite/Gemeinsam/3d-service/Top-Darlehens-Konditionen/Startseite/Gemeinsam/versicherungen/gebaeude/Startseite/www.ferien-immobilien.de/ferien-ib/startseite/Top-Darlehens-Konditionen/anforderungsformular.htm -http://free.polbox.pl/p/pphromar/OFERTA.htm -http://www.burstnet.com/ads/ad5788a-map.cgi/tr00010005_12 -http://www.private-immobilien-boerse.de/ungarn/verkauf/GmbH-Kauf-Verkauf-Insolvenz-konkurs/Startseite/Gemeinsam/Immolink/3d-service/IIM-Teil/Startseite/froben.htm -http://l-infonet.phkk.fi/fi/TIETOPALVELUT/KIRJASTO-+JA+TIETOPALVELUT/ammattikorkeakoulukirjastot/lahti/toisen+asteen+koulutus/ammattikorkeakoulut/ -http://www.geomag.com/pirates/html/4books.html -http://www.lithoquoter.com/Scripts/WebObjects.exe/Printers.woa/559420000049560000009753100000548302/main.wo/7016200000448302/0/-/prime -http://www.adventurecentre.com/Framesets/intrside/csh.htm -http://mitglied.tripod.de/vox0/negrostodos/de_sexo_dobles.html -http://www.sasinstitute.com/offices/asiapacific/taiwan/whatsnew/art1999/art091601.html -http://oss.sgi.com/cgi-bin/cvsweb.cgi/gdb/sim/ppc/Attic/ppc-opcode-complex?only_with_tag=HEAD -http://www.yorosiku.net:8080/-_-http://www.suntory.co.jp/eco/what.html -http://www.yorosiku.net:8080/-_-http://www.suntory.co.jp/culture/birds/welcome.html -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/linux/music/misc/unitest/lit/pushkin.html -http://sunsite.uakom.sk/tucows/adnload/69291_28346.html -http://members.tripod.com/yamabito2/gardening_000416_0502_n22.htm -http://www.affiliate.hpstore.hp.co.uk/do/session/380775/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/REGISTRATION/entry.asp -http://www.onsemi.com.cn/pub/prod/0,1193,products1_Disty_order=MC100H642FNR2,00.html -http://perso.wanadoo.fr/michel.brunel/Infographie/content/contacts.htm -http://mindit.netmind.com/proxy/http://www.film.com/RGI/FC.(/watch/broadband.jhtml).def...RGI//reviews/features/mow/blairwitch2.jhtml -http://www.doc.ic.ac.uk/lab/labsrc_area/firstyear/submissions/1997-98/jmc1/labs/Ex09/gv197/?N=D -http://www-d0.fnal.gov/d0dist/dist/releases/test/l3fmuo_unpack/rcp/?N=D -http://students.lsu.edu/students/main.nsf/c81d2bf8cb0b80ff862566fb00105ab2/44dc495cc7534894862566fe00127751!OpenDocument&ExpandSection=7,10,4,9 -http://www.zdnet.com/gamespot/filters/printerfriendly/0,10855,2531809-95,00.html -http://l-infonet.phkk.fi/fi/TIETOPALVELUT/asiasanahaku/el%25C3%2583%25C2%25A4kelaitokset/vakuutuslaitokset/rahoitus/el%E4kerahastot/ -http://coe.ier.hit-u.ac.jp/BibEc/data/Papers/fthteavfo2-96.html -http://polygraph.ircache.net:8181/http_-2ESPN.SportsZone.com/nfl/mall/http_-2www.excite.com/http_-2www.exploreuw.com/cards/ -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=cosido&l=pt -http://fazmali.bigsmart.com/mall/allinone/comparison_chart_new.html -http://sunsite.ualberta.ca/pub/Mirror/gnu/etc/ORDERS -http://www.bumppo.net/lists/realbasic-dr/1998/12/msg00347.html -http://www.bumppo.net/lists/realbasic-dr/1998/12/msg00363.html -http://www.bumppo.net/lists/realbasic-dr/1998/12/msg00482.html -http://www.bumppo.net/lists/realbasic-dr/1998/12/msg00483.html -http://www.bumppo.net/lists/realbasic-dr/1998/12/msg00499.html -http://www.bumppo.net/lists/realbasic-dr/1998/12/msg00508.html -http://www.bumppo.net/lists/realbasic-dr/1998/12/msg00518.html -http://it.sports.yahoo.com/000911/90/of8m.html -http://ftp.support.compaq.com/public/dunix/v3.2g/TruCluster_V1.0/?M=A -http://ftp.support.compaq.com/public/dunix/v3.2g/TruCluster_V1.0/ReleaseNotes.pdf -http://www.quzhou.gov.cn/flfg.nsf/0a043ae26eb50247002564640039f21d/e3cb86464a9f805a002564ac0039422d!OpenDocument&ExpandSection=5,1,9 -http://www.quzhou.gov.cn/flfg.nsf/0a043ae26eb50247002564640039f21d/e3cb86464a9f805a002564ac0039422d!OpenDocument&ExpandSection=6,1,9 -http://polygraph.ircache.net:8181/Keyboards/http_-2www.sky.net/~robertf/http_-2domino.findyn.com/fdi.nsf/http_-2home.netscape.com/ -http://www.nv.cc.va.us/home/jakim -http://itcareers.careercast.com/texis/it/itjs/+nwwBmJe0B-deVmwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewXhmoBGnaqdGpdGwBodDaDnBidGAoDta5O5BnM5amo5BGox1BnmanDtoDnnGaMw55wqr15nBB5a51ppdGBamnVncdpaBn5BaMFqhTfR20DzmeQtwwwpBme-WD86eyxwww5rmesdwwwBrmeZpwww/morelike.html -http://itcareers.careercast.com/texis/it/itjs/+MwwBme7WD86JwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewXhmoBGnaqdGpdGwBodDaDnBidGAoDta5O5BnM5amo5BGox1BnmanDtoDnnGaMw55wqr15nBB5a51ppdGBamnVncdpaBn5BaMFqhTfR20DzmeQtwwwpBme-WD86eyxwww5rme4dwwwBrmeZpwww/jobpage.html -http://my.dreamwiz.com/hideyu/couple/couplemain.htm -http://www.noras.bizland.com/top_pages/top_gen_1.htm -http://www.nomade.fr/catm6/entreprises_economi/electricite_electro/electricite/composants_fournitu/index5.shtml -http://www.staroriental.net/nav/soeg_c/ihf,aeb,s0,363,黎明.html -http://online.excite.de/lifestyle/katalog/27990 -http://www.linux.com/networking/network/performance/install/news/Linux/ -http://www.linux.com/networking/network/performance/install/news/kernel/ -http://tw.yahoo.com/Regional/Countries_and_Regions/China/Provinces__Regions_and_Municipalities/Shandong/Cities_and_Towns/He_Zhe/Government/ -http://kernel2.adver.com.tw/Counter/log/kernel2.adver.com.tw/ReadAdverData/2000-10-29/12/972792271154.txt -http://independent-sun-01.whoc.theplanet.co.uk/news/Sport/Football/Bradford/ipswich221000.shtml -http://www.emis.de/journals/EJDE/Monographs/Volumes/Monographs/1996/05-Hetzer/Hetzer-tex -http://oss.sgi.com/cgi-bin/cvsweb.cgi/linux-2.3-4/linux/arch/arm/def-configs/assabet?only_with_tag=LINUX-2_4_0-test1 -http://www.nrk.no/finnmark/x22_8_96/arkivet/ -http://pelit.saunalahti.fi/.9/telenation/valveworld/games/Half-Life/?S=A -http://pelit.saunalahti.fi/.9/telenation/valveworld/games/Half-Life/_Dedicated.txt -http://pelit.saunalahti.fi/.9/telenation/valveworld/games/Half-Life/_Mods.txt -http://ftp.sunet.se/pub/FreeBSD/ports/ports-stable/games/bugsx/?N=D -http://ring.yamanashi.ac.jp/archives/NetBSD/packages/1.4.1/sparc/databases/ -http://citeseer.nj.nec.com/cidcontext/260967 -http://members.tripod.co.jp/jojo6251/sasamineHP.htm -http://www.segodnya.ru/w3s.nsf/Archive/2000_96_life_vrez_noname2.html -http://www.citybrasil.com.br/rs/ivora/cidadefala.htm -http://web62.com/engl/fashion/pompoes/nav.htm -http://www.jufo.com/netcenter/house/item/bglz/477_lmt.html -http://gatekeeper.dec.com/pub/BSD/FreeBSD/FreeBSD-current/src/gnu/libexec/uucp/uupick/ -http://smb.slac.stanford.edu/cgi-bin/nph-proxy.cgi/000/http/lelandsystems.stanford.edu/announce/pubsw/ -http://www.schleuse.de/maschine/World/Deutsch/Kultur/Literatur/Autoren_und_Autorinnen/D/Dominik,_Hans/ -http://www.elsur.cl/archivo/mayo2000/8mayo2000/elsur/espectaculos/ind2.php3 -http://www.jpc-neuheiten.de/2881737.htm -http://www.digitaldrucke.de/(aktuell,arbeitsvermittlung,computer,creaccess,gaestebuch,hilfe,hilfeallgemein,individualverkehr,kultur,onlineservice,schnellübersicht,sense,veranstaltungen,verkehr,von)/_fort/html/themen/computer/soft/links/softquad.htm -http://bbs.syu.ac.kr/NetBBS/Bbs.dll/groupbbs031/rcm/zka/B2-kB23m/qqo/004A/qqatt/^ -http://www.city-map.de/city/print/nl/Niedersachsen/Osterholz/actueel_&_nieuw/onroerendgoed_&_woningen/k012700681.html -http://members.tripod.com/sultana_2/thiskindalife.htm -http://members.tripod.com/sultana_2/thisthing.htm -http://members.tripod.com/sultana_2/believeinthis.html -http://tulips.ntu.edu.tw/search*chi/m586.47+4412/m586.47+4412/-5,-1,0,B/frameset&F=m586.48+0146&1,1 -http://btp1da.phy.uni-bayreuth.de/ftp/pub/FreeBSD/ports/www/linbot/?S=A -http://pub6.ezboard.com/fbiblediscussionandsharingparableorversesharing.subscribeUnregisteredToTopic?topicID=113.topic -http://www.cs.rit.edu/usr/local/pub/atk/course_descr/481.dir/?M=A -http://neptune.guestworld.com/gear/gateway.cfm?action=manage&owner=Nickdays -http://retailer.gocollect.com/do/session/1912673/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/company_info/shipping_policy.asp -http://tucows.minorisa.es/adnload/001-006-009-001.html -http://www.cwi.nl/~jack/spunk/texts/pubs/sekhmet/8/sp001225.txt -http://homepage.yesky.com/33554432/36700160/103524.htm -http://cvs.php.net/viewcvs.cgi/php3/functions/gd.c?annotate=1.65&sortby=log -http://www.genexchange.com/deathreg.cfm?state=nc&county=pasquotank -http://www.genexchange.com/schoolreg.cfm?state=nc&county=pasquotank -http://www.tagnet.org/uva/Eventos/Emergencia99/Fotos/FotosOccidente01.htm -http://itcareers.careercast.com/texis/it/itjs/+CwwBmue0B-dswwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqew6nmoBGnaqdGpdGwBodDa5oBnaoDqc1mnanLqnca15naGn31oGnma5Aocc5awqqd1DBoDtamn5oGwxcnaMFqhTfR20Dzme9twwwpBme+6D865www5rmesDwwwBrmeRdwww/jobpage.html -http://retailer.gocollect.com/do/session/1912638/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/clubhouse/suggestions.asp -http://kulichki-win.rambler.ru/inkwell/bio/zitinsk.htm -http://www.thestateofcolorado.com/e1tatpiercing.html -http://www.pc-schulmusik.purespace.de/seminar/START.HTM -http://www.feeler.nl/rubrieken/index.xml/818004059 -http://ftp.dartmouth.edu/~mcb/faculty/fiering.html -http://ustlib.ust.hk/search*chi/cHD30.28+.C56+1995/chd+++30.28+c56+1995/-17,-1,0,E/2browse -http://herndon1.sdrdc.com/cgi-bin/com_detail/C00325258/ -http://www.linux.com/networking/network/industry/press_release/linuxworld/Linux/ -http://mindit.netmind.com/proxy/http://www.abc.net.au/children/bananas/dreamtime/page1.htm -http://www.allkorea.co.jp/cgi-bin/allkorea.front/972959860700/Catalog/1000188 -http://207.87.5.36/pc/news/saa7108/ -http://musicalproducts.asiaep.com/muspro5a.htm -http://www.trax.nilex.co.uk/trax.cgi/A1S/A1U/1AL/A1S/A2S/C1L/ -http://www.cjga.com/JamMoviesCanadianO/obsessed.html -http://www.symantec.se/region/jp/support/mac/utiliti/num352/num352up.html -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=catapultaras&l=pt -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=catapultai&l=pt -http://no.egroups.com/group/Chenzhou-families -http://www.teenplatinum.com/barelylegal/anal-sexass/young-adultbest-friends/hardaction/slutsnude/red-toenail-polishfoot-fetish/toenail-polish.html -http://beatles.sonicnet.com/allmusic/ai_links.jhtml?ai_id=1000 -http://www.luecos.de/wow/art/fu_satir_30142.html -http://nw1.newsweek.com/nw-srv/inetguide/iguide_4505343.html -http://www.si.uniovi.es/mirror/squid/mail-archive/squid-users/200002/0637.html -http://sunsite.compapp.dcu.ie/pub/perl/modules/by-category/08_User_Interfaces/Tk/NI-S/Tk402.004.readme -http://www.amzn.com/exec/obidos/tg/feature/-/44435/ -http://www.amzn.com/exec/obidos/tg/feature/-/2869/ -http://www.hanter21.co.kr/NetBBS/Bbs.dll/dhliter02/lst/qqeq/1/zka/B2-kBINo/qqo/PRMY -http://www.linux.com/networking/network/help/email/web/security/ -http://www.linux.com/networking/network/help/email/web/Slackware/ -http://www.linux.com/networking/network/help/email/web/e-commerce/ -http://www.linux.com/networking/network/help/email/web/release/ -http://debian.tod.net/debian/dists/stable/contrib/binary-all/web/?S=A -http://ftp.sunet.se/pub/FreeBSD/ports/ports-current/devel/fastcrc/pkg-descr -http://www.trax.nilex.co.uk/trax.cgi/A1C/A2S/B1S/B3S/B1S/C1U/ -http://www.trax.nilex.co.uk/trax.cgi/A1C/A2S/B1S/B3S/B1S/C1D/ -http://rex.skyline.net/html/Metalurgy.html?266,supplies,hobbies,painting,arts -http://infoseek.wunderground.com/geo/BigtempBannerPromo/US/CO/Cortez.html -http://www.kaernten.at/1Root/Kontinent/6/Staat/7/Bundesland/17/Ort/820/Pension/304806/Homepage/h_homepage...1.html -http://dellnet.excite.de/nachrichten/katalog/6663 -http://www.users.skynet.be/eloymarc/infomobil2/sobeen13.htm -http://www.outpersonals.com/cgi-bin/w3com/pws/out/hXRIA9gT9KNJakAdbkyW2SaEFRyXAJCa2tpUDiYF1BHxbpYG0_go-roWL4XPWFopknXRvCQG4gmCQLNceomD4GJpJ4hvR4eYeQbgN2CFeSPhxakPczINPvttFOQK3IDjjmYz66jR -http://www.outpersonals.com/cgi-bin/w3com/pws/out/_cRIZWRepq55uG8fC8ijlWOJrkBzrY7AXdlxz7fhosBeDRNPqhpYFY3uMBgWodvLAPXL2sPRQ7GqKF66xzHYxHZISDRz4dfZjEKnEShXdRFhDxBcOPx4ufr7uXHA0sNvRvMq6Z1j -http://polygraph.ircache.net:8181/health/http_-2cyril.com/http_-2www.americanexpress.com/corp/consumerinfo/privacy/privacystatement.shtml -http://polygraph.ircache.net:8181/health/http_-2cyril.com/arch.html -http://www.villager.com/ctg/cgi-bin/Villager/home/AAAksrACwAAACCOAAI -http://www.medoc-ias.u-psud.fr:81/synoptic/gif/950829/?D=A -http://members.tripod.lycos.nl/unlimited_pagez/pld2.html -http://www.thisislancashire.co.uk/lancashire/archive/1996/01/25/FEATURES0VQ.html -http://members.tripod.com/rebelstrange/buxoms.html -http://fi.egroups.com/message/TEZKo/3 -http://www.yamato.jp.ibm.com/servers/eserver/xseries/about/availa.html -http://polygraph.ircache.net:8181/NetworkInfo/http_-2www.thepetsupply.com/3d/web.html -http://polygraph.ircache.net:8181/NetworkInfo/http_-2www.thepetsupply.com/3d/http_-2www.sccsi.com/welcome.html -http://www.luf.org/wiki/edit/GIG/GenericCodingTerm -http://208.178.109.85/msgshow.cfm/msgboard=822531545582878&msg=50215618980084&page=1&idDispSub=-1 -http://mercury.spaceports.com/~xenical/diet-food.html -http://de.news.yahoo.com/991202/3/echc.html -http://web.tiscalinet.it/ipsiang/uviafede/tertulli.html -http://www.brio.de/BRIO.catalog/39fdb8820423a4d82740d472aa780733/Customer/Register -http://rainforest.parentsplace.com/dialog/thread.pl/bradley2/16/2.html?dir=prevResponse -http://www.centc251.org/forums/aca-1/dispatch.cgi/isowg4/folderFrame/100012/0/def/1208103 -http://www.bemi-immobilien.de/Startseite/www.ferien-immobilien.de/ferien-ib/startseite/Gemeinsam/versicherungen/gebaeude/Gemeinsam/Inserieren/Gemeinsam/MarketingStrategie/Gemeinsam/erreichenPartner/Gemeinsam/versicherungen/unfall/Top-Darlehens-Konditionen/anforderungsformular.htm -http://www.planetit.com/techcenters/docs/internet_&_intranet/news/PIT20000630S0024/threads?comment_status=on -http://ftp.eq.uc.pt/software/unix/Linux/redhat/redhat-6.2/doc/HOWTOS/localization/Hellenic-HOWTO-html/Hellenic-HOWTO-8.html -http://help.sap.com/saphelp_45b/helpdata/de/20/7be8341545ab06e10000009b38f83b/applet.htm -http://www.imagestation.com/member/?name=RonnyClas6&c=1 -http://www.egroups.com/messages/cmass-syd-talk/1170 -http://bellsouth-cl.tucows.com/winnt/xwinservernt_size.html -http://ftp.surfnet.nl/os/FreeBSD/cdrom/development/FreeBSD-CVS/ports/mail/youbin/patches/home.html -http://chat.bigchurch.com/cgi-bin/w3com/pws/bc/PDhIf1s64yA1us4SS1FzmCsroIgpwrmcmdaKEhvT295b5JjMxs9ttaP_gpBzDbn5VR9hkgTaiz3efTGjRK64ORbhJMs0Q8ONiYshBhnFHdkQjl3uSSwZim5B5Layd_SDwYDTVgHM659c -http://www.starshop.co.uk/Masson-Andre/Masson-Andre-Soleil-3200802.html -http://www.21hk.com/book/wx1/wx/zpj/h/huanzhulouzhu/shushan/4/ -http://www.dietrich-computer.de/creativegrafik.htm -http://forum.kf.kommorg.no/forum/agenda21/dispatch.cgi/disk_1/showFolder/100005/9206559 -http://mindit.netmind.com/proxy/http://abc.net.au/rn/schedule/wed.htm -http://www.fogdog.com/cedroID/ssd3040183156802/nav/stores/adventure_travel/ -http://www.fogdog.com/cedroID/ssd3040183156802/nav/stores/tennis/ -http://link.fastpartner.com/do/session/600349/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/nordicliving.php -http://members2.clubphoto.com/luisf216501/TAMARINDO/icons.phtml -http://www.affiliate.hpstore.hp.co.uk/do/session/380795/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/SMARTTIPS/brocdesign.asp -http://www.hblb.org.uk/hblbweb.nsf/$Pages/NewsArchive1!OpenDocument&ExpandSection=3,7,14,5,13,4,12 -http://www.chaos.dk/sexriddle/d/l/t/i/a/ -http://www.crutchfield.com/S-s7BJxKzNmKr/shop/ -http://www.crutchfield.com/cgi-bin/S-s7BJxKzNmKr/email.asp?sid=S-s7BJxKzNmKr -http://tucows.interbaun.com/winme/adnload/137104_47064.html -http://iland.tucows.com/win2k/adnload/73990_29810.html -http://ftp.uk.debian.org/debian/dists/woody/contrib/binary-alpha/text/?M=A -http://sound-dist.secured.co.uk/cgi-bin/psShop.cgi/add|10P02|972959526|Warm===and===Dry|user|0|1,0,0,1 -http://pub14.ezboard.com/fjavagateforum69255multibasicboard -http://www.xrefer.com/entry/317621 -http://library.cuhk.edu.hk/search*chi/aChen,+Jih-peng./achen+jih+peng/-5,-1,0,B/frameset&F=achen+jie+qi&1,1 -http://library.cuhk.edu.hk/search*chi/aChen,+Jih-peng./achen+jih+peng/-5,-1,0,B/exact&F=achen+jih+hsin&1,2 -http://yp.gates96.com/5/50/60/53.html -http://yp.gates96.com/5/50/60/98.html -http://yp.gates96.com/5/50/61/14.html -http://yp.gates96.com/5/50/61/60.html -http://yp.gates96.com/5/50/62/0.html -http://yp.gates96.com/5/50/63/12.html -http://yp.gates96.com/5/50/63/14.html -http://yp.gates96.com/5/50/63/51.html -http://yp.gates96.com/5/50/63/52.html -http://yp.gates96.com/5/50/64/2.html -http://yp.gates96.com/5/50/64/31.html -http://yp.gates96.com/5/50/65/36.html -http://yp.gates96.com/5/50/65/44.html -http://yp.gates96.com/5/50/65/58.html -http://yp.gates96.com/5/50/65/78.html -http://yp.gates96.com/5/50/66/33.html -http://yp.gates96.com/5/50/66/38.html -http://yp.gates96.com/5/50/67/3.html -http://yp.gates96.com/5/50/67/83.html -http://yp.gates96.com/5/50/68/40.html -http://yp.gates96.com/5/50/69/2.html -http://yp.gates96.com/5/50/69/36.html -http://yp.gates96.com/5/50/69/49.html -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=cochichastes&l=pt -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=cochicharam&l=pt -http://www.affiliate.hpstore.hp.co.uk/do/session/380791/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp.com/cposupport/fr/?CTRYcod=FR -http://www.affiliate.hpstore.hp.co.uk/do/session/380791/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/FR/REGISTRATION/entry.asp -http://pub22.ezboard.com/fworldofmugenfrm2.showMessage?topicID=131.topic&index=1 -http://pub23.ezboard.com/fmugenshowdownfrm8.showMessage?topicID=36.topic&index=1 -http://www.questlink.com/QL/CDA/Research/ProductBrief/1,1768,0_11203_135680_85724,00.html -http://www.jamba.de/KNet/_KNet-KBq8j1-gEd-138pd/showInfo-special1.de/node.0/cde7f1uou -http://www.leg.wa.gov/pub/rcw%20-%20text/title_41/chapter_050/rcw_41_50_650.txt -http://www.tiscover.ch/1Root/Kontinent/6/Staat/30/Bundesland/31/Ort/234/Ferienpaket/20120/Homepage/buchen...1.html -http://family.go.com/Categories/Features/family_2000_02/kidv/kidv0200resourceiii/ -http://www.online.kokusai.co.jp/Service/V0043469/wrd/G200/service/service.html -http://www.linux.com/networking/network/help/hardware/website/ISP/ -http://store1.europe.yahoo.com/I/freemans_1592_58696403 -http://202.99.23.195/BIG5/channel5/745/20000427/51173.html -http://www-usa10.cricket.org/link_to_database/GROUNDS/WI/ALBION/ALBION_SPORTS_COMPLEX_00772/ -http://www16.freeweb.ne.jp/computer/taka34/ -http://books.hyperlink.co.uk/bookinfo/Caught_in_a_Tornado/Ross/James_R./155553192X -http://ftp.uni-stuttgart.de/pub/security/unix/SSLapps/doc/?S=A -http://www.moviestarpages.com/rebecca_romijn-stamos/picture05.htm -http://html.tucows.ciaoweb.it/adnload/001-009-008-022.html -http://html.tucows.ciaoweb.it/adnload/001-009-008-019.html -http://www.brio.de/BRIO.catalog/39fe2f4306cb75f4273fd472aa780708/UserTemplate/2 -http://www.hole.kommune.no/hole/journweb.nsf/weboffjournal!OpenView&Start=92&Count=50&Expand=170 -http://polygraph.ircache.net:8181/docs/Win95/MSdialer/http_-2www.fastcounter.com/http_-2home.netscape.com/home/http_-2www.bildhome.com/plantationhomes/bale1500.htm -http://polygraph.ircache.net:8181/docs/Win95/MSdialer/http_-2www.fastcounter.com/http_-2home.netscape.com/home/http_-2www.bildhome.com/plantationhomes/bale8000.htm -http://writer.heha.net/poetics/90_poetics.htm -http://yp.gates96.com/5/55/20/98.html -http://yp.gates96.com/5/55/21/17.html -http://yp.gates96.com/5/55/21/75.html -http://yp.gates96.com/5/55/22/2.html -http://yp.gates96.com/5/55/22/22.html -http://yp.gates96.com/5/55/22/92.html -http://yp.gates96.com/5/55/23/11.html -http://yp.gates96.com/5/55/23/46.html -http://yp.gates96.com/5/55/23/66.html -http://yp.gates96.com/5/55/23/90.html -http://yp.gates96.com/5/55/24/2.html -http://yp.gates96.com/5/55/24/83.html -http://yp.gates96.com/5/55/24/85.html -http://yp.gates96.com/5/55/25/62.html -http://yp.gates96.com/5/55/26/38.html -http://yp.gates96.com/5/55/26/48.html -http://yp.gates96.com/5/55/28/5.html -http://yp.gates96.com/5/55/28/77.html -http://yp.gates96.com/5/55/29/14.html -http://yp.gates96.com/6/50/40/47.html -http://yp.gates96.com/6/50/40/60.html -http://yp.gates96.com/6/50/40/62.html -http://yp.gates96.com/6/50/41/81.html -http://yp.gates96.com/6/50/41/83.html -http://yp.gates96.com/6/50/42/58.html -http://yp.gates96.com/6/50/42/90.html -http://yp.gates96.com/6/50/42/93.html -http://yp.gates96.com/6/50/43/29.html -http://yp.gates96.com/6/50/43/79.html -http://yp.gates96.com/6/50/43/85.html -http://yp.gates96.com/6/50/44/40.html -http://yp.gates96.com/6/50/44/76.html -http://yp.gates96.com/6/50/44/81.html -http://yp.gates96.com/6/50/45/15.html -http://yp.gates96.com/6/50/45/52.html -http://yp.gates96.com/6/50/46/15.html -http://yp.gates96.com/6/50/46/19.html -http://yp.gates96.com/6/50/46/92.html -http://yp.gates96.com/6/50/47/2.html -http://yp.gates96.com/6/50/47/7.html -http://yp.gates96.com/6/50/47/33.html -http://yp.gates96.com/6/50/49/29.html -http://yp.gates96.com/6/50/49/36.html -http://www.outpersonals.com/cgi-bin/w3com/pws/out/wRtIx3JBCL5wVzA1pIKradbm9z4Oo2BbPRx_FVh-j4UyLzjojbipsV0nsuM2iF9RxJ1jG2C4LUy3YP5pJl7qDqPdnqV765l2x5hJ0fIUUJuWLaccxO0svbclJ4-alyBQj6Y5dO8YdURyhf9q05q8mJ25FlvF62sm -http://213.36.119.69/do/session/152980/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www3.travelprice.com/voyages/recherche.phtml -http://yp.gates96.com/6/2/20/11.html -http://yp.gates96.com/6/2/21/12.html -http://yp.gates96.com/6/2/21/51.html -http://yp.gates96.com/6/2/21/56.html -http://yp.gates96.com/6/2/22/8.html -http://yp.gates96.com/6/2/22/38.html -http://yp.gates96.com/6/2/22/65.html -http://yp.gates96.com/6/2/23/14.html -http://yp.gates96.com/6/2/23/50.html -http://yp.gates96.com/6/2/23/57.html -http://yp.gates96.com/6/2/23/75.html -http://yp.gates96.com/6/2/24/15.html -http://yp.gates96.com/6/2/24/31.html -http://yp.gates96.com/6/2/24/43.html -http://yp.gates96.com/6/2/24/70.html -http://yp.gates96.com/6/2/24/87.html -http://yp.gates96.com/6/2/25/22.html -http://yp.gates96.com/6/2/25/53.html -http://yp.gates96.com/6/2/25/90.html -http://yp.gates96.com/6/2/26/25.html -http://yp.gates96.com/6/2/26/26.html -http://yp.gates96.com/6/2/26/45.html -http://yp.gates96.com/6/2/26/76.html -http://yp.gates96.com/6/2/27/34.html -http://yp.gates96.com/6/2/28/1.html -http://yp.gates96.com/6/2/28/25.html -http://yp.gates96.com/6/2/29/2.html -http://yp.gates96.com/6/2/29/31.html -http://yp.gates96.com/6/2/29/57.html -http://yp.gates96.com/6/2/29/74.html -http://archive.bitcon.no/tucows//winme/preview/136862.html -http://archive.bitcon.no/tucows//winme/preview/138371.html -http://archive.bitcon.no/tucows//winme/preview/137011.html -http://archive.bitcon.no/tucows//winme/preview/137897.html -http://archive.bitcon.no/tucows//winme/preview/138157.html -http://www.ngmag.com/books/reference/0792275667.html -http://socrates.berkeley.edu:4231/pth.html -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/lit/music/midi/lit/quizz/lit/multiple.html -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/lit/music/midi/lit/quizz/lit/god.html -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/lit/music/midi/lit/quizz/misc/colorart/ -http://retailer.gocollect.com/do/session/1912687/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/postcards/index.asp -http://www.affiliate.hpstore.hp.co.uk/do/session/380807/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/creative/entry.asp -http://home.swipnet.se/~w-29806/Tab/Guitar/Svenska/h/Jakob%20Hellman/VACKERT_.TXT -http://jupiter.u-3mrs.fr/~msc41www/releves/16860204.HTM -http://citeseer.nj.nec.com/cidcontext/1003669 -http://citeseer.nj.nec.com/cidcontext/1003675 -http://citeseer.nj.nec.com/cidcontext/1003676 -http://www.escribe.com/religion/nondualitysalon/m10801.html -http://www.escribe.com/religion/nondualitysalon/m10824.html -http://www.tvstore.com/browse/TV/PATCH/s.bCooTxTe -http://digilander.iol.it/lorciao/computer.htm -http://yosemite.epa.gov/r9/sfund/overview.nsf/ef81e03b0f6bcdb28825650f005dc4c1/1d8f2e36da9dc1de8825660b007ee696?OpenDocument&ExpandSection=-1,-8,-4 -http://cn.egroups.com/post/ukr_liga?act=reply&messageNum=40 -http://www.lithoquoter.com/Scripts/WebObjects.exe/Printers.woa/048720000079262000002260000000798302/Session_Expired_Page.wo/6144200000698302/0/-/prime -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=coadjuvaram&l=pt -http://www.craft-supplies.co.uk/cgi-bin/psProdDet.cgi/LW132|972959517|Liming_&_Patinating|user|0|0,0,1,1 -http://www.angelfire.com/va/boogiescamp -http://www.kyotei.or.jp/JLC/VS/19/991209/0212.htm -http://www.affiliate.hpstore.hp.co.uk/do/session/380800/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/assistance/entry.asp -http://www.city-map.nl/city/map/en/Niedersachsen/Landkreis_Cuxhaven/customers/Dr.rer.nat._Büro_für_Erdwiss.Untersuchungen_Udo_Lade/contact.html -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=consternais&l=pt -http://muenchen.bda.de/freizeitparks/gastbuch/gaestebuch003.html -http://www.linux.com/networking/network/industry/growth/editing/SAP/ -http://www.linux.com/networking/network/industry/growth/editing/mobile/ -http://lists.omnipotent.net/qmail/199909/msg00892.html -http://lists.omnipotent.net/qmail/199909/msg00952.html -http://lists.omnipotent.net/qmail/199909/msg00964.html -http://ftp.cc.chuo-u.ac.jp/home/pub/lang/perl/CPAN/ports/msdos/old/?N=D -http://www3.buch-per-sms.de/faq.jsp$ID=To7697mC5277111659640048At0.5320036065114109 -http://www3.buch-per-sms.de/wir_ueber_uns.jsp$ID=To7697mC5277111659640048At0.5337056452821441 -http://tradersdirectory.com/channel/jobs/insurance/insurance_policy_clerk/b.2166.g.2360.html -http://www.mapion.co.jp/custom/nikkei/admi/13/13119/takashimadaira/7chome/27/ -http://www.dispatch.co.za/1998/02/19/easterncape/MARCHANC.HTM -http://www.techsupplies.com/sleuth/33/1/10703/523434/ -http://fi.egroups.com/message/911dispatchers/171 -http://polygraph.ircache.net:8181/services/define/toast/congress2000/http_-2www.sportfish.net/fish.htm -http://polygraph.ircache.net:8181/services/define/toast/congress2000/MS.htm -http://polygraph.ircache.net:8181/services/define/toast/congress2000/http_-2leader.linkexchange.com/1/X171400/clicklogo -http://polygraph.ircache.net:8181/services/define/toast/congress2000/cfiref.htm -http://www.digitaldrucke.de/(aktuell,arbeitsvermittlung,computer,daham,hilfe,individualverkehr,kultur,literatur,veranstaltungen,verkehr)/_fort/html/themen/aktuell/events/events.htm#regional -http://dellnet.excite.de/computer/katalog/7054 -http://read.cnread.net/cnread1/ztxs/b/baitian/lmss/006.htm -http://www-d0.fnal.gov/d0dist/dist/releases/psim01.02.00/l2utils/GNUmakefile -http://www.allgemeine-immobilien-boerse.de/Frankreich/Verkauf/Private-IB/Startseite/Gemeinsam/erreichenPartner/Gemeinsam/Inserieren/Allgemeine-IB/ -http://wish.themes.tucows.com/adnload/14495.html -http://wish.themes.tucows.com/preview/14494.html -http://wish.themes.tucows.com/preview/78220.html -http://www.uwm.edu/IMT/Computing/sasdoc8/sashtml/af/z0230835.htm -http://www.bdnet.com/Taiga/H/Fulu/fiche_serie.htm -http://se.egroups.com/message/clippingts/14?source=1 -http://adelaida.net/music/texts/trex_s1.html -http://archive.bitcon.no/pub/cica/handheld/desktop/ -http://www.jacksonhewitt.com/ctg/cgi-bin/JacksonHewitt/disclaimers/AAAksrACwAAACCMAAC -http://ftp.cc.chuo-u.ac.jp/home/pub/TeX/CTAN/language/ethiopia/ethtex/lj_fonts/?N=D -http://sirac.inrialpes.fr/Infos/Personnes/Christophe.Rippert/ressources/jdk1.3/docs/guide/jdbc/spec/jdbc-spec.frame16.html -http://www.linux.com/networking/network/release/press_release/competition/web/ -http://www.linux.com/networking/network/release/press_release/competition/internet/ -http://www.linux.com/networking/network/release/press_release/competition/HTTP/ -http://hughes.tucows.com/win2k/share2k_size.html -http://icq.planetout.com/popcornq/movienews/98/10/23/money/careers -http://go3.163.com/_NTES/~cntop07/files/k20808/zengby-k201/zengby-k201-09.html -http://uunetnl.pda.tucows.com/palm/pqa_news_license.html -http://uunetnl.pda.tucows.com/palm/preview/54359.html -http://uunetnl.pda.tucows.com/palm/preview/58637.html -http://uunetnl.pda.tucows.com/palm/adnload/72726_21807.html -http://uunetnl.pda.tucows.com/palm/adnload/62079_21796.html -http://uunetnl.pda.tucows.com/palm/preview/33674.html -http://uunetnl.pda.tucows.com/palm/preview/33501.html -http://uunetnl.pda.tucows.com/palm/adnload/52518_21780.html -http://ftp.dei.uc.pt/pub/net/ip/trace/traffic/?N=D -http://dreamgallery.simplenet.com/lobby/yrestless/sets/26/yrz19.htm -http://sanqin.net/wenyuan/gudian/fengshen/a/fengshen24.html -http://windows.tucows.com/preview/001-010-005-007C.html -http://windows.tucows.com/preview/001-010-005-004C.html -http://proshikanet.tucows.com/win2k/preview/37883.html -http://www5.cplaza.ne.jp/auth/kingdom/bbs/rescue/no70/182.html -http://www5.cplaza.ne.jp/auth/kingdom/bbs/rescue/no70/84.html -http://www5.cplaza.ne.jp/auth/kingdom/bbs/rescue/no70/82.html -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=7,19,34,20,29 -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=36,19,34,20,29 -http://www.ne.jp/asahi/kume-kume/kume/photogellery/zoo/nihon_saru/html/nihon_saru04.html -http://www.ne.jp/asahi/kume-kume/kume/photogellery/zoo/nihon_saru/html/nihon_saru05.html -http://www.iabusnet.org:90/forums/aca-1/dispatch.exe/survey/showNextUnseen/fol/100001/2443194 -http://www.chaos.dk/sexriddle/t/r/p/c/p/ -http://www.ld.com/cbd/archive/1999/09(September)/13-Sep-1999/16sol007.htm -http://www.ld.com/cbd/archive/1999/09(September)/13-Sep-1999/16sol024.htm -http://www.ld.com/cbd/archive/1999/09(September)/13-Sep-1999/16sol025.htm -http://www.ld.com/cbd/archive/1999/09(September)/13-Sep-1999/16sol030.htm -http://debian.linux.org.tw/debian/dists/Debian2.1r4/non-free/binary-alpha/oldlibs/?N=D -http://www.tamil.net/list/2000-04/nav00304.html -http://www.2pl.com/b/se/to/1/01/05/v2/1010500263-7.htm -http://www.2pl.com/b/se/to/1/01/05/v2/1010500263-8.htm -http://www.mirror.ac.uk/sites/ftp.microsoft.com/deskapps/powerpt/KB/Q129/5/ -http://www.gbnf.com/genealogy/royal92/html/d0028/I307.HTM -http://www-linux.gsi.de/linux-doc/libqt2/examples/qfd/?M=A -http://www.arm.com/sitearchitek/support.ns4/html/sdt_debug!OpenDocument&ExpandSection=24,6,37,7 -http://us.mandrakesoft.com/cgi-bin/cvsweb.cgi/kdeutils/kab/kab_kab1importer.h?sortby=log&only_with_tag=KDE_2_0_RELEASE -http://www.allgemeine-immobilien-boerse.de/nordrhein-Westfalen/bielefeld/Verkauf/Allgemeine-IB/Gemeinsam/versicherungen/gebaeude/Private-IB/Gemeinsam/erreichenPartner/email3d.htm -http://www.allgemeine-immobilien-boerse.de/nordrhein-Westfalen/bielefeld/Verkauf/Allgemeine-IB/Gemeinsam/versicherungen/gebaeude/Private-IB/3d-service/info.htm -http://satlink.tucows.com/winme/htmleditme_rating.html -http://satlink.tucows.com/winme/adnload/137630_29066.html -http://satlink.tucows.com/winme/adnload/137653_29087.html -http://yp.gates96.com/5/55/40/63.html -http://yp.gates96.com/5/55/40/93.html -http://yp.gates96.com/5/55/41/8.html -http://yp.gates96.com/5/55/41/27.html -http://yp.gates96.com/5/55/41/93.html -http://yp.gates96.com/5/55/42/1.html -http://yp.gates96.com/5/55/42/65.html -http://yp.gates96.com/5/55/43/15.html -http://yp.gates96.com/5/55/43/26.html -http://yp.gates96.com/5/55/43/94.html -http://yp.gates96.com/5/55/44/70.html -http://yp.gates96.com/5/55/44/83.html -http://yp.gates96.com/5/55/45/17.html -http://yp.gates96.com/5/55/46/3.html -http://yp.gates96.com/5/55/46/39.html -http://yp.gates96.com/5/55/46/43.html -http://yp.gates96.com/5/55/47/18.html -http://yp.gates96.com/5/55/48/23.html -http://yp.gates96.com/5/55/48/40.html -http://yp.gates96.com/5/55/48/72.html -http://yp.gates96.com/5/55/48/93.html -http://yp.gates96.com/5/55/49/7.html -http://yp.gates96.com/5/55/49/8.html -http://yp.gates96.com/5/55/49/20.html -http://yp.gates96.com/5/55/49/37.html -http://yp.gates96.com/5/55/49/49.html -http://yp.gates96.com/5/55/49/60.html -http://yp.gates96.com/5/55/49/69.html -http://www.ramtron.com/pages/visiters.htm -http://genforum.genealogy.com/cgi-genforum/forums/oh/wayne.cgi?56 -http://freebsd.ntu.edu.tw/perl/modules/by-module/DB_File/STAS/?N=D -http://sunsite.org.uk/public/usenet/news-faqs/alt.answers/us-visa-faq/?D=A -http://circumstance.co.kr/www.globalvillage.com/support/software.html -http://mediate.magicbutton.net/do/session/625589/vsid/4385/tid/4385/cid/88138/mid/1702/rid/2114/chid/3393/url/http://www.worldgallery.co.uk/frameset-top50.html -http://itcareers.careercast.com/texis/it/itjs/+9wwBmev6D86wwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewGPndhBiwGna5O5BnManDtoDnnGamnVncdpoDtaBn5Baw1BdMwBodDaGn31oGnma5Aocc5anLpnGonDqnaGnwcaMFqhTfR20DzmeTtwwwpBm3eP0-dmwww5rmehDwwwBrmeZpwww/morelike.html -http://library.bangor.ac.uk/search/dProtestant+churches+--+New+York+(State)+--+History+--+19th+century/dprotestant+churches+new+york+state+history+++19th+century/-17,-1,0,B/frameset&F=dprotestant+churches+england+history+++16th+century&2,,3 -http://augustachronicle.com/stories/021299/fea_223-4914.000.shtml -http://dreamcity.gaiax.com/www/dreamcity/k/n/kint/menu.html -http://commerce.was-inc.com/cgi-bin/abtwsam.dll/LbkWebCommerceMallCategories-BBC709D6_97E3_3D628A3FC67830F4FB7BD0E0AC833504 -http://www.mirror.kiev.ua:8082/paper/2000/07/1251/text/07-09-1.htm -http://www.burstnet.com/ads/ad7826a-map.cgi/1025131450 -http://link.fastpartner.com/do/session/600341/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/se/ -http://topcu.tucows.com/winme/adnload/137966_29370.html -http://topcu.tucows.com/winme/adnload/137990_29378.html -http://itcareers.careercast.com/texis/it/itjs/+9wwBmeS+D86swwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqew6hwAwMwoaBnqrDoqwcaqdD51cBoDta5wcn5aqdD51cBwDB5aBnqrDdcdton5apGd5pnqBoVnaq15BdMnG5apGdm1qBaBnwMaMFqtwAwMwoDzmehxwwwpBmeV+D86eqxwww5rmedDwwwBrmeZpwww/jobpage.html -http://itcareers.careercast.com/texis/it/itjs/+DwwBmeoWD86eDqwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqew6hwAwMwoaBnqrDoqwcaqdD51cBoDta5wcn5aqdD51cBwDB5aBnqrDdcdton5apGd5pnqBoVnaq15BdMnG5apGdm1qBaBnwMaMFqtwAwMwoDzmehxwwwpBmeV+D86eqxwww5rmeqDwwwBrmeZpwww/morelike.html -http://itcareers.careercast.com/texis/it/itjs/+QwwBme4+D86qxwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqew6hwAwMwoaBnqrDoqwcaqdD51cBoDta5wcn5aqdD51cBwDB5aBnqrDdcdton5apGd5pnqBoVnaq15BdMnG5apGdm1qBaBnwMaMFqtwAwMwoDzmehxwwwpBmeV+D86eqxwww5rm+mwwBrmeZpwww/jobpage.html -http://wwwbackup.trinler.net/anleitungen/manual/mod/mod_dll.html -http://wwwbackup.trinler.net/anleitungen/manual/mod/mod_log_agent.html -http://as400bks.rochester.ibm.com/pubs/html/as400/v4r5/ic2962/info/RZAIENETDOTDATA.HTM -http://www.gov.ie/educ/000928.htm -http://www.gov.ie/educ/speech/000928.htm -http://pub3.ezboard.com/utaela.showPublicProfile?language=EN -http://genforum.genealogy.com/cody/messages/700.html -http://genforum.genealogy.com/cody/messages/525.html -http://genforum.genealogy.com/cody/messages/494.html -http://genforum.genealogy.com/cody/messages/447.html -http://ftp.surfnet.nl/os/FreeBSD/cdrom/development/FreeBSD-CVS/ports/editors/psgml-emacs/files/home.html -http://www.mic.hr/PGBURZA:135556 -http://pub8.ezboard.com/fthecompanionswebboardfrm19 -http://pub8.ezboard.com/fthecompanionswebboardarchive -http://gallery2.simplenet.com/lobby/main/videocaps/ghoffman/precious/ghsp36.htm -http://www.symantec.ru/avcenter/venc/data/unashamed.html -http://www.symantec.ru/avcenter/cgi-bin/virauto.cgi?vid=7000 -http://www.symantec.ru/avcenter/cgi-bin/virauto.cgi?vid=1685 -http://www.symantec.ru/avcenter/cgi-bin/virauto.cgi?vid=5358 -http://rex.skyline.net/navigate.cgi?reading,retail,hobbies,painting,arts -http://rex.skyline.net/navigate.cgi?forsale,retail,hobbies,painting,arts -http://pds.nchu.edu.tw/cpatch/ftp/cuteftp/?S=A -http://www.tel.de/s/M/MCFIT.htm -http://zeus.uni-trier.de/~ley/db/indices/a-tree/s/Stevenson:Allan.html -http://www.alsapresse.com/jdj/00/07/14/SA/article_16.html -http://link.fastpartner.com/do/session/600359/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/jobpilot.php -http://link.fastpartner.com/do/session/600359/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/index.php -http://news.dreamwiz.com/news_lg/04/20001025/joins/200010251653041653193.html -http://news.dreamwiz.com/news_lg/04/20001025/joins/200010250820040820583.html -http://windows.tucows.com/winnt/adnload/71593_30161.html -http://213.36.119.69/do/session/152979/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/FR/reserver/encheres/ -http://213.36.119.69/do/session/152979/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/IT_IT/ -http://www.centc251.org/forums/aca-1/dispatch.cgi/isowg4/showNextUnseen/fol/100012/1220541 -http://bigpanda.net/46/alphabetical.html -http://bigpanda.net/46/io.html -http://fi.egroups.com/message/puzzles/547 -http://theaceshow.com/drawinglinda.html -http://theaceshow.com/drawingsketch.html -http://ftp.jp.debian.org/debian/dists/woody/main/binary-all/news/?D=A -http://www.trax.nilex.co.uk/trax.cgi/A1S/A2L/1AS/B3U/B4L/C2S/ -http://www.trax.nilex.co.uk/trax.cgi/A1S/A2L/1AS/B3U/B4L/C4D/ -http://in.egroups.com/message/islaam/3 -http://in.egroups.com/message/islaam/29 -http://ustlib.ust.hk/search*chi/a%7B233e68%7D%7B215976%7D%7B213e2e%7D/a%7B233e68%7D%7B215976%7D%7B213e2e%7D/-5,-1,0,B/browse -http://yp.gates96.com/13/8/20/68.html -http://yp.gates96.com/13/8/21/25.html -http://yp.gates96.com/13/8/21/32.html -http://yp.gates96.com/13/8/21/49.html -http://yp.gates96.com/13/8/21/63.html -http://yp.gates96.com/13/8/21/88.html -http://yp.gates96.com/13/8/22/2.html -http://yp.gates96.com/13/8/22/10.html -http://yp.gates96.com/13/8/22/67.html -http://yp.gates96.com/13/8/22/79.html -http://yp.gates96.com/13/8/23/19.html -http://yp.gates96.com/13/8/23/31.html -http://yp.gates96.com/13/8/25/64.html -http://yp.gates96.com/13/8/25/68.html -http://yp.gates96.com/13/8/25/73.html -http://yp.gates96.com/13/8/26/6.html -http://yp.gates96.com/13/8/26/11.html -http://yp.gates96.com/13/8/26/12.html -http://yp.gates96.com/13/8/26/39.html -http://yp.gates96.com/13/8/26/54.html -http://yp.gates96.com/13/8/26/55.html -http://yp.gates96.com/13/8/26/82.html -http://yp.gates96.com/13/8/27/89.html -http://yp.gates96.com/13/8/28/22.html -http://yp.gates96.com/13/8/28/61.html -http://yp.gates96.com/13/8/29/13.html -http://yp.gates96.com/13/8/29/33.html -http://yp.gates96.com/13/8/29/83.html -http://www.private-immobilien-boerse.de/baden-wuertemberg/ostalb-kreis/Verkauf/Versteigerungen-IB/Startseite/Gemeinsam/erreichenPartner/IIM-Teil/Startseite/GmbH-Kauf-Verkauf-Insolvenz-konkurs/Startseite/indexbeginn.htm -http://www2.so-net.ne.jp/mc/columns/nakama/1112/ -http://ring.shibaura-it.ac.jp/archives/pack/x68/personal/tokei/00_index.txt -http://yp.gates96.com/5/32/0/0.html -http://yp.gates96.com/5/32/0/99.html -http://yp.gates96.com/5/32/1/92.html -http://yp.gates96.com/5/32/1/93.html -http://yp.gates96.com/5/32/3/68.html -http://yp.gates96.com/5/32/4/21.html -http://yp.gates96.com/5/32/4/72.html -http://yp.gates96.com/5/32/5/87.html -http://yp.gates96.com/5/32/6/64.html -http://yp.gates96.com/5/32/7/25.html -http://yp.gates96.com/5/32/7/32.html -http://yp.gates96.com/5/32/7/44.html -http://yp.gates96.com/5/32/7/68.html -http://yp.gates96.com/5/32/7/78.html -http://yp.gates96.com/5/32/8/40.html -http://yp.gates96.com/5/32/8/59.html -http://yp.gates96.com/5/32/8/90.html -http://yp.gates96.com/5/32/8/95.html -http://yp.gates96.com/5/32/9/3.html -http://yp.gates96.com/5/32/9/54.html -http://yp.gates96.com/5/32/9/62.html -http://yp.gates96.com/5/32/9/77.html -http://tucows.soneraplaza.nl/winme/preview/138260.html -http://www.cnnews.com/maya/finance/cjsy/gncj/item/2000_07/206341.shtml -http://212.31.0.37/hur/turk/98/09/23/dunya/02dun.htm -http://212.31.0.37/hur/turk/98/09/12/dunya/01dun.htm -http://ftp.cwi.nl/ftp/mdr/LOCKED/ -http://ftp.cwi.nl/ftp/mdr/PICH/ -http://www.ncte.org/lists/ncte-talk/jan2000/msg02008.html -http://www.russ.ru/forums/prav-dir/conf2/695_r.htm -http://www.doc.ic.ac.uk/lab/labsrc_area/firstyear/submissions/1997-98/jmc1/labs/Ex05/mjp97/?D=A -http://www.affiliate.hpstore.hp.co.uk/do/session/380786/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/search.asp -http://www.flapjack.de/main/2ndHP/jangl43637.htm -http://195.166.55.201/vfg-uk/HTML/P145232.HTM -http://www.greenleaves.com/bookcat/gb_0689826788.html -http://webraft.its.unimelb.edu.au/730452/students/sgm/pub/ -http://ring.omp.ad.jp/pub/NetBSD/packages/pkgsrc/print/teTeX-share/files/ -http://ww.egroups.com/subscribe/wtcjk_purnawirawan -http://167.8.29.14/life/travel/ski/skinj.htm -http://www.nrk.no/finnmark/x26_5_97/fastesid/abonn.htm -http://www.brio.de/BRIO.catalog/39fe2f41050aa9b82741d472aa7806dd/UserTemplate/6 -http://207.25.71.143/golf/news/2000/04/18/heintz/ -http://weekends.worldres.com/script/gen_review.asp?hotel_id=4291&n=1231 -http://www.netitor.com/photos/schools/bc/sport/m-footbl/auto_pdf/weekly-release-082800.pdf -http://www.3w-sciencefiction.de/SmytheRH/SmytheRH0785808744.htm -http://www.zdnet.com/gamespot/stories/screens/0,10865,2617426-32,00.html -http://ftp.lip6.fr/pub2/sgml-tools/website/HOWTO/Root-RAID-HOWTO/t1450.html -http://webusers.siba.fi/doc/texmf/latex/ms/?M=A -http://www.trax.nilex.co.uk/trax.cgi/A1S/1AL/A3L/A1U/A3S/1AS/ -http://www.trax.nilex.co.uk/trax.cgi/A1S/1AL/A3L/A1U/A3S/D1U/ -http://www.trax.nilex.co.uk/trax.cgi/A1S/1AL/A3L/A1U/A3S/D3S/ -http://thaigate.rd.nacsis.ac.jp/ftp/thaisoft/nectec/linux.tle/6.01/Mandrake/?S=D -http://www-ind5.cricket.org/link_to_database/ARCHIVE/2000-01/AUS_LOCAL/GRADE/NSW/SCA/WOMEN/SCA-WOMEN_2000-01_FIXTURES.html -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=abbratend&l=de -http://www.webvillage.org/mBEDJPsite/html/downloadplugins.html -http://www.gov.karelia.ru:8081/gov/Karelia/658/8.html -http://www.private-immobilien-boerse.de/bayern/ingolstadt/Verkauf/GmbH-Kauf-Verkauf-Insolvenz-konkurs/Startseite/Gemeinsam/Inserieren/Gemeinsam/erreichenPartner/Ferien-IB/Startseite/ -http://pillsonline.00go.com/lowfatdiet/lifetime_fitness.htm -http://tecfa2.unige.ch/guides/java/examples/JavaClassLibExamples/io/FileReader/Main.class -http://www.burstnet.com/ads/ad7826a-map.cgi/1933336291 -http://l-infonet.phkk.fi/fi/TIETOPALVELUT/asiasanahaku/Hong%2520Kong/aasia/talous/pika-+ja+perustilastoja/ -http://home.tiscalinet.be/oaseidstad/vonk/optop2000.html -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=19,36,22,32,23 -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=29,36,22,32,23 -http://cn.egroups.com/messages/virtualaccess/194 -http://jerken.grida.no/nor/soeno97/ozone/frames/pressure.htm -http://online.excite.de/erotik/katalog/6213 -http://online.excite.de/erotik/katalog/6187 -http://online.excite.de/erotik/katalog/6221 -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=28,7,35,25,13 -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=31,7,35,25,13 -http://genforum.genealogy.com/cgi-genforum/forums/loughlin.cgi?11 -http://freesoftware.missouri.edu/pub/CPAN/authors/id/J/JS/JSWARTZ/?D=A -http://link.fastpartner.com/do/session/600360/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/fastpartner.php -http://www.jobvillage.com/channel/jobs/sciences/life_sciences/soil_plant_scientist/b.1041.g.251.html -http://ftp.debian.org/dists/Debian2.2r0/non-free/binary-sparc/mail/?D=A -http://generalstore.everdream.com/kore/catalog/Office_Supplies/General_Office_Supplies/Tape_Flags/Arrow/GRP-US6663/product.html -http://www.hig.se/(date,if,set,tablify,user)/~jackson/roxen/ -http://www.hig.se/(date,if,language,set,tablify)/~jackson/roxen/ -http://www.cyber-pages.com/0prog/classifieds_display.cgi?oakland=WEMP=0 -http://202.84.17.6/csnews/articles/141_18691.htm -http://202.84.17.6/csnews/articles/142_18526.htm -http://ftp.dti.ad.jp/pub/FreeBSD/FreeBSD-current/www/es/releases/1.1.5/ -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=9&discrim=247,207,129 -http://ftp.up.pt/Linux/debian/dists/unstable/main/disks-i386/?M=A -http://www.unterhaltungs-cd.de/HillJonny/B000025087.htm -http://filebox.vt.edu/users/aneal/excess/_fpclass/ -http://www.jamba.de/KNet/_KNet-JOt8j1-OEd-139q0/showInfo-presse.de/node.0/cde7f1uou -http://www.tercera.cl/diario/1997/12/05/win.html -http://yp.gates96.com/14/88/20/8.html -http://yp.gates96.com/14/88/20/13.html -http://yp.gates96.com/14/88/22/30.html -http://yp.gates96.com/14/88/25/28.html -http://yp.gates96.com/14/88/25/65.html -http://yp.gates96.com/14/88/26/3.html -http://bsdweb.pasta.cs.uit.no/bsdweb.cgi/~checkout~/pkgsrc/math/grace/pkg/ -http://ftp.tokyonet.ad.jp/pub/Linux/debian-jp/dists/unstable-jp/contrib/binary-m68k/math/?S=A -http://my.dreamwiz.com/piramos/lan.htm -http://pub8.ezboard.com/fselfreliantlivingfrm16.showMessage?topicID=11.topic -http://pub8.ezboard.com/fselfreliantlivingfrm16.showMessage?topicID=4.topic -http://www.affiliate.hpstore.hp.co.uk/do/session/380798/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/SMARTTIPS/vacationcards.asp -http://systemlogic.neoseeker.com/Companies/productportfolios/NEC_Interchannel/?sortby=sections -http://www.houses-apartment-rentals.com/Virginia/city_search_criteria.asp?state=VA&City=DALHART -http://www.wcbcourses.com/wcb2/schools/MERCED/merced/dhauser/2/forums/forum2/messages/17.html -http://www.wcbcourses.com/wcb2/schools/MERCED/merced/dhauser/2/forums/forum2/messages/10.html -http://beautifulsavers.subportal.com/sn/Shell_and_Desktop/Quick_Shutdown_Tools/2702.html -http://polygraph.ircache.net:8181/getting_started/http_-2www.lucent.com/micro/K56flex/http_-2home.netscape.com/comprod/mirror/http_-2www.wtcsf.org/mall/http_-2www.cdnow.com/http_-2www.microsoft.com/msoffice/publicaffairs.html -http://polygraph.ircache.net:8181/getting_started/http_-2www.lucent.com/micro/K56flex/http_-2home.netscape.com/comprod/mirror/http_-2www.wtcsf.org/mall/http_-2www.cdnow.com/http_-2www.microsoft.com/msoffice/videobroadcast/ -http://www.yagoo.co.kr/stats/pitching.asp?Mlbmanid=JESPEN7599 -http://www.4hotfantasy.com/acommon/guests/python4.html -http://boerseninfos.ksk-tut.de/dynamic/ak/adhoc/news/519000-20000316-150811.html -http://boerseninfos.ksk-tut.de/dynamic/ak/adhoc/news/519000-19991025-082814.html -http://cn.yahoo.com/Regional/Countries_and_Regions/China/Provinces__Regions_and_Municipalities/Zhejiang/Cities_and_Towns/Li_Hsua/Business/Companies/Books/ -http://www.affiliate.hpstore.hp.co.uk/do/session/380810/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/FR/REGISTRATION/entry.asp -http://kuyper.calvin.edu/fathers2/NPNF1-01/npnf1-01-12.htm -http://library.bangor.ac.uk/search/dModernism+(Literature)/dmodernism+literature/-5,-1,0,E/2browse -http://aleph.tau.ac.il:4500/ALEPH/ENG/ATA/AAS/AAS/SHORT/410519/1/ -http://pub1.ezboard.com/fflashboard1flashjunkiestalk.showAddReplyScreenFromWeb?topicID=190.topic&index=2 -http://www.inforiese.de/db_cargo/typ_b_files/db_cargo_cargo_ansprechpartner.shtml -http://www.gbnf.com/genealogy/dehart/html/d0005/I985.HTM -http://btclickfam.excite.co.uk/directory/categories/670199 -http://www.worldmedicus.com/servlet/Controller/$7008040516620000.sj_viewc/ -http://www.worldmedicus.com/servlet/Controller/$7008040528250000.sj/ -http://207.25.71.143/features/galleries/then_and_now/belinsky/belinsky01_lg_01.html -http://wiem.onet.pl/wiem/002c66.html -http://www.peopledaily.com.cn/GB/paper40/544/58242.html -http://www.uihealthcare.com////PatientsVisitors/MedMuseum/CenturyOfCaring/UniversityHospitals/05Quarantine.html -http://se.egroups.com/login.cgi?login_target=%2Fmessages%2Fwotccglist%2F333 -http://se.egroups.com/message/wotccglist/334 -http://se.egroups.com/message/wotccglist/350 -http://se.egroups.com/message/wotccglist/358 -http://www.msn.expedia.co.uk/wg/North_America/United_States/P30131.asp -http://www.uol.com.br/cinemaonline/starwars -http://www.perotech.ch/d/securedb/html/listtopic.php?7396 -http://moviestore.zap2it.com/browse/X-FILES/POSTCARD/s.goFzN1Lb -http://zeus.uni-trier.de/~ley/db/indices/a-tree/m/Morgoev:Vladimir_K=.html -http://www.3w-buecher.de/GilliesRobertJ/GilliesRobertJ0122839803.htm -http://www.buybuddy.com/sleuth/27/1/11002/6637/ -http://ftp.uk.debian.org/debian/dists/unstable/contrib/binary-powerpc/oldlibs/?D=A -http://no.egroups.com/login.cgi?login_target=%2Fgroup%2Fwww.members.xoom.com%2FLibertyFlame -http://www.aelita.net/products/support/sitemap/Reg/QuoteRegister/news/company/Copyright.htm -http://www.aelita.net/products/support/sitemap/Reg/QuoteRegister/news/services/default.htm -http://www.amateurplatinum.com/spankingfantasy/fertiletrophy-wife/hot-hardcore-fuckinglongest/red-toenail-polishfeet-fucking-/vietnamesewomen/chinesechi/womenpetite.html -http://www.amateurplatinum.com/spankingfantasy/fertiletrophy-wife/hot-hardcore-fuckinglongest/red-toenail-polishfeet-fucking-/vietnamesewomen/fuckinghard/actionsmacking.html -http://genforum.genealogy.com/cgi-bin/print.cgi?fikes::26.html -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/lit/programs/unlambda/lit/quizz/music/midi/ -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/lit/programs/unlambda/lit/quizz/computers/callcc.html -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/lit/programs/unlambda/lit/quizz/misc/colorart/ -http://www.musiciansfriend.com/ex/ds/live/001030182726064208037002434823 -http://www.musiciansfriend.com/ex/ds/home/funzone/001030182726064208037002434823?doc=doc,postcard.html -http://www.musiciansfriend.com/ex/ds/home/platinum/001030182726064208037002434823?g,home.platinum.html -http://www.musiciansfriend.com/ex/ds/home/articles/001030182726064208037002434823?dbase=gw,gwmain.html -http://www.musiciansfriend.com/ex/ds/home/articles/001030182726064208037002434823?dbase=info,privacy.html -http://preview.egroups.com/dir/Business/Training_and_Schools/Management_Training/Consultants?st=4 -http://hammer.prohosting.com/~nieting/html1216/lmtf015.htm -http://planetfreebies.subportal.com/sn/Information_Management/Misc__Information_Databases/12835.html -http://dada.linuxberg.com/kdehtml/adnload/61589_33448.html -http://www.wlu.ca/~wwwregi/95-96/cal/ucourses/GM/GM151.html -http://walkabout.tucows.com/win2k/adnload/61015_28629.html -http://www.1001e.net/02/qbt/09.htm -http://se.egroups.com/post/webfaaa?act=reply&messageNum=3 -http://smb.slac.stanford.edu/cgi-bin/nph-proxy.cgi/000/http/keats.admin.virginia.edu/asbestos/home.html -http://www.hotelboulevard.com/fr/riviera/standard/htmlf752567459c6d803842381c50e94fd9f/sessionLang/ANG/gettingstarted.html -http://ring.omp.ad.jp/pub/NetBSD/packages/pkgsrc/print/transfig/?N=D -http://citeseer.nj.nec.com/cidcontext/2339336 -http://www.uk.multimap.com/p/browse.cgi?pc=LS287DR -http://topcu.linux.tucows.com/x11html/adnload/46019_3809.html -http://www.mon.de/nr/stuemges -http://www.tamil.net/list/1998-10/msg00212.html -http://retailer.gocollect.com/do/session/1912682/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/company_info/terms_and_conditions.asp -http://pl.php.net/manual/nl/function.pfpro-version.php -http://members.tripod.co.jp/millenium/top.html -http://community.webshots.com/photo/4331085/4331572GooaFzYUAJ -http://community.webshots.com/photo/4331085/4331589oKrBmsJbga -http://community.webshots.com/photo/4331085/4331620zgfyMLoSjs -http://www.utdallas.edu/~chansen/text/qabbala9.html -http://www.jobvillage.com/channel/jobs/installation_repair/safety_equipment/fire_alarm/b.2283.g.3516.html -http://www.geocities.com/Area51/Chamber/8750/DoesKitEverTalkAboutTheSubjectOnHand.html -http://www.geocities.com/Area51/Chamber/8750/TheMotherofAllMissleBoats.html -http://www.geocities.com/Area51/Chamber/8750/Tomahawk2.html -http://www.thecitizennews.com/main/archive-000628/thecitizennews/citizen.html -http://links2go.publiweb.com/expert/topic/Mp3_Hardware -http://webhelp.promovacances.net/S02/BL/BEGYP/SAI00512024/cal.htm?d=1013 -http://205.161.150.96/cgi-bin/c2k/title_talent.html&id=143786&title_star=DOMINICK -http://dennou-q.geo.kyushu-u.ac.jp/library/Linux/debian-jp/dists/stable/non-free-jp/binary-all/net/?S=A -http://wow-online.vhm.de/Wirtschaft/Unternehmen/Versicherungen/Versicherungsgesellschaften/Signal_Versicherung.html -http://www.linux.com/networking/network/firewall/web/communications/?kw_offset=50 -http://www.leg.wa.gov/pub/rcw%20-%20text/title_28b/chapter_056/rcw_28b_56_090.txt -http://pub12.ezboard.com/flalaland96545listeningbooth.showMessage?topicID=74.topic -http://www.fogdog.com/cedroID/ssd3040183156032/crs/pw__/wld/fogdog_sports/lee_sport/fan_memorabilia/apparel/new_york_yanke_2000_ameri_leagu_champ_tee_shi.html -http://www.fogdog.com/cedroID/ssd3040183156032/nav/stores/adventure_travel/ -http://www.hoovers.com/travel/cityguide/detailed/0,3368,46_119158,00.html -http://user.chollian.net/~mlsc/ -http://www.158china.com/data/stock/fundowner/default.asp?stck_cd=0548 -http://www.affiliate.hpstore.hp.co.uk/do/session/380803/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/SMARTTIPS/createbroch.asp -http://rcsl.auto.inha.ac.kr/~treeman/Documents/HOWTO/Consultants-HOWTO-3.html -http://www.diogenes.ch/4DACTION/web_rd_aut_prview/a_id=7056427&area=&ID=483330 -http://polygraph.ircache.net:8181/http_-2www.horizonfinance.com/http_-2www.netscape.com/download/http_-2www.microsoft.com/ie/http_-2207.91.150.20/links.html -http://www.multicosm.com/facade/www.adobe.com/support/techguides/printpublishing/scanning/psscanning01b.html -http://yp.gates96.com/0/50/10/62.html -http://yp.gates96.com/0/50/10/95.html -http://yp.gates96.com/0/50/11/1.html -http://yp.gates96.com/0/50/11/18.html -http://yp.gates96.com/0/50/11/49.html -http://yp.gates96.com/0/50/12/55.html -http://yp.gates96.com/0/50/13/48.html -http://yp.gates96.com/0/50/13/96.html -http://yp.gates96.com/0/50/14/15.html -http://yp.gates96.com/0/50/14/73.html -http://yp.gates96.com/0/50/15/50.html -http://yp.gates96.com/0/50/15/80.html -http://yp.gates96.com/0/50/16/1.html -http://yp.gates96.com/0/50/16/8.html -http://yp.gates96.com/0/50/17/50.html -http://yp.gates96.com/0/50/17/71.html -http://yp.gates96.com/0/50/18/25.html -http://yp.gates96.com/0/50/18/73.html -http://yp.gates96.com/0/50/18/82.html -http://yp.gates96.com/0/50/18/84.html -http://yp.gates96.com/0/50/18/90.html -http://cisne.sim.ucm.es/search*spi/dBallets+--+Gran+Bretaña+--+Discos+compactos/dballets+gran+bretan~aa+discos+compactos/-29,-1,0,B/browse -http://opac.lib.ntnu.edu.tw/search*chi/++ftlist/bp20005025/-17,-1,0,B/browse -http://www.trax.nilex.co.uk/trax.cgi/A1S/1AL/A3L/A4R/B1D/A3S/ -http://php.nic.fi/manual/html/function.cpdf-open.html -http://php.nic.fi/manual/html/function.cpdf-fill.html -http://php.nic.fi/manual/html/function.cpdf-setrgbcolor-fill.html -http://www.classiccmp.org/mail-archive/classiccmp/1998-04/1426.html -http://text.csn.ul.ie/~danny/tabs/p/proclaimers/?N=D -http://mirror.nucba.ac.jp/mirror/FreeBSD/branches/3.0-stable/ports/japanese/zangband/?N=D -http://augustachronicle.com/stories/100197/spo_fishing.html -http://www.symatrixinc.com/website/website.nsf/0/3e40df86fb357cd5882568720079613f!OpenDocument&ExpandSection=10,8,9,5 -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/linux/music/quizz/pics.html -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/linux/music/quizz/lit/ldvelh.html -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/linux/music/quizz/misc/unitest/ -http://mirror.nucba.ac.jp/mirror/FreeBSD/branches/3.0-stable/ports/japanese/ptex-pkfonts360/?N=D -http://www.2pl.com/b/ru/fi/1/24/06/b1/1240601249-11023.htm -http://galaxy.einet.net/galaxy/Community/United-States/States/Minnesota/Cities-and-Regions/Winona/Education/K--12/Middle/Public.html -http://www.hotelboulevard.com/fr/paris/standard/htmlc866e5cecf73322551f00b0108eb84bc/sessionLang/ANG/prov/browse/cp/75001/resultatSearch.html -http://btp1da.phy.uni-bayreuth.de/ftp/pub/FreeBSD/ports/japanese/dvipsk-vflib/pkg-descr -http://32548news.subportal.com/sn/Utilities/Misc__Encryption_Utilities/ -http://www.hongen.com/proedu/hext/zxks/dxyw/html/dxy62804.htm -http://www.users.globalnet.co.uk/~roy/InternetTree/WC01/WC01_226.htm -http://www2.msstate.edu/~eaddy/famtread/html/nti07339.htm -http://www.trackinfo.com/trakdocs/hound/ca/RESULTS/ARCHIVE/1996/0996/GRCA19S.HTM -http://www.idg.net/crd_essential_110984.html -http://www.zdnet.de//news/artikel/2000/09/06015-wc.html -http://www.secinfo.com/d114Cu.52.htm -http://www.kfi640.com/shared/mod_perl/looksmart/looksmart/eus1/eus141561/eus174865/eus327367/eus327527/eus331435/ -http://enjoy100.com.cn/200005/23/ -http://link.fastpartner.com/do/session/600348/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/mediatransfer.php -http://www.chaos.dk/sexriddle/t/z/p/b/b/ -http://www.brio.de/BRIO.catalog/39fe2f4106ca8ce0273fd472aa7806ff/UserTemplate/6 -http://link.fastpartner.com/do/session/600352/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/robinhus.php -http://link.fastpartner.com/do/session/600352/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/create/index.php -http://www.underground-online.com/companyfinder/filters/products/0,9996,1793-101,00.html -http://mediate.magicbutton.net/do/session/625588/vsid/3342/tid/3342/cid/88020/mid/2008/rid/2313/chid/2648/url/http://www1.getmapping.com/viewer.cfm -http://aol.digitalcity.com/houston/recreation/event.dci?eid=6452 -http://www.linux.com.hk/mirror/ldp/LDP/LG/issue10/lg_bytes10.html -http://www.linux.com.hk/mirror/ldp/LDP/LG/issue10/issue10.txt -http://www.beauty.net.cn/main/japanese/mie.htm -http://www.allgemeine-immobilien-boerse.de/kanada/verkauf/Gemeinsam/Inserieren/Allgemeine-IB/Ferien-IB/Startseite/Private-IB/Startseite/Default.htm -http://www.kodak.co.uk/US/en/corp/store/catalog/Product.jhtml?PRODID=2113&CATID=2234 -http://opac.lib.ntnu.edu.tw/search*chi/f373+017/f373+017/-5,-1,,B/browse -http://ftp.du.se/disk3/mandrake/7.1/Mandrake/mdkinst/etc/pcmcia/?M=A -http://www.teenplatinum.com/barelylegal/anal-sexass/taismall/almond-skinned/{gaylink} -http://194.128.65.4/pa/cm199697/cmhansrd/vo970318/debtext/70318-11.htm -http://netlondon.hotelbook.com/live/photos/19368 -http://www.centc251.org/forums/aca-1/dispatch.cgi/hsi/folderFrame/100205/0/author/1243894 -http://www.teacherformation.org/html/od/facilitators.cfm/task1,login/discussion_id,2/xid,5474/yid,3022999 -http://polygraph.ircache.net:8181/environment_energy/heritage/http_-2www.apache.org/ -http://plat.debian.or.jp/debian/dists/unstable/main/binary-alpha/math/?D=A -http://home.hiwaay.net/~bjacobs/genealogy/laster/html/d0054/g0000038.html -http://www.northampton.ac.uk/cgi-bin/liberation/betsie/betsie.pl/1005/www.northampton.ac.uk/cgi-bin/liberation/betsie/betsie.pl/1037/www.northampton.ac.uk/lrs/Information/refword.html -http://ustlib.ust.hk/search*chi/cPL1275+.F426+1991/cpl+1275+f426+1991/-5,1,1,E/frameset&F=cpl+1273+y36+1982&1,1, -http://stormix.com/en/resources/packages/tex/devel/debmake -http://stormix.com/en/resources/packages/tex/devel/doc++ -http://stormix.com/en/resources/packages/tex/devel/ftnchek -http://stormix.com/en/resources/packages/tex/devel/libnet0-dev -http://stormix.com/en/resources/packages/tex/devel/libobgtk-dev -http://stormix.com/en/resources/packages/tex/devel/netatalk-dev -http://stormix.com/en/resources/packages/tex/devel/pact-base -http://stormix.com/en/resources/packages/tex/devel/scalapack1-mpich -http://members.tripod.co.jp/sugisaka/?M=A -http://www.szinfo.com/book/wai/no/fa/h/hongyuhei/011.htm -http://www.szinfo.com/book/wai/no/fa/h/hongyuhei/054.htm -http://www.centc251.org/forums/aca-1/dispatch.cgi/hsi/listUnseen/fol/100205/20,0/1230074 -http://www.crutchfield.com/cgi-bin/S-p5rPnwuC0SA/Auto.asp -http://www.abb.co.uk/global/seapr/SEAPR035.NSF/viewUNID/f79b6db19a951ce0c125697300319a41!OpenDocument&ExpandSection=6,4,8,5 -http://freebsd.ntu.edu.tw/perl/authors/id/A/AO/AOCINAR/?S=A -http://www.gaymencam.com/elke.html -http://www.linux.com/networking/network/industry/new/web_server/website/ -http://www.tccomputers.com/cgi-bin/bp/1899758621/products/removeabledrives/removeabledrives.htm -http://www.tccomputers.com/cgi-bin/bp/1899758621/store/showcart.html -http://www.highwired.net/Guidance/Section/0,1860,1779-27626,00.html -http://gd.cnread.net/cnread1/net/zpj/r/repinsky/005.htm -http://www.amateurplatinum.com/tubal-ligationmilk/pregnanttubal-ligation/off-the-ragnipples/jizz-dribbling-cumshotscumming/{amateurlink} -http://home.dqt.com.cn/~why/wenzhang/ckpajq/.htm -http://ftp.fi.debian.org/debian/dists/woody/non-free/binary-all/doc/?D=A -http://www.linux.com/networking/network/website/hardware/howto/Linuxcare/ -http://www.linux.com/networking/network/website/hardware/howto/sales/ -http://shn.webmd.com/printing/asset/adam_imagepage_8626 -http://www.geocities.co.jp/Outdoors/2127/bangai_makuyama.html -http://www2.to/souhey -http://www.hotelboulevard.com/fr/paris/standard/html73b90b9d262d517e98c9d779b3b09b7a/sessionLang/ANG/prov/browse/cp/75017/resultatSearch.html -http://perso.wanadoo.fr/olivier.leieber/page22.html -http://www.computer-networking.de/studenten/dv_labor/onlinebuecher/apache/sections.html -http://saejong.pufs.ac.kr/~cilim/homepage/link.html -http://cafe3.daum.net/Cafe-bin/Bbs.cgi/hopepds/qry/zka/B2-kCYFp/qqatt/^ -http://www3.newstimes.com/archive99/jun1899/lch.htm -http://www.7thlevel.com/python/cwot/demo/ -http://www.paidmania.com/getpaid/signup/100/4632 -http://yp.gates96.com/12/14/0/31.html -http://yp.gates96.com/12/14/0/43.html -http://yp.gates96.com/12/14/0/60.html -http://yp.gates96.com/12/14/1/18.html -http://yp.gates96.com/12/14/1/44.html -http://yp.gates96.com/12/14/1/64.html -http://yp.gates96.com/12/14/1/82.html -http://yp.gates96.com/12/14/2/84.html -http://yp.gates96.com/12/14/3/61.html -http://yp.gates96.com/12/14/4/65.html -http://yp.gates96.com/12/14/5/24.html -http://yp.gates96.com/12/14/5/49.html -http://yp.gates96.com/12/14/5/60.html -http://yp.gates96.com/12/14/5/62.html -http://yp.gates96.com/12/14/6/20.html -http://yp.gates96.com/12/14/6/51.html -http://yp.gates96.com/12/14/7/28.html -http://yp.gates96.com/12/14/7/85.html -http://yp.gates96.com/12/14/7/93.html -http://planet.gaiax.com/home/kito/main -http://www.svt.se/falun/packat/program/603/images/1rep/?D=A -http://volunteersolutions.org/swt/volunteer/opp/one_151124_printer_detailed.html -http://fyi.cnn.com/ASIANOW/asiaweek/97/1003/nat1.html -http://www.farhi.org/ps09/ps09_233.htm -http://yp.gates96.com/6/8/30/27.html -http://biz.yahoo.com/apf/000929/tire_death_7.html -http://www.studentadvantage.gamers.com/game/135583 -http://www.studentadvantage.gamers.com/game/45759 -http://yp.gates96.com/6/8/30/44.html -http://yp.gates96.com/6/8/30/50.html -http://yp.gates96.com/6/8/30/72.html -http://yp.gates96.com/6/8/30/86.html -http://yp.gates96.com/6/8/30/89.html -http://yp.gates96.com/6/8/31/78.html -http://yp.gates96.com/6/8/31/88.html -http://yp.gates96.com/6/8/32/3.html -http://yp.gates96.com/6/8/32/24.html -http://yp.gates96.com/6/8/32/34.html -http://yp.gates96.com/6/8/33/14.html -http://yp.gates96.com/6/8/33/42.html -http://yp.gates96.com/6/8/33/75.html -http://yp.gates96.com/6/8/34/32.html -http://yp.gates96.com/6/8/34/97.html -http://yp.gates96.com/6/8/35/53.html -http://yp.gates96.com/6/8/35/98.html -http://yp.gates96.com/6/8/36/74.html -http://yp.gates96.com/6/8/36/99.html -http://yp.gates96.com/6/8/38/92.html -http://yp.gates96.com/6/8/38/97.html -http://yp.gates96.com/6/8/39/45.html -http://yp.gates96.com/6/8/39/69.html -http://tour.stanford.edu/tour/29.0/gMlPb -http://idl.tucows.com/winme/adnload/138396_30343.html -http://idl.tucows.com/winme/adnload/138395_29743.html -http://web.singnet.com.sg/~tay7012i/family.htm -http://www.chaos.dk/sexriddle/p/f/g/j/o/ -http://lcweb2.loc.gov/ll/llnt/070/?S=A -http://lcweb2.loc.gov/ll/llnt/070/0100/ -http://www.crosswinds.net/~lucifern/ -http://pub14.ezboard.com/fblazinofdablazinestdabattledome.subscribeUnregisteredToTopic?topicID=190.topic -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/computers/computers/lit/quizz/programs/unlambda/misc/peanuts.html -http://members.se.tripod.de/svdata/inglis/sida2.htm -http://www.fogdog.com/cedroID/ssd3040183217284/crs/hp/nav/stores/golf/ -http://198.103.152.100/search*frc/tOperations+guide+to+ZIM/toperations+guide+to+zim/-17,-1,0,E/2browse -http://herndon1.sdrdc.com/cgi-bin/com_detail/C00186353 -http://www.j2ee.com/products/javamail/javadocs/javax/mail/Flags.html -http://www.j2ee.com/products/javamail/javadocs/javax/mail/Header.html -http://www.intellicast.com/Sail/World/UnitedStates/FourCorners/Arizona/LakeMeadCanyon/LocalWinds/d1_18/ -http://genforum.genealogy.com/cgi-bin/print.cgi?guill::871.html -http://in.egroups.com/message/ucc-medicine/9 -http://in.egroups.com/message/ucc-medicine/14 -http://www-uk3.cricket.org/link_to_database/PLAYERS/WOMEN/AUS/WILSON_B_02011221/index.NSW-WOMEN.html -http://ftp.du.se/disk4/FreeBSD/FreeBSD-current/www/ja/releases/?M=A -http://www.citythek.de/koeln/eduscho/fsinhalt.htm -http://198.103.152.100/search*frc/cCA1+MPY30+97C31/cca1+mpy30+97c31/-5,-1,,E/browse -http://ftp.nsysu.edu.tw/Linux/RedHat/doc/en/HOWTOS/localization/Serbian/?N=D -http://mk158.tripod.co.jp/old/praga1/do/bio.html -http://oneplace.adbureau.net/accipiter/adclick/site=ONEPLACE/area=INDEX/POSITION=FOOTER/AAMSZ=468x60/ACC_RANDOM=449975866078 -http://members.tripod.co.jp/Primrose/honeydcolumn3.html -http://911codes.com/games/platform/n64/sect/div/cont/list_cheat/spray/y/id/0000009564/gid/0000003291/_cheats/_walkthroughs/_codes/_pc/_n64/_psx/_gameboy/_playstation/ -http://iqseek.shop.goto.com/compperiph/monfol/mon/search/detail.jhtml?MANUF=ViewSonic&MODEL=E790 -http://iqseek.shop.goto.com/compperiph/monfol/mon/search/detail.jhtml?MANUF=ViewSonic&MODEL=GA655 -http://plat.debian.or.jp/debian/dists/stable/main/binary-powerpc/shells/?M=A -http://retailer.gocollect.com/do/session/1912686/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/company_info/shipping_policy.asp -http://vvv.geocities.co.jp/Playtown-Yoyo/5287/ -http://vvv.geocities.co.jp/Playtown-Yoyo/5714/ -http://vvv.geocities.co.jp/Playtown-Yoyo/5750/ -http://genforum.genealogy.com/cgi-genforum/forums/charpia.cgi?3 -http://www.amateurplatinum.com/tubal-ligationmilk/plus-sizecoushin-for-the-pushin/best-friendsjail-bait/vietnamese/ac/dclubrication/bisexualelbow-grease.html -http://library.bangor.ac.uk/search/tContemporary+psychology+series/tcontemporary+psychology+series/-17,-1,0,B/2exact&F=tcontemporary+problems+in+geography&1,4 -http://www-d0.fnal.gov/cgi-bin/cvsweb.cgi/calreco/VERSION?only_with_tag=p05-br -http://www.158china.com/news/2000/08/21/52747.htm -http://www.ln.cei.gov.cn/dh/hgjj/wscf/hx/hx031009.txt -http://www.ln.cei.gov.cn/dh/hgjj/wscf/hx/hx031106.txt -http://www.ln.cei.gov.cn/dh/hgjj/wscf/hx/hx031208.txt -http://www.ln.cei.gov.cn/dh/hgjj/wscf/hx/hx031507.txt -http://www.ln.cei.gov.cn/dh/hgjj/wscf/hx/hx032406.txt -http://www.ln.cei.gov.cn/dh/hgjj/wscf/hx/hx032902.txt -http://www.ln.cei.gov.cn/dh/hgjj/wscf/hx/hx041501.txt -http://www.ln.cei.gov.cn/dh/hgjj/wscf/hx/hx041611.txt -http://www.ln.cei.gov.cn/dh/hgjj/wscf/hx/hx1.txt -http://wuarchive.wustl.edu/edu/math/software/multi-platform/SLATEC/G/G2/G2H/G2H2/sbols/ -http://www.loststars.net/story4/ab200-2.html -http://www.indian-express.com/ie/daily/19981219/35350564.html -http://www.indian-express.com/ie/daily/19981219/35351234.html -http://www.homestead.com/jennyb/pets.html -http://www.allgemeine-immobilien-boerse.de/kanada/verkauf/Gemeinsam/Inserieren/Allgemeine-IB/Versteigerungen-IB/Startseite/Gemeinsam/suche.htm -http://www.sankei.co.jp/databox/paper/9808/06/paper/today/sports/soccer/06soc002.htm -http://rex.skyline.net/navigate.cgi?history,collectibles,recreation,sculpture,arts -http://tjohoo.se/sport/snowboard/2.php3 -http://www.du-et.net/prof/n/nkaworu.html -http://www.iwon.com/home/movies/movies_summary_page/0,13160,383543,00.html -http://www.iwon.com/home/movies/movies_summary_page/0,13160,481885,00.html -http://www.iwon.com/home/movies/movies_summary_page/0,13160,372508,00.html -http://pub13.ezboard.com/fvisualbasicexplorergettingstarted.emailToFriend?topicID=861.topic -http://www.fogdog.com/cedroID/ssd3040183158417/customer_service/ -http://www.fogdog.com/cedroID/ssd3040183158417/cgi-bin/CedroCommerce?func=EditBasket -http://www.fogdog.com/cedroID/ssd3040183158417/nav/products/cycling/1y/software/ -http://www.niwl.se/wais/new/28/28189.htm -http://retailer.gocollect.com/do/session/1912674/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/clubhouse/suggestions.asp -http://www.trax.nilex.co.uk/trax.cgi/A1C/A2R/A2U/B3R/A1U/Resign/ -http://www.sofitware.com/books/sci05/0471969664.html -http://www.genome.wustl.edu:8021/gsc1/est/zebrafish_reports/old_rank_reports/zebrafish.rank.990322 -http://www.genome.wustl.edu:8021/gsc1/est/zebrafish_reports/old_rank_reports/zebrafish.rank.991004 -http://www.farhi.org/ps01/ps01_015.htm -http://www-usa10.cricket.org/link_to_database/ARCHIVE/WORLD_CUPS/WC99/STATS/BY_TEAM/SL/WC99_BOWL_BEST_INNS_SR_SL.html -http://www.online.kokusai.co.jp/Stock_corner/V0043480/wrd/G500/stock_corner/stock_corner.html -http://www.online.kokusai.co.jp/Mmf_corner/V0043480/mmf_corner/mmf_corner/url -http://mediate.magicbutton.net/do/session/625604/vsid/4385/tid/4385/cid/88138/mid/1702/rid/2114/chid/3393/url/http://www.worldgallery.co.uk/frameset-cust.html -http://www.malaysia.net/lists/sangkancil/1999-05/frm00449.html -http://www.bigstar.com/contest/index.cfm/4ae093fg371d8ddg3?fa=contest -http://www.bigstar.com/tv/index.cfm/4ae093fg371d8ddg3 -http://linux.tucows.dia.dk/gnomehtml/adnload/49933_5879.html -http://dc.web.aol.com/roanoke/health/directories.dci?type=professionals -http://dc.web.aol.com/roanoke/health/categories.dci?category=fitnessdiet -http://oss.sgi.com/cgi-bin/cvsweb.cgi/linux/drivers/isdn/icn/Makefile?only_with_tag=davem-cvs-merge -http://dennou-h.gfd-dennou.org/arch/cc-env.old/db/?M=A -http://www.envy.nu/wildcats/gare.html -http://www.envy.nu/wildcats/horst.html -http://www.linux.com/networking/network/release/performance/updates/Netscape/ -http://ftpsearch.belnet.be/pub/os/linux/Linux-sunsite.unc/distributions/ultra/Users-Guide/?S=A -http://www.chaos.dk/sexriddle/n/f/p/g/a/ -http://pub24.ezboard.com/fphilosophersstonefrm7.showAddTopicScreenFromWeb -http://pub24.ezboard.com/fphilosophersstonefrm7.showMessage?topicID=10.topic -http://www.yorosiku.net:8080/-_-http://www2.biglobe.ne.jp/~animenet/jan222/note/bbs2.html -http://www.web-chart.com/Detail.htm?s=2568&c=229 -http://www.brio.de/BRIO.catalog/39fe2f5009021d362740d472aa780645/UserTemplate/8 -http://www.service911.com/egghead/step/0,2743,10+55+157+24348+17295_2,00.html -http://home.pchome.com.tw/computer/judy7777/fast-7.htm -http://big5.peopledaily.com.cn/zdxw/11/20000126/200001261111.html -http://www.nhic.or.kr/netbbs/Bbs.cgi/nhic31792/lst/qqo/012D -http://sunsite.org.uk/public/usenet/news-faqs/alt.answers/paranormal/faq -http://newsone.net/nnr/listl/alt.bbs.elebbs/1 -http://ourworld.compuserve.com/homepages/hallg/mg_vor.htm -http://www.world001.com/forum/yue/1573.html -http://www.greenleaves.com/bookcat/gb_1567112730.html -http://quotidiano.monrif.net/chan/motori:1119539:/2000/10/30: -http://quotidiano.monrif.net/chan/motori:926303:/2000/10/30: -http://quotidiano.monrif.net/chan/motori:944719:/2000/10/30: -http://home.online.tj.cn/~madgoe/subtitle/nt/nt363.htm -http://home.online.tj.cn/~madgoe/subtitle/nt/nt352.htm -http://home.online.tj.cn/~madgoe/subtitle/nt/nt343.htm -http://home.online.tj.cn/~madgoe/subtitle/nt/nt327.htm -http://home.online.tj.cn/~madgoe/subtitle/nt/nt320.htm -http://www.collectingnation.com/cgi-bin/bn/request_email.mod?EHANDLE=Vincze -http://www.beanienation.com/cgi-bin/bn/view_feedback.mod?HANDLE=ving -http://www.collectingnation.com/cgi-bin/bn/request_email.mod?EHANDLE=Vinrye -http://www.collectingnation.com/cgi-bin/bn/request_email.mod?EHANDLE=Vinzy -http://www.beanienation.com/cgi-bin/bn/view_feedback.mod?HANDLE=violinist -http://www.beanienation.com/cgi-bin/bn/view_feedback.mod?HANDLE=Violin -http://www.collectingnation.com/cgi-bin/bn/request_email.mod?EHANDLE=vione -http://www.beanienation.com/cgi-bin/bn/view_feedback.mod?HANDLE=viper0669 -http://www.missouri.edu/HyperNews/get/writery/poetry/1.html?embed=-1 -http://www.missouri.edu/HyperNews/get/writery/poetry/6.html?outline=1&embed=1 -http://www.missouri.edu/HyperNews/get/writery/poetry/9.html?outline=-1&embed=1 -http://www.missouri.edu/HyperNews/get/writery/poetry/20.html?outline=3&embed=1 -http://www.missouri.edu/HyperNews/get/writery/poetry/21.html?outline=-1&embed=1 -http://www.missouri.edu/HyperNews/get/writery/poetry/23.html?outline=1&embed=1 -http://www.missouri.edu/HyperNews/get/writery/poetry/38.html?outline=1&embed=1 -http://fi.egroups.com/messages/Avon3DayBoston/5 -http://www.online.kokusai.co.jp/Demo/V0043481/wrd/G400/demo/ -http://www.jamba.de/KNet/_KNet-TQt8j1-PEd-139qr/showInfo-werbung.de/node.0/cde7f1uou -http://computalynx.tucows.com/winnt/adnload/73435_29524.html -http://www.intellicast.com/Golf/World/UnitedStates/Northwest/Oregon/OregonDunes/THUNDERcast/d2_06/ -http://202.105.55.146/h0/news/200009/20/jty7.htm -http://pda.tucows.edisontel.com/newton/newtsfiction_size.html -http://pda.tucows.edisontel.com/newton/adnload/33238_19961.html -http://hem.fyristorg.com/lottaleman/LLfar/1_2942.htm -http://www.norrblom.com/..\hund\1996\s2665496.htm -http://www.ferien-immobilien.de/niedersachsen/weserbergland/Verkauf/Gemeinsam/MarketingStrategie/Allgemeine-IB/Gemeinsam/Super-Zins-Konditionen/Private-IB/Startseite/Default.htm -http://nathanael.upi.jussieu.fr/tele6.nsf/autres+centres+de+formations!OpenPage&ExpandSection=14,18,11,9,15,8 -http://dennou-h.gfd-dennou.org/arch/cc-env.old/xtop/TEBIKI.top.rs590 -http://www.amzn.com/exec/obidos/search-handle-url/index=vhs&field-director=Jim%20Stenstrum/ -http://www.amzn.com/exec/obidos/tg/browse/-/169237/ -http://www.flora.org/flora.oclug/old-6088 -http://www.msn.expedia.co.uk/wg/Images/P24601.htm -http://www.asahi-net.or.jp/~ei2h-kdu/photos/rail/sanin/amarube3.html -http://au.yahoo.com/Business_and_Economy/Shopping_and_Services/Health/Providers/By_Region/U_S__States/Montana/Complete_List/ -http://www.staroriental.net/nav/soeg/ihf,aai,n2,118,Electric+Wave+Girl+1998.html -http://www.hig.se/(accessed,formoutput,referrer,smallcaps,sqlquery)/~jackson/roxen/ -http://carefinder.digitalcity.com/fargond/sports/team.dci?league=NF2&team=VAC -http://carefinder.digitalcity.com/fargond/sports/team.dci?league=NF2&team=GAA -http://carefinder.digitalcity.com/fargond/sports/team.dci?league=NF2&team=AAB -http://carefinder.digitalcity.com/fargond/sports/team.dci?league=NF2&team=AAF -http://newnova.tucows.com/preview/60922.html -http://www-d0.fnal.gov/d0dist/dist/releases/test/l3fsmtcluster/rcp/?S=A -http://www.cs.rit.edu/~ats/inferno/man/html/proto8.htm -http://dandini.cranfield.ac.uk/vl=-39835473/cl=140/nw=1/rpsv/cw/web/nw1/browse.htm -http://homepage.mac.com/nanameneko/job/architecture-oriented/OHP/Why/why_05.html -http://ftp.sunet.se/pub/FreeBSD/FreeBSD-current/ports/games/CaribbeanStud/?M=A -http://ftp.sunet.se/pub/FreeBSD/FreeBSD-current/ports/games/CaribbeanStud/distinfo -http://ads3.zdnet.com/c/g=r734&c=a53975&idx=2000.10.30.21.30.24/www.zdnet.com/downloads/stories/info/0,,000FDG,.html -http://yp.gates96.com/6/57/80/89.html -http://yp.gates96.com/6/57/81/42.html -http://yp.gates96.com/6/57/81/66.html -http://yp.gates96.com/6/57/82/16.html -http://yp.gates96.com/6/57/82/61.html -http://yp.gates96.com/6/57/83/37.html -http://yp.gates96.com/6/57/83/54.html -http://yp.gates96.com/6/57/84/14.html -http://yp.gates96.com/6/57/85/7.html -http://yp.gates96.com/6/57/85/24.html -http://yp.gates96.com/6/57/85/35.html -http://yp.gates96.com/6/57/85/64.html -http://yp.gates96.com/6/57/86/80.html -http://yp.gates96.com/6/57/86/96.html -http://yp.gates96.com/6/57/87/15.html -http://yp.gates96.com/6/57/89/2.html -http://yp.gates96.com/6/57/89/95.html -http://www.oncology.com/v2_MainFrame/1,1614,_12|00332|00_21|002|00_04|0039|00_38|00188,00.html -http://library.bangor.ac.uk/search/aEllis,+Gail/aellis+gail/-5,-1,0,B/exact&F=aellis+griffith+1844+1913&1,9 -http://www.rezel.enst.fr/ftp/linux/distributions/debian/CD-2/debian/dists/unstable/contrib/source/mail/?S=A -http://itcareers.careercast.com/texis/it/itjs/+SwwBmeYKD86e8hwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewhPndhBiwGna5O5BnManDtoDnnGamn5otDamnVncdpaGnwcaBoMnaoDhdGMwBodDaDnBidGAanLpnGonDqnaMFqhTfR20Dzme4twwwpBmex_D86ejxwww5rme6dwwwBrmeZpwww/morelike.html -http://esatnet.tucows.com/winnt/adnload/31316_29136.html -http://home.c2i.net/w-225961/steinare/brosjyre.htm -http://aleph.tau.ac.il:4500/ALEPH/ENG/ATA/AAS/AAS/FIND-ACC/0860271 -http://www.chaos.dk/sexriddle/v/c/w/d/r/ -http://www9.hmv.co.uk:5555/do/session/1347760/vsid/199/tid/199/cid/1061396/mid/1020/rid/1052/chid/1029/parser/yes/imref/eqqLmwlGltt5tkeHjskKZlkKrhlK/url/http://www.hmv.co.uk/hmv/departments/d135_sd0_pt0.html -http://tagesanzeiger.ch/archiv/99november/991122/79295.HTM -http://www.pacifictech.com.cn/pcsoftware/sj/jq/00803.htm -http://www.pacifictech.com.cn/pcsoftware/sj/jq/00430b.htm -http://www.pacifictech.com.cn/pcsoftware/zl/syjq/dmtgj/old/tuxing/3d/20000131.html -http://www.building.com/communities/texis/db/go/+DexVFdeKmYnwrmwxerJOwrmwx3exmww/profile.html -http://my.egroups.com/message/mathies/43?source=1 -http://www.brio.de/BRIO.catalog/39fe2f5706df064c273fd472aa78067c/UserTemplate/6 -http://www.brio.de/BRIO.catalog/39fe2f5706df064c273fd472aa78067c/UserTemplate/9 -http://www.egroups.com/messages/GollyBeenz/44 -http://www.buybuddy.com/sleuth/15/1/1020507/495848/ -http://www.brio.de/BRIO.catalog/39fe2f41010c308a2742d472aa7806a7/UserTemplate/5 -http://www.ferien-immobilien.de/hessen/bad-hersfeld/Verkauf/IIM-Teil/Startseite/Private-IB/Allgemeine-IB/Gemeinsam/versicherungen/gebaeude/deckungsumfang.htm -http://www.ferien-immobilien.de/hessen/bad-hersfeld/Verkauf/IIM-Teil/Startseite/Private-IB/Allgemeine-IB/Gemeinsam/impressum.htm -http://beetle.marion.ohio-state.edu/Bratt2000/D0029/I10769.html -http://members.tripod.lycos.co.kr/RAINBOR/?D=A -http://www.eos.ncsu.edu/eos/info/bae/bae324_info/ -http://www.chez.com/mousis/vg/aqui/pages/0006.htm -http://search.chollian.net/cgi-bin/filter.cgi?cid=2052&p=1 -http://channel.nytimes.com/1998/03/15/technology/cybertimes/eurobytes/ -http://www4.nas.edu/ohr.nsf/All+Documents/Major+Units?OpenDocument&ExpandSection=13,4,2,7,11 -http://uk.dir.yahoo.com/Regional/Countries/Mexico/States/Baja_California/Cities/Ensenada/Travel_and_Transportation/Accommodation/Caravan_Parks_and_Campgrounds/ -http://ring.toyama-ix.net/archives/mac/info-mac/inet/_Mail/_Eudora/ -http://sport.voila.fr/it/calcio/euro2000/teams/por/squad/nunogomes.html -http://idefix-41.cs.kuleuven.ac.be/~henk/DPS/ -http://library.bangor.ac.uk/search/dLaw+--+Study+and+teaching+--+Great+Britain/dlaw+study+and+teaching+great+britain/-5,-1,0,B/buttonframe&F=dlaw+study+and+teaching+great+britain&7,,7 -http://www.eveclub.com/cgi-bin/eveclub.front/972959440822/Catalog/1000002 -http://www.eveclub.com/cgi-bin/eveclub.front/972959440822/Catalog/1000062 -http://ring.shibaura-it.ac.jp/archives/FreeBSD-PC98/dists/4.0-RELEASE/XF86336/PC98-Servers/?N=D -http://www.uq.edu.au/site-index/index.phtml?site_tree_data=1,91,95,203,338,344,2,6,182,148 -http://www.uq.edu.au/site-index/index.phtml?site_tree_data=1,91,95,203,338,344,2,6,182,163 -http://www.xmission.com/(apocalypse,art,caffiene,geek,misc,music,music,caffiene,art,toys,dots,edge,misc,shopping,ftp,places,privacy,geek,cuseeme,apocalypse,people,stuffiuse,people,places,shopping,stuffiuse,toys)/~bill/links.html -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=confinarias&l=pt -http://www.xmission.com/(apocalypse,art,caffiene,cuseeme,geek,misc,music,music,caffiene,art,toys,dots,edge,misc,shopping,ftp,places,privacy,geek,cuseeme,apocalypse,people,stuffiuse,places,privacy,stuffiuse,toys)/~bill/links.html -http://www.gigclub.co.jp/tanigawa/tanigawa/980915/menu.html -http://www.3w-sciencefiction.de/SmithWilliamK/SmithWilliamK0126528756.htm -http://w3c1.inria.fr/Mobile/posdep/Presentations/Mogid/sld014.htm -http://members.tripod.co.jp/view_i/p.html -http://202.99.23.245/zdxw/11/20000317/200003171117.html -http://www.jpc-music.com/7334085.htm -http://library.bangor.ac.uk/search/aLibrary+Association/alibrary+association/-5,-1,0,B/buttonframe&F=alibrary+association&2,,64 -http://www.sf.digitalcity.com/puntagordafl/sports/team.dci?league=FSL&team=CHA -http://www.sf.digitalcity.com/puntagordafl/sports/team.dci?league=FSL&team=LAK -http://brain.brent.gov.uk/__802564ff0045d739.nsf/vWebAllPagesByLocsSrvd!OpenView&Start=33&Count=60&Collapse=45 -http://www.nypost.com/news/933.htm -http://www.nypost.com/business/979.htm -http://www.nypost.com/living/951.htm -http://www.computer-networking.de/studenten/cn_intern/bauer/jobst/k07-graphik-gui/controls/swing/ -http://194.55.30.33/albanian/tema_gjermane/67823.html -http://194.55.30.33/albanian/tema_gjermane/65962.html -http://yp.gates96.com/14/85/10/12.html -http://yp.gates96.com/14/85/11/98.html -http://yp.gates96.com/14/85/12/24.html -http://yp.gates96.com/14/85/13/57.html -http://yp.gates96.com/14/85/14/92.html -http://yp.gates96.com/14/85/16/37.html -http://yp.gates96.com/14/85/16/51.html -http://yp.gates96.com/14/85/16/78.html -http://yp.gates96.com/14/85/17/38.html -http://yp.gates96.com/14/85/17/48.html -http://yp.gates96.com/14/85/17/91.html -http://yp.gates96.com/14/85/19/35.html -http://yp.gates96.com/14/85/19/88.html -http://genforum.genealogy.com/cgi-genforum/forums/deppen.cgi?3 -http://www.ferien-immobilien.de/nordrhein-Westfalen/Muehlheim-ruhr/Verkauf/Private-IB/Startseite/Gemeinsam/Inserieren/Versteigerungen-IB/Startseite/Ferien-IB/Startseite/ -http://www.redrocksports.com/sports/webSession/shopper/RR972959668-31057/store/dept-5/department/dept-5/item/51800 -http://www.redrocksports.com/sports/webSession/shopper/RR972959668-31057/store/dept-5/department/dept-5/item/53510 -http://www.redrocksports.com/sports/webSession/shopper/RR972959668-31057/store/dept-5/department/dept-5/item/52600 -http://www.redrocksports.com/sports/webSession/shopper/RR972959668-31057/store/dept-5/department/dept-5/item/50510 -http://www.redrocksports.com/sports/webSession/shopper/RR972959668-31057/store/dept-5/department/dept-5/item/50400 -http://polygraph.ircache.net:8181/http_-2www.horizonfinance.com/http_-2www.netscape.com/download/http_-2www.microsoft.com/ie/http_-2207.91.150.20/http_-2www.updowntowner.org/julyjamm/headliners.html -http://www.ccurrents.com/magazine/national/1702/nets31702.html -http://adept.subportal.com/sn/Themes/Vehicle_Themes/5090.html -http://www.fogdog.com/cedroID/ssd3040183211390/nav/products/outlet/1a/fishing/ -http://www.linux.com/networking/network/communications/article/unix/sales/ -http://fyi.cnn.com/content/US/9902/25/germans.death.penalty.ap/ -http://fyi.cnn.com/US/9902/09/monk.execute.ap.02/ -http://fyi.cnn.com/WORLD/asiapcf/9902/06/PM-Philippines-DeathPena.ap/ -http://pub11.ezboard.com/ucivik.showPublicProfile -http://playboy.software.net/PKIN005896/prod.htm -http://www.linux.com/networking/network/help/free/performance/install/ -http://www.linux.com/networking/network/help/free/performance/X/ -http://se.egroups.com/message/ghost_tales/1490 -http://niteowl.userfriendly.net/linux/RPM/rawhide/1.0/i386/usr_src_linux-2.4.0_include_Tree.html -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=coexistissem&l=pt -http://promed.univ-rennes1.fr/cerf/ico_an/IDRE/21_HADM.HTM -http://promed.univ-rennes1.fr/cerf/ico_an/IDRE/25_HADM.HTM -http://promed.univ-rennes1.fr/cerf/ico_an/IDRE/86_HADM.HTM -http://promed.univ-rennes1.fr/cerf/ico_an/IDRE/88_HADM.HTM -http://promed.univ-rennes1.fr/cerf/ico_an/IDRE/90_HADM.HTM -http://promed.univ-rennes1.fr/cerf/ico_an/IDRE/HADM6.HTM -http://www.estrelladigital.es/000814/articulos/economia/correos.htm -http://itcareers.careercast.com/texis/it/itjs/+awwBme4CD86LxwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewPPnBwpcnaqdGpdGwBnaoDhdGMwBodDahoDma5BdGnaq15BdMnGa5nGVoqnaqdDBwqBamo5BGox1BodDaMwDwtnMnDBaMFqrIRE7P0IDzme_xwwwpBmHe0B-deaqwww5rmsmwwBrme7Dwww/morelike.html -http://yp.gates96.com/3/79/50/30.html -http://yp.gates96.com/3/79/50/54.html -http://yp.gates96.com/3/79/51/1.html -http://yp.gates96.com/3/79/51/11.html -http://yp.gates96.com/3/79/51/80.html -http://yp.gates96.com/3/79/52/27.html -http://yp.gates96.com/3/79/52/81.html -http://yp.gates96.com/3/79/53/81.html -http://yp.gates96.com/3/79/54/0.html -http://yp.gates96.com/3/79/54/31.html -http://yp.gates96.com/3/79/55/74.html -http://yp.gates96.com/3/79/55/78.html -http://yp.gates96.com/3/79/56/72.html -http://yp.gates96.com/3/79/57/0.html -http://yp.gates96.com/3/79/58/27.html -http://yp.gates96.com/3/79/58/31.html -http://yp.gates96.com/3/79/58/48.html -http://yp.gates96.com/3/79/58/76.html -http://yp.gates96.com/3/79/58/99.html -http://yp.gates96.com/3/79/59/27.html -http://yp.gates96.com/3/79/59/32.html -http://yp.gates96.com/3/79/59/49.html -http://yp.gates96.com/3/79/59/81.html -http://yp.gates96.com/3/79/59/83.html -http://startribune.atevo.com/misc/print_article/0,3869,4504302,00.html -http://browse.carnaby.com/home/showcase/6/381/2078/A0638120780000EA01.html -http://www.checkout.com/music/earmail/form/1,7650,325272-1761567,00.html -http://ring.shibaura-it.ac.jp/archives/doc/jpnic/minutes/committee/200007/shiryou-4-1.txt -http://www.secinfo.com/d1ZMQs.51h.htm -http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/AtlantisPBEM/CVSROOT/modules?only_with_tag=MAIN -http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/AtlantisPBEM/CVSROOT/modules?only_with_tag=HEAD -http://ftp.bitcon.no/tucows/adnload/4961_28325.html -http://yp.gates96.com/3/37/0/21.html -http://yp.gates96.com/3/37/0/29.html -http://yp.gates96.com/3/37/0/80.html -http://yp.gates96.com/3/37/0/87.html -http://yp.gates96.com/3/37/1/9.html -http://yp.gates96.com/3/37/2/83.html -http://yp.gates96.com/3/37/2/92.html -http://yp.gates96.com/3/37/3/26.html -http://yp.gates96.com/3/37/4/9.html -http://yp.gates96.com/3/37/4/29.html -http://yp.gates96.com/3/37/5/31.html -http://yp.gates96.com/3/37/5/49.html -http://yp.gates96.com/3/37/5/51.html -http://yp.gates96.com/3/37/5/63.html -http://yp.gates96.com/3/37/5/95.html -http://yp.gates96.com/3/37/6/0.html -http://yp.gates96.com/3/37/6/4.html -http://yp.gates96.com/3/37/7/22.html -http://yp.gates96.com/3/37/8/10.html -http://yp.gates96.com/3/37/8/50.html -http://yp.gates96.com/3/37/8/92.html -http://yp.gates96.com/3/37/9/46.html -http://ftp.digex.net/debian/dists/woody/contrib/binary-sh/libs/?N=D -http://students.lsu.edu/students/main.nsf/c81d2bf8cb0b80ff862566fb00105ab2/7f3436ae9cb1268886256773006f9288!OpenDocument&ExpandSection=4,15,12,16 -http://in.egroups.com/group/bbw-uk -http://home.swipnet.se/~w-20817/ -http://shop.puretec.de/kunden/19867293/detailansicht_Aku1025B.html -http://www.rezeptkoch.de/Rezepte/Heimisches_/Gemuse/Sommerliche_Gemusegerichte/sommerliche_gemusegerichte_2.html -http://www.rezeptkoch.de/Rezepte/Heimisches_/Gemuse/Kohl/kohl_4.html -http://www.rezeptkoch.de/Rezepte/Heimisches_/Gemuse/Kohl/kohl_11.html -http://www.chinainvest.com.cn/C/Showdetail/20359.html -http://tucows.sp-plus.nl/winme/preview/141310.html -http://www.al-hujjat.grid9.net/gnomehtml/ent_enhance_rating.html -http://www.warmbloods.net/breeding/_vti_bin/shtml.dll/disc123_post.htm?1260 -http://ftp.sunet.se/pub/FreeBSD/FreeBSD-current/ports/net/ruby-snmp/Makefile -http://basil.cs.uwp.edu/Documentation/java/jdk/docs/guide/sound/prog_guide/chapter3.fm.html -http://tucows.1web.it/winme/preview/75525.html -http://uk-wire.ukinvest.com/articles/200009180701200586R.html -http://www.ozon.ru/detail.cfm/ent=33&id=953&add2navigator=1&txt=1 -http://cometweb01.comet.co.uk/do!session=131984&vsid=700&tid=20&cid=37030&mid=1000&rid=1060&chid=1713&url=eqqLmwlGltt5tkkHbqpLZXmLbkZHljlKaltLkilLXalKfkaLbukKeqjLi1 -http://community.webshots.com/photo/3922869/3923445TSuTSQIWpD -http://www.eveclub.com/cgi-bin/eveclub.front/972959447434/Catalog/1000040 -http://www.tvstore.com/browse/TV/NIGHTSHI/s.nXZNPRgQ -http://www.tvstore.com/browse/TV/COMIC/s.nXZNPRgQ -http://www.xmwb.sh.cn/xmwb/19981016/GB/13389^8101623.htm -http://helios.nlib.ee/search*est/tThe+threshold+series/tthreshold+series/-5,-1,0,B/frameset&F=tthrillers&1,1 -http://www4.nas.edu/ohr.nsf/All+Documents/Major+Units?OpenDocument&ExpandSection=23,9,7,18 -http://ftp.bitcon.no/pub/windowsce/epoc/desktop5.htm -http://ftp.lip6.fr/pub2/sgml-tools/website/HOWTO/Multicast-HOWTO/t1595.html -http://ftp.rge.com/pub/X/XFree86/3.3.3.1/untarred/xc/programs/Xserver/ -http://ftp.rge.com/pub/X/XFree86/3.3.3.1/untarred/xc/programs/xwud/ -http://syix.tucows.com/win2k/adnload/73370_29328.html -http://yp.gates96.com/0/54/80/40.html -http://yp.gates96.com/0/54/80/56.html -http://yp.gates96.com/0/54/80/61.html -http://yp.gates96.com/0/54/80/79.html -http://yp.gates96.com/0/54/81/11.html -http://yp.gates96.com/0/54/81/25.html -http://yp.gates96.com/0/54/81/58.html -http://yp.gates96.com/0/54/82/48.html -http://yp.gates96.com/0/54/82/75.html -http://yp.gates96.com/0/54/83/0.html -http://yp.gates96.com/0/54/84/12.html -http://yp.gates96.com/0/54/84/67.html -http://yp.gates96.com/0/54/85/47.html -http://yp.gates96.com/0/54/85/59.html -http://yp.gates96.com/0/54/86/52.html -http://yp.gates96.com/0/54/86/55.html -http://yp.gates96.com/0/54/86/79.html -http://yp.gates96.com/0/54/86/87.html -http://yp.gates96.com/0/54/87/12.html -http://yp.gates96.com/0/54/87/81.html -http://yp.gates96.com/0/54/88/97.html -http://yp.gates96.com/0/54/89/90.html -http://www.yorosiku.net:8080/-_-http://liinwww.ira.uka.de/bibliography/Distributed/SIGCOMM.94.html -http://news.pchome.com.tw/ftv/health/20000915/ -http://www.emis.de/journals/EJDE/Volumes/Volumes/Monographs/1998/05/?N=D -http://travelocity-dest.excite.com/DestGuides/0,1840,TRAVELOCITY|5706|3|1|159040|photo_id|4022,00.html -http://travelocity-dest.excite.com/DestGuides/0,1840,TRAVELOCITY|5706|3|1|159040|photo_id|4020,00.html -http://lhcbsoft.web.cern.ch/LHCbSoft/simmuon/v1/mgr/CVS/Root -http://tucows.soneraplaza.nl/winme/adnload/137454_28942.html -http://www.borland.nl/techpubs/jbuilder/jbuilder3/ui/wclass.html -http://fi.egroups.com/links/dssf -http://www.homestead.com/jcv2000/MBoard.html -http://careershop.resumeshotgun.com/directory/italy/sardegna/o.10.p.4408.html -http://www.hantsnet.co.uk/istcclr/cch32751.html -http://www.hantsnet.co.uk/istcclr/cch16729.html -http://www.hantsnet.co.uk/istcclr/cch03788.html -http://www.hantsnet.co.uk/istcclr/cch05491.html -http://www.hantsnet.co.uk/istcclr/cchr0418.html -http://www.hantsnet.co.uk/istcclr/cchh2289.html -http://www.hantsnet.co.uk/istcclr/cchh2074.html -http://www.hantsnet.co.uk/istcclr/cch30426.html -http://www.hantsnet.co.uk/istcclr/cch11726.html -http://www.hantsnet.co.uk/istcclr/cch03858.html -http://www.hantsnet.co.uk/istcclr/cche0920.html -http://www.hantsnet.co.uk/istcclr/cch34768.html -http://www.hantsnet.co.uk/istcclr/cchc2067.html -http://www.hantsnet.co.uk/istcclr/cche1085.html -http://www.v2music.com/Scripts/WebObjects-ISAPI.dll/V2_New_Publisher.woa/53771000000443000000339400000065451/v2tvindex.wo/614720000055451/1.14/3/Webobjects1 -http://www.sternonline.de/magazin/fotogalerie/hinz/index5.html -http://www.envy.nu/Sing.html -http://employment.subportal.com/sn/Themes/ -http://www.diogenes.ch/4DACTION/web_rd_aut_prview/a_id=7002120&area=&ID=483332 -http://wlink.tucows.com/winme/adnload/137847_29260.html -http://tucows.computalynx.net/winnt/adnload/71633_28766.html -http://ftp.up.pt/Linux/debian/dists/stable/main/disks-m68k/?M=A -http://lcweb2.loc.gov/ll/llnt/009/0000/ -http://www.magma.ca/~denisd/africa/day02.html -http://www.magma.ca/~denisd/africa/day16.html -http://content.health.msn.com/message_board_author/802072 -http://ep.com/js/about/c0/189455 -http://ep.com/js/about/c0/154005 -http://www.realbig.com/miata/miata/1999-12/2340.html -http://www.multimap.com/wi/33738.htm -http://www.multimap.com/wi/148724.htm -http://www.bemi-immobilien.de/Landhaus-Bordeaux/Gemeinsam/3d-service/Gemeinsam/versicherungen/lebensversicherung/Startseite/www.ferien-immobilien.de/ferien-ib/startseite/Gemeinsam/versicherungen/lebensversicherung/Gemeinsam/MarketingStrategie/Strategie.htm -http://link.fastpartner.com/do/session/600347/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/create/learn.htm -http://pub16.ezboard.com/fisnforumsfrm16.subscribeUnregisteredToTopic?topicID=731.topic -http://freesoftware.subportal.com/sn/Business/Application_Add-ins/726.html -http://people.freebsd.org/~knu/cgi-bin/cvsweb.cgi/ports/deskutils/genius/files/?sortby=date -http://www.madein.nnov.ru/stat/index.phtml?cid=418&t=3 -http://citeseer.nj.nec.com/correct/294145 -http://www.phillips.semiconductors.com/pip/PCF5001H -http://www.tvstore.com/browse/TV/BANK/s.Vaphccqs -http://www.tvstore.com/browse/TV/SCRIPT/s.Vaphccqs -http://www.tvstore.com/aboutus/s.Vaphccqs -http://www.fogdog.com/cedroID/ssd3040183205929/nav/products/featured_brands/3b/arm_warmers/ -http://orders.mkn.co.uk/bear/steiff/classic/order/now.en$NOK?what-e=1 -http://www.crutchfield.com/S-jtpRS1P7vRY/help/ -http://www06.u-page.so-net.ne.jp/tb3/y-miyu/azure/kodatour.htm -http://ftp.sunet.se/pub/FreeBSD/ports/ports-stable/japanese/escpf/distinfo -http://no.egroups.com/subscribe/Theater_plays -http://www.equipe.fr/Football/FootballFicheJoueur8954_0.html -http://www.equipe.fr/Football/FootballFicheJoueur6039_0.html -http://www.pmdc.org.uk/dogsdb/p00/P00133.HTM -http://ip.tosp.co.jp/i.asp?i=nononatti3 -http://tucows.wlink.com.np/adnload/144221_48889.html -http://store.yahoo.co.jp/I/naturum_1590_147867488 -http://providenet.office.tucows.com/adnload/77414_41755.html -http://providenet.office.tucows.com/adnload/73011_41097.html -http://www.goldersgreen.londonengland.co.uk/medicalequipmentrentalandleasing.htm -http://www.online.kokusai.co.jp/Mmf_corner/V0043462/mmf_corner/mmf_corner/url -http://www.qth.net/archive/packrats/200008/20000804.html -http://www.expage.com/buffykat11nelly -http://dk.egroups.com/login.cgi?login_target=%2Fmessages%2Fbbs_people -http://dk.egroups.com/message/bbs_people/23 -http://www.linux.com/networking/network/technology/free/development/learning/ -http://www.chaos.dk/sexriddle/r/x/z/t/l/ -http://www.opensecrets.org/lobbyists/98profiles/5918.htm -http://www.cbs.sportsline.com/u/football/nfl/kids/players/3418.htm -http://www.cbs.sportsline.com/u/football/nfl/kids/players/3868.htm -http://www.cbs.sportsline.com/u/football/nfl/kids/players/133268.htm -http://www.hig.se/(apre,clientname,countdown,language,set_cookie)/~jackson/roxen/ -http://www.platogmbh.de/plato/home.nsf/c81870434660ba41c125652a0029a47a/fb7566ed772f8580c12566f00036ac59!OpenDocument&ExpandSection=4,8,11,12 -http://www.fogdog.com/cedroID/ssd3040183211315/nav/products/featured_brands/2m/kick_sprint_boards/ -http://www.iabusnet.org:90/forums/aca-1/dispatch.exe/survey/folderFrame/100001/0/alpha/2458960 -http://www.jamba.de/KNet/_KNet-ONt8j1-NEd-139p9/showInfo-jobs.de/node.0/cde7f1uou -http://www.jamba.de/KNet/_KNet-ONt8j1-NEd-139pf/browse.de/node.0/cdzqggtyb -http://iland.tucows.com/win2k/adnload/38318_29882.html -http://builder.hw.net/frmRestDir/0,1112,'1~21~325~1~S~020060~04880',00.html -http://builder.hw.net/frmRestDir/0,1112,'1~21~325~1~S~020060~35840',00.html -http://builder.hw.net/frmRestDir/0,1112,'1~21~325~1~S~020060~90237',00.html -http://sunsite.org.uk/public/usenet/news.answers/alt.answers/self-impr-faq/part1 -http://ftp.bitcon.no/pub/simtelnet/win95/fileutl/?S=A -http://totalsports.aol.com/stats/bbo/mlb/20000517/bal.at.ana.game.html -http://au.yahoo.com/Regional/U_S__States/Virginia/Counties_and_Regions/Henrico_County/Business_and_Shopping/Shopping_and_Services/Travel/ -http://ftp.up.pt/Linux/debian/dists/unstable/main/binary-all/math/ -http://students.lsu.edu/students/main.nsf/c81d2bf8cb0b80ff862566fb00105ab2/7f3436ae9cb1268886256773006f9288!OpenDocument&ExpandSection=10,17,13,14 -http://ftp.sunet.se/pub/FreeBSD/ports/ports-stable/japanese/vfghostscript/Makefile -http://polygraph.ircache.net:8181/yp/User_Contribs/http_-2home.netscape.com/comprod/mirror/ -http://www.emis.de/journals/EJDE/Volumes/Monographs/Volumes/1998/26/?S=A -http://www.smartshop.com/cgi-bin/main.cgi?c=314&a=contactus -http://213.36.119.69/do/session/152986/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/BE_NL/ -http://www.outdoorwire.com/lists/dirt/200009/msg01273.html -http://chicagocow.com/top/1,1419,M-Metromix-Home-Carryout!InputReview-9757--0,00.html -http://www.lithoquoter.com/Scripts/WebObjects.exe/Printers.woa/659920000022582000008720100000129302/main.wo/9193100000029302/4/-/prime -http://groups.haas.berkeley.edu/hcs/Docs/SASv8/sasdoc/sashtml/proc/z0292493.htm -http://groups.haas.berkeley.edu/hcs/Docs/SASv8/sasdoc/sashtml/proc/z0292495.htm -http://groups.haas.berkeley.edu/hcs/Docs/SASv8/sasdoc/sashtml/proc/z0292496.htm -http://www.outpersonals.com/cgi-bin/w3com/pws/out/jlhIVflnBPgWmpC4eFAjXlk3QXcFhcK-b9D_cbZyHLtTP5aigpMrgot7TKiIhNzg8y23_mmQAn7GVTQsvALIGIvJI8RFNXRZDuyGCzJ8JFs6ysbZfjgM3ik0nyIt5yhT_ujQhRI-42lzAOeb666j -http://www.nissan.co.jp/RENAULT-DEALERS/PASSPORT/view.cgi/admission/972959588-- -http://www.intellicast.com/Golf/World/UnitedStates/MidAtlantic/Virginia/RoyalNewKentGC/LocalWinds/d1_12/ -http://gbchinese.yahoo.com/headlines/001028/sports/ycwb/ycba28c003txttyxw00102800.html -http://gbchinese.yahoo.com/headlines/001028/sports/ycwb/ycba28c004txttyxw00102800.html -http://mx.php.net/manual/hu/language.references.unset.php -http://www.cbtravelguide.com/north_america/united_states/info_2.htm?sortby=city -http://www.intellicast.com/Sail/World/UnitedStates/Northwest/Idaho/Targhee/LocalWinds/d1_03/ -http://ftp.sunet.se/pub/FreeBSD/ports/ports-current/devel/libgii/distinfo -http://biblioteca.upv.es/bib/doc/doc_fisbd/816/149599//C/1826373/0////25/S/MLTPAI -http://willsmith.sonicnet.com/events/jay_z/index_sonicnet.jhtml -http://tucows.soneraplaza.nl/winme/tucowsme_license.html -http://people.freebsd.org/~knu/cgi-bin/cvsweb.cgi/src/usr.sbin/fdcontrol/Makefile?only_with_tag=MAIN -http://www.kurit.com/ip/a5iu/dungeon/showsw1.html -http://www.mapion.co.jp/custom/AOL/admi/13/13118/minamisenju/3chome/index-30.html -http://yp.gates96.com/3/2/10/4.html -http://yp.gates96.com/3/2/10/19.html -http://yp.gates96.com/3/2/10/48.html -http://yp.gates96.com/3/2/10/52.html -http://yp.gates96.com/3/2/10/82.html -http://yp.gates96.com/3/2/11/10.html -http://yp.gates96.com/3/2/11/13.html -http://yp.gates96.com/3/2/13/31.html -http://yp.gates96.com/3/2/13/41.html -http://yp.gates96.com/3/2/13/43.html -http://yp.gates96.com/3/2/14/3.html -http://yp.gates96.com/3/2/14/19.html -http://yp.gates96.com/3/2/15/54.html -http://yp.gates96.com/3/2/15/72.html -http://yp.gates96.com/3/2/16/84.html -http://yp.gates96.com/3/2/17/22.html -http://yp.gates96.com/3/2/17/61.html -http://yp.gates96.com/3/2/18/1.html -http://yp.gates96.com/3/2/18/41.html -http://yp.gates96.com/3/2/18/58.html -http://yp.gates96.com/3/2/19/56.html -http://yp.gates96.com/3/2/19/79.html -http://www.stas.net/lonlywtrsoul/minesweeper/ms.html -http://ksu.freeyellow.com/ -http://www.genome.wustl.edu:8021/gsc10/est/yt/yt69/ -http://www.genome.wustl.edu:8021/gsc10/est/yt/yt82/ -http://www.winsite.com/info/pc/win95/miscutil/cutty10.exe/downltop.html -http://habenix.uni-muenster.de/Rektorat/Forschungsberichte-1997-1998/fo05bbe03.htm -http://www.jobvillage.com/channel/jobs/installation_repair/bicycle/g.3370.html -http://www.mordkommission.de/ratgeber/praxis/service/broschueren/40504/ -http://www.aelita.net/products/news/solutions/sitemap/company/library/default.htm -http://www.beanienation.com/cgi-bin/bn/view_feedback.mod?HANDLE=acejet -http://cgi1.washingtonpost.com/wp-dyn/metro/va/alexandria/ -http://www.linux.com/networking/network/applications/interface/linux/distro/ -http://www2.brent.gov.uk/bv1nsf.nsf/031d5c68638196618025664000760871/963fe55ca97ccaa5802568f900503269!OpenDocument&Start=57.3&Count=60&Expand=69 -http://www2.brent.gov.uk/bv1nsf.nsf/031d5c68638196618025664000760871/963fe55ca97ccaa5802568f900503269!OpenDocument&Start=57.3&Count=60&Expand=72 -http://www2.brent.gov.uk/bv1nsf.nsf/031d5c68638196618025664000760871/963fe55ca97ccaa5802568f900503269!OpenDocument&Start=57.3&Count=60&Expand=87 -http://genforum.genealogy.com/cgi-genforum/forums/youngs.cgi?26 -http://www.tvstore.com/browse/TV/CAP/s.IRspZRIy -http://210.178.135.1/netbbs/Bbs.cgi/nhic30592/qry/zka/B2-kB2-p/pno/0/qqo/012A/qqatt/^ -http://home.sol.no/~leskjerv/aner/12063.htm -http://pub6.ezboard.com/fwatckkeepersgeneralwatchkeeperdiscussion?page=5 -http://www.centc251.org/forums/aca-1/dispatch.cgi/hsi/folderFrame/100217/0/def/1210456 -http://ftp.sunet.se/pub/FreeBSD/ports/ports-stable/games/xosmulti/?S=A -http://opac.lib.rpi.edu/search/ddata+processing+english+language+style/7,-1,0,B/browse -http://yp.gates96.com/7/40/0/5.html -http://yp.gates96.com/7/40/0/33.html -http://yp.gates96.com/7/40/1/27.html -http://yp.gates96.com/7/40/3/25.html -http://yp.gates96.com/7/40/3/36.html -http://yp.gates96.com/7/40/4/67.html -http://yp.gates96.com/7/40/4/77.html -http://yp.gates96.com/7/40/6/28.html -http://yp.gates96.com/7/40/6/49.html -http://yp.gates96.com/7/40/6/89.html -http://yp.gates96.com/7/40/7/21.html -http://yp.gates96.com/7/40/9/24.html -http://indonesian.wunderground.com/geo/GizmoTempBigPromo/global/stations/07434.html -http://www.teenplatinum.com/barelylegal/anal-sexass/legsred-toenail-polish/swallowspit/submissiondiscipline/maledomspanking/hardcorebondage.html -http://cgi.cnnsi.com/basketball/college/women/scoreboards/aeast/2000/10/18/ -http://cgi.cnnsi.com/basketball/college/women/scoreboards/aeast/2000/10/16/ -http://bellona.itworld.com:8080/cwi/Printer_Friendly_Version/frame/0,1212,NAV63-128-1357-1367_STO48482-,00.html -http://cdrwww.who.int/fsf/ehec.pdf -http://tw.yahoo.com/Regional/Countries_and_Regions/China/Provinces__Regions_and_Municipalities/Jiangxi/Cities_and_Towns/Nanchang/Real_Estate/ -http://tw.yahoo.com/Regional/Countries_and_Regions/China/Provinces__Regions_and_Municipalities/Jiangxi/Cities_and_Towns/Nanchang/Society_and_Culture/ -http://www.camden-industrial.com/supply/webSession/shopper/CI972959657-31048/store/dept-8 -http://www.msb.malmo.se/search*swe/mQdfm/mqdfm/-5,-1,0,E/2browse -http://tagesanzeiger.ch/archiv/96september/960903/213235.htm -http://yp.gates96.com/3/7/20/3.html -http://yp.gates96.com/3/7/20/28.html -http://yp.gates96.com/3/7/20/42.html -http://yp.gates96.com/3/7/21/5.html -http://yp.gates96.com/3/7/21/61.html -http://yp.gates96.com/3/7/22/18.html -http://yp.gates96.com/3/7/22/20.html -http://yp.gates96.com/3/7/22/24.html -http://yp.gates96.com/3/7/23/33.html -http://yp.gates96.com/3/7/23/49.html -http://yp.gates96.com/3/7/23/57.html -http://yp.gates96.com/3/7/24/22.html -http://yp.gates96.com/3/7/24/23.html -http://yp.gates96.com/3/7/24/27.html -http://yp.gates96.com/3/7/24/36.html -http://yp.gates96.com/3/7/24/45.html -http://yp.gates96.com/3/7/25/98.html -http://yp.gates96.com/3/7/26/56.html -http://yp.gates96.com/3/7/26/77.html -http://yp.gates96.com/3/7/26/94.html -http://yp.gates96.com/3/7/27/10.html -http://yp.gates96.com/3/7/27/17.html -http://yp.gates96.com/3/7/27/61.html -http://yp.gates96.com/3/7/27/73.html -http://yp.gates96.com/3/7/27/81.html -http://yp.gates96.com/3/7/27/82.html -http://yp.gates96.com/3/7/27/87.html -http://yp.gates96.com/3/7/28/48.html -http://yp.gates96.com/3/7/29/1.html -http://yp.gates96.com/3/7/29/8.html -http://yp.gates96.com/3/7/29/32.html -http://www.crit.org/http://www-mel.nrlmry.navy.mil/%ff:words:(MEL-is-a-sponsored-distributed-environmental-data-access-system-which-allows-users-to-search-for-browse-and-retrieve-environmental-data-from-distributed-sources) -http://www.crit.org/http://crit.org/pub/radiks.net/jwoods/%ff:words:jwoods-radiks-net-(A-More-Graceful-Transition)-An-expanded-definition -http://shn.webmd.com/roundtable_reply/802056 -http://shn.webmd.com/roundtable_author/802056 -http://bbs.bianca.com/mforums/e/expounder/posts/2000_Jan_09/3067/3073.html -http://www.spaindustry.com/ita/geosearch/navarra/navarra/ESLAVA.html -http://www.backflip.org/members/rj2nagle/4643211 -http://www.backflip.org/members/rj2nagle/7211888 -http://www.backflip.org/members/rj2nagle/5066953 -http://www.backflip.org/members/rj2nagle/5346740 -http://www.backflip.org/members/rj2nagle/5382951 -http://www.linux.com/networking/network/performance/help/va_linux_systems/server/ -http://www.secinfo.com/d178s.ad.htm -http://www.secinfo.com/d178s.9d.htm -http://www.secinfo.com/d178s.8b.htm -http://www.secinfo.com/d178s.8y.htm -http://iceberg.adhomeworld.com/cgi-win/redirect.exe/1153874888 -http://tmxy.363.net/refer-e.htm -http://www.narodnaobroda.sk/20000210/10_007.html -http://retailer.gocollect.com/do/session/1912712/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/index.asp -http://retailer.gocollect.com/do/session/1912712/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/halloween/halloween.asp -http://www.larevista.elmundo.es/documentos/secciones/ciencia.html -http://ftpsearch.belnet.be/mirrors/ftp.isc.org/pub/usenet/control/brightnet/?M=A -http://www.5a8.com/book/zt/zpj/k/kelisidi/wanshenjie/006.htm -http://www.5a8.com/book/zt/zpj/k/kelisidi/wanshenjie/019.htm -http://www.northwoods.bigsmart.com/mall/cat_automotive.cfm?drop_menu=yes -http://www.leg.wa.gov/pub/rcw%20-%20text/title_41/chapter_004/rcw_41_04_220.txt -http://www.leg.wa.gov/pub/rcw%20-%20text/title_41/chapter_004/rcw_41_04_364.txt -http://www.leg.wa.gov/pub/rcw%20-%20text/title_41/chapter_004/rcw_41_04_400.txt -http://www.leg.wa.gov/pub/rcw%20-%20text/title_41/chapter_004/rcw_41_04_630.txt -http://bsd.tucows.mol.com/x11html/adnload/69206_8129.html -http://ldp.teihal.gr/LDP/LG/issue22/notes-mode.html -http://ldp.teihal.gr/LDP/LG/issue22/haters.html -http://members.nbci.com/design_res/software_ftp.htm -http://www.nativeamerican-jewelry.com/necklace53.htm -http://members.theglobe.com/pamile/Pamela0004.html -http://webtools.familyeducation.com/whatworks/item/front/0,2551,22-9696-7350-1099-49655,00.html -http://wwws.br-online.de/geld/boerse/970909/072001.html -http://212.31.0.37/fix98/75yil/1938.htm -http://212.31.0.37/fix98/75yil/1950.htm -http://212.31.0.37/fix98/75yil/26ekl.htm -http://212.31.0.37/fix98/75yil/28ekl.htm -http://212.31.0.37/fix98/75yil/38ekl.htm -http://212.31.0.37/fix98/75yil/67ekl.htm -http://212.31.0.37/fix98/75yil/92ekl.htm -http://212.31.0.37/fix98/75yil/15ekl.htm -http://www.insurequotes.com/wa2/71J2.html -http://cn.egroups.com/message/csreye/112 -http://ring.crl.go.jp/archives/lang/perl/CPAN/authors/id/J/JA/JARIAALTO/?D=A -http://ds.dial.pipex.com/town/drive/kch36/select/s31/ch027.html -http://ds.dial.pipex.com/town/drive/kch36/select/s31/ch056.html -http://ds.dial.pipex.com/town/drive/kch36/select/s31/ch043.html -http://202.99.23.245/huadong/199905/25/no_4.html -http://www.linux.com/networking/network/industry/training/services/business/ -http://www.writtenbyme.com/articles/849308468.shtml -http://members.tripod.com/TroupeLynx/index_m.htm -http://polygraph.ircache.net:8181/http_-2www.horizonfinance.com/https_-2www.truste.org/validate/http_-2www.ziplink.net/~ralphb/newsroom/http_-2www.travelsc.com/industry/home.html -http://ftp.bitcon.no/pub/tucows/preview/1095.html -http://ftp.bitcon.no/pub/tucows/preview/870.html -http://ftp.bitcon.no/pub/tucows/preview/144675.html -http://ftp.bitcon.no/pub/tucows/preview/144869.html -http://ftp.bitcon.no/pub/tucows/preview/31162.html -http://ftp.bitcon.no/pub/tucows/preview/7724.html -http://ftp.bitcon.no/pub/tucows/preview/2691.html -http://ftp.bitcon.no/pub/tucows/preview/72841.html -http://ftp.bitcon.no/pub/tucows/preview/72185.html -http://www.jacksonhewitt.com/ctg/cgi-bin/JacksonHewitt/company_profile/AAAksrACwAAABtvAAX -http://search.excaliburfilms.com/moviepgs/goodbadanddirty.htm?currency=NOK&stock=8377V1 -http://search.excaliburfilms.com/moviepgs/goodbadanddirty.htm?currency=FRF&stock=8377V1 -http://genforum.genealogy.com/cgi-bin/print.cgi?torian::44.html -http://retailer.gocollect.com/do/session/1912702/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/exclusives/newintros.asp -http://www.retrobytes.org/classiccmp/9911/msg00941.html -http://ftp.support.compaq.com/public/dunix/v3.2d-1/dce/?S=A -http://www.collectingnation.com/cgi-bin/bn/request_email.mod?EHANDLE=CoyoteChief -http://www.collectingnation.com/cgi-bin/bn/request_email.mod?EHANDLE=cpatch -http://www.beanienation.com/cgi-bin/bn/view_feedback.mod?HANDLE=cpegasus -http://www.quzhou.gov.cn/flfg.nsf/0a043ae26eb50247002564640039f21d/483ed12afec2b31d002564ac0039427a!OpenDocument&ExpandSection=7,6,5 -http://www.luecos.de/wow/art/mu_newsc_12080.html -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/quizz/misc/lit/programs/simple/pages_new.html -http://library.cuhk.edu.hk/search*chi/aChen,+Hui-fen./achen+hui+fen/31,-1,0,E/frameset&F=achen+hung&4,,0 -http://www.vedomosti.spb.ru/2000/arts/spbved-82-art-2.html -http://www.vedomosti.spb.ru/2000/arts/spbved-82-art-21.html -http://www.vedomosti.spb.ru/2000/arts/spbved-82-art-45.html -http://caller-times.com/1999/june/26/today/national/2447.html -http://cafe5.daum.net/Cafe-bin/Bbs.cgi/vision20pds/lst/qqeq/1/zka/B2-kB2Np -http://www.crutchfield.com/S-q8jdM6hvouc/sales.html -http://www.crutchfield.com/S-q8jdM6hvouc/cgi-bin/Catalog.asp?sid=S-q8jdM6hvouc -http://www.crutchfield.com/S-q8jdM6hvouc/copyright.html -http://deliveryc.aftonbladet.se/puls/stockholmsguiden/presentation/0,1714,2000023149,00.html -http://deliveryc.aftonbladet.se/puls/stockholmsguiden/presentation/0,1714,2000023162,00.html -http://deliveryc.aftonbladet.se/puls/stockholmsguiden/presentation/0,1714,2000023220,00.html -http://www.tnonline.com/archives/news/2000weeklies/09.20/pocono/pocono/police.html -http://retailer.gocollect.com/do/session/1912688/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/sports/index.asp -http://ftp.fas.org/irp/world/iraq/hadi/ -http://rusf.ru/kb/stories/kogda_chapaev_ne_utonul/text.htm -http://ring.yamanashi.ac.jp/pub/FreeBSD-PC98/dists/4.1-RELEASE/packages/chinese/?M=A -http://www3.buch-per-sms.de/anmeldung0.jsp$ID=To7737mC4935289641883087At0.9095524774481786 -http://www3.buch-per-sms.de/impressum.jsp$ID=To7737mC4935289641883087At0.9104482951702283 -http://ftp.uni-bremen.de/pub/linux/dist/suse/6.4/i386.de/suse/contents/ -http://ftp.uni-bremen.de/pub/linux/dist/suse/6.4/i386.de/suse/pay3/ -http://ftp.uni-bremen.de/pub/linux/dist/suse/6.4/i386.de/suse/xdev2/ -http://www.mlbworldseries.com/u/baseball/mlb/players/moreplayer_7649.htm -http://www.rismedia.com/consumer/27/5192/ -http://www.rismedia.com/consumer/27/18760/ -http://library.cuhk.edu.hk/search*chi/aZhang,+Wei-Yuan./azhang+wei+yuan/-5,-1,0,B/browse -http://itcareers.careercast.com/texis/it/itjs/+XwwBmeSFy86xwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqew8awn5otDanDtoDnnGaxdo5na5BwBnazdxanLpnGonDqnamnVncdpaBnwMahoGMiwGna31wcohoqwBodDaMFqpl0bP0RRe2PftgQE2yDzmesxwwwpBmeAFy86Kwww5rmepdwwwBrmeZpwww/morelike.html -http://itcareers.careercast.com/texis/it/itjs/+zwwBmerEy86e+xwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqew8awn5otDanDtoDnnGaxdo5na5BwBnazdxanLpnGonDqnamnVncdpaBnwMahoGMiwGna31wcohoqwBodDaMFqpl0bP0RRe2PftgQE2yDzmesxwwwpBmeAFy86Kwww5rmeADwwwBrmeZpwww/jobpage.html -http://itcareers.careercast.com/texis/it/itjs/++wwBmex8286xwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqew8awn5otDanDtoDnnGaxdo5na5BwBnazdxanLpnGonDqnamnVncdpaBnwMahoGMiwGna31wcohoqwBodDaMFqpl0bP0RRe2PftgQE2yDzmesxwwwpBmeAFy86Kwww5rm6mwwBrmeZpwww/jobpage.html -http://archive.soccerage.com/s/de/09/b2445.html -http://archive.soccerage.com/s/de/09/b2408.html -http://archive.soccerage.com/s/de/09/b2272.html -http://archive.soccerage.com/s/de/09/b2256.html -http://archive.soccerage.com/s/de/09/b2249.html -http://archive.soccerage.com/s/de/09/b2245.html -http://archive.soccerage.com/s/de/09/b2246.html -http://archive.soccerage.com/s/de/09/b2237.html -http://archive.soccerage.com/s/de/09/b2207.html -http://genforum.genealogy.com/cgi-genforum/forums/wickham.cgi?296 -http://ftpsearch.belnet.be/packages/CPAN/authors/id/N/NE/NEDKONZ/?S=A -http://www.cheatscape.com/amiga/a/game53cindex_1.htm -http://www.best.com/~radko/lounge/messages/3572.html -http://www.best.com/~radko/lounge/messages/3542.html -http://www.best.com/~radko/lounge/messages/3563.html -http://www.best.com/~radko/lounge/messages/3502.html -http://www.best.com/~radko/lounge/messages/3431.html -http://user.tninet.se/~lrg243i/leo2.htm -http://www.pocketbible.co.kr/new/hebrews/hebrews07/hebrews7-5.htm -http://www.pocketbible.co.kr/new/hebrews/hebrews07/hebrews7-10.htm -http://members.tripod.co.jp/sugart/?D=A -http://www.linux.com/networking/network/industry/growth/new/server/ -http://kdecvs.stud.fh-heilbronn.de/cvsweb/kdegames/kspaceduel/sprites/?hideattic=0&sortby=log -http://karate.list.ru/catalog/10621.html -http://www.digitaldrucke.de/(aktuell,arbeitsvermittlung,computer,hilfe,individualverkehr,kultur,mix,nuernberg,sense,software,verkehr)/_fort/html/themen/aktuell/verkehr.htm -http://www.digitaldrucke.de/(aktuell,arbeitsvermittlung,computer,hilfe,individualverkehr,kultur,mix,nuernberg,sense,software,verkehr)/_fort/html/themen/aktuell/fahrzeug/fahrzeug.htm -http://www.digitaldrucke.de/(aktuell,arbeitsvermittlung,computer,creaccess,hilfe,individualverkehr,kultur,mix,nuernberg,schnellübersicht,sense,software,verkehr,von)/_fort/html/themen/hilfe/getall.htm -http://polygraph.ircache.net:8181/http_-2www.infolane.com/http_-2www.neosoft.com/~nitemoon/technical/http_-2www2.davidweekleyhomes.com/advancedproj.html -http://wow-online.vhm.de/Regional/Sri_Lanka/Nachrichten.html -http://www.bell.bellnet.com/suchen/sport/rodeo.html -http://netway.pda.tucows.com/palm/adnload/67796_21902.html -http://netway.pda.tucows.com/palm/preview/48544.html -http://netway.pda.tucows.com/palm/adnload/139037_47478.html -http://netway.pda.tucows.com/palm/adnload/73256_21914.html -http://netway.pda.tucows.com/palm/adnload/71930_21910.html -http://netway.pda.tucows.com/palm/adnload/136499_47294.html -http://netway.pda.tucows.com/palm/adnload/77938_21926.html -http://wap.jamba.de/KNet/_KNet-g_v8j1-4Fd-13aaq/browse.de/node.0/cde7f2elw -http://www.oreilly.com/medical/autism/news/research.html -http://www.geocities.co.jp/HeartLand-Namiki/5523/kopen.html -http://br-online.de/wissenschaft/wimfs/tm/tm9611/tt9611ol.htm -http://retailer.gocollect.com/do/session/1912709/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/exclusives/preorder.asp -http://rac.co.kr/www.avm.de/ -http://rac.co.kr/www.aztech.com.sg/ -http://rac.co.kr/www.simple.com.au/drivers.htm -http://www.egroups.com/messages/Wrestlings2ndComing/263 -http://mediate.magicbutton.net/do/session/625584/vsid/3342/tid/3342/cid/88020/mid/2008/rid/2313/chid/2648/url/http://www1.getmapping.com/index.cfm -http://ben.aspads.net/ex/c/643/874990125 -http://www.hri.org/docs//statedep/1998/98-05-26.std.html -http://member1.shangdu.net/home2/longing/byzs/036.htm -http://web.tiscalinet.it/informacitta/n2Maggio2000/n2Maggio2000/Pagine/P16.htm -http://www.eveclub.com/cgi-bin/eveclub.front/972959455723/Catalog/11000155 -http://www.eveclub.com/cgi-bin/eveclub.front/972959455723/Basket/View/1000038 -http://student.monterey.edu/sz/troxellphillipju/campus/ -http://readers.thevines.com/leaf/AA0000401329/45///&act=24-1-11&bref=1601 -http://caller-times.com/1999/september/30/today/business/750.html -http://www.online.kokusai.co.jp/Mmf_corner/V0043482/mmf_corner/mmf_corner/url -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=27,33,21,19,32 -http://jupiter.u-3mrs.fr/~msc41www/GRATXT/PD6483.HTM -http://webtools.familyeducation.com/whatworks/item/front/0,2551,1-9696-7765-539-51377,00.html -http://parallel.fh-bielefeld.de/ti/vorlesung/sp/jdk_doc/java/text/class-use/FieldPosition.html -http://cinemabilia.de/details/katnr/239509/ -http://ftp.sunet.se/pub/FreeBSD/FreeBSD-current/ports/games/xgolgo/pkg-comment -http://yp.gates96.com/13/2/50/12.html -http://yp.gates96.com/13/2/50/68.html -http://yp.gates96.com/13/2/52/56.html -http://yp.gates96.com/13/2/53/71.html -http://yp.gates96.com/13/2/54/13.html -http://yp.gates96.com/13/2/54/21.html -http://yp.gates96.com/13/2/54/43.html -http://yp.gates96.com/13/2/54/52.html -http://yp.gates96.com/13/2/54/94.html -http://yp.gates96.com/13/2/55/25.html -http://yp.gates96.com/13/2/55/57.html -http://yp.gates96.com/13/2/56/95.html -http://yp.gates96.com/13/2/57/24.html -http://yp.gates96.com/13/2/57/34.html -http://yp.gates96.com/13/2/57/35.html -http://yp.gates96.com/13/2/57/64.html -http://yp.gates96.com/13/2/58/92.html -http://yp.gates96.com/13/2/59/2.html -http://yp.gates96.com/13/2/59/31.html -http://www.outpersonals.com/cgi-bin/w3com/pws/out/RLhI7rcI1D4JxQFT7-3mEP5SJK8AVzq_FCHTmPD4oB4tzM54LVISOGr6gaW80TieiLj3vEEhfqMBuYuDKIQXk3pROAhdckz6dDnbPsi72aC9ZSsK2o3j3J8YlLpw-uOtcBIEsA4ZZATUNj1D6atp66I4 -http://www.dulux.co.uk/UKRETAIL:1938649915:DFinity.1QJiP4jRabmkmb -http://www.dulux.co.uk/UKRETAIL:1938649915:DFinity.1QJiP4jMomdoclfieh -http://www.egroups.com/messages/raite-dvd/1442 -http://www3.newstimes.com/archive2000/jun28/bzd.htm -http://yp.gates96.com/2/75/20/35.html -http://yp.gates96.com/2/75/20/42.html -http://yp.gates96.com/2/75/20/48.html -http://yp.gates96.com/2/75/21/28.html -http://yp.gates96.com/2/75/21/88.html -http://yp.gates96.com/2/75/21/91.html -http://yp.gates96.com/2/75/21/93.html -http://yp.gates96.com/2/75/21/96.html -http://yp.gates96.com/2/75/22/23.html -http://yp.gates96.com/2/75/23/50.html -http://yp.gates96.com/2/75/24/13.html -http://yp.gates96.com/2/75/24/47.html -http://yp.gates96.com/2/75/24/90.html -http://yp.gates96.com/2/75/25/33.html -http://yp.gates96.com/2/75/25/46.html -http://yp.gates96.com/2/75/25/84.html -http://yp.gates96.com/2/75/26/37.html -http://yp.gates96.com/2/75/26/40.html -http://yp.gates96.com/2/75/27/30.html -http://yp.gates96.com/2/75/27/66.html -http://yp.gates96.com/2/75/27/81.html -http://yp.gates96.com/2/75/28/34.html -http://yp.gates96.com/2/75/28/55.html -http://yp.gates96.com/2/75/29/12.html -http://yp.gates96.com/2/75/29/19.html -http://yp.gates96.com/2/75/29/45.html -http://yp.gates96.com/2/75/29/56.html -http://yp.gates96.com/2/75/29/86.html -http://yp.gates96.com/2/75/29/99.html -http://cn.egroups.com/message/agribusiness1/31 -http://biblio.cesga.es:81/search*gag/jLugo+(Provincia).+Mapas+topográficos.+[1890%3F]/jlugo+provincia+mapas+topograficos+1890/31,-1,0,B/browse -http://bbs.lineone.net/news/uknews/msg01030.html -http://bbs.lineone.net/news/uknews/msg01047.html -http://bbs.lineone.net/news/uknews/msg01026.html -http://bbs.lineone.net/news/uknews/msg00976.html -http://bbs.lineone.net/news/uknews/msg00960.html -http://bbs.lineone.net/news/uknews/msg00952.html -http://idl.tucows.com/winnt/adnload/1380_28802.html -http://retailer.gocollect.com/do/session/1912681/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/christmas/holiday_shoppe.asp -http://www1.zdnet.co.uk/software/fstore/A/9/000BA9.html -http://polygraph.ircache.net:8181/home/http_-2www.tauchbali.com/SERV.HTM -http://channel.nytimes.com/1998/05/01/technology/cybertimes/artsatlarge/ -http://ftp.sunet.se/pub/FreeBSD/ports/ports/japanese/linux-netscape47-communicator/?D=A -http://www9.hmv.co.uk:5555/do/session/1347757/vsid/199/tid/199/cid/1061396/mid/1020/rid/1052/chid/1029/parser/yes/imref/eqqLmwlGltt5tkeHjskKZlkKrhlK/url/http://www.hmv.co.uk/hmv/hiddenframe.html -http://www9.hmv.co.uk:5555/do/session/1347757/vsid/199/tid/199/cid/1061396/mid/1020/rid/1052/chid/1029/parser/yes/imref/eqqLmwlGltt5tkeHjskKZlkKrhlK/url/http://www.hmv.co.uk/hmv/logoframe.html -http://www-usa9.cricket.org/link_to_database/ARCHIVE/1999-2000/WI_IN_NZ/ARTICLES/ -http://www-usa9.cricket.org/link_to_database/ARCHIVE/1999-2000/WI_IN_NZ/SCORECARDS/ -http://a228.g.akamai.net/7/228/289/55d96730f1ea56/news.indiainfo.com/2000/08/13/floods.html -http://caller-times.com/1999/august/08/today/texas_me/4241.html -http://ftp.uni-bremen.de/pub/doc/news.answers/movies/winona-ryder-faq/part3 -http://www.globalsources.com/gsol/owa/website.gold/GP3/8801728414/HOME.HTM -http://eds.kse.or.kr/jaemoo/jipyo_e/k_grp/E01683.htm -http://eds.kse.or.kr/jaemoo/jipyo_e/i_grp/E01116.htm -http://eds.kse.or.kr/jaemoo/jipyo_e/i_grp/E01126.htm -http://eds.kse.or.kr/jaemoo/jipyo_e/d_grp/E00366.htm -http://eds.kse.or.kr/jaemoo/jipyo_e/h_grp/E00929.htm -http://www.jobvillage.com/channel/jobs/cleaning/pruner/g.1276.html -http://www.affiliate.hpstore.hp.co.uk/do/session/380817/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/assistance/entry.asp -http://gamingplace.zeelandnet.nl/poker_rating.html -http://no.egroups.com/message/DVD-Info/111 -http://www.relax.ch/static/it/lazurigo/mercatodellavoro/oben.html -http://internet.exit.de/mees-online/left_geld.html -http://www.redrocksports.com/sports/webSession/shopper/RR972959658-31049/store/dept-5/department/dept-5/item/footwear -http://www.redrocksports.com/sports/webSession/shopper/RR972959658-31049/store/dept-5/department/dept-5/item/52550 -http://www11.cplaza.ne.jp/babyweb/bbs/bdnmp01/no16/61N.html -http://www.daimi.au.dk/dIntProg/java/jdk1.2.2/docs/api/javax/swing/plaf/basic/BasicScrollBarUI.ArrowButtonListener.html -http://www.daimi.au.dk/dIntProg/java/jdk1.2.2/docs/api/javax/swing/plaf/basic/BasicScrollBarUI.ModelListener.html -http://www.angelfire.com/nc/Percosolation/POSDerisions.html -http://yp.gates96.com/3/4/40/80.html -http://yp.gates96.com/3/4/41/23.html -http://yp.gates96.com/3/4/41/24.html -http://yp.gates96.com/3/4/41/37.html -http://yp.gates96.com/3/4/41/90.html -http://yp.gates96.com/3/4/42/26.html -http://yp.gates96.com/3/4/42/71.html -http://yp.gates96.com/3/4/42/90.html -http://yp.gates96.com/3/4/44/44.html -http://yp.gates96.com/3/4/45/52.html -http://yp.gates96.com/3/4/45/75.html -http://yp.gates96.com/3/4/45/77.html -http://yp.gates96.com/3/4/46/0.html -http://yp.gates96.com/3/4/46/85.html -http://yp.gates96.com/3/4/47/19.html -http://yp.gates96.com/3/4/47/20.html -http://yp.gates96.com/3/4/47/23.html -http://yp.gates96.com/3/4/47/72.html -http://yp.gates96.com/3/4/48/4.html -http://yp.gates96.com/3/4/48/16.html -http://yp.gates96.com/3/4/48/45.html -http://yp.gates96.com/3/4/48/51.html -http://yp.gates96.com/3/4/49/16.html -http://ftpsearch.belnet.be/pub/mirror/sunsite.cnlab-switch.ch/mirror/harvest/contrib/Example-Customizations/?S=A -http://pub9.ezboard.com/fgaprforeignrelationdepartment.showAddTopicScreenFromWeb -http://pub9.ezboard.com/fgaprforeignrelationdepartment.showMessage?topicID=4.topic -http://www.asstr.org/nifty/gay/authoritarian/adonis-brotherhood/adonis-brotherhood-3 -http://www.brio.de/BRIO.catalog/39fe2f4c06d41844273fd472aa7806a9/UserTemplate/8 -http://itcareers.careercast.com/texis/it/itjs/+HwwBmeH_D86aqwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqew6nxqdDdMoqax15oDn55a5BwhhawDwcO5o5aqd5Ban5BoMwBoDtaGo5Aa5nGVoqnaADdicnmtnaBddc5aMFqhTfR20DzmenxwwwpBmeWWD86exhwww5rmeWcwwwBrmeZpwww/jobpage.html -http://polygraph.ircache.net:8181/http_-2www.whowhere.com/http_-2www.updowntowner.org/julyjamm/frmain.htm -http://213.36.119.69/do/session/152987/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/FR/reserver/spectacles/ -http://www.jobvillage.com/channel/jobs/health_care/physician/anesthesiologist/b.9467.g.1575.html -http://www.private-immobilien-boerse.de/friesland/verkauf/IIM-Teil/Startseite/Gemeinsam/Super-Zins-Konditionen/Gemeinsam/Inserieren/Gemeinsam/MarketingStrategie/inhalt.htm -http://se.egroups.com/message/yemdiscussion/38 -http://se.egroups.com/message/yemdiscussion/45 -http://home.bip.net/kerstin.hjelm/Stamtavla%20Z-kullen.html -http://mediate.magicbutton.net/do/session/625616/vsid/4385/tid/4385/cid/88138/mid/1702/rid/2114/chid/3393/url/http://www.worldgallery.co.uk/frameset-abou.html -http://members.tripod.lycos.co.kr/KWEN3607/?S=A -http://cpan.clix.pt/authors/id/B/BP/BPOWERS/String-StringLib-1.02.readme -http://www.gbnf.com/genealogy/bookout/html/d0001/I3283.HTM -http://m4.findmail.com/group/Opera2Developers -http://m4.findmail.com/group/acctworks -http://retailer.gocollect.com/do/session/1912690/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/product_display/top_ten.asp?pagenum=1 -http://retailer.gocollect.com/do/session/1912690/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/postcards/index.asp -http://platsbanken.amv.se/kap/text/47/001023,170030,140912,11,1276051947.shtml -http://www.gamespot.com/features/dunesg/dune6a.html -http://tucows.iquest.net/winme/preview/138053.html -http://tucows.iquest.net/winme/preview/137529.html -http://tucows.iquest.net/winme/preview/138641.html -http://archive.soccerage.com/s/pt/09/03721.html -http://archive.soccerage.com/s/pt/09/07102.html -http://www10.nytimes.com/library/national/science/health/021500hth-women-diabetes.html -http://smb.slac.stanford.edu/cgi-bin/nph-proxy.cgi/000/http/www.phy.bnl.gov/e949/e949_update.txt -http://www.mapion.co.jp/custom/AOL/admi/13/13105/otsuka/3chome/index-7.html -http://go18.163.com/_NTES/~starseeker/gin/saga/gin01/gin0100.htm -http://village.infoweb.ne.jp/~fvgg8450/t91.html -http://clickahouse.mp2.homes.com/content/articles/locks.html -http://findmail.com/messages/studentdoctor/354 -http://ldp.mirror.nettuno.it/Linux/LDP/LDP/lkmpg/node3.html -http://ldp.mirror.nettuno.it/Linux/LDP/LDP/lkmpg/node13.html -http://fi.egroups.com/group/sandycove -http://www.fogdog.com/cedroID/ssd3040183219992/boutique/nike/ -http://www.fogdog.com/cedroID/ssd3040183219992/boutique/harbinger/ -http://www.fogdog.com/cedroID/ssd3040183219992/customer_service/employment.html -http://www.genoma.de/shop/736a8b4b4c331e80f780899842a4b0b4/99/b -http://sjsulib1.sjsu.edu:81/search/tbraille+transcription+project+of+santa+clara+county+inc/-5,-1,1,B/frameset&tbook+reviews+in+the+humanities&1,1, -http://students.washington.edu/emgall/eng481/final/ -http://www.vc-graz.ac.at/ilct/ffe_349_99.htm -http://www.vc-graz.ac.at/ilct/ffe_372_00.htm -http://www.vc-graz.ac.at/ilct/ffe_375_00.htm -http://www.escribe.com/computing/virtcom/m452.html -http://members.tripod.com/~TreasureIsland/welcom/e.htm -http://augustachronicle.com/stories/022699/obi_038-5494.001.shtml -http://augustachronicle.com/stories/022699/obi_038-5477.001.shtml -http://ring.edogawa-u.ac.jp/archives/X/opengroup/R6.5.1/xc/lib/Imakefile -http://www.elop.de/d0-1015-2044-3001-top.html -http://www.ibiblio.org/pub/languages/java/blackdown.org/JDK-1.1.7/i386/glibc/v1a/?S=D -http://www.linux.com/networking/network/enterprise/integration/management/Linux/ -http://www.mapion.co.jp/custom/AOL/admi/13/13221/matsuyama/2chome/index-7.html -http://www.mapion.co.jp/custom/AOL/admi/13/13221/matsuyama/2chome/index-12.html -http://ftp.sunet.se/pub/FreeBSD/ports/ports/japanese/tcl76/Makefile -http://ftp.lip6.fr/pub2/sgml-tools/website/HOWTO/Consultants-HOWTO/t19977.html -http://www.irishnews.com/archive2000/06072000/sportuk1.html -http://allmacintosh.ii.net/adnload/71893.html -http://allmacintosh.ii.net/adnload/70339.html -http://www.museumshops.co.uk/Bonnefoit-Alain/Bonnefoit-Alain-Die-Schoene-mit-dem-Pelz-3000062.html -http://www.timesoc.com/editions/orange/20001030/t000103758.html -http://www.musiciansfriend.com/ex/ds/bv/001030182803064208037039434033 -http://www.beneteau-owners.com/library.nsf/Library+By+System!OpenView&Start=41.4&Count=45&Expand=49 -http://www.musiciansfriend.com/ex/search/guitar/001030182759064208037059215342?FIND=BABX&q=c -http://www.musiciansfriend.com/ex/search/guitar/001030182759064208037059215342?FIND=ASAX&q=c -http://www.iabusnet.org:90/forums/aca-1/dispatch.exe/survey/showNextUnseen/fol/100001/2467632 -http://tucows.wish.net/winme/adnload/137243_28721.html -http://yp.gates96.com/3/71/10/71.html -http://yp.gates96.com/3/71/11/12.html -http://yp.gates96.com/3/71/11/27.html -http://yp.gates96.com/3/71/11/34.html -http://yp.gates96.com/3/71/11/40.html -http://yp.gates96.com/3/71/11/62.html -http://yp.gates96.com/3/71/11/78.html -http://yp.gates96.com/3/71/12/70.html -http://yp.gates96.com/3/71/13/34.html -http://yp.gates96.com/3/71/13/38.html -http://yp.gates96.com/3/71/13/82.html -http://yp.gates96.com/3/71/14/94.html -http://yp.gates96.com/3/71/15/0.html -http://yp.gates96.com/3/71/15/88.html -http://yp.gates96.com/3/71/17/28.html -http://yp.gates96.com/3/71/17/85.html -http://yp.gates96.com/3/71/18/37.html -http://yp.gates96.com/3/71/18/69.html -http://yp.gates96.com/3/71/19/55.html -http://www.kodak.ca/US/en/corp/jobs/samplingMechanicalProds.shtml -http://ring.crl.go.jp/archives/lang/perl/CPAN/authors/id/G/GR/GRICHTER/HTML-Embperl-1.3b4.readme -http://www7.freeweb.ne.jp/photo/lystra/a/n_aikawa.html -http://www.imagesofengland.org.uk/31/73/317339.htm -http://webraft.its.unimelb.edu.au/110080/students/ojb/pub/?D=A -http://pub.chinaccm.com/13/news/200010/31/155751.asp -http://pub.chinaccm.com/13/news/200010/21/162140.asp -http://go18.163.com/_NTES/~chen0580/y25.htm -http://pub17.ezboard.com/fcometalkfreetalk.showMessage?topicID=15.topic -http://pub17.ezboard.com/fcometalkfreetalk.showMessage?topicID=6.topic -http://mediate.magicbutton.net/do/session/625593/vsid/4385/tid/4385/cid/88138/mid/1702/rid/2114/chid/3393/url/http://www.worldgallery.co.uk/frameset-tips.html -http://213.36.119.69/do/session/152982/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/FR/wap/lancement.html -http://wap.jamba.de/KNet/_KNet-Drs8j1-yEd-1395x/showInfo-presse.de/node.0/cde7f1uou -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=choramingar&l=pt -http://www.amcity.com/philadelphia/stories/1998/11/09/story5.html?t=email_story -http://www.mic.hr/PGMARKET:553666 -http://cn.egroups.com/messages/KristinChenoweth/2280 -http://quest7.proteome.com/databases/YPD/PombePD/SPAC343.03.html -http://www.engines.org.uk/white/fld19/ -http://www.engines.org.uk/white/fld27/ -http://se.egroups.com/subscribe/plusgothswap -http://www.headlight.com/invoice_process/1,1074,adpa-4049-2423-69-718,00.html -http://www.findarticles.com/cf_0/m4PRN/1999_Nov_3/57153314/p1/article.jhtml -http://www.iabusnet.org:90/forums/aca-1/dispatch.exe/survey/folderFrame/100001/0/alpha/2480022 -http://archive.soccerage.com/s/it/06/10903.html -http://innopac.lib.tsinghua.edu.cn/search*chi/dProduction+engineering/dproduction+engineering/-5,-1,0,B/browse -http://www.consource.com/communities/profile_categories/1759/1510 -http://column.daum.net/Column-bin/Bbs.cgi/thinkaboutrbs/new/zka/B2-kB2Np -http://wwws.br-online.de/geld/boerse/960301/0730.html -http://www.2pl.com/asp/tools/fili1.asp?sp=ro&fi=pppp0003zi -http://www.proviser.co.uk/regional/towns/alford/property_prices/compare_current_prices/terraced.html -http://cometweb01.comet.co.uk/do!session=131998&vsid=700&tid=20&cid=37030&mid=1000&rid=1060&chid=1713&url=eqqLmwlGltt5tkZHljbLqkZHlkrHhlZHdfjKYfkLlkZ5ljjLboZLbplG3XqLbdlLov4LfpmLiXvL-Zd5jbkLYozKvot0cZd5ockLYozKvsm0utt0cZX5qkXLjbzKMfaLblpLbom0bos0bom04M4Lbom0miXLvboLp1 -http://cometweb01.comet.co.uk/do!session=131998&vsid=700&tid=20&cid=37030&mid=1000&rid=1060&chid=1713&url=eqqLmwlGltt5tkZHljbLqkZHlkrHhlZHdfjKYfkLlkZ5ljjLboZLbplG3XqLbdlLov4LfpmLiXvL-Zd5jbkLYozKvot0cZd5ockLYozKvsm0uqo0cZX5qkXLjbzKG3pLibo0miX5mqlLmpbKomb0osb0oml1odXLkfpLbopL -http://www.geocities.co.jp/Milano/8578/profile.html -http://ftp.dti.ad.jp/pub/XFree86/3.3.3/binaries/NetBSD-1.2/Servers/?N=D -http://ftp.dti.ad.jp/pub/XFree86/3.3.3/binaries/NetBSD-1.2/Servers/?D=A -http://www.best.com/~radko/lounge/messages/3742.html -http://www.best.com/~radko/lounge/messages/3711.html -http://www.best.com/~radko/lounge/messages/3619.html -http://www.linux.com/networking/network/help/email/business/RuleSpace/ -http://www.financialexpress.com/fe/daily/20000918/fco17026.html -http://209.67.27.70/comics/dilbert/scott/dawn/pg19.html -http://209.67.27.70/comics/dilbert/scott/dawn/pg22.html -http://flamingo.promote.ru/href.pl?fct_051 -http://pda.saa.net/palm/adnload/34404_22152.html -http://www.outpersonals.com/cgi-bin/w3com/pws/out/q6tIzhLNlKeaaMXYVAPJiOq7V33Ul08VcQoPAomjWMQzOxA0cR6_kRLx42D4nA_uumPVc2DRZtv6CVpWQCyNUgVZQ2P9F7bqqvcf_5WqCdUM7UIRKBdjb9lTbrCrrl5_jZ6cQsstJDqry3XrFI0toILqSCSm66j2 -http://www.home.ch/~spaw9012/ps11/ps11_003.htm -http://help.sap.com/saphelp_45b/helpdata/de/1c/e464b20437d1118b3f0060b03ca329/frameset.htm -http://abc.ru/cgi-bin/get_firminfo.pl?firm=comsys -http://www.pressa.spb.ru/newspapers/nevrem/arts/nevrem-1749-art-28.html -http://www.pressa.spb.ru/newspapers/nevrem/arts/nevrem-1749-art-32.html -http://admin.afiliando.com/do/session/189435/vsid/1507/tid/1507/cid/23455/mid/1025/rid/1168/chid/1205/parser/yes/imref/eqqLmwlGltt5tkpHrYjLXofLklkKZljLkju5lZa5l0/url/http://www.submarino.com.mx/pesquisa/jutherC.asp?id_categoria=57&id_tipo=C -http://admin.afiliando.com/do/session/189435/vsid/1507/tid/1507/cid/23455/mid/1025/rid/1168/chid/1205/parser/yes/imref/eqqLmwlGltt5tkpHrYjLXofLklkKZljLkju5lZa5l0/url/http://www.submarino.com.mx/extra/talk_to_sub.asp -http://cometweb01.comet.co.uk/do!session=131998&vsid=700&tid=20&cid=37030&mid=1000&rid=1060&chid=1713&url=eqqLmwlGltt5tkZHljbLqkZHlkrHhlZHdfjKYfkLlkZ5ljjLboZLbplG3XqLbdlLov4LfpmLiXvL-Zd5jbkLYozKvot0cZd5ockLYozKvsn0mvm0cZX5qkXLjbzKGelLkbpL -http://yp.gates96.com/3/39/30/1.html -http://yp.gates96.com/3/39/30/53.html -http://yp.gates96.com/3/39/31/22.html -http://yp.gates96.com/3/39/32/0.html -http://yp.gates96.com/3/39/32/39.html -http://yp.gates96.com/3/39/32/41.html -http://yp.gates96.com/3/39/32/45.html -http://yp.gates96.com/3/39/32/97.html -http://yp.gates96.com/3/39/34/39.html -http://yp.gates96.com/3/39/34/50.html -http://yp.gates96.com/3/39/34/68.html -http://yp.gates96.com/3/39/34/72.html -http://yp.gates96.com/3/39/35/14.html -http://yp.gates96.com/3/39/35/84.html -http://yp.gates96.com/3/39/36/3.html -http://yp.gates96.com/3/39/36/19.html -http://yp.gates96.com/3/39/36/20.html -http://yp.gates96.com/3/39/36/84.html -http://yp.gates96.com/3/39/36/88.html -http://yp.gates96.com/3/39/37/37.html -http://yp.gates96.com/3/39/38/60.html -http://yp.gates96.com/3/39/38/63.html -http://yp.gates96.com/3/39/39/52.html -http://yp.gates96.com/3/39/39/56.html -http://yp.gates96.com/3/39/39/58.html -http://yp.gates96.com/3/39/39/63.html -http://yp.gates96.com/13/9/80/14.html -http://yp.gates96.com/13/9/80/92.html -http://yp.gates96.com/13/9/81/23.html -http://yp.gates96.com/13/9/81/47.html -http://yp.gates96.com/13/9/82/45.html -http://yp.gates96.com/13/9/82/59.html -http://yp.gates96.com/13/9/82/65.html -http://yp.gates96.com/13/9/82/71.html -http://yp.gates96.com/13/9/82/77.html -http://yp.gates96.com/13/9/83/86.html -http://yp.gates96.com/13/9/83/88.html -http://yp.gates96.com/13/9/84/4.html -http://yp.gates96.com/13/9/84/28.html -http://yp.gates96.com/13/9/84/77.html -http://yp.gates96.com/13/9/85/34.html -http://yp.gates96.com/13/9/85/59.html -http://yp.gates96.com/13/9/86/22.html -http://yp.gates96.com/13/9/86/28.html -http://yp.gates96.com/13/9/86/30.html -http://yp.gates96.com/13/9/86/37.html -http://yp.gates96.com/13/9/86/85.html -http://yp.gates96.com/13/9/87/1.html -http://yp.gates96.com/13/9/87/2.html -http://yp.gates96.com/13/9/88/58.html -http://yp.gates96.com/13/9/89/17.html -http://yp.gates96.com/13/9/89/49.html -http://yp.gates96.com/13/9/89/51.html -http://yp.gates96.com/13/9/89/64.html -http://yp.gates96.com/13/9/89/69.html -http://yp.gates96.com/13/9/89/79.html -http://www.diogenes.ch/4DACTION/web_rd_aut_frlist_az/ID=483337&chr=D -http://ngi.tucows.com/win2k/adnload/37473_28857.html -http://www4.nas.edu/ohr.nsf/All+Documents/Major+Units?OpenDocument&ExpandSection=1,4,21,7,17 -http://www4.nas.edu/ohr.nsf/All+Documents/Major+Units?OpenDocument&ExpandSection=2,4,21,7,17 -http://www4.nas.edu/ohr.nsf/All+Documents/Major+Units?OpenDocument&ExpandSection=15,4,21,7,17 -http://www4.nas.edu/ohr.nsf/All+Documents/Major+Units?OpenDocument&ExpandSection=16,4,21,7,17 -http://www.susi.de/cgi-bin/order/segelzentrum-kagerer/c134-5021905270003,de -http://www.egroups.com/messages/iraq-l/9973 -http://www2.kbank.no/Web/nlpublish.nsf/Published/ord_og_uttrykk!OpenDocument&ExpandSection=29,24,30,11 -http://www.etoys.com/prod/book/51604361 -http://link.fastpartner.com/do/session/600358/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/itjobbank.php -http://link.fastpartner.com/do/session/600358/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/shopnett.php -http://mirror.nucba.ac.jp/mirror/FreeBSD/branches/2.2-stable/ports/devel/mips64orion-rtems-objc/?S=A -http://www-uk5.cricket.org/link_to_database/NATIONAL/ENG/FC_TEAMS/SOMERSET/STATS/CAREER/SOMERSET_CAREER_J.html -http://www.linux.com/networking/network/performance/install/distro/industry/ -http://www.linux.com/networking/network/performance/install/distro/tools/ -http://www.linux.com/networking/network/performance/install/distro/enterprise/ -http://mx.php.net/manual/de/language.basic-syntax.php -http://mx.php.net/manual/fr/language.basic-syntax.php -http://moviestore.zap2it.com/browse/MOVIES/SCRIPT/s.UxBwM3db -http://www.armouries.org.uk/bjarni/introduction.htm -http://mirror.cc.utsunomiya-u.ac.jp/mirror/CPAN/authors/id/C/CT/CTWETEN/?D=A -http://atlanta.webmd.com/related_results/1/25/article/1738.50204 -http://www.ccnet.com/tzimmer/?M=A -http://go2.163.com/~xinhua/ -http://www.ualberta.ca/FTP/OpenBSD/src/regress/lib/libc/_setjmp/CVS/Root -http://www.dqt.com.cn/wymb/military/jinyong/金庸全集.htm -http://www.hole.kommune.no/hole/journweb.nsf/7e180336094ef23a412568cd004a5093/2fd09f96f20814cac12568e300443d50!Navigate&To=Next -http://classifieds.alberta.com/js/mi/c16000/b16000/n15/858640.html -http://classifieds.alberta.com/js/mi/c16000/b16000/n15/861013.html -http://homepages.go.com/homepages/b/n/g/bngholo/ -http://www.aelita.net/products/news/library/support/Reg/Subscribe/library/default.htm -http://www.chaos.dk/sexriddle/j/a/b/s/e/ -http://www.chaos.dk/sexriddle/j/a/b/s/t/ -http://213.36.119.69/do/session/152985/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/FR/contact/info-publicite.html -http://www.indian-express.com/fe/daily/19990807/corporate.html -http://web.cln.com/archives/atlanta/newsstand/atl100795/1316.htm -http://web.cln.com/archives/atlanta/newsstand/atl100795/1317.htm -http://plaza.gaiax.com/www/plaza/k/n/kenta/friends.html -http://polygraph.ircache.net:8181/docs/eudora/http_-2www.kentuckylake.com/rates/http_-2www.hubbell-wiring.com/NEMA/admin/additional.html -http://gd.cnread.net/cnread1/wxxs/d/dongfangying/pljc/015.htm -http://www.bemi-immobilien.de/Startseite/www.ferien-immobilien.de/ferien-ib/startseite/Startseite/Gemeinsam/versicherungen/gebaeude/Gemeinsam/versicherungen/unfall/Startseite/www.ferien-immobilien.de/ferien-ib/startseite/Gemeinsam/versicherungen/lebensversicherung/Gemeinsam/versicherungen/gebaeude/anforderungsformular.htm -http://www.linux.com/networking/network/help/free/red_hat/competition/ -http://www.linux.com/networking/network/help/free/red_hat/development/ -http://www.linux.com/networking/network/help/free/red_hat/SuSE/ -http://search.chollian.net/d/%b1%e2%be%f7,%c8%b8%bb%e7/%b0%e1%c8%a5/%c5%e4%c5%bb%bf%fe%b5%f9%bc%ad%ba%f1%bd%ba/16.html -http://no.egroups.com/message/plowshares/840 -http://www.pressa.spb.ru/newspapers/nevrem/arts/nevrem-1872-art-13.html -http://www.bemi-immobilien.de/Startseite/www.allgemeine-immobilien-boerse.de/allgemeine-ib/landkreiszwickau/Verkauf/29109700708107kirchbergvillamü/Gemeinsam/erreichenPartner/Startseite/Gemeinsam/versicherungen/lebensversicherung/Top-Darlehens-Konditionen/Gemeinsam/versicherungen/unfall/anforderungsformular.htm -http://www.affiliate.hpstore.hp.co.uk/do/session/380819/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.france.hp.com/main/respect/ -http://www-rn.informatik.uni-bremen.de/home/ftp/pub/linux/redhat/updates/6.2EE/i586/ -http://archive.soccerage.com/s/es/09/12718.html -http://www.intel.es/kr/hangul/pressroom/archive/releases/dp990218.htm -http://www.intel.es/kr/hangul/pressroom/archive/releases/dp990105.htm -http://sunsite.informatik.rwth-aachen.de/cgi-bin/ftp/ftpshow/pub/Linux/sunsite.unc.edu/distributions/caldera/eServer/updates/2.3/021/RPMS/ -http://library.bangor.ac.uk/search/aMatis,+James+H/amatis+james+h/-5,-1,0,B/browse -http://polygraph.ircache.net:8181/http_-2www.microsoft.com/frontpage/html/http_-2www.sharkyextreme.com/hardware/hercules_tnt/ -http://ring.nihon-u.ac.jp/archives/pack/win95/net/fee/?N=D -http://dbc.copystar.com.tw/bcbchat/199804/msg03730.htm -http://dbc.copystar.com.tw/bcbchat/199804/msg03761.htm -http://dbc.copystar.com.tw/bcbchat/199804/msg03787.htm -http://www.private-immobilien-boerse.de/nordrhein-Westfalen/grevenbroich/Verkauf/Gemeinsam/Super-Zins-Konditionen/Exklusiv-IB/Startseite/IIM-Teil/Startseite/Gemeinsam/IIMMitglieder.htm -http://www.private-immobilien-boerse.de/nordrhein-Westfalen/grevenbroich/Verkauf/Gemeinsam/Super-Zins-Konditionen/Exklusiv-IB/Startseite/IIM-Teil/Startseite/Gemeinsam/vertriebspartner.htm -http://pd.shiseido.co.jp/s9604tub/html_00/win00051.htm -http://solaris.license.virginia.edu/os_product_patches/patches/5.7/107094-04/SUNWdtbas/pkgmap -http://www.eveclub.com/cgi-bin/eveclub.front/972959470432/Catalog/11000034 -http://www.sportinggreen.com/news/20001007/fbo/fbc/aar/001007.0607.html -http://www-x500-1.uni-giessen.de:8890/Lcn%3dBelloch%20Belloch%5c,%20Juana%20Maria,ou%3dFacultad%20de%20Medicina%20y%20Odontologia,o%3dUniversidad%20de%20Valencia,c%3dES -http://retailer.gocollect.com/do/session/1912723/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/exclusives/limited_editions.asp -http://www.jufo.com/netcenter/chemistry/item/000904/16888.htm -http://ww2.comune.fe.it/cgi-win/hiweb.exe/a2/d29/b14,8,1f,1d,1d,,19,,1f,19, -http://www.2pl.com/b/ru/to/1/24/16/v2/1241600107-8.htm -http://ring.htcn.ne.jp/pub/text/CTAN/fonts/metrics/polish/plpsfont/?D=A -http://config.tucows.com/winme/adnload/26398_28890.html -http://ocean.ntou.edu.tw/search*chi/aRadojcic,+Riko,+jt.+auth./aradojcic+riko/-5,-1,0,B/frameset&F=aradomsky+nellie+a&1,1 -http://www.intellicast.com/Sail/World/UnitedStates/Northwest/Montana/Beaverhead/LocalWinds/d1_09/ -http://www.bild.de/service/archiv/2000/mar/31/sport/coulthard/coulthard.html -http://ustlib.ust.hk/search*chi/a%7B215a36%7D%7B213246%7D%7B215e42%7D+1926/a{215a36}{213246}{215e42}+1926/-5,-1,0,B/frameset&F=a{215a36}{213230}{214e70}&1,1 -http://mediate.magicbutton.net/do/session/625620/vsid/4385/tid/4385/cid/88138/mid/1702/rid/2114/chid/3393/url/http://www.worldgallery.co.uk/frameset-top50.html -http://mediate.magicbutton.net/do/session/625620/vsid/4385/tid/4385/cid/88138/mid/1702/rid/2114/chid/3393/url/http://www.worldgallery.co.uk/frameset-corp.html -http://www.amateurplatinum.com/mouthlicking/eunuchhershey-highway/bad-girlsubmission/petitebeauties/actionno-boundaries/fellatiogoing-down-on/give-headcock-suckers.html -http://www.brd.net/brd-cgi/brd_dkameras/filmscanner_fotodrucker/FZ00F0EF/beurteilung/ci=972751646.htm -http://www.niwl.se/WAIS/31607/31607073.htm -http://www.magicvillage.de/Login/magicvillage/magiclife/Lucullus/%2328706045/Reply -http://polygraph.ircache.net:8181/consumer/rel_meet_main.html -http://sunsite.informatik.rwth-aachen.de/cgi-bin/ftp/ftpshow/pub/Linux/sunsite.unc.edu/distributions/debian/dists/potato/non-free/binary-i386/x11/ -http://www.great-cyber-mall.com/SelectCompany.asp?CityID=67&CatID=5 -http://www.great-cyber-mall.com/SelectCompany.asp?CityID=67&CatID=50 -http://rainforest.parentsplace.com/dialog/get/bradley2/39/1/1.html?embed=2 -http://www.users.yun.co.jp/cgi-bin/moriq/pigeon/pigeon.cgi/DataSet.after_post?c=e -http://www.chaos.dk/sexriddle/n/f/p/x/x/ -http://www.amcity.com/dayton/stories/2000/03/20/smallb1.html?t=email_story -http://www.linux.com/networking/network/industry/web_server/windows_nt/Red_Hat/ -http://www.du-et.net/cgi/mail.cgi?NickName=naiki -http://gameboyz.com/g/demos_p1_c41_lV_w2.html -http://intelinfo.subportal.com/sn/Games/Strategy_Games/9289.html -http://home.kimo.com.tw/maso-kid/index2.html -http://citeseer.nj.nec.com/nrelated/1377121/289677 -http://citeseer.nj.nec.com/nrelated/0/289677 -http://ccar.ust.hk/~dataop/rs_ocean_cd/WVS/wvsplus/wvs003m/bat/q/h/lf/ -http://home.baoding.cn.net/~tjhlove/dzrwy/l11.htm -http://home.baoding.cn.net/~tjhlove/dzrwy/l23.htm -http://208.178.109.85/msgshow.cfm/msgboard=129014524422386&msg=3558983275052&page=1&idDispSub=-1 -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=4,9,33,27,35 -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=29,9,33,27,35 -http://config.tucows.com/win2k/adnload/76944_30007.html -http://www1.zdnet.com/zdnn/stories/news/0,4586,1021147,00.html -http://www.fogdog.com/cedroID/ssd3040183236187/nav/stores/snowboarding/ -http://www.fogdog.com/cedroID/ssd3040183236187/nav/stores/institutional/ -http://debian.linux.org.tw/debian/dists/sid/main/disks-powerpc/current/source/?M=A -http://satftp.soest.hawaii.edu/dlr/slides/ql21176.html -http://www.linux.com/networking/network/industry/new/help/internet/ -http://www.linux.com/networking/network/industry/new/help/growth/ -http://flint.freethemes.com/skins/winamp/preview/46994.html -http://flint.freethemes.com/skins/winamp/preview/24628.html -http://flint.freethemes.com/skins/winamp/preview/25113.html -http://flint.freethemes.com/skins/winamp/preview/24645.html -http://flint.freethemes.com/skins/winamp/preview/25319.html -http://flint.freethemes.com/skins/winamp/preview/25017.html -http://flint.freethemes.com/skins/winamp/preview/26154.html -http://flint.freethemes.com/skins/winamp/preview/24669.html -http://flint.freethemes.com/skins/winamp/preview/24674.html -http://flint.freethemes.com/skins/winamp/preview/69522.html -http://flint.freethemes.com/skins/winamp/preview/58805.html -http://flint.freethemes.com/skins/winamp/preview/71909.html -http://flint.freethemes.com/skins/winamp/preview/24389.html -http://flint.freethemes.com/skins/winamp/preview/25052.html -http://flint.freethemes.com/skins/winamp/preview/77185.html -http://flint.freethemes.com/skins/winamp/preview/56733.html -http://flint.freethemes.com/skins/winamp/preview/24736.html -http://flint.freethemes.com/skins/winamp/preview/24408.html -http://flint.freethemes.com/skins/winamp/preview/24744.html -http://flint.freethemes.com/skins/winamp/preview/24424.html -http://flint.freethemes.com/skins/winamp/preview/25075.html -http://flint.freethemes.com/skins/winamp/preview/71807.html -http://nomade.fr/cat/informatique_tele/informatique/progiciels_logiciel/utilitaires/communication -http://pub9.ezboard.com/umetalman5566.showPublicProfile?language=EN -http://archiv.leo.org/pub/comp/usenet/comp.binaries.atari.st/texinfo31/texif31b.zoo/ -http://www.maas.ccr.it/cgi-win/hiweb.exe/a18/d13/b261,4,d,,be,d, -http://citeseer.nj.nec.com/cidcontext/608466 -http://l-infonet.phkk.fi/fi/TIETOPALVELUT/asiasanahaku/strategia/kansainv%E4listyminen/ulkomaankauppa/kansainv%E4linen+kauppa/ -http://cms.letsmusic.com/directory/search/albuminfo/1,1125,af0127818000000,00.asp -http://www.musiciansfriend.com/ex/ds/other/001030182805064208037054818832 -http://www.musiciansfriend.com/ex/search/other/001030182805064208037054818832?FIND=IBAX&q=c -http://www.mapion.co.jp/custom/tv/admi/13/13106/kuramae/3chome/19/ -http://dblab.comeng.chungnam.ac.kr/~dolphin//db/journals/ac/ac11.html -http://archive.soccerage.com/s/de/09/c4816.html -http://archive.soccerage.com/s/de/09/c4698.html -http://archive.soccerage.com/s/de/09/c4664.html -http://archive.soccerage.com/s/de/09/c4463.html -http://archive.soccerage.com/s/de/09/c4423.html -http://archive.soccerage.com/s/de/09/c4422.html -http://workingfamilies.digitalcity.com/tampabay/penpals/browse.dci?cat=teens&sort=f -http://www.bemi-immobilien.de/Startseite/www.allgemeine-immobilien-boerse.de/allgemeine-ib/landkreiszwickau/Verkauf/29109700708107kirchbergvillamü/Gemeinsam/Inserieren/Startseite/Gemeinsam/immolink/Top-Darlehens-Konditionen/Gemeinsam/versicherungen/unfall/anforderungsformular.htm -http://www.samba.org/cgi-bin/cvsweb/gnokii/xgnokii/docs/help/en_US/windows/main/?sortby=log -http://www.accesslasvegas.com/shared/health/adam/ency/article/002669sym.html -http://www.egroups.com/message/gaywrestle/33 -http://lfs.cyf-kr.edu.pl:8888/3Lcn%3dDirectory%20Manager,%20o%3dSPRITEL,%20c%3dES -http://www.acfas.ca/congres/congres66/S10.htm -http://hansard.www.act.gov.au/2000/week02/423.htm -http://207.25.71.142/cycling/2000/tour_de_france/stages/4/ -http://207.25.71.142/cycling/2000/tour_de_france/news/2000/07/20/pantani_reflects -http://207.25.71.142/cycling/2000/tour_de_france/news/2000/07/19/driver_charged/ -http://207.25.71.142/POLL/results/1142011.html -http://www2.kbank.no/Web/nlpublish.nsf/Published/ord_og_uttrykk!OpenDocument&ExpandSection=6,14,27,22 -http://www2.kbank.no/Web/nlpublish.nsf/Published/ord_og_uttrykk!OpenDocument&ExpandSection=29,14,27,22 -http://www.affiliate.hpstore.hp.co.uk/do/session/380816/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.france.hp.com/ -http://www.affiliate.hpstore.hp.co.uk/do/session/380816/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/products/entry.asp -http://ads.carltononline.com/accipiter/adclick/site=purejamba/area=jamba.home_page/AAMSZ=POPUP/ACC_RANDOM=972959547609 -http://retailer.gocollect.com/do/session/1912714/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/company_info/contact.asp -http://208.178.101.41/news/1998/12/10newsd.html -http://208.178.101.41/news/1998/03/05news.html -http://208.178.101.41/news/1998/03/03news.html -http://208.178.101.41/news/1998/01/09news.html -http://hff.shunde.net/mobile/radio2000.163.net/radio2000.163.html -http://hff.shunde.net/mobile/www.tohome.net/www.tohome.html -http://www.egroups.com/login.cgi?login_target=%2Fmessages%2FShayrs%2F31 -http://moviestore.zap2it.com/browse/MOVIES/BANK/s.bsk4qCBs -http://moviestore.zap2it.com/browse/MOVIES/STATION/s.bsk4qCBs -http://moviestore.zap2it.com/browse/MOVIES/VIDEO/s.bsk4qCBs -http://ftp.fi.debian.org/debian/dists/unstable/contrib/source/x11/?N=D -http://link.fastpartner.com/do/session/600364/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/company/jobs.htm -http://pub16.ezboard.com/uprieni.showPublicProfile -http://ftp.du.se/disk4/FreeBSD/branches/4.0-stable/ports/x11-servers/XFree86-4-FontServer/ -http://ftp.du.se/disk4/FreeBSD/branches/4.0-stable/ports/x11-servers/XttXF98srv-NKVNEC/ -http://www.generation-formation.fr/services/adrutils/GUIDES/CCI.HTM---o21zAo0UaWo0Ol9A074fo65iyfmKlze8SUeecTAseLvI5ehw7se7NeCfeZJPAPfVbNyqgBecVktePbBxehwwlezc9fAb0vyApuRtAhGqGdisSLdspt6dsSAtdsNhJdspt6dsrvrdjlhkfbu.htm -http://www.generation-formation.fr/services/adrutils/GUIDES/DRIRE.HTM---o21zAo0UaWo0Ol9A074fo65iyfmKlze8SUeecTAseLvI5ehw7se7NeCfeZJPAPfVbNyqgBecVktePbBxehwwlezc9fAb0vyApuRudNnJpo1XCjdRsR3djaPfdNjfcdRsR3djakUApvGdhcmdfbv.htm -http://198.103.152.100/search*frc/aMayer,+Anita/amayer+anita/-5,-1,0,B/frameset&F=amaybank+j+e&1,1 -http://198.103.152.100/search*frc/aMayer,+Anita/amayer+anita/-5,-1,0,B/2exact&F=amaycunich+ann&1,3 -http://kobenhavn.icepage.se/hilfe/XFree86/3.9.18/DECtga2.html -http://itcareers.careercast.com/texis/it/itjs/+YwwBmeJf5C6wwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewyhw1Bdmn5AanLnq1BoVnawmMoDo5BGwBoVnazdxamnpwGBMnDBaGnpdGB5a5BdGnaqddGmoDwBnanMwoca5Aocc5aMFqoEuRZy0IQDzmeJqwwwpBmeBFZ86mwww5rmehpwwwBrmeZpwww/morelike.html -http://itcareers.careercast.com/texis/it/itjs/+cwwBmetKD86eMmwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewyhw1Bdmn5AanLnq1BoVnawmMoDo5BGwBoVnazdxamnpwGBMnDBaGnpdGB5a5BdGnaqddGmoDwBnanMwoca5Aocc5aMFqoEuRZy0IQDzmeJqwwwpBmeBFZ86mwww5rmeODwwwBrmeZpwww/morelike.html -http://bbs.syu.ac.kr/NetBBS/Bbs.dll/scbbs008/rcm/zka/B2-kB27p/qqo/005A/qqatt/^ -http://musicmabey.subportal.com/sn/Themes/Misc__Themes/ -http://www.intel.it/eBusiness/pdf/prod/ia64/SAS_IA-64_Paper.pdf -http://elflife.bigpanda.net/2866/io.html -http://www.excelsior.com.mx/9609/960911/nac11.html -http://www.allgemeine-immobilien-boerse.de/ungarn/verkauf/Private-IB/Ferien-IB/Startseite/Allgemeine-IB/GmbH-Kauf-Verkauf-Insolvenz-konkurs/Startseite/indexbeginn.htm -http://www.allgemeine-immobilien-boerse.de/ungarn/verkauf/Private-IB/Ferien-IB/Startseite/Allgemeine-IB/Gemeinsam/geschaeftsbedingungen.htm -http://www.wingateinns.com/ctg/cgi-bin/Wingate/look_over/AAAksrACwAAACCPAAT -http://my.netian.com/~rakyun/?N=D -http://www.bemi-immobilien.de/Landhaus-Bordeaux/Gemeinsam/versicherungen/gebaeude/Gemeinsam/immolink/Top-Darlehens-Konditionen/Gemeinsam/Inserieren/Gemeinsam/suche.htm -http://www.mirror.kiev.ua:8083/paper/2000/04/1251/text/04-07-5.htm -http://ring.toyama-u.ac.jp/archives/NetBSD/packages/1.4.2/sun3/?N=D -http://ring.toyama-u.ac.jp/archives/NetBSD/packages/1.4.2/sun3/lang/ -http://www.vstore.com/vstorecomputers/8store/ -http://indiadirectory.indiatimes.com/webdirectory/1514pg1.htm -http://indiadirectory.indiatimes.com/webdirectory/1513pg1.htm -http://www.online.kokusai.co.jp/Map/V0002508/wrd/G400/demo/ -http://www.gamespot.com.au/features/everquest_gg/creatures1.html -http://www.jxi.gov.cn/yw-ty001.nsf/view!OpenView&Start=38.11&Count=30&Expand=40 -http://www.jxi.gov.cn/yw-ty001.nsf/view!OpenView&Start=38.11&Count=30&Expand=42 -http://yp.gates96.com/6/0/40/22.html -http://yp.gates96.com/6/0/40/85.html -http://yp.gates96.com/6/0/41/26.html -http://yp.gates96.com/6/0/41/94.html -http://yp.gates96.com/6/0/42/50.html -http://yp.gates96.com/6/0/43/30.html -http://yp.gates96.com/6/0/43/76.html -http://yp.gates96.com/6/0/44/43.html -http://yp.gates96.com/6/0/44/61.html -http://yp.gates96.com/6/0/44/99.html -http://yp.gates96.com/6/0/45/37.html -http://yp.gates96.com/6/0/45/84.html -http://yp.gates96.com/6/0/47/33.html -http://yp.gates96.com/6/0/47/43.html -http://yp.gates96.com/6/0/47/54.html -http://yp.gates96.com/6/0/48/30.html -http://yp.gates96.com/6/0/48/47.html -http://yp.gates96.com/6/0/49/5.html -http://hammer.prohosting.com/~kobeweb/cgi-bin/nagaya/nagaya.cgi?room=036&action=mente -http://www.petropages.com/kproduct/k4267p.htm -http://webraft.its.unimelb.edu.au/536029/students/plam/pub/?M=A -http://www.ld.com/cbd/archive/1999/09(September)/13-Sep-1999/Fawd001.htm -http://www.caijing.yesky.com/33554432/36700160/122010.htm -http://yp.gates96.com/14/85/0/7.html -http://yp.gates96.com/14/85/2/86.html -http://yp.gates96.com/14/85/3/90.html -http://yp.gates96.com/14/85/6/37.html -http://yp.gates96.com/14/85/8/82.html -http://yp.gates96.com/14/85/8/88.html -http://cn.egroups.com/messages/Toledo_Storm/228 -http://mediate.magicbutton.net/do/session/625598/vsid/4385/tid/4385/cid/88138/mid/1702/rid/2114/chid/3393/url/http://www.worldgallery.co.uk/frameset-cart.html -http://rainforest.parentsplace.com/dialog/thread.pl/bradley2/10/2.html?dir=prevResponse -http://tvstore.zap2it.com/browse/TV/JACKET/s.CmMildAx -http://tvstore.zap2it.com/browse/TV/CLOCK/s.CmMildAx -http://findmail.com/post/studentdoctor?act=forward&messageNum=2315 -http://www.chaos.dk/sexriddle/d/j/l/a/y/ -http://gandalf.neark.org/pub/distributions/OpenBSD/src/gnu/egcs/libstdc++/testsuite/libstdc++.tests/?D=A -http://gd.cnread.net/cnread1/net/zpj/s/shenfang/004.htm -http://www.imagesignworks.com/vinylmasksforacidetching/index.nhtml -http://209.249.170.32/stores/dir/bycat/Holiday_and_Seasonal/Christmas.shtml -http://www.allkorea.co.jp/cgi-bin/allkorea.front/972959867726/Catalog/1000107 -http://www.allkorea.co.jp/cgi-bin/allkorea.front/972959867726/Catalog/1000108 -http://www.linux.com/networking/network/applications/interface/microsoft/IBM/ -http://www.linux.com/networking/network/applications/interface/microsoft/Corel/ -http://www.linux.com/networking/network/applications/interface/microsoft/?kw_offset=50 -http://www.tiefbau-suhl.de/Leistung/Stuetzmauern/stuetzmauern2.htm -http://providenet.tucows.com/win2k/adnload/38394_29124.html -http://smb.slac.stanford.edu/cgi-bin/nph-proxy.cgi/000/http/index.opentext.net/weather/detail.cgi?us-dc -http://iceberg.adhomeworld.com/cgi-win/redirect.exe/2133549064 -http://www.dc.digitalcity.com/charlestonwvarea/announce/main.dci?page=letusknow -http://members.tripod.co.jp/yoshihiro_2/yotete.html -http://www.bemi-immobilien.de/Startseite/www.allgemeine-immobilien-boerse.de/allgemeine-ib/landkreiszwickau/Verkauf/29109700708107kirchbergvillamü/Gemeinsam/immolink/Startseite/Gemeinsam/versicherungen/lebensversicherung/Gemeinsam/Startseite/www.ferien-immobilien.de/ferien-ib/startseite/ -http://ftp.debian.org/dists/Debian2.2r0/non-free/binary-arm/web/?N=D -http://www.complete-skier.co.uk/resorts/survey/submit.asp?ResortID=1755 -http://members.tripod.com/~BHS_CC/boys_times_1997.html -http://fi.egroups.com/post/mens-health?act=forward&messageNum=11 -http://nomade.fr/cat/famille_sante/sante/medecine_pratique/medecine_generale/ -http://home.att.net/~mlbvault/mac8.htm -http://mirror.nucba.ac.jp/mirror/Perl/authors/id/ROSCH/String-ShellQuote-1.00.readme -http://www.nrk.no/finnmark/x12_9_96/nyh6.htm -http://ftp.debian.org/dists/Debian2.2r0/non-free/binary-m68k/editors/?N=D -http://134.84.160.1/infoserv/lists/nih-image/archives/nih-image-9702/0141.html -http://www.philly.digitalcity.com/saintjosephmo/penpals/browse.dci?cat=seniors&sort=m -http://www.idg.net/crd_percent_19960.html -http://204.202.130.51/playerfile/profile/mark_karcher.html -http://www.redrocksports.com/sports/webSession/shopper/RR972959692-31077/store/dept-5/department/dept-5/item/52800 -http://www.redrocksports.com/sports/webSession/shopper/RR972959692-31077/store/dept-5/department/dept-5/item/52900 -http://www.online.kokusai.co.jp/Service/V0043510/wrd/G200/service/service.html -http://www.service911.com/mvu/step/0,2632,1+13+139+23899+17191_4,00.html -http://216.34.146.180/141000afp/14worl21.htm -http://www.chaos.dk/sexriddle/t/p/v/r/i/ -http://www.chaos.dk/sexriddle/t/p/v/r/x/ -http://www.ualberta.ca/FTP/Mirror/debian/dists/potato-proposed-updates/eruby_0.0.9-1potato1_arm.changes -http://www.hbdaily.com.cn/scznb/20000622/BIG5/scznb^1104^16^Zn16014.htm -http://www.linux.com/networking/network/administrator/internet/ftp/install/ -http://bsdweb.pasta.cs.uit.no/bsdweb.cgi/xsrc/xc/lib/Xt/PassivGrab.c?sortby=author -http://bsdweb.pasta.cs.uit.no/bsdweb.cgi/xsrc/xc/lib/Xt/ConstrainP.h?sortby=author -http://www.jamba.de/KNet/_KNet-EAA8j1-vFd-13b95/browse.de/node.0/cdel3j591 -http://vvv.geocities.co.jp/SiliconValley-SanJose/5688/sn-3.html -http://vvv.geocities.co.jp/SiliconValley-SanJose/5688/n.html -http://www.amel.net/english/computer/games/b/X0006_Backstab__.html -http://www.amel.net/english/computer/games/b/X0059_Bumper_Ships_1.1.html -http://retailer.gocollect.com/do/session/1912693/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/sports/index.asp -http://www.hig.se/(apre,formoutput,modified,set,set_cookie)/~jackson/roxen/ -http://yp.gates96.com/3/73/80/18.html -http://yp.gates96.com/3/73/81/27.html -http://yp.gates96.com/3/73/81/48.html -http://yp.gates96.com/3/73/81/58.html -http://yp.gates96.com/3/73/82/38.html -http://yp.gates96.com/3/73/83/30.html -http://yp.gates96.com/3/73/83/43.html -http://yp.gates96.com/3/73/83/49.html -http://yp.gates96.com/3/73/83/52.html -http://yp.gates96.com/3/73/84/33.html -http://yp.gates96.com/3/73/84/75.html -http://yp.gates96.com/3/73/85/2.html -http://yp.gates96.com/3/73/85/44.html -http://yp.gates96.com/3/73/85/70.html -http://yp.gates96.com/3/73/86/37.html -http://yp.gates96.com/3/73/86/59.html -http://yp.gates96.com/3/73/87/97.html -http://yp.gates96.com/3/73/87/99.html -http://yp.gates96.com/3/73/88/58.html -http://yp.gates96.com/3/73/88/63.html -http://yp.gates96.com/3/73/88/97.html -http://yp.gates96.com/3/73/89/31.html -http://yp.gates96.com/3/73/89/40.html -http://deseretbook.com/products/4108132/stock-38.html -http://workingfamilies.digitalcity.com/madison/search/ -http://debian.linux.org.tw/debian/dists/Debian2.2r0/main/disks-sparc/current/?D=A -http://debian.linux.org.tw/debian/dists/Debian2.2r0/main/disks-sparc/current/base-contents.txt -http://www.wizardsoftheweb.com/news/183.shtml -http://mathematics.fiz-karlsruhe.de/stn/whyonline/why_0367.html -http://www.nrk.no/finnmark/x27_11_98/nyh3.htm -http://rex.skyline.net/navigate.cgi?computers,agriculture,nature,agriculture,computers -http://www.secinfo.com/d1ZG7r.78.htm -http://www.secinfo.com/d1ZG7r.74.htm -http://www.freesoftware.com.cn/python.org.cn/doc/essays/ppt/hp-training/tsld051.htm -http://www.nrk.no/finnmark/x28_5_96/nyh1.htm -http://www.areteoutdoors.com/channel/snow/downhilling/b.354.g.2944.html -http://www.areteoutdoors.com/channel/snow/downhilling/b.357.g.2944.html -http://www.mywebmd.net/roundtable_message/662348 -http://lovers-lane.porncity.net/216/ -http://myhome.thrunet.com/~estefe/seng/sen18.htm -http://myhome.thrunet.com/~estefe/seng/sen42.htm -http://myhome.thrunet.com/~estefe/seng/sen52.htm -http://myhome.thrunet.com/~estefe/seng/sen73.htm -http://no.egroups.com/login.cgi?login_target=%2Fmessages%2Fenglish-zone -http://www.uzp.gov.pl/biulety/1998/100/100_1327.html -http://www.uzp.gov.pl/biulety/1998/100/100_1341.html -http://www.uzp.gov.pl/biulety/1998/100/100_1372.html -http://www.uzp.gov.pl/biulety/1998/100/100_1377.html -http://www.uzp.gov.pl/biulety/1998/100/100_1428.html -http://www.hotelboulevard.com/fr/riviera/standard/html40f8403856d2fa84c9080a860b7608ba/sessionLang/ANG/prov/browse/lstLieu[0]/Saint-Tropez/resultatSearch.html -http://polygraph.ircache.net:8181/http_-2www.microsoft.com/frontpage/speeches/Pages/funds/portfolio.html -http://www9.hmv.co.uk:5555/do/session/1347778/vsid/199/tid/199/cid/1061396/mid/1020/rid/1052/chid/1029/parser/yes/imref/eqqLmwlGltt5tkeHjskKZlkKrhlK/url/http://www.hmv.co.uk/hmv/departments/d40_sd0_pt0.html -http://edc.uni-augsburg.de/doc/susehilf/pak/paket_doinst_insure.html -http://www.schlagerplatten.de/NewmanJimmyC/B000009PXU.htm -http://cn.egroups.com/message/pro92/604 -http://wwws.br-online.de/geld/boerse/980107/190001.html -http://faqs.bilkent.edu.tr/faqs/sgi/faq/performer/section-3.html -http://faqs.bilkent.edu.tr/faqs/sgi/faq/performer/section-46.html -http://faqs.bilkent.edu.tr/faqs/sgi/faq/performer/section-105.html -http://faqs.bilkent.edu.tr/faqs/sgi/faq/performer/section-111.html -http://newsone.net/nnr/prep/maus.soziales.recht -http://www.mapion.co.jp/custom/tv/admi/14/14131/yako/3chome/1/ -http://info.verwaltung.uni-freiburg.de/doc/packages/qt/html/qpicture-members.html -http://www.allkorea.co.jp/cgi-bin/allkorea.front/972959870915/ContentView/1000091/1/1200207 -http://tour.stanford.edu/cgi/locate2.prl/135.5/jltA -http://mapquest.digitalcity.com/daytonarea/salaries/main.dci?page=admin -http://linuxberg.zeelandnet.nl/x11html/adnload/9146_6809.html -http://medwebplus.com/subject/Alternative%20and%20Complementary%20Medicine/Population/Lists%20of%20Internet%20Resources?^ftc=240&^cc=ftc -http://ftp.du.se/disk0/slackware/slackware-current/contrib/ham/login/package_descriptions -http://yp.gates96.com/12/56/70/0.html -http://yp.gates96.com/12/56/70/14.html -http://yp.gates96.com/12/56/70/62.html -http://yp.gates96.com/12/56/71/19.html -http://yp.gates96.com/12/56/71/38.html -http://yp.gates96.com/12/56/71/46.html -http://yp.gates96.com/12/56/72/49.html -http://yp.gates96.com/12/56/72/78.html -http://yp.gates96.com/12/56/72/91.html -http://yp.gates96.com/12/56/73/18.html -http://yp.gates96.com/12/56/73/52.html -http://yp.gates96.com/12/56/74/15.html -http://yp.gates96.com/12/56/74/54.html -http://yp.gates96.com/12/56/74/79.html -http://yp.gates96.com/12/56/75/28.html -http://yp.gates96.com/12/56/75/68.html -http://yp.gates96.com/12/56/75/71.html -http://yp.gates96.com/12/56/75/76.html -http://yp.gates96.com/12/56/75/88.html -http://yp.gates96.com/12/56/75/94.html -http://yp.gates96.com/12/56/76/27.html -http://yp.gates96.com/12/56/76/57.html -http://yp.gates96.com/12/56/76/73.html -http://yp.gates96.com/12/56/77/60.html -http://yp.gates96.com/12/56/78/3.html -http://yp.gates96.com/12/56/78/45.html -http://yp.gates96.com/12/56/78/64.html -http://yp.gates96.com/12/56/78/86.html -http://yp.gates96.com/12/56/78/91.html -http://yp.gates96.com/12/56/78/95.html -http://yp.gates96.com/12/56/79/39.html -http://yp.gates96.com/12/56/79/75.html -http://www.alldata.com/TSB/19/831915CS.html -http://polygraph.ircache.net:8181/iisadmin/libraries/http_-2www.travelsc.com/welcome_v3/form1.html -http://majordomo.cgu.edu/cgi-bin/lwgate/NEMAI/archives/nemai.archive.0003/Date/article-9.html -http://home.tiscalinet.be/fysinet/studententips/tipsVanStudentenNicolas/sld007.htm -http://www4.netease.com/~abac/writting/zpnr/xw.htm -http://64.209.212.162/learnlots/step/0,2891,47+75+26299+10981_5,00.html -http://www.adcentral.com/cgi-bin/w3com/pws/adsites/KLhIZjY9X9xD5moK2JGI9yyxCV4tsONpzxjYyzP1Uq5ZFTlQAg3Wd-d9dlZbdFK8g3p8_O5GT8q_tKPHmrHXekF-PEpGmxPO69EhQYYR0fwhi_k2GqJa7eAy8n4PQUv0fLw2IIBwNP_qQkQpWEvx666v -http://www.nrc.nl/W2/Nieuws/1998/08/01/ -http://online.excite.de/unterhaltung/katalog/38320 -http://202.167.121.158/ebooks/jetro/tra1-1-1.html -http://ftp.uni-paderborn.de/aminet/aminet/demo/tp94/Blur.readme -http://www.symatrixinc.com/website/website.nsf/0/3e40df86fb357cd5882568720079613f!OpenDocument&ExpandSection=11,14,12,26 -http://www.intellicast.com/Ski/World/UnitedStates/Northeast/NewYork/WingedFootGCWest/WindChill/d1_12/ -http://yp.gates96.com/10/17/80/25.html -http://yp.gates96.com/10/17/80/66.html -http://yp.gates96.com/10/17/80/92.html -http://yp.gates96.com/10/17/82/56.html -http://yp.gates96.com/10/17/82/80.html -http://yp.gates96.com/10/17/83/48.html -http://yp.gates96.com/10/17/83/71.html -http://yp.gates96.com/10/17/83/85.html -http://yp.gates96.com/10/17/84/9.html -http://yp.gates96.com/10/17/84/20.html -http://yp.gates96.com/10/17/84/56.html -http://yp.gates96.com/10/17/84/63.html -http://yp.gates96.com/10/17/85/88.html -http://yp.gates96.com/10/17/86/4.html -http://yp.gates96.com/10/17/86/43.html -http://yp.gates96.com/10/17/86/45.html -http://yp.gates96.com/10/17/86/89.html -http://yp.gates96.com/10/17/86/97.html -http://yp.gates96.com/10/17/87/2.html -http://yp.gates96.com/10/17/87/46.html -http://yp.gates96.com/10/17/88/0.html -http://yp.gates96.com/10/17/89/21.html -http://yp.gates96.com/10/17/89/83.html -http://smb.slac.stanford.edu/cgi-bin/nph-proxy.cgi/000/http/www.w3.org/International/O-URL-and-ident -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=(9,6)+21,0+3,0 -http://polygraph.ircache.net:8181/http_-2www.hystuff.com/nrc.htm -http://jproxy.uol.es/jproxy/http://www.ocregister.com/beaches/capistrano -http://www1.zdnet.com/companyfinder/filters/products/0,9996,38071-58,00.html -http://www.ftp.uni-erlangen.de/pub/mirrors/_other/afterstep.foo.net/AfterStep/binaries/?M=A -http://www.genome.wustl.edu:8021/gsc10/mouse/up/?D=A -http://www.genome.wustl.edu:8021/gsc10/mouse/up/up24/ -http://rotten-tomatoes.com/movies/browse/1074473/reviews.php?view=reviews.source -http://www.virtual-impact-mktg.com/fx110001.htm -http://genforum.genealogy.com/hagen/messages/164.html -http://genforum.genealogy.com/hagen/messages/111.html -http://genforum.genealogy.com/hagen/messages/7.html -http://genforum.genealogy.com/hagen/messages/271.html -http://genforum.genealogy.com/hagen/messages/40.html -http://nt.mortgage101.com/partner-scripts/1024.asp?p=cashsolutions -http://nt.mortgage101.com/partner-scripts/1026.asp?p=cashsolutions -http://library.cuhk.edu.hk/search*chi/t龿ƒ…三地+%26%2359%3B+[3]/t%7B21632b%7D%7B213e5b%7D%7B213024%7D%7B213779%7D++++3/-5,-1,0,B/browse -http://ftp.net.uni-c.dk/pub/linux/redhat/redhat-6.2/sparc/misc/src/anaconda/isys/?S=A -http://ftp.net.uni-c.dk/pub/linux/redhat/redhat-6.2/sparc/misc/src/anaconda/isys/modutils/ -http://cobrand.altrec.com/shop/detail/8273/30 -http://pegasus.infor.kanazawa-it.ac.jp/~hatlab/kaga/docs/jdk1.3-beta_api/jdk1.3/docs/api/java/lang/class-use/ClassFormatError.html -http://bci.tucows.com/winnt/adnload/58788_28761.html -http://www.buybuddy.com/sleuth/33/1/1020503/300/ -http://203.116.23.91/computer/pages2/it120800e.html -http://203.116.23.91/special/newspapers/2000/pages4/computer030700.html -http://203.116.23.91/computer/pages1/software131197.html -http://dic.empas.com/show.tsp/?q=anarchically&f=B -http://noodle.tigris.org/source/browse/subversion/subversion/libsvn_vcdiff/tests/target0.txt -http://www.dbservicestore.de/home/db_reise_touristik/angebote/db_rt_gat_muenster.shtml -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=2&discrim=16,237,275 -http://www.narodnaobroda.sk/20000926/06_006.html -http://mandijin.chinamarket.com.cn/C/Showdetail_company/22591.html -http://202.167.121.158/ebooks/jetro/t6.html -http://a228.g.akamai.net/7/228/289/dd50406be5fc91/news.indiainfo.com/2000/08/17/world-index.html -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=disaminerei&l=it -http://polygraph.ircache.net:8181/http_-2www.eastnebr.net/html/conversions.htm -http://www.secinfo.com/d2wVq.7ar.htm -http://www.secinfo.com/d2wVq.7B5.htm -http://www.secinfo.com/d2wVq.6cd.htm -http://www.secinfo.com/d2wVq.59x.htm -http://www.jamba.de/KNet/_KNet-xdz8j1-mFd-13b2b/browse.de/node.0/cenv0b09a -http://213.36.119.69/do/session/152991/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/FR/jeux/jeux_himalaya.html -http://www.dailyexcelsior.com/99sep30/edit.htm -http://www.dailyexcelsior.com/99sep30/sports.htm -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/misc/misc/music/lit/quizz/computers/netwars.html -http://cometweb01.comet.co.uk/do!session=132020&vsid=700&tid=20&cid=37030&mid=1000&rid=1060&chid=1713&url=eqqLmwlGltt5tkjHfZoLlplLcqkKZljLlfb5lal5tkiLlXaLl0 -http://www.affiliate.hpstore.hp.co.uk/do/session/380832/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/search.asp -http://208.216.182.15/exec/obidos/ASIN/0516206443/qid=972959559/sr=1-22/ -http://fi.egroups.com/messages/alau/2350 -http://ads.puntopartenza.com/cgi-bin/redirect.cgi/31033631 -http://pds.nchu.edu.tw/cpatch/ftp/ftpctrl/?N=D -http://www.brio.de/BRIO.catalog/39fe2f5606def942273fd472aa7806e2/UserTemplate/5 -http://ep.com/js/mi/c7246/b0/832275.html -http://ep.com/js/mi/c7246/b0/837505.html -http://ep.com/js/mi/c7246/b0/764046.html -http://www.fogdog.com/cedroID/ssd3040183223072/nav/products/nhl/pittsburgh_penguins/fan/gender/autographed_pucks/ -http://netway.pda.tucows.com/palm/preview/33567.html -http://netway.pda.tucows.com/palm/preview/34007.html -http://cometweb01.comet.co.uk/do!session=132006&vsid=700&tid=20&cid=37030&mid=1000&rid=1060&chid=1713&url=eqqLmwlGltt5tkjHfZoLlplLcqkKZljLlfb5lal5tkiLlXaLl0 -http://www.udn.com.tw/ARCHIVE/2000/08/04/DOMESTIC/YUNLIN/587058.htm -http://www.linux.com/networking/network/support/web/news/services/ -http://www.linux.com/networking/network/support/web/news/website/ -http://www.linux.com/networking/network/support/web/news/business/ -http://ads.carltononline.com/accipiter/adclick/site=purejamba/area=jamba.home_page/AAMSZ=IAB_FULL_BANNER//ACC_RANDOM=972959548213 -http://www-x500-1.uni-giessen.de:8890/Lcn%3dConsuelo%20Alvarez,ou%3dDpto.%20Fisiologia%20y%20Biologia%20Animal,o%3dUniversidad%20de%20Sevilla,c%3dES -http://www.chaos.dk/sexriddle/b/q/v/y/n/ -http://www.cs.kuleuven.ac.be/~java/docs/tutorial/uiswing/converting/example-1dot1/ListDemo.html -http://golfonline.comfluent.net/cgi.pan$player&lpga82&Debbie_Raso&lpga?golfstats -http://acetoys.com/cgi-bin/exec/modify_cart_button=1&cart_id=1999923.7130.303&page=/tystore/htmlfiles/eden/dw.html -http://www.bigchurch.com/cgi-bin/w3com/pws/bc/y1hIyNzn0Bl2XX5GzG9wVnUEhWD8GTd-XbpDm6aNI4ZMGTnV_YsP2OjB0RrwLpDbJub1pKlzEMrInSQi9hRM-Rz4WNq8C1vKJ9STiU9leUD_a3PBVh-7OMZDzJtyEBAXTehiRqme6jBR -http://www.bigchurch.com/cgi-bin/w3com/pws/bc/mChIR_iy1798J8x9InaTkzOfisuwH2hv2KUj0e64IQ9CeS327muTnTo70bT5YC4YznUddEOY5WdX70keIPRlsQibJtG6uzZtaaPmL58O5zJ0z_2PkJNxmBS5dj5-gWoeBgE0zaSvCbi66Grq -http://wap.jamba.de/KNet/_KNet-8qB8j1-FFd-13blo/browse.de/node.0/cde7f2elw -http://collection.nlc-bnc.ca/100/201/300/info_tabac/html/1997/bull7/fdacarol.html -http://pub17.ezboard.com/fzhaostempleofenlightenmentzhaosforum.showMessage?topicID=116.topic -http://www.home.ch/~spaw4360/HOWTO_fr/Ethernet-HOWTO-5.html -http://www.chaos.dk/sexriddle/s/g/n/y/j/ -http://polygraph.ircache.net:8181/http_-2www.horizonfinance.com/https_-2www.truste.org/validate/page3.html -http://marketbiz.subportal.com/sn/Themes/Sports_Themes/288.html -http://www.chinaccm.com/04/news/200004/20/120305.asp -http://www.american.webtourist.net/travel/northamerica/usa/lagunabeach/bwlagunareefinn.htm -http://elib.zib.de/pub/visual/avs/mirror/imperial/new/?S=A -http://www.burstnet.com/ads/ad7826a-map.cgi/969206790 -http://yp.gates96.com/14/82/10/81.html -http://yp.gates96.com/14/82/12/82.html -http://yp.gates96.com/14/82/13/55.html -http://yp.gates96.com/14/82/14/27.html -http://yp.gates96.com/14/82/14/31.html -http://yp.gates96.com/14/82/15/52.html -http://yp.gates96.com/14/82/17/16.html -http://yp.gates96.com/14/82/17/93.html -http://www.outpersonals.com/cgi-bin/w3com/pws/out/P2hI5ODQEZ1-vIl-agOzeOeNg4wShDlZrsCbdT5YZ3TrprEU4rb4NnnDXiGmf5cX3dh8ltMer04TMDd3q-cE5Mne85eH57ltxsi4ZQfER6vkktoaaYlS9JFTzylmCJZ2_PAT9uu2oWvIjgMzt9toyeuV -http://www.mirror.ac.uk/sites/ftp.microsoft.com/deskapps/powerpt/KB/Q226/7/ -http://mirror.nucba.ac.jp/mirror/Perl/authors/id/MIKEKING/?M=A -http://lists.insecure.org/linux-kernel/2000/Jun/4357.html -http://www.nlc-bnc.ca/indexmus-bin/resultsum/m=0/e=0/h=25/p=1/f=AU/t=Siroir,+Maryse+Angrignon -http://genforum.genealogy.com/cgi-bin/print.cgi?leavy::19.html -http://www.egroups.com/message/malaysiakini/219 -http://wuarchive.wustl.edu/graphics/mirrors/ftp.povray.org/.3/netlib/ode/rksuite/?S=A -http://www.earthsystems.org/list/greenyes/jan2000/1999-2/0858.html -http://pp3.shef.ac.uk:4040/search=browse/dn=countryName%3DGB%40organizationName%3DUniversity+of+Sheffield%40organizationalUnitName%3DAutomatic+Control+and+Systems+Engineering%40commonName%3DI+D+Durkacz -http://cobrand.altrec.com/shop/detail/6133/15/sizing -http://cobrand.altrec.com/shop/detail/5624/17/write -http://members.theglobe.com/inwardpath/history.htm -http://findmail.com/post/studentdoctor?act=reply&messageNum=5168 -http://www.service911.com/everythingtele/step/0,2675,3+26057+24201+16394_0,00.html -http://www.linux.com/networking/network/free/release/development/mysql/ -http://www.nbip.com.cn/books/xdwx/Hongyan/hongyan14.html -http://ftp.jp.debian.org/debian-non-US/dists/sid/non-US/non-free/binary-hurd-i386/?N=D -http://homepage.swissonline.ch/chico_logo/www.Link008 -http://homepage.swissonline.ch/chico_logo/www.Link009 -http://citeseer.nj.nec.com/cidcontext/3719857 -http://itcareers.careercast.com/texis/it/itjs/+CwwBme3AT+6e-xwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewXnmoBGnamwBwxw5naBnqrDdcdtOaOnwGaMdDBramwOaqmwBwamn5otDamnVncdpoDtanDtoDnnGoDtaMFqhTfR20DzmebmwwwpBme3AT+6ekxwww5rmeXdwwwBrmeZpwww/jobpage.html -http://www.amazon.com.hk/exec/obidos/tg/stores/detail/-/pro-tools/B0000224UB/customer-reviews/ref=th_hp_rs_2_6/ -http://www.ard-buffet.de/buffet/teledoktor/1998/02/16/ -http://pub19.ezboard.com/fmissionimplausiblewhatpeoplearesaying.emailToFriend?topicID=41.topic -http://no.egroups.com/message/NikonCoolPix/211 -http://www.gasex.com/free.gay.sex/gay.men.dick.dicks.html -http://www.centc251.org/forums/aca-1/dispatch.cgi/hsi/showFolder/100001/1255931 -http://www.uni-duesseldorf.de/ftp/ftp/pf/s/yagirc-0.65.6/?N=D -http://www.outpersonals.com/cgi-bin/w3com/pws/out/uIhI1DhpdvAdxVFONIJuaNcvtSTejSMmZIBgOwsZamHFS4JpS3i6VWNOSb8LsLcmqmG0gp2hs1YjuScHwXmociV5L_3_fCYngafHC4CIYDuKoI-rOZldw1RU5K3jOfh5d3PxatRmmHqB662F -http://www.kfi640.com/shared/mod_perl/looksmart/looksmart/elax176954/eus53832/eus155852/eus53907/eus62316/ -http://www.magictraders.com/cgi-bin/ubb/ubbmisc.cgi?action=getbio&UserName=Ammo187 -http://fi.egroups.com/login.cgi?login_target=%2Fgroup%2Fweirdchicks -http://www.accesslasvegas.com/shared/health/adam/ency/article/000589.images.html -http://pp3.shef.ac.uk:4040/search=browse/dn=countryName%3DGB%40organizationName%3DAberdeen+University%40organizationalUnitName%3DGeneral+Practice%40commonName%3DMorrison+S -http://worldres.lycos.com/script/gen_amen.asp?hotel_id=2252&n=2089 -http://tulips.ntu.edu.tw/search*chi/dSymbolism+in+fairy+tales/dsymbolism+in+fairy+tales/-5,-1,0,B/browse -http://ftp.du.se/disk4/FreeBSD/branches/4.0-stable/ports/x11-clocks/pclock/ -http://ftp.du.se/disk4/FreeBSD/branches/4.0-stable/ports/x11-clocks/xtimer/ -http://polygraph.ircache.net:8181/cgi-win/lincoln/$cgi4wpro.exe/http_-2www.k56.com/http_-2www.webexplorer.net/c/SHLFFREZ.HTM -http://www.ecs.soton.ac.uk/~seg7/private/contact.html -http://wiem.onet.pl/wiem/00de68-s.html -http://lcweb2.loc.gov/ll/llnt/008/?M=A -http://www.alladvantage.com/pressroom.asp?refid=CBI-463 -http://herndon1.sdrdc.com/cgi-bin/ind_detail/FERRELL|PORTER|FORT+WORTH|TX|76107|SINGLE+SERVER+COMMUNICATIONS/ -http://herndon1.sdrdc.com/cgi-bin/ind_detail/HARRIS|WILLIAM|FAIRFAX|VA|22031|HARRIS+AND+ASSOCIATES/ -http://herndon1.sdrdc.com/cgi-bin/ind_detail/HUTCHER|LARRY|NEW+YORK|NY|10023|DAVIDOFF+AND+MALITO/ -http://herndon1.sdrdc.com/cgi-bin/ind_detail/ISIKOFF|NATHAN+R|WASHINGTON|DC|20007|CAREY-WINSTON+CO/ -http://www.linux.com/networking/network/communications/security/wireless/protocol/ -http://www.linux.com/networking/network/communications/security/wireless/technology/ -http://retailer.gocollect.com/do/session/1912719/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/company_info/about.asp -http://retailer.gocollect.com/do/session/1912719/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/exclusives/limited_editions.asp -http://retailer.gocollect.com/do/session/1912719/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/clubhouse/suggestions.asp -http://www9.hmv.co.uk:5555/do/session/1347779/vsid/199/tid/199/cid/1061396/mid/1020/rid/1052/chid/1029/parser/yes/imref/eqqLmwlGltt5tkeHjskKZlkKrhlK/url/http://www.hmv.co.uk/hmv/hiddenframe.html -http://pub9.ezboard.com/fwestlifedublinmessageboardwestlifemessageboard.showMessage?topicID=8.topic -http://no.egroups.com/subscribe/hardzero -http://link.fastpartner.com/do/session/600378/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/index.php -http://link.fastpartner.com/do/session/600378/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/gosafe.php -http://link.fastpartner.com/do/session/600378/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/bitconomy.php -http://www.hello.co.jp/~daichi2/ -http://bbs.nsysu.edu.tw/txtVersion/treasure/ChiaYi/M.937783175.A/M.959916136.M.html -http://chat.hani.co.kr/NetBBS/Bbs.dll/chosun21/lst/qqeq/1/zka/B2-kB2Bp/qqo/PRMY -http://www.gartenfachmarkt.de/haus/schleifen/so.htm -http://links2go.publiweb.com/topic/US_Department_of_Agriculture -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=14,15,6,36,22 -http://www.linux.com/networking/network/new/hardware/open_source/operating_system/ -http://www.linux.com/networking/network/new/hardware/open_source/availability/ -http://tokyo.cool.ne.jp/pure0101/Oblivion_dust.html -http://www.digitaldrucke.de/(aktuell,computer,gaestebuch,hilfe,hilfeallgemein,individualverkehr,kultur,onlineservice,peripherie,sense,veranstaltungen,verkehr)/_fort/html/themen/computer/hard/links/mitsu.htm -http://www.gbnf.com/genealogy/jenkins/html/d0097/I4129.HTM -http://www.geocities.co.jp/Outdoors-River/1625/hakuba0502.htm -http://ftp.fi.debian.org/OpenBSD/src/regress/share/man/ -http://www3.buch-per-sms.de/angemeldet.jsp$ID=To7767mC050667397857644736At0.8818825373175998 -http://www2.kbank.no/Web/nlpublish.nsf/Published/ord_og_uttrykk!OpenDocument&ExpandSection=15,25,16,27 -http://debian.tod.net/debian/dists/sid/main/binary-sparc/electronics/?D=A -http://hs1.takeoff.ne.jp/~hatuse/ -http://polygraph.ircache.net:8181/Keyboards/http_-2www.sky.net/~robertf/handson/engine.html -http://www.gbnf.com/genealogy/jenkins/html/d0005/I3818.HTM -http://sepwww.stanford.edu/oldreports/sep67/old_src/jon/extend/junk.listing -http://www.kol.net/~calldj/cyberstar/map/dw25a.htm -http://citeseer.nj.nec.com/cidcontext/1297195 -http://citeseer.nj.nec.com/cidcontext/1297207 -http://books.hyperlink.co.uk/xt2/Peace_Verses_War/Cole/Derek/0722329539 -http://www.spousehouse.com/ -http://futures.homeway.com.cn/lbi-html/news/special/zhzt/jdht/twparty/zhengfu94652.shtml -http://www.yorosiku.net:8080/-_-http://www.zdnet.co.jp/zdii/interviews/interviews.html -http://library.cwu.edu/search/aIdaho+State+University/aidaho+state+university/-5,-1,0,E/frameset&F=aidaho+state+university&2,,0 -http://pelit.saunalahti.fi/.1/tucows/preview/68721.html -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=34,20,30,36,32 -http://pike-community.org/(base=/forums/show.html,forum=7,show=146,t=972959487953431)/forums/show.html -http://pike-community.org/(base=/forums/show.html,forum=7,show=185,t=972959487953431)/forums/show.html -http://pike-community.org/(base=/forums/show.html,explode=763,forum=7,t=972959487953431)/forums/show.html -http://pike-community.org/(base=/forums/show.html,forum=7,show=870,t=972959487953431)/forums/show.html -http://pike-community.org/(base=/forums/show.html,forum=7,show=890,t=972959487953431)/forums/show.html -http://ww2.comune.fe.it/cgi-win/hiweb.exe/a2/d3/b34,8,1,,1f,1,65,,1f,65, -http://www.telematik.informatik.uni-karlsruhe.de/osf/sw/v4.0x/lp2/bst320/kit/ -http://cafe3.daum.net/Cafe-bin/Bbs.cgi/harukypds/rnw/zka/B2-kB2Zq -http://www.digitaldrucke.de/(computer,hilfe)/_fort/html/themen/computer/hard/links/escom.htm -http://www2.ipc.pku.edu.cn/scop/pdb.cgi?sid=d6stdb_ -http://www2.ipc.pku.edu.cn/scop/pdb.cgi?sid=d4stdc_ -http://www.shopworks.com/index.cfm/action/specials/userid/00029735-2E1C-19FE-AF65010C0A0A8CF2 -http://www.shopworks.com/index.cfm/action/search/userid/00029735-2E1C-19FE-AF65010C0A0A8CF2 -http://www.helpnow.net.cn/helpnow/hardware/bbs/cpu/?D=A -http://books.hyperlink.co.uk/xt1/Light_My_Fire/Manzarek/Ray/0099280655 -http://bsd.sinica.edu.tw/cgi-bin/cvsweb.cgi/src/crypto/heimdal/appl/ftp/ftp/?sortby=author -http://tucows.interbaun.com/winme/adnload/5147_28523.html -http://tucows.interbaun.com/winme/adnload/137019_28530.html -http://moviestore.zap2it.com/browse/MOVIES/COLLECTI/s.NedNjpDf -http://moviestore.zap2it.com/browse/MOVIES/STRAW/s.NedNjpDf -http://www.online.kokusai.co.jp/Words/V0043505/wrd/G700/words/kana_main.html -http://www.mirror.edu.cn/res/sunsite/pub/X11/contrib/window_managers/gwm/patches/gwm_patch_1.8a_001 -http://www.musicblvd.com/cgi-bin/tw/270242907922133_20_hip -http://www.cowo.de/archiv/1991/21/9121c045.html -http://www.russ.ru:8080/netcult/nevod/19990827-pr.html -http://usol.linux.tucows.com/x11html/preview/26680.html -http://usol.linux.tucows.com/x11html/preview/10385.html -http://yp.gates96.com/7/22/20/54.html -http://yp.gates96.com/7/22/20/67.html -http://yp.gates96.com/7/22/20/71.html -http://yp.gates96.com/7/22/22/26.html -http://yp.gates96.com/7/22/22/55.html -http://yp.gates96.com/7/22/22/74.html -http://yp.gates96.com/7/22/22/94.html -http://yp.gates96.com/7/22/23/38.html -http://yp.gates96.com/7/22/23/59.html -http://yp.gates96.com/7/22/24/43.html -http://yp.gates96.com/7/22/24/60.html -http://yp.gates96.com/7/22/24/64.html -http://yp.gates96.com/7/22/24/66.html -http://yp.gates96.com/7/22/24/72.html -http://yp.gates96.com/7/22/24/85.html -http://yp.gates96.com/7/22/26/11.html -http://yp.gates96.com/7/22/26/69.html -http://yp.gates96.com/7/22/27/3.html -http://yp.gates96.com/7/22/27/11.html -http://yp.gates96.com/7/22/27/22.html -http://yp.gates96.com/7/22/27/48.html -http://yp.gates96.com/7/22/27/69.html -http://yp.gates96.com/7/22/28/13.html -http://yp.gates96.com/7/22/28/30.html -http://yp.gates96.com/7/22/29/39.html -http://yp.gates96.com/7/22/29/58.html -http://www.allgemeine-immobilien-boerse.de/frankfurt/verkauf/Gemeinsam/Super-Zins-Konditionen/Private-IB/Startseite/IIM-Teil/Startseite/Gemeinsam/Super-Zins-Konditionen/anforderungsformular.htm -http://cobrand.altrec.com/shop/detail/8470/9/description -http://oa-nett.no/0/73/90/2.html -http://www.nordi.no/~steinsk/ -http://www02.geocities.co.jp/Stylish/6692/ -http://no.egroups.com/login.cgi?login_target=%2Fmessages%2Fsan-diego-tango -http://no.egroups.com/message/san-diego-tango/390 -http://www.jamba.de/KNet/_KNet-m_C8j1-PFd-13bt7/showInfo-special1.de/node.0/cenv0b09a -http://www.bemi-immobilien.de/Ferien-IB/Startseite/Gemeinsam/immolink/Startseite/www.ferien-immobilien.de/ferien-ib/startseite/Startseite/Gemeinsam/versicherungen/gebaeude/Startseite/froben.htm -http://it.egroups.com/post/pimnews-homeworker?act=reply&messageNum=661 -http://members.es.tripod.de/remoto/t2/p3b.htm -http://no.egroups.com/post/Translat2000?act=reply&messageNum=530 -http://www.opengroup.com/pabooks/081/0816631352.shtml -http://www6.freeweb.ne.jp/feminine/ki18/portrait10/p21.htm -http://genforum.genealogy.com/cgi-genforum/forums/cantrell.cgi?2117 -http://www9.hmv.co.uk:5555/do/session/1347769/vsid/199/tid/199/cid/1061396/mid/1020/rid/1052/chid/1029/parser/yes/imref/eqqLmwlGltt5tkeHjskKZlkKrhlK/url/http://www.hmv.co.uk/hmv/departments/d30_sd0_pt0.html -http://polygraph.ircache.net:8181/docs/Win95/MSdialer/http_-2www.fastcounter.com/http_-2www.perrypip.com/http_-2www.scruz.net/~dvb/cam.html -http://polygraph.ircache.net:8181/docs/Win95/MSdialer/http_-2www.fastcounter.com/http_-2www.perrypip.com/~logan/ -http://polygraph.ircache.net:8181/docs/Win95/MSdialer/http_-2www.fastcounter.com/http_-2www.perrypip.com/http_-2hits.omino.com/ -http://javatest.a-net.nl/servlet/pedit.Main/http://epidem13.plantsci.cam.ac.uk/~js/glossary/course-glossary.html -http://www.hellefors.se/ulf/akno/alla/p0349c5e1e.html -http://home.no.net/islamnor/had.sira.html -http://www.gutenberg2000.de/immerman/muenchim/muen1171.htm -http://www.gutenberg2000.de/immerman/muenchim/muen3091.htm -http://www.gutenberg2000.de/immerman/muenchim/muen7011.htm -http://www.sikhnet.com/sikhnet/music.nsf/by%20Shabad!OpenView&Start=30&Count=20&Expand=2 -http://www.proteome.com/databases/PombePD/reports/SPCC613.01.html -http://www.midwestvanlines.com/oh/indexC.html -http://ring.tains.tohoku.ac.jp/pub/linux/debian/debian-jp/dists/stable/contrib/binary-arm/electronics/?S=A -http://members.tripod.com/~infolog/Genhouses/Chap12.htm -http://www.4positiveimages.com/4positiveimages/1998693855/UserTemplate/2 -http://www.greenleaves.com/bookcat/gb_096855900X.html -http://www-rn.informatik.uni-bremen.de/home/X11R6/xc/doc/hardcopy/test/?M=A -http://rex.skyline.net/html/Shipping_of_Goods.html?48,airplanes,transportation,collectibles,transportation -http://rex.skyline.net/html/Automobile_Classified_Listings.html?59,airplanes,transportation,collectibles,transportation -http://www.admin.co.martin.fl.us/GOVT/depts/cas/corresp/2000/cas00l.133.html -http://www.admin.co.martin.fl.us/GOVT/depts/cas/corresp/2000/cas00l.126.html -http://www.affiliate.hpstore.hp.co.uk/do/session/380834/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hpstore.hewlett-packard.fr/gp -http://link.fastpartner.com/do/session/600367/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/no/ -http://smb.slac.stanford.edu/cgi-bin/nph-proxy.cgi/000/http/www-library.lbl.gov/photo/gallery/ -http://dogbert.wu-wien.ac.at/UniverCD/cc/td/doc/product/core/cis12012/bfrcfig/4334acps/?M=A -http://ftp.uni-stuttgart.de/pub/tex/nonfree/support/latexdraw/doc/ltdmanual.html.g/node10.html -http://se.egroups.com/message/911dispatchers/718 -http://ftp.eecs.umich.edu/.1/people/jfr/Pinata_Book/?D=A -http://community.bigchalk.com/servlet/schools_ProcServ/DBPAGE=cge&GID=66001000660906746080215398&PG=66001000660906746080492039 -http://www2.kbank.no/Web/nlpublish.nsf/Published/ord_og_uttrykk!OpenDocument&ExpandSection=16,27,29,4 -http://www2.kbank.no/Web/nlpublish.nsf/Published/ord_og_uttrykk!OpenDocument&ExpandSection=22,27,29,4 -http://pds.nchu.edu.tw/cpatch/ftp/dap/cdap_4002.txt -http://pds.nchu.edu.tw/cpatch/ftp/dap/source/ -http://kuyper.calvin.edu/fathers2/ANF-03/anf03-22.htm -http://kuyper.calvin.edu/fathers2/ANF-03/anf03-27.htm -http://blisty.internet.cz/1250/9908/19990813a.html -http://ring.shibaura-it.ac.jp/archives/doc/jpnic/minutes/committee/200008/shiryou-2-8-2.txt -http://194.128.65.4/pa/cm199697/cmhansrd/vo970306/text/70306w14.htm -http://www.mortgagemag.com/guide/c096/c096573.htm -http://link.fastpartner.com/do/session/600369/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/mondosoft.php -http://link.fastpartner.com/do/session/600369/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/gosafe.php -http://cometweb01.comet.co.uk/do!session=132008&vsid=692&tid=20&cid=37051&mid=1000&rid=1060&chid=1702&url=eqqLmwlGltt5tkjHfZoLlplLcqkKZljLlfb5lal5tkiLlXaLl0 -http://www.vh.org///////Patients/IHB/FamilyPractice/AFP/November1994/HormoneReplacement.html -http://ftp.sunet.se/pub/unix/OpenBSD/distfiles/md5/74892a6ae002937d011d3e1102269b7f/?M=A -http://www.pcdads.com/pressroom/archive/releases/cn112999.htm -http://www.pcdads.com/pressroom/archive/releases/Fe90199a.htm -http://www.pcdads.com/pressroom/archive/releases/Cn042199.htm -http://www.cheap-cds.com/surf/order/017172 -http://www.hani.co.kr/ECONOMY/data/9909/day09/print/p00909060.html -http://www.bemi-immobilien.de/Startseite/www.allgemeine-immobilien-boerse.de/allgemeine-ib/landkreiszwickau/Verkauf/29109700708107kirchbergvillamü/Gemeinsam/MarketingStrategie/Startseite/Gemeinsam/Inserieren/Gemeinsam/Gemeinsam/versicherungen/unfall/anforderungsformular.htm -http://www.sj-rmall.com/Mall/Catalog/Product/ASP/product-id/57419/store-id/1000400121.html -http://www.travelodge.com/ctg/cgi-bin/Travelodge/home/AAAksrACwAAABvTAAd -http://ctc.org.cn/ctc2/news/internet/develop/news0322-6.htm -http://www.schlagertempel.de/FallbachTrio/B000025MBP.htm -http://www.fogdog.com/cedroID/ssd3040183238127/nav/products/nike/1b/all/10.html -http://www.fogdog.com/cedroID/ssd3040183238127/customer_service/security_policy.html -http://in.egroups.com/login.cgi?login_target=%2Fgroup%2Fradiotutorium -http://yp.gates96.com/7/87/70/43.html -http://yp.gates96.com/7/87/70/61.html -http://yp.gates96.com/7/87/71/85.html -http://yp.gates96.com/7/87/72/75.html -http://yp.gates96.com/7/87/73/1.html -http://yp.gates96.com/7/87/73/5.html -http://yp.gates96.com/7/87/73/60.html -http://yp.gates96.com/7/87/74/34.html -http://yp.gates96.com/7/87/75/9.html -http://yp.gates96.com/7/87/75/50.html -http://yp.gates96.com/7/87/75/92.html -http://yp.gates96.com/7/87/76/2.html -http://yp.gates96.com/7/87/76/59.html -http://yp.gates96.com/7/87/76/92.html -http://yp.gates96.com/7/87/78/30.html -http://yp.gates96.com/7/87/78/32.html -http://yp.gates96.com/7/87/78/75.html -http://yp.gates96.com/7/87/78/85.html -http://yp.gates96.com/7/87/78/93.html -http://yp.gates96.com/7/87/79/30.html -http://yp.gates96.com/7/87/79/50.html -http://yp.gates96.com/7/87/79/71.html -http://yp.gates96.com/7/87/79/85.html -http://interhotel.com/luxembourg/es/hoteles/45691.html -http://interhotel.com/luxembourg/es/hoteles/73094.html -http://bart.kullen.rwth-aachen.de/~quake3/Html_log/471_chat.html -http://search.yam.com.tw/en/search/rec/travel/domest/resorts/miaolir/ -http://www.narodnaobroda.sk/19991009/23_006.html -http://news.china.com/zh_cn/social/1007/20001027/7624.html -http://www.fila.com.br/ -http://www.jobvillage.com/channel/jobs/health_care/female_health/b.3122.g.2360.html -http://online.excite.de/bildung/katalog/35461 -http://deportes.ole.com/ocio/articulo/articulo.cfm?ID=OCI8055 -http://yp.gates96.com/3/36/90/2.html -http://yp.gates96.com/3/36/90/37.html -http://yp.gates96.com/3/36/90/55.html -http://yp.gates96.com/3/36/90/79.html -http://yp.gates96.com/3/36/91/7.html -http://yp.gates96.com/3/36/92/59.html -http://yp.gates96.com/3/36/92/95.html -http://yp.gates96.com/3/36/93/76.html -http://yp.gates96.com/3/36/93/88.html -http://yp.gates96.com/3/36/94/41.html -http://yp.gates96.com/3/36/94/64.html -http://yp.gates96.com/3/36/95/16.html -http://yp.gates96.com/3/36/95/33.html -http://yp.gates96.com/3/36/95/39.html -http://yp.gates96.com/3/36/96/36.html -http://yp.gates96.com/3/36/96/53.html -http://yp.gates96.com/3/36/99/30.html -http://yp.gates96.com/3/36/99/73.html -http://download.sourceforge.net/mirrors/turbolinux/turbolinux-cn/pub/turbolinux/updates/TLC3.0.2/?S=D -http://www.jobvillage.com/channel/jobs/administrative/mrd/courier/b.4728.g.3366.html -http://www.jobvillage.com/channel/jobs/administrative/mrd/shipping_clerk/b.4713.g.3366.html -http://quote.fool.com/simple.asp?symbols=NS -http://itcareers.careercast.com/texis/it/itjs/+NwwBmeIXD86dxwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewXhmoBGnaqdGpdGwBodDaqdMp1BnGadpnGwBodD5aMw55wqr15nBB5aqdGpdGwBnahoDwDqowcaMwocaBn5BoDtapGdxcnMaMFqhTfR20DzmetmwwwpBme_9D86eYmwww5rme1DwwwBrmeZpwww/jobpage.html -http://www.shopworks.com/index.cfm/action/info/userid/00066256-1160-19FE-A703010D0A0A8CF2 -http://isbn.nu/0716723212/fatbrain -http://isbn.nu/0716723212/amazon.ceo.html -http://ftp.nacamar.de/pub/NetBSD/NetBSD-current/pkgsrc/www/p5-URI/?N=D -http://213.36.119.69/do/session/152993/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/FR/preparer/sante.htm -http://213.36.119.69/do/session/152993/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/FR/jeux/jeux_himalaya.html -http://213.36.119.69/do/session/152993/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/DE_DE/ -http://www.linux.com/networking/network/support/open_source/investors/consulting/ -http://www.linux.com/networking/network/support/open_source/investors/research/ -http://sunsite.uakom.sk/doc/FAQ/alt-sex/fetish-fashion/?S=A -http://sunsite.uakom.sk/doc/FAQ/alt-sex/fetish-fashion/?D=A -http://phnet.tucows.com/winme/preview/75994.html -http://www.fivedoves.com/letters/june99/trish67.htm -http://www.teacherformation.org/html/od/facilitators.cfm/task1,about/discussion_id,2/xid,8571/yid,4064381 -http://pub24.ezboard.com/fnightmagicfrm1.showMessage?topicID=3.topic -http://infoserv2.ita.doc.gov/efm/efm.nsf/Sources!OpenView&Start=53.28&Count=30&Expand=54 -http://www.linux.com/networking/network/communications/management/windows_nt/website/ -http://www.linux.com/networking/network/communications/management/windows_nt/?kw_offset=50 -http://www.epinions.com/cmd-review-593A-C9BAC2B-3987B6DC-prod1 -http://www.bande-dessinee.org/bd/bd02.nsf/InterDescenaristes!OpenView&Start=1&Count=50&Collapse=51 -http://www.business-partner.ch/static/fr/pourlesfirmes/lesgrandesentreprises/whateveryouwant/solutionsspecifiquesalabranche/transport/main.html -http://ads.carltononline.com/accipiter/adclick/site=purejamba/area=JAMBA.HOME_PAGE/AAMSZ=KSJAMBA//ACC_RANDOM=972959547161 -http://expert.cc.purdue.edu/~yoko/simpsons/front.html -http://dailynews.sina.com.cn/society/2000-06-14/97332.html -http://ftp.dti.ad.jp/pub/Linux/debian-jp/dists/potato/main/binary-all/editors/?M=A -http://www.babyheirlooms.com/catalog/htmlos.cat/041124.1.5608817466 -http://www9.hmv.co.uk:5555/do/session/1347791/vsid/199/tid/199/cid/1061396/mid/1020/rid/1052/chid/1029/parser/yes/imref/eqqLmwlGltt5tkeHjskKZlkKrhlK/url/http://www.hmv.co.uk/hmv/departments/d100_sd0_pt0.html -http://www.jobvillage.com/channel/jobs/health_care/pharmaceutical/pharmacist/b.3231.g.1267.html -http://yp.gates96.com/11/24/80/12.html -http://yp.gates96.com/11/24/80/18.html -http://yp.gates96.com/11/24/80/84.html -http://yp.gates96.com/11/24/80/90.html -http://yp.gates96.com/11/24/81/6.html -http://yp.gates96.com/11/24/81/9.html -http://yp.gates96.com/11/24/81/54.html -http://yp.gates96.com/11/24/81/74.html -http://yp.gates96.com/11/24/81/98.html -http://yp.gates96.com/11/24/82/17.html -http://yp.gates96.com/11/24/82/96.html -http://yp.gates96.com/11/24/83/54.html -http://yp.gates96.com/11/24/83/58.html -http://yp.gates96.com/11/24/84/44.html -http://yp.gates96.com/11/24/84/52.html -http://yp.gates96.com/11/24/84/63.html -http://yp.gates96.com/11/24/85/35.html -http://yp.gates96.com/11/24/85/77.html -http://yp.gates96.com/11/24/85/78.html -http://yp.gates96.com/11/24/87/15.html -http://yp.gates96.com/11/24/87/77.html -http://yp.gates96.com/11/24/88/0.html -http://yp.gates96.com/11/24/88/63.html -http://yp.gates96.com/11/24/89/93.html -http://www.iabusnet.org:90/forums/aca-1/dispatch.exe/survey/listUnseen/fol/100001/20,0/2498053 -http://www.zeenzone.com/movies/1,4003,1040-21565,00.html -http://www.zeenzone.com/movies/1,4003,1040-99354,00.html -http://www.zeenzone.com/movies/1,4003,1040-109493,00.html -http://forum.rai.it/aca-finestre/dispatch.cgi/FORUM/folderFrame/100001/0/author/627181 -http://moshkow.rsl.ru/alt/MORUA/letters.txt -http://members.tripod.co.jp/muttley2000/?M=A -http://www.shopworks.com/index.cfm/action/specials/userid/000A8C31-2EFD-19FE-9038010B0A0ADCF2 -http://www.bookhome.net/xiandangdai/other1/chunjiang/006.html -http://www.bookhome.net/xiandangdai/other1/chunjiang/013.html -http://www.dailyrush.dk/clans/145 -http://www.berlinonline.de/wissen/berliner_kurier/archiv/2000/0429/auto/0210/ -http://www.berlinonline.de/wissen/berliner_kurier/archiv/2000/0429/brandenburg/0011/ -http://www.berlinonline.de/wissen/berliner_kurier/archiv/2000/0429/lokales/0077/ -http://www.berlinonline.de/wissen/berliner_kurier/archiv/2000/0429/lokales/0009/ -http://www.berlinonline.de/wissen/berliner_kurier/archiv/2000/0429/lokales/0111/ -http://www.berlinonline.de/wissen/berliner_kurier/archiv/2000/0429/lokales/0117/ -http://www.berlinonline.de/wissen/berliner_kurier/archiv/2000/0429/lokales/0014/ -http://www.berlinonline.de/wissen/berliner_kurier/archiv/2000/0429/sport/0018/ -http://www.berlinonline.de/wissen/berliner_kurier/archiv/2000/0429/sport/0158/ -http://www.berlinonline.de/wissen/berliner_kurier/archiv/2000/0429/tv/0209/ -http://www.multicosm.com/facade/www.contigo.com/ -http://www.boston.digitalcity.com/cincinnati/health/conditions.dci?condition=sids -http://www.onlineathens.com/1998/041498/0414.a2zbriefs.html -http://ist.linux.tucows.com/conhtml/adnload/52224_1782.html -http://www.outpersonals.com/cgi-bin/w3com/pws/out/-2hIv4VApV7948YHO6tPdd62dgSdHSwg0xTrLhYidK4__IjhefvQTQrwpTMkkPdR5C5XRGbdA57_pJIxtMRvHJmrtjKdnzn_di6Er9p9vwIk1rLYwssqdvQbgeNAvSgd2M1a7O5NWleCth4ETxMfqPQS -http://www.outpersonals.com/cgi-bin/w3com/pws/out/VwhIXbmwUfG9PK362Tf07_xy8BQY7YBwNspFlCmPD_syQhuUcYEAU2eNoW3Liccn5fOj3JHbx2nCG9Tkl-PZwI9bR0uW5_3bO8O3kRwFm2Sp0E8MBNqJ9FvuLKt4pS_X3qzA8sbHcygn7lFrBe9ZZqi565Rs -http://www.crutchfield.com/cgi-bin/S-5ILchLS19Z9/auto.asp -http://www.quzhou.gov.cn/flfg.nsf/0a043ae26eb50247002564640039f21d/7cdda9dbc7e2b2bb002564ac00393b48!OpenDocument&ExpandSection=1,7,6 -http://opac.lib.ntnu.edu.tw/search*chi/m92+R627/m92+r627/-5,-1,0,B/buttonframe&F=m92+r449m&1,1 -http://www03.u-page.so-net.ne.jp/fc4/kazumasa/tdl/side2/side2.html -http://launchbase.com/Home/Personal_Organization/communication/information/Bank_Rates_&_Info.htm -http://launchbase.com/Home/Personal_Organization/communication/entertainment/Sports.htm -http://launchbase.com/Home/Personal_Organization/communication/shopping/Flowers.htm -http://launchbase.com/Home/Personal_Organization/communication/shopping/Pro-Audio.htm -http://www.nissan.co.jp/RENAULT-DEALERS/PASSPORT/view.cgi/admission/972959587-- -http://channel.nytimes.com/1998/10/15/technology/ -http://www.la.gunma-u.ac.jp/S97/thtml/m/kiso/41808.html -http://www1.ocn.ne.jp/~yaiba/_private/kobanasi/tyouhen/haraguroido/noroi.htm -http://www.duluxvalentine.com/FRANCE:1161209847:DFinity.1QJiP4jmPgipihoa -http://fi.egroups.com/messages/mediamalle-letter/6 -http://personal.wol.com.cn/lxz20a/gp13.htm -http://eclat.gaiax.com/www/eclat/y/k/yoko_mama/main.html -http://eclat.gaiax.com/www/eclat/y/k/yoko_mama/bbs.html -http://findmail.com/login.cgi?login_target=%2Fgroup%2Fohsama-iroiro -http://www.fogdog.com/cedroID/ssd3040183248487/crs/po__/wld/fogdog_sports/superfeet/outdoor/footwear/green_hi-profile.html -http://www.fogdog.com/cedroID/ssd3040183248487/nav/stores/baseball/ -http://www.fogdog.com/cedroID/ssd3040183248487/nav/stores/winter_sports/ -http://www.consource.com/members/signup/signup_temp_user.html?tAccountID=561 -http://213.36.119.69/do/session/152994/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/FR/reserver/voit.htm -http://213.36.119.69/do/session/152994/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/BE_NL/ -http://webcvs.kde.org/cgi-bin/cvsweb.cgi/kdevelop/Attic/configure.in?r1=1.62&sortby=rev -http://webcvs.kde.org/cgi-bin/cvsweb.cgi/kdevelop/Attic/configure.in?annotate=1.53&sortby=rev -http://webcvs.kde.org/cgi-bin/cvsweb.cgi/kdevelop/Attic/configure.in?r1=1.46&sortby=rev -http://www.aelita.net/products/solutions/sitemap/Reg/QuoteRegister/solutions/products/default.htm -http://sunsite.org.uk/public/public/packages/pine/docs/?S=A -http://sunsite.org.uk/public/public/packages/pine/docs/QandA.txt -http://www.sfc.keio.ac.jp/~s98008na/miniproject/0.html -http://www.allkorea.co.jp/cgi-bin/allkorea.front/972959867760/Catalog/1000023 -http://www.msn.expedia.co.uk/wg/Africa/Mauritius/P39048.asp -http://l-infonet.phkk.fi/fi/TIETOPALVELUT/asiasanahaku/rakennesuunnittelu/talonrakennus/rakennukset/ohjeet/ -http://www.ericsson.cl/education/centers/dtmexic.shtml -http://ftp.gigabell.net/debian/dists/Debian2.2r0/main/binary-powerpc/web/?S=A -http://dirs.educationamerica.net/Colorado/Localities/C/Colorado_Springs/News_and_Media/Television/ -http://polygraph.ircache.net:8181/services/define/jeff/http_-2web01.hq.cyberserv.com/ryanhomes/http_-2www.travelsc.com/cgi-bin/news/NewsList.cfm?ID=1 -http://salinas2000.com/index.cfm/r/960/a/95.htm -http://213.36.119.69/do/session/152988/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www3.travelprice.com/voyages/recherche.phtml -http://213.36.119.69/do/session/152988/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/FR/connaitre/questions-reponses.htm -http://ftp.cpan.org/src/5.0/sperl-2000-08-05/?D=A -http://virtualpubliclibrary.com/hallofanima/moresports/JOELOUIS.ORG//hallofanima/music/ -http://x500.rz.uni-karlsruhe.de:8000/Lcn%3dMonika%20Vogel,%20ou%3dPersonalabteilung,%20ou%3dUniversitaetsleitung%20und%20-verwaltung,%20o%3dUniversitaet%20Konstanz,%20c%3dDE -http://bsd.sinica.edu.tw/cgi-bin/cvsweb.cgi/ports/korean/pine/files/patch-ai?only_with_tag=RELEASE_2_2_2 -http://ftp.ring.gr.jp/archives/XFree86/4.0.1/binaries/Linux-ix86-glibc21/RELNOTES -http://homepage1.nifty.com/SAKURAISANS/itoshi.html -http://www.expage.com/savetucker -http://ring.edogawa-u.ac.jp/archives/pack/os2/prog/rexx/?N=D -http://www.saarreisen.de/rueckel-reisen/fluege-buchen/barbados/reise-ibiza.htm -http://debian.linux.org.tw/debian/dists/sid/contrib/binary-powerpc/interpreters/?S=A -http://ricoh.co.jp/rtoss/School/other/other/lotus_syo/pg7.html -http://www.kfi640.com/shared/mod_perl/looksmart/looksmart/eus1/eus52213/eus52841/eus236353/eus591199/eus937052/ -http://www.mapion.co.jp/custom/AOL/admi/23/23101/higashiyamatori/4chome/index-17.html -http://stocks.tradingcharts.com/stocks/charts/swti-bb/w/javachart -http://ftp.univ-lyon1.fr/gnu/Manuals/diffutils-2.7/html_chapter/diff_15.html -http://www.elfoco.com/EL_Foco/CDA/PrintPage/1,2171,2_53_28444,00.html -http://www.debian.org.cn/Bugs/db/61/61000.html -http://www.debian.org.cn/Bugs/db/66/66591.html -http://www.debian.org.cn/Bugs/db/57/57112.html -http://www.gxrb.com.cn/26/tbzl.htm -http://opac.lib.rpi.edu/search/dyosemite+national+park+water+resources+development+research+california/-5,-1,0,E/2browse -http://ring.omp.ad.jp/pub/NetBSD/NetBSD-current/src/usr.sbin/dhcp/client/scripts/openbsd -http://attach1.egroups.com/attach/1087162/28/gs-108=71=1087162/10-1-10-160/application=octet-stream/IntOrganist.htm -http://www.brainerddispatch.com/stories/071299/obi_0712990015.shtml -http://webusers.siba.fi/doc/HOWTO/en-html/Multi-Disk-HOWTO-27.html -http://www.pressa.spb.ru/newspapers/nevrem/arts/nevrem-1667-art-30.html -http://www4.ocn.ne.jp/~l-tommy/C1024.html -http://pub13.ezboard.com/fsequelossavannasoftwaredevelopment.showMessage?topicID=74.topic -http://pub13.ezboard.com/fsequelossavannasoftwaredevelopment.showMessage?topicID=109.topic -http://www.z-plus.de/freizeit/kino/galerie/unhold/kritikdpa.html -http://www.tiscover.com/1Root/Kontinent/6/Staat/7/Bundesland/16/Ort/515/Privatvermieter/326225/Homepage/m_homepage...2.html -http://wap.jamba.de/KNet/_KNet-NKE8j1-2Gd-13c6l/showInfo-wir.de/node.0/cde7f1uou -http://www.refdag.nl/kl/990706kl02.html -http://www.ferien-immobilien.de/nordrhein-Westfalen/soest/Verkauf/Versteigerungen-IB/Startseite/Gemeinsam/versicherungen/gebaeude/Versteigerungen-IB/Startseite/Gemeinsam/Super-Zins-Konditionen/anforderungsformular.htm -http://caller-times.com/1999/september/18/today/local_sp/78.html -http://link.fastpartner.com/do/session/600350/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/mondosoft.php -http://providenet.tukids.tucows.com/mac/9-12/adnload/11899_25711.html -http://providenet.tukids.tucows.com/mac/9-12/adnload/51475_24795.html -http://fivestar.subportal.com/sn/Network_and_Internet/Dial-up_Networking_Dialers/11735.html -http://www.kenley.londonengland.co.uk/newspaperandmagazinepublishers.htm -http://builder.hw.net/frmRestDir/0,1112,'1~21~325~1~C~013800~07790',00.html -http://builder.hw.net/frmRestDir/0,1112,'1~21~325~1~C~013800~54357',00.html -http://ftp1.support.compaq.com/public/vms/vax/v6.0/sls/2.6/?M=A -http://cpan.clix.pt/authors/id/I/IL/ILYAM/Mail-CheckUser-0.15.readme -http://www.maasvlakte-cam.nl/webcams/23/stavanger__norway/2000/10/12/?D=A -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/computers/music/midi/computers/quizz/lit/arnheim.html -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/computers/music/midi/computers/quizz/misc/colorart/ -http://www.taftp.com/A555D3/WebDir.nsf/MBC!OpenView&Start=89.2&Count=30&Expand=106 -http://jundavid.subportal.com/sn/Shell_and_Desktop/Animal_Cursors/11879.html -http://www.netitor.com/photos/schools/ucla/sports/m-wpolo/98-99action/?M=A -http://cpan.nitco.com/modules/by-module/Devel/MSCHWERN/Class-DBI-0.03.readme -http://cpan.nitco.com/modules/by-module/Devel/MSCHWERN/Text-Metaphone-0.02.readme -http://www.digitaldrucke.de/(aktuell,computer,gaestebuch,kino,literatur,nuernberg,rundfunk,sense,veranstaltungen,zeitschriften)/_fort/html/themen/kultur/literat/links/bin.htm -http://194.128.65.4/pa/cm199899/cmhansrd/vo990727/text/90727w01.htm -http://194.128.65.4/pa/cm199899/cmhansrd/vo990727/text/90727w15.htm -http://213.36.119.69/do/session/152989/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/FR/jeux/jeux_himalaya.html -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/computers/misc/quizz/lit/misc/cv.html -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/computers/misc/quizz/lit/misc/lit/larme.html -http://www.hblb.org.uk/hblbweb.nsf/$Pages/NewsArchive1!OpenDocument&ExpandSection=6,7,3,5,1,8,11 -http://www.identer.co.kr/ì‚¶ì˜ì—¬ìœ /ë°ì´íŠ¸ì •ë³´/ë°ì´íŠ¸ì •ë³´/ -http://allmacintosh.arrakis.es/adnload/54801.html -http://link.fastpartner.com/do/session/600380/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/brleksaker.php -http://link.fastpartner.com/do/session/600380/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/local/redirect.php -http://icm.html.tucows.com/adnload/001-009-003-014.html -http://www.rakuten.co.jp/coffee/forum/forum-w.cgi?p=131&url=coffee -http://jxi.gov.cn/yw-cj001.nsf/6770fc9e7685796c482568c70008a30a!OpenView&Start=69&Count=30&Expand=70 -http://jxi.gov.cn/yw-cj001.nsf/6770fc9e7685796c482568c70008a30a!OpenView&Start=69&Count=30&Expand=72 -http://freehomepage.taconet.com.tw/This/is/taconet/top_hosts//tsyang/test9g.htm -http://www11.cplaza.ne.jp/babyweb/bbs/bdnm01/no33/130N.html -http://library.cuhk.edu.hk/search*chi/a憪���/a{213972}{213230}/-5,-1,0,B/frameset&F=a{213972}{213233}{215b34}&1,1 -http://library.cuhk.edu.hk/search*chi/a憪���/a{213972}{213230}/-5,-1,0,B/frameset&F=a{213972}{21323e}{213165}+1947&1,1 -http://library.cuhk.edu.hk/search*chi/a撱嗅ˊ,+904-975./a{213d32}{213877}++904++975/-5,-1,0,B/frameset&F=a{213d32}{213a67}{213779}{213455}+china+{215f7a}{213579}{213966}{21363e}{21435a}+{214241}{213c37}&1,1 -http://www.online.kokusai.co.jp/Service/V0043539/wrd/G200/service/service.html -http://quote.morningstar.com/Quote.html?ticker=GASFX -http://uoi.linux.tucows.com/x11html/adnload/9826_7194.html -http://dk.egroups.com/post/batoco?act=forward&messageNum=2017 -http://www.chaos.dk/sexriddle/b/h/l/o/h/ -http://www.picktips.com/category-1031-1174_1171_1170-4_3_2 -http://www.schmunzelecke.de/pic18.htm -http://sun1.rrzn-user.uni-hannover.de/zzzzgart/matlab/help/techdoc/umg/chhand20.html -http://sun1.rrzn-user.uni-hannover.de/zzzzgart/matlab/help/techdoc/umg/chhand25.html -http://sun1.rrzn-user.uni-hannover.de/zzzzgart/matlab/help/techdoc/umg/chhand30.html -http://sun1.rrzn-user.uni-hannover.de/zzzzgart/matlab/help/techdoc/umg/chimag16.html -http://sun1.rrzn-user.uni-hannover.de/zzzzgart/matlab/help/techdoc/umg/chimag26.html -http://sun1.rrzn-user.uni-hannover.de/zzzzgart/matlab/help/techdoc/umg/chlight3.html -http://sun1.rrzn-user.uni-hannover.de/zzzzgart/matlab/help/techdoc/umg/chspec34.html -http://sun1.rrzn-user.uni-hannover.de/zzzzgart/matlab/help/techdoc/umg/chspec35.html -http://sun1.rrzn-user.uni-hannover.de/zzzzgart/matlab/help/techdoc/umg/chview15.html -http://sun1.rrzn-user.uni-hannover.de/zzzzgart/matlab/help/techdoc/umg/chvolvi5.html -http://www.t-onlien.de/dtag/mail/kontaktseite/1,3606,160,00.html -http://yumemi.ne.jp/bbs/hiroba/ky/view/h/hiroba3/8_wdsmcn_wdsmcn.html -http://yumemi.ne.jp/bbs/hiroba/ky/view/h/hiroba3/8_mrlinl_tcincn.html -http://yumemi.ne.jp/bbs/hiroba/ky/view/h/hiroba3/8_caouny_hixlcy.html -http://students.lsu.edu/students/main.nsf/c81d2bf8cb0b80ff862566fb00105ab2/7f3436ae9cb1268886256773006f9288!OpenDocument&ExpandSection=20,9,13,16 -http://www.crn.com/sections/BreakingNews/breakingnews.asp?ArticleID=5760 -http://dennou-h.ees.hokudai.ac.jp/library/Linux/debian-jp/dists/hamm/main-jp/binary-all/tex/?M=A -http://www.cmyk21.com/photo1-3.htm -http://www.cs.ruu.nl/mirror/CPAN/modules/by-category/14_Security_and_Encryption/User/ILYAZ/images/?N=D -http://www.egroups.com/login.cgi?login_target=%2Fmessage%2FFloodsystems%2F45 -http://www.mirnet.org/ccsi/nisorgs/ukraine/kyiv/renaisnc.htm -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=231&discrim=2,125,10 -http://ring.omp.ad.jp/archives/lang/perl/CPAN/authors/id/BRADAPP/PodParser-1.17.readme -http://www.amzn.com.ref.digital-price.com/redir/amzn.com/prods/0553373730 -http://library.cwu.edu/search/dGermany+--+Politics+and+government+--+1918-1933/dgermany+politics+and+government+1918+1933/-5,-1,0,B/marc&F=dgermany+politics+and+government+1918+1933+bibliography&1,1, -http://www.multicosm.com/facade/www.unisys.com/partners/default.asp?cn=su -http://enjoy100.com.cn/200006/08/sssh/sssh_ssjp.html -http://enjoy100.com.cn/200006/08/yskj/b_s_big3_f.jpg.html -http://www.hoops.ne.jp/~zuikaku/photo2000/0811/rie11.html -http://pub23.ezboard.com/fiolaniy2kmessageboardfrm1.showMessage?topicID=66.topic -http://ring.htcn.ne.jp/archives/lang/perl/CPAN/modules/by-module/CGI/ULPFR/Wais-2.301.readme -http://www3.newstimes.com/archive99/mar1199/spg.htm -http://ftp1.support.compaq.com/public/vms/axp/v6.2-1h2/dsnlink/2.2/dsnlinkd022.CVRLET_TXT -http://ftp.nacamar.de/pub/redhat/cpan/6.2/CPAN-archive/doc/manual/html/pod/perldsc.html -http://ftp.nacamar.de/pub/redhat/cpan/6.2/CPAN-archive/doc/manual/html/pod/perlfaq5.html -http://info.cs.unitn.it/sdb/de/html/keylist.SOFTWARE.html -http://www.online.kokusai.co.jp/Mmf_corner/V0043545/mmf_corner/mmf_corner/url -http://www.office.com/global/0,2724,66-15915,FF.html -http://polygraph.ircache.net:8181/home/ISO9001.htm -http://www.allgemeine-immobilien-boerse.de/niedersachsen/emsland/Verkauf/Versteigerungen-IB/Startseite/Allgemeine-IB/GmbH-Kauf-Verkauf-Insolvenz-konkurs/Startseite/Gemeinsam/hilfe.htm -http://launchbase.com/Health/Home_Health/communication/information/Science.htm -http://library.cwu.edu/search/aLockyer,+Norman,+Sir,+1836-1920/alockyer+norman+sir+1836+1920/-17,-1,0,B/frameset&F=alockwood+victoria+s+1953&1,1 -http://bbs.kcm.co.kr/NetBBS/Bbs.dll/chbod05/lst/qqa/r/qqo/004D/zka/B2-kCYFl -http://www.egroups.com/post/bhagavad_gita?act=forward&messageNum=101 -http://carriage.de/Schoner/Literatur/info-e/Geschichte/modelle/ -http://carriage.de/Schoner/Literatur/info-e/Geschichte/history/ -http://carriage.de/Schoner/Literatur/info-e/Geschichte/literature/ -http://wwwftp.ciril.fr/pub/linux/kernel///people/andrea/kernels -http://www.inctechnology.com/guide/item/0,7462,AGD6_GDE79,00.html -http://live.sportsline.com/u/basketball/college/teams/injuries/VATECH.htm -http://www-1.cisco.com/univercd/cc/td/doc/product/lan/28201900/1928v67x/28icg67x/28icpref.pdf -http://www.hitlist.com/music/presult/003948.php3 -http://ip.tosp.co.jp/Eki/TosiE000.asp?I=Jerryfish -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=(20,0)-16,0-9,2 -http://www.bigchurch.com/cgi-bin/w3com/pws/bc/RLhIotYxW-B0bt7seq4d876RzKIuJDYbydJP1qooxhzSKDVca77BUHQv6tsO2JdNpkx837SBl7FHRIEy00rmcLBk9Y1kQEmni0_YSk5mrym8WALtovIPQU_vlEtiMcNswNyh9z6CjU-2oS2uurrk666t -http://www.secinfo.com/d2wVq.7hv.htm -http://www.secinfo.com/d2wVq.6yd.htm -http://www.secinfo.com/d2wVq.6Y5.htm -http://www.secinfo.com/d2wVq.5gf.htm -http://www.secinfo.com/d2wVq.5hp.htm -http://www.secinfo.com/d2wVq.5y4.htm -http://ring.htcn.ne.jp/pub/text/CTAN/graphics/psfig/unsupported/macdemo/macfigs/?N=D -http://ring.htcn.ne.jp/pub/text/CTAN/graphics/psfig/unsupported/macdemo/macfigs/?M=A -http://books.hyperlink.co.uk/xt2/Drakelow_Unearthed/Stokes/Paul/0904015408 -http://www.homestead.com/rebeccah/files/ -http://sunsite.compapp.dcu.ie/pub/linux/redhat/redhat-6.1/alpha/usr/share/locale/ga_IE/LC_TIME -http://www.gbnf.com/genealogy/rockwel4/html/d0037/I2684.HTM -http://www.yorosiku.net:8080/-_-http://www.dd.iij4u.or.jp/~oni9/skebe/aindex18.html -http://www.yorosiku.net:8080/-_-http://www.dd.iij4u.or.jp/~oni9/skebe/aindex12.html -http://www.yorosiku.net:8080/-_-http://www.dd.iij4u.or.jp/~oni9/skebe/atg05.html -http://shn.webmd.net/content/article/1700.50808 -http://home.clara.net/cornell/woodcraft/spring2000/contents.htm -http://dic.empas.com/show.tsp/EDACITY -http://www.sanxia.net/beauty/Eriimai/417.htm -http://www.judds-resort.com/judds/Lake-Winni-pike-lodge/97menu/fallphoto/playground/boat/photo/12.html -http://www.judds-resort.com/judds/Lake-Winni-pike-lodge/97menu/fallphoto/playground/boat/fallphoto/2.html -http://imageserver2.tibetart.com:8087/fif=fpxbuddhistreverse/56.fpx&init=0.0,0.0,1.0,1.0&rect=0.0,0.25,0.5,0.75&wid=1443&hei=400&lng=en_US&enablePastMaxZoom=OFF&page=image.html&obj=uv,1.0&cmd=W -http://www.jamba.nl/KNet/_KNet-krE8j1-KC4-pv5y/showInfo-hilfe.nl/node.0/ce6u2jadf -http://www.babyheirlooms.com/catalog/htmlos.cat/011639.1.3372173854 -http://community.webshots.com/photo/441160/441363 -http://www.kaos.dk/sexriddle/x/n/d/x/b/ -http://isbn.nu/088730866X/chapters -http://login.hq.cricinfo.org/link_to_database/ARCHIVE/1992-93/AUS_LOCAL/MMC/WA_NSW_MMC_11OCT1992.html -http://login.hq.cricinfo.org/link_to_database/ARCHIVE/1991-92/AUS_LOCAL/FAI/WA_TAS_FAI_11OCT1991.html -http://login.hq.cricinfo.org/link_to_database/ARCHIVE/1991-92/AUS_LOCAL/FAI/WA_QLD_FAI-SEMI_19OCT1991.html -http://login.hq.cricinfo.org/link_to_database/ARCHIVE/1980S/1987-88/AUS_LOCAL/MDC/WA_SOA_MDC_06MAR1988.html -http://login.hq.cricinfo.org/link_to_database/ARCHIVE/1980S/1981-82/AUS_LOCAL/MDC/QLD_WA_MDC_08NOV1981.html -http://www.chaos.dk/sexriddle/x/k/l/y/h/ -http://tucows.teihal.gr/winnt/preview/6004.html -http://tucows.teihal.gr/winnt/preview/5986.html -http://tucows.teihal.gr/winnt/preview/71328.html -http://tucows.teihal.gr/winnt/preview/2757.html -http://www.medoc-ias.u-psud.fr:81/synoptic/gif/950724/?N=D -http://www4.nas.edu/ohr.nsf/All+Documents/Major+Units?OpenDocument&ExpandSection=18,7,21,20,4 -http://members.xoom.fr/logart/Anciens/Liste25/Selection_Navlist25.html -http://polygraph.ircache.net:8181/http_-2www.arthritis.org/http_-2pathfinder.com/si/swimsuit/swim97/terms2.html -http://polygraph.ircache.net:8181/http_-2www.arthritis.org/http_-2pathfinder.com/si/swimsuit/swim97/products2.html -http://debian.linux.org.tw/debian/dists/Debian2.2r0/main/disks-m68k/current/doc/ -http://findmail.com/dir/Arts/Writing/Fan_Fiction?st=1943 -http://www.telecombroker.com/q/001p/tgcb/4izQYz7mc.htm -http://www.free-phone.com/q/001p/tgcb/ItMd2D3jdEM.htm -http://www.123bestlongdistance.com/q/001p/tgcb/msN54jfl4mE.htm -http://www.netitor.com/photos/schools/nw/sport/w-baskbl/97action/?S=A -http://excite.de/katalog/katalog/33823 -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/programs/simple/music/midi/lit/misc/unitest/programs/ -http://yp.gates96.com/14/43/40/9.html -http://yp.gates96.com/14/43/40/43.html -http://yp.gates96.com/14/43/40/82.html -http://yp.gates96.com/14/43/40/85.html -http://yp.gates96.com/14/43/41/6.html -http://yp.gates96.com/14/43/41/18.html -http://yp.gates96.com/14/43/41/44.html -http://yp.gates96.com/14/43/41/96.html -http://yp.gates96.com/14/43/42/12.html -http://yp.gates96.com/14/43/46/38.html -http://yp.gates96.com/14/43/46/66.html -http://yp.gates96.com/14/43/46/68.html -http://yp.gates96.com/14/43/47/4.html -http://yp.gates96.com/14/43/47/37.html -http://yp.gates96.com/14/43/47/64.html -http://yp.gates96.com/14/43/47/68.html -http://yp.gates96.com/14/43/47/70.html -http://yp.gates96.com/14/43/48/68.html -http://yp.gates96.com/14/43/48/69.html -http://yp.gates96.com/14/43/49/7.html -http://yp.gates96.com/14/43/49/36.html -http://yp.gates96.com/14/43/49/37.html -http://yp.gates96.com/14/43/49/52.html -http://sound-dist.secured.co.uk/cgi-bin/psProdDet.cgi/5P005|972959562|Accessories|user|0|1,0,0,1 -http://school.educities.org/card/judy180.html -http://207.138.41.133/message/the-voice1/123 -http://207.138.41.133/message/the-voice1/124 -http://www-d0.fnal.gov/d0dist/dist/releases/p05.00.00/muo_analyze/?S=A -http://sjsulib1.sjsu.edu:81/search/cernest+haberkern+director/-5,-1,0,B/frameset&cgeorge+miller+director&1,1 -http://ring.nii.ac.jp/pub/pack/x68/net/00_index.txt -http://pub24.ezboard.com/fdoyoustillneedtoventfrm43.showMessage?topicID=19.topic -http://pub24.ezboard.com/fdoyoustillneedtoventfrm43.showMessage?topicID=15.topic -http://ukinvest.ukwire.com/articles/200007200700261473O.html -http://www.brd.net/brd-cgi/brd_multimedia/lautsprecher/LZ7460LK/ci=972822952.htm -http://my.netian.com/~haeng14/tatler_july6.htm -http://genforum.genealogy.com/cgi-genforum/forums/anderton.cgi?122 -http://www.excelsior.com.mx/0001/000125/for03.html -http://www.jobvillage.com/channel/jobs/sciences/b.9070.g.1675.html -http://us.mandrakesoft.com/cgi-bin/cvsweb.cgi/www/contact.html?annotate=1.19&sortby=author -http://us.mandrakesoft.com/cgi-bin/cvsweb.cgi/www/contact.html?r1=1.12&sortby=author -http://www.doc.ic.ac.uk/lab/labsrc_area/firstyear/submissions/1998-99/jmc1/labs/Ex06/skw98/?N=D -http://www.jamba.de/KNet/_KNet-fNw8j1-6Fd-13acp/browse.de/node.0/cde7f1uou -http://www.jamba.de/KNet/_KNet-fNw8j1-6Fd-13act/browse.de/node.0/cdel3j591 -http://www.nedstat.nl/cgi-bin/viewstat?name=mrbertmat -http://no.egroups.com/message/acessibilidade/1092 -http://no.egroups.com/message/acessibilidade/1099 -http://sound-dist.secured.co.uk/cgi-bin/psShop.cgi/add|38P08A|972959552|Communications|user|0|1,0,0,1 -http://213.36.119.69/do/session/152990/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/FR/reserver/spectacles/ -http://213.36.119.69/do/session/152990/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/CA_EN/ -http://wiki2.parsimony.net/wiki2954/ -http://www.f2.parsimony.net/forum2954/messages/214.htm -http://www.f2.parsimony.net/forum2954/messages/181.htm -http://www.f2.parsimony.net/forum2954/messages/292.htm -http://www.f2.parsimony.net/forum2954/messages/115.htm -http://www.f2.parsimony.net/forum2954/messages/290.htm -http://www.f2.parsimony.net/forum2954/messages/54.htm -http://home.pchome.com.tw/cool/162203/wunew15.htm -http://hem.fyristorg.com/lottaleman/LLfar/1_6721.htm -http://www.babyheirlooms.com/catalog/htmlos.cat/011628.1.4596216338 -http://www.affiliate.hpstore.hp.co.uk/do/session/380833/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/search.asp -http://www.outdoorwire.com/content/lists/dirt/200007/msg00127.html?{LoadingFrameset} -http://adept.subportal.com/sn/Programming/ActiveX/11674.html -http://www.staroriental.net/nav/soeg/ihf,aog,s0,10,Lam+Hei-Lui.html -http://www-d0.fnal.gov/d0dist/dist/releases/p05.00.01/man/?N=D -http://members.tripod.com/bluti/PSX/V/VACUUM.HTM -http://connexus.tucows.com/winme/adnload/138384_29728.html -http://wwwtios.cs.utwente.nl/archive/wilyfans/msg00265.html -http://custom.clubnet.zeelandnet.nl/eckhardt/myself.htm -http://ftp.tokyonet.ad.jp/pub/Linux/debian/dists/potato/contrib/binary-arm/otherosfs/?D=A -http://www.amcity.com/charlotte/stories/1997/07/07/daily4.html?t=email_story -http://www.generation-formation.fr/chiffrec.htm---o21zAo0UbDo0Ol9A074fo6Td4ezyr6feZJPAPfVbNyqHSezTHkekydMfeZJPdspt6dsSAtdsNhJdspt6dsrvrdjlhkfbi.htm -http://tv.thevines.com/leaf/AA0000369140/2 -http://kuyper.calvin.edu/fathers2/NPNF2-02/Npnf2-02-06.htm -http://www.intellicast.com/Ski/World/UnitedStates/Southeast/Florida/FortWaltonBeach/TEMPcast/d0_12/ -http://stevebarnes.studiostore.com/aboutus/b.EMERCH/s.P01EBK2I -http://student.monterey.edu/Students_N-R/richterheidil/private/ -http://ds.dial.pipex.com/town/drive/kch36/select/s30/ch052.html -http://ds.dial.pipex.com/town/drive/kch36/select/s30/ch027.html -http://ds.dial.pipex.com/town/drive/kch36/select/s30/ch077.html -http://ds.dial.pipex.com/town/drive/kch36/select/s30/ch092.html -http://soneraplaza.tucows.com/winme/adnload/137026_28536.html -http://www.egroups.com/post/realtyindia -http://www.kita.or.kr/untpdc/incubator/zwe/tphar/ZIMB0037.htm -http://citeseer.nj.nec.com/nrelated/126165/187254 -http://citeseer.nj.nec.com/cachedpage/187254/1 -http://citeseer.nj.nec.com/cidcontext/2417551 -http://yp.gates96.com/13/6/1/36.html -http://yp.gates96.com/13/6/1/61.html -http://yp.gates96.com/13/6/1/83.html -http://yp.gates96.com/13/6/1/91.html -http://yp.gates96.com/13/6/3/39.html -http://yp.gates96.com/13/6/3/45.html -http://yp.gates96.com/13/6/3/65.html -http://yp.gates96.com/13/6/4/46.html -http://yp.gates96.com/13/6/4/57.html -http://yp.gates96.com/13/6/5/44.html -http://yp.gates96.com/13/6/6/21.html -http://yp.gates96.com/13/6/6/42.html -http://yp.gates96.com/13/6/7/0.html -http://yp.gates96.com/13/6/7/30.html -http://yp.gates96.com/13/6/7/69.html -http://yp.gates96.com/13/6/7/82.html -http://yp.gates96.com/13/6/8/5.html -http://yp.gates96.com/13/6/8/98.html -http://yp.gates96.com/13/6/9/45.html -http://home.wanadoo.nl/hockeyclub.nieuwegein/Teams/Dames/Dames_IV/body_dames_iv.html -http://pub3.ezboard.com/fthe4thdimensiongeneralinsanity.subscribeUnregisteredToTopic?topicID=38.topic -http://pub3.ezboard.com/fthe4thdimensiongeneralinsanity.unsubscribeUnregisteredToTopic?topicID=38.topic -http://moviestore.zap2it.com/help_shipping/s.hXCLyc56 -http://www.geocities.co.jp/Outdoors/2363/typoon1.html -http://ua.php.net/manual/it/function.pg-numrows.php -http://kidneyfailure.shn.net/roundtable_reply/727640 -http://itcareers.careercast.com/texis/it/itjs/+HwwBmje0B-deZqwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewyPxGwproqamn5otDnGaoDm15BGowcamn5otDapGdm1qBamnVncdpa5dhBiwGna5BGwBnton5ah1DqBodDanD51GnaMFqnFZI0DzmzwwwpBmje0B-deZqwww5rmeZpwwwBrmeZpwww/morelike.html -http://itcareers.careercast.com/texis/it/itjs/+lwwBmex6D86egqwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewyPxGwproqamn5otDnGaoDm15BGowcamn5otDapGdm1qBamnVncdpa5dhBiwGna5BGwBnton5ah1DqBodDanD51GnaMFqnFZI0DzmzwwwpBmje0B-deZqwww5rmeacwwwBrmeZpwww/morelike.html -http://pub23.ezboard.com/fhardoverclockfrm1.showAddReplyScreenFromWeb?topicID=43.topic&index=3 -http://www.adquest3d.com/content.cfm?BRD=1578&PAG=63 -http://pelit.saunalahti.fi/.1/tucows/adnload/51_28438.html -http://pelit.saunalahti.fi/.1/tucows/preview/70307.html -http://www.maillist.com.tw/maillist/publicboard_newform.pl?maillist_id=softuse -http://dennou-t.ms.u-tokyo.ac.jp/arch/cc-env/Linux/debian-jp/dists/woody/non-free-jp/binary-alpha/news/?M=A -http://ustlib.ust.hk/search*chi/amarcot+bruce+g/amarcot+bruce+g/-5,-1,0,B/frameset&F=amarcotty+michael+1931&1,1 -http://wine.cc.chuo-u.ac.jp/home/pub/TeX/CTAN/support/rtf2tex/?M=A -http://netchief.tucows.com/winme/preview/75911.html -http://yp.gates96.com/4/57/60/83.html -http://yp.gates96.com/4/57/60/99.html -http://yp.gates96.com/4/57/62/17.html -http://yp.gates96.com/4/57/62/88.html -http://yp.gates96.com/4/57/63/9.html -http://yp.gates96.com/4/57/63/39.html -http://yp.gates96.com/4/57/63/64.html -http://yp.gates96.com/4/57/64/33.html -http://yp.gates96.com/4/57/65/41.html -http://yp.gates96.com/4/57/65/70.html -http://yp.gates96.com/4/57/66/18.html -http://yp.gates96.com/4/57/66/56.html -http://yp.gates96.com/4/57/66/61.html -http://yp.gates96.com/4/57/66/94.html -http://yp.gates96.com/4/57/67/0.html -http://yp.gates96.com/4/57/67/63.html -http://yp.gates96.com/4/57/67/85.html -http://yp.gates96.com/4/57/69/1.html -http://yp.gates96.com/4/57/69/56.html -http://citeseer.nj.nec.com/cs?q=dbnum%3D1,DID%3D9262,qtype%3Dsamesite: -http://citeseer.nj.nec.com/cidcontext/163444 -http://www.amazon.com.au/exec/obidos/change-style/tg/stores/detail/-/books/0873995562/e-mail-friend/ -http://www.sdinfonet.com.cn/411/24/411249999.htm -http://pub14.ezboard.com/fallpodsgotoroswellsayhello.threadControl?topicID=17.topic -http://in.egroups.com/message/sexualidades-noticias/14 -http://in.egroups.com/message/sexualidades-noticias/37 -http://library.cuhk.edu.hk/search*chi/dChinese+literature+--+20th+century+--+Periodicals/dchinese+literature+++20th+century+periodicals/-5,-1,0,B/frameset&F=dchinese+literature+++20th+century+periodicals&26,,188 -http://www.3w-zeitschriften.de/EyreLinda/EyreLinda1582380570.htm -http://cometweb01.comet.co.uk/do!session=132027&vsid=700&tid=20&cid=37030&mid=1000&rid=1060&chid=1713&url=eqqLmwlGltt5tkjHfZoLlplLcqkKZljLlfb5lal5tkiLlXaLl0 -http://retailer.gocollect.com/do/session/1912774/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/company_info/contact.asp -http://providenet.games.tucows.com/adnload/71993_40744.html -http://www.geocities.co.jp/playtown-Toys/6366/bbsp.html -http://www.hnby.com.cn/docroot/jzrb/200001/19/km01/19031711.htm -http://213.36.119.69/do/session/152997/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/IT_IT/ -http://www.jamba.de/KNet/_KNet-p7t8j1-FEd-139gj/showInfo-datenschutz.de/node.0/cde7f1uou -http://www.jamba.de/KNet/_KNet-p7t8j1-FEd-139gn/browse.de/node.0/cdzqggtyb -http://www.paidmania.com/getpaid/signup/42/2518 -http://www.pressa.spb.ru/newspapers/nevrem/arts/nevrem-1679-art-13.html -http://jproxy.uol.es/jproxy/http://jama.ama-assn.org/issues/current/related/joc00479.html -http://www.mirror.kiev.ua:8082/paper/2000/11/1251/text/11-08-2.htm -http://my.netian.com/~eco71/wzmain.html -http://www.craft-supplies.co.uk/cgi-bin/psProdDet.cgi/HT206|972959540|Deluxe_Dividers|user|0|0,0,1,1 -http://www.trax.nilex.co.uk/trax.cgi/A1S/1AR/A3R/B3D/A4R/A4S/ -http://www.linux.com/networking/network/network/development/project/growth/ -http://www.linux.com/networking/network/development/project/growth/sales/ -http://www.icopyright.com/1.1653.134616 -http://retailer.gocollect.com/do/session/1912718/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/company_info/about.asp -http://www.dw-tv.de/indonesia/sari_pers/19793.html -http://freethemes.netc.pt/skins/icq/preview/44470.html -http://freethemes.netc.pt/skins/icq/adnload/26145.html -http://freethemes.netc.pt/skins/icq/preview/52524.html -http://freethemes.netc.pt/skins/icq/adnload/52040.html -http://students.lsu.edu/students/main.nsf/c81d2bf8cb0b80ff862566fb00105ab2/7f3436ae9cb1268886256773006f9288!OpenDocument&ExpandSection=7,18,9,16 -http://golfonline.comfluent.net/cgi.pan$player&pga93&John_Morse&pga?golfstats -http://wai.camera.it/_presidenti/003.htm -http://www.pcmagazine.de/produkte/artikel/komp/200003/mainboards01_00-wc.html -http://www.pcmagazine.de/produkte/artikel/komp/199908/asus_00-wc.html -http://se.sslug.dk/emailarkiv/locale/2000_09/msg00053.html -http://se.sslug.dk/emailarkiv/locale/2000_09/msg00057.html -http://se.sslug.dk/emailarkiv/locale/2000_09/msg00115.html -http://www.brio.de/BRIO.catalog/39fe2f7406fad828273fd472aa7806ff/UserTemplate/8 -http://link.fastpartner.com/do/session/600389/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/jobpilot.php -http://www.shopworks.com/grizzlygulch/index.cfm/action/search/userid/000B40E3-1177-19FE-A703010D0A0A8CF2 -http://www.shopworks.com/grizzlygulch/index.cfm/action/product/prodid/0001AF94-3FC3-19E7-A703010D0A0A8CF2/userid/000B40E3-1177-19FE-A703010D0A0A8CF2 -http://spiritwolf52.subportal.com/sn/Web_Authoring/Misc__Programming_Tools/2670.html -http://www.chaos.dk/sexriddle/o/g/j/h/t/ -http://link.fastpartner.com/do/session/600394/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/learn/ -http://opac.lib.rpi.edu/search/dpolitical+corruption+united+states/-5,-1,0,B/frameset&dpolitical+corruption+united+states&7,,22 -http://cnnsi.com/baseball/mlb/news/2000/01/28/ -http://amrr.com/agents/contact.html?Agents_id=3707 -http://www.dulux.co.uk/UKRETAIL:1489107816:DFinity.1QJiP4jMomdkbEc -http://www.geocities.com/SiliconValley/Screen/9059/ -http://www.nrk.no/finnmark/x17_4_96/nyh4.htm -http://in.egroups.com/message/islaam/288 -http://www.incestpornstories.com/knocked-upepisiotomy/fertileoff-the-rag/one-night-standlubrication/japaneseslanted-eyes/{storieslink} -http://kuyper.calvin.edu/fathers2/ANF-04/anf04-30.htm -http://wuarchive.wustl.edu/systems/unix/NetBSD/NetBSD-release/src/sys/arch/sun3/stand/bootxx/ -http://polygraph.ircache.net:8181/services/define/noframes/http_-2www.microsoft.com/ie/download/http_-2www.microsoft.com/infoserv/about.html -http://pub23.ezboard.com/fferion80369frm4.showMessage?topicID=192.topic -http://pub23.ezboard.com/fferion80369frm4.showMessage?topicID=182.topic -http://www.cs.ruu.nl/mirror/CPAN/authors/id/N/NO/?S=A -http://yp.gates96.com/1/40/30/16.html -http://yp.gates96.com/1/40/30/72.html -http://yp.gates96.com/1/40/30/99.html -http://yp.gates96.com/1/40/31/25.html -http://yp.gates96.com/1/40/31/42.html -http://yp.gates96.com/1/40/31/54.html -http://yp.gates96.com/1/40/31/61.html -http://yp.gates96.com/1/40/31/95.html -http://yp.gates96.com/1/40/32/39.html -http://yp.gates96.com/1/40/32/88.html -http://yp.gates96.com/1/40/32/92.html -http://yp.gates96.com/1/40/33/33.html -http://yp.gates96.com/1/40/34/24.html -http://yp.gates96.com/1/40/34/51.html -http://yp.gates96.com/1/40/34/62.html -http://yp.gates96.com/1/40/34/72.html -http://yp.gates96.com/1/40/35/38.html -http://yp.gates96.com/1/40/36/80.html -http://yp.gates96.com/1/40/36/98.html -http://yp.gates96.com/1/40/37/35.html -http://yp.gates96.com/1/40/37/89.html -http://yp.gates96.com/1/40/38/13.html -http://yp.gates96.com/1/40/38/67.html -http://yp.gates96.com/1/40/39/8.html -http://yp.gates96.com/1/40/39/11.html -http://yp.gates96.com/1/40/39/42.html -http://netway.pda.tucows.com/palm/preview/33466.html -http://netway.pda.tucows.com/palm/preview/70276.html -http://netway.pda.tucows.com/palm/adnload/76963_22012.html -http://netway.pda.tucows.com/palm/preview/33676.html -http://www.private-immobilien-boerse.de/berlin-immobilien/verkauf/Private-IB/Startseite/Gemeinsam/versicherungen/gebaeude/Gemeinsam/Immolink/Gemeinsam/Super-Zins-Konditionen/anforderungsformular.htm -http://www.ne.jp/asahi/matinami/gallery/mati/hokkaido/hakodate/ph_l011.html -http://www.findarticles.com/cf_0/m0EKF/14_46/61415465/p1/article.jhtml -http://www.trax.nilex.co.uk/trax.cgi/A1C/A2S/B1S/B1L/B4S/A1S/ -http://students.lsu.edu/students/main.nsf/c81d2bf8cb0b80ff862566fb00105ab2/7f3436ae9cb1268886256773006f9288!OpenDocument&ExpandSection=1,21,16,5 -http://students.lsu.edu/students/main.nsf/c81d2bf8cb0b80ff862566fb00105ab2/7f3436ae9cb1268886256773006f9288!OpenDocument&ExpandSection=18,21,16,5 -http://ddb.libnet.kulib.kyoto-u.ac.jp/exhibit/fl3/image/fl3lhf/fl3lh0344.html -http://www.trnonline.com/archives/2000archives/04072000/sports/26732.shtml -http://www.linux.com/networking/network/new/press_release/management/editor/ -http://www.linux.com/networking/network/new/press_release/management/experiences/ -http://jundavid.subportal.com/sn/Business/Misc__Phone_Tools/index3.html -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=27,9,23,14,19 -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/music/misc/thoughts/lit/music/midi/mirroring.html -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/music/misc/thoughts/lit/music/midi/legendes/ -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/music/misc/thoughts/lit/music/midi/lit/laurent.txt -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/music/misc/thoughts/lit/music/midi/misc/colorart/ -http://www.lz.gs.cninfo.net/news/shenghuo/messages/361.html -http://www.egroups.com/messages/skarmflyg/683 -http://www.egroups.com/message/skarmflyg/675 -http://www.egroups.com/message/skarmflyg/681 -http://www.genoma.de/shop/0d79e8c12cc42ea8242eafc8a0c5586a/99/b -http://travelocity-dest.excite.com/Vacations/Reviews/Cruise/Submit/1,2586,0_228__,00.html -http://www02.geocities.co.jp/HeartLand-Sakura/1068/history.html -http://www.streetprices.com/Electronics/Computer_Software_PC/Programming/MAKE+DIGITAL/sortproductbyhighprice/SP275945.html -http://www.streetprices.com/Electronics/Computer_Software_PC/Programming/MAKE+DIGITAL/sortproductbyhighprice/SP246217.html -http://www.emerchandise.com/help_privacy/b.TV%20SATNIGHTLIVE/s.BOkfj8Vk -http://ftp.ccu.edu.tw/pub/documents/faq/mail/setup/?S=A -http://iceberg.adhomeworld.com/cgi-win/redirect.exe/304063772 -http://pdacentral.zeelandnet.nl/rim/email_license.htm -http://pdacentral.zeelandnet.nl/rim/adnload/139471_47673.html -http://www.loisirs.ch/tfhglx/17/ltxeld.html -http://au.yahoo.com/Business_and_Economy/Shopping_and_Services/Health/Providers/By_Region/U_S__States/Mississippi/Cities/ -http://sound-dist.secured.co.uk/cgi-bin/psProdDet.cgi/15P02A|972959527|Helmet|user|0|1,0,0,0 -http://news.dreamwiz.com/news_lg/04/20001030/yonhap/200010301014041007292.html -http://news.dreamwiz.com/news_lg/04/20001028/yonhap/ -http://pds.nchu.edu.tw/cpatch/ftp/ftpnav/?D=A -http://members.tripod.lycos.co.kr/BONGBAE/?N=D -http://www9.hmv.co.uk:5555/do/session/1347758/vsid/199/tid/199/cid/1061396/mid/1020/rid/1052/chid/1029/parser/yes/imref/eqqLmwlGltt5tkeHjskKZlkKrhlK/url/http://www.hmv.co.uk/hmv/departments/d50_sd0_pt0.html -http://itcareers.careercast.com/texis/it/itjs/+xwwBmeHWD86YwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewDhmoBGnaqdGpdGwBodDarGo5awDwcO5Baiw5roDtBdDaGn31n5BaGn31oGnmamnVncdpar1MwDaGn5d1Gqn5aMFqhTfR20DzmehrwwwpBmefWD86mwww5rmeddwwwBrmeZpwww/morelike.html -http://www.3w-buecher.de/GibbonsRob/GibbonsRob1572152214.htm -http://sennka.hoops.livedoor.com/%91%90%8a%a0%93%fa%98a%81%f4.htm -http://www.uni-duesseldorf.de/ftp/ftp/pf/s/netscape-v451/?S=A -http://www.outpersonals.com/cgi-bin/w3com/pws/out/0nhIQeA1Kelaujy0pUaBOo2AAoNruJ7MPpvxwl5qu-YeCeEn6SDc5vURHb5rk8dZP84c_4bSWkIDaPe8dCV5mfxj4LA69UDbXc_J2Z-eZg7dURZLZinceqCXYFUYC4pqT29R1BQKpdPvHP0APgIYRhQG -http://208.178.109.85/msgshow.cfm/msgboard=4779506785434&msg=80064825094809&page=1&idDispSub=-1 -http://interbox.tucows.com/preview/61367.html -http://www.crutchfield.com/cgi-bin/S-CI62JsDkHYX/viewcart.asp -http://www.hig.se/(aconf,formoutput,if,modified,set_cookie)/~jackson/roxen/ -http://www.trax.nilex.co.uk/trax.cgi/A1C/1AS/B1D/A3L/A1S/1AR/ -http://www.trax.nilex.co.uk/trax.cgi/A1C/1AS/B1D/A3L/A1S/C1R/ -http://www.trax.nilex.co.uk/trax.cgi/A1C/1AS/B1D/A3L/A1S/B4L/ -http://www.haikou.hi.cn/pandect/nj/n96ei3.htm -http://se.egroups.com/message/dailydreamers/36 -http://sunsite.org.uk/Mirrors/ftp.cdrom.com/pub/linux/slackware/contrib/contrib-sources/gcc-2.7.2.3/ -http://hp-partner.whowhere.lycos.com/hp/excite/Online_Communities/Angelfire/wi/index9.html -http://www.cse.unsw.edu.au/archives/linux/redhat/beta/?M=A -http://www.webcrawler.com/entertainment/music/artists_and_genres/folk_and_acoustic/artists_s/simon_and_garfunkel/garfunkel_art/interviews/ -http://www.russ.ru:8081/journal/media/98-05-21/telen0.htm -http://www.chaos.dk/sexriddle/x/r/k/o/w/ -http://www.jt.com.br/noticias/98/06/22/sd2.htm -http://retailer.gocollect.com/do/session/1912734/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/product_display/gifts/gift_floor.asp -http://www.ualberta.ca/CNS/RESEARCH/Software/SAS/gis/z0782606.htm -http://www.sentientnet.com/univercd/cc/td/doc/product/rtrmgmt/bluelist/cwblue21/cwbwsug/features.htm -http://pub5.ezboard.com/fthekojiroestrogenbrigadeconsolegaming.threadControl?topicID=16.topic -http://www.zjrs.zei.gov.cn/economy/text/policy/LHB/LHBA0909.TXT -http://seascape.tucows.com/winnt/adnload/2060_29646.html -http://seascape.tucows.com/winnt/adnload/2063_29648.html -http://seascape.tucows.com/winnt/adnload/2066_29651.html -http://ben.aspads.net/ex/c/641/517693268 -http://yp.gates96.com/7/63/80/20.html -http://yp.gates96.com/7/63/80/22.html -http://yp.gates96.com/7/63/80/80.html -http://yp.gates96.com/7/63/80/87.html -http://yp.gates96.com/7/63/81/50.html -http://yp.gates96.com/7/63/81/77.html -http://yp.gates96.com/7/63/81/79.html -http://yp.gates96.com/7/63/81/91.html -http://yp.gates96.com/7/63/82/36.html -http://yp.gates96.com/7/63/82/73.html -http://yp.gates96.com/7/63/84/6.html -http://yp.gates96.com/7/63/84/91.html -http://yp.gates96.com/7/63/85/30.html -http://yp.gates96.com/7/63/85/57.html -http://yp.gates96.com/7/63/85/98.html -http://yp.gates96.com/7/63/89/13.html -http://yp.gates96.com/7/63/89/20.html -http://yp.gates96.com/7/63/89/32.html -http://yp.gates96.com/7/63/89/65.html -http://www.rarf.riken.go.jp/archives/tex-archive/macros/latex//contrib/supported/linguex/?M=A -http://members.tripod.com/shelly34/shellyphotos/page12.html -http://ftp.nsysu.edu.tw/Unix/Perl/modules/by-category/23_Miscellaneous_Modules/Bundle/PlRPC-0.2003.readme -http://www.affiliate.hpstore.hp.co.uk/do/session/380827/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/SMARTTIPS/vacationcards.asp -http://www.marktplatz-hs.de/cgi-bin/ChioEditionShop.s/39fe2ee3005fd9642740d47540f806e1/IconBar -http://home.sprynet.com/~keithco/london.htm -http://earth.collectingnation.com/cgi-bin/bn/post.mod/aupn?B=cna&R=48 -http://earth.collectingnation.com/cgi-bin/bn/post.mod/aupn?B=cna&R=38 -http://www.realize.com/am747b81.htm,qt=e784fe2f=2a38a234-e-1adebfb-80000000-0-0-3-- -http://www.opengroup.com/dfbooks/009/0091856140.shtml -http://www.egroups.org/message/fotografya/216 -http://www.cn.informatik.fh-furtwangen.de/studenten/dv_labor/onlinebuecher/php/function.yaz-errno.html -http://www.cn.informatik.fh-furtwangen.de/studenten/dv_labor/onlinebuecher/php/function.yaz-hits.html -http://www.cn.informatik.fh-furtwangen.de/studenten/dv_labor/onlinebuecher/php/function.yaz-wait.html -http://www.catholicstore.com/search/index.cfm/FuseAction/detailSearch/SKU/17311/category/Bo/subCategory/G/subject/1 -http://www.cc.ntut.edu.tw/~584ce040/anne-1.htm -http://www.intervoz.com.ar/2000/09/23/sociedad_n11.htm -http://pub22.ezboard.com/frecipegoldminesharearecipe.showAddReplyScreenFromWeb?topicID=4.topic -http://opencity.kulichki.ru/moshkow/PROZA/LIPSKEROV/okno.txt -http://www.tccomputers.com/cgi-bin/bp/1021890426/products/modems/modems.htm -http://www.tccomputers.com/cgi-bin/bp/1021890426/services/sitemap.htm -http://library.bangor.ac.uk/search/dCrystallography+--+Periodicals/dcrystallography+periodicals/-5,-1,0,B/frameset&F=dcrystallography+mathematical&8,,9 -http://music.excite.ca/artist/-264813 -http://www.gameboyz.com/g/review_465_p4_n3.html -http://library.cwu.edu/search/aCarande,+Robert/acarande+robert/-5,-1,0,B/2exact&F=acarande+robert&1,2 -http://www.townstuff.com/search.cfm?directory=1040&town=285 -http://bsd.sinica.edu.tw/cgi-bin/cvsweb.cgi/ports/graphics/png/files/patch-aa?only_with_tag=RELEASE_2_2_7 -http://www.amcity.com/columbus/stories/1997/07/07/focus6.html?t=email_story -http://retailer.gocollect.com/do/session/1912716/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/checkout/shopping_cart.asp -http://ds.dial.pipex.com/town/drive/kch36/select/s12/ch034.html -http://ds.dial.pipex.com/town/drive/kch36/select/s12/ch118.html -http://www.dbring.de/160/16005-09.html -http://198.103.152.100/search*frc/lHQ+769+E3614/lhq++769+e3614/7,-1,0,B/frameset&F=lhq++777.4+d47&1,1 -http://yp.gates96.com/7/27/70/14.html -http://yp.gates96.com/7/27/70/27.html -http://yp.gates96.com/7/27/70/35.html -http://yp.gates96.com/7/27/70/37.html -http://yp.gates96.com/7/27/70/62.html -http://yp.gates96.com/7/27/71/38.html -http://yp.gates96.com/7/27/71/80.html -http://yp.gates96.com/7/27/72/62.html -http://yp.gates96.com/7/27/72/80.html -http://yp.gates96.com/7/27/73/10.html -http://yp.gates96.com/7/27/73/61.html -http://yp.gates96.com/7/27/73/78.html -http://yp.gates96.com/7/27/74/7.html -http://yp.gates96.com/7/27/74/16.html -http://yp.gates96.com/7/27/75/62.html -http://yp.gates96.com/7/27/76/90.html -http://yp.gates96.com/7/27/77/7.html -http://yp.gates96.com/7/27/77/92.html -http://yp.gates96.com/7/27/78/21.html -http://yp.gates96.com/7/27/79/21.html -http://yp.gates96.com/7/27/79/57.html -http://yp.gates96.com/7/27/79/96.html -http://moviestore.zap2it.com/help/b.STARWARSSAGA%20STARWARS-ROJ/s.nrF6V2sr -http://www2.kbank.no/Web/nlpublish.nsf/Published/ord_og_uttrykk!OpenDocument&ExpandSection=8,27,13,5 -http://newspaper.swww.com.cn/1999/cdwb/199912/26/html/1003.html -http://newspaper.swww.com.cn/1999/cdwb/199912/26/html/1008.html -http://iworld.freethemes.com/adnload/77752.html -http://iworld.freethemes.com/adnload/15251.html -http://iworld.freethemes.com/adnload/54697.html -http://iworld.freethemes.com/adnload/15232.html -http://www.fogdog.com/cedroID/ssd3040183238457/nav/products/ice_hockey/1d/gear_accessories/ -http://www.ftp.uni-erlangen.de/pub/Linux/DEBIAN/dists/Debian2.2r0/main/binary-m68k/doc/ -http://www.ftp.uni-erlangen.de/pub/Linux/DEBIAN/dists/Debian2.2r0/main/binary-m68k/sound/ -http://library.cwu.edu/search/aThimbleby,+Harold/athimbleby+harold/-5,-1,0,B/exact&F=athilde+jean&1,2 -http://www5.pconline.com.cn/pcedu/soft/doc/001024/2.htm -http://member.nifty.ne.jp/kaito-mist/nifty5.htm -http://www.cc.yamaguchi-u.ac.jp/~archive/doc/jdk1.2.2/docs/api/java/awt/image/BandedSampleModel.html -http://www.sandiego.digitalcity.com/honolulu/arts/occurrence.dci?ecid=75 -http://ubahn.exit.de/ffm/pic/pp/?S=A -http://www.visiobroker.com/opcvm/details/4/43591.html -http://www.visiobroker.com/opcvm/details/9/9765.html -http://ring.toyama-ix.net/archives/linux/debian/debian-jp/dists/woody-towns/?M=A -http://www.asahi-net.or.jp/~ZI3H-KWRZ/lawylegalaid.html -http://mayu.sourceforge.net/cgi-bin/nph-ml.cgi/000/http/www.geocrawler.com/archives/3/195/1999/7/0/ -http://www.buybuddy.com/sleuth/27/1/1060103/490578/ -http://java.javasoft.com/products/jdk/1.2/ja/docs/ja/api/java/awt/image/BandedSampleModel.html -http://mitglied.tripod.de/~HTTC/mannschaften/3LigaGr1_0001.htm -http://opac.lib.rpi.edu/search/anightingale+peggy+1942/-5,-1,0,B/browse -http://ftp.unina.it/pub/Amiga/NetBSD/NetBSD-current/pkgsrc/editors/ssam/files/ -http://kikakusvr3.city.yokohama.jp/y/j/e25/ktt/ktt.html -http://members.spree.com/entertainment/juskickit/http//members.spree.com/sports/comicus1 -http://www.butuanon.tsx.org/ -http://archive.soccerage.com/s/de/07/05375.html -http://mayu.sourceforge.net/cgi-bin/nph-ml.cgi/000/http/www.geocrawler.com/archives/3/151/1995/10/0/859255/ -http://mayu.sourceforge.net/cgi-bin/nph-ml.cgi/000/http/www.geocrawler.com/archives/3/151/1995/10/50 -http://polygraph.ircache.net:8181/http_-2www.soniajekums.com/docs/Http_-2ua.battle-zone.com/html/html/on_line.html -http://www.affiliate.hpstore.hp.co.uk/do/session/380855/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-creativeworld.com/creativeworld.asp?lang=f -http://mirror.cc.utsunomiya-u.ac.jp/mirror/CPAN/authors/id/T/TO/TOSTI/vstadaf-0.01.readme -http://www.xmission.com/~dkenison/cgi/lwgate.cgi/KLR650/archives/v02.n1633/Subject/article-16.html -http://www.realize.com/p25581.htm,qt=e784fe2f=2a38a234-7-da710e-0-0-0-1-- -http://www.realize.com/am947681.htm,qt=e784fe2f=2a38a234-7-da6e1d-80000000-0-0-3-- -http://www.realize.com/am2c3a81.htm,qt=e784fe2f=2a38a234-7-da6e1d-80000000-0-0-3-- -http://www.realize.com/amd15381.htm,qt=e784fe2f=2a38a234-7-da6e1d-1-84-0-3-- -http://link.fastpartner.com/do/session/600403/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/speednames.php -http://home.freeuk.net/lyne/work.htm -http://www.gotocity.com/local/2/us/AZ/p/85643/people/ -http://www.service911.com/egghead/step/0,2743,6+33+121+25440+18092_4,00.html -http://www.jamba.de/KNet/_KNet-irv8j1-WEd-139z7/showInfo-werbung.de/node.0/cenv0b09a -http://ustlib.ust.hk/search*chi/dbeijing+mandarin+dialects+china+slang/dbeijing+mandarin+dialects+china+slang/-5,1,1,B/frameset&F=dbeijing+mayors+china+fiction&1,1, -http://www.linux.org.tw/~chester/xlib/GC/convenience-functions/XSetGraphicsExposures.html -http://www.linux.org.tw/~chester/xlib/graphics/font-metrics/XUnloadFont.html -http://www.chaos.dk/sexriddle/c/f/j/u/c/ -http://www.chaos.dk/sexriddle/c/f/j/u/q/ -http://www.bornloser.com/comics/committed/archive/committed-20001027.html -http://tulips.ntu.edu.tw/search*chi/dDeath+lc/ddeath+lc/-17,-1,0,E/frameset&F=ddeath+in+adolescence+abstracts&1,,0 -http://hem.fyristorg.com/lottaleman/LLfar/1_6955.htm -http://preview.egroups.com/post/scoresheet-talk?act=reply&messageNum=7013 -http://209.52.189.2/profile.cfm/TimmyJ -http://archive.soccerage.com/s/pt/37/04816.html -http://pub16.ezboard.com/fleftbehindmessageboardfellowshiphall.showMessage?topicID=456.topic&index=16 -http://www.2pl.com/asp/tools/fili1.asp?sp=se&fi=pppp0005s8 -http://link.fastpartner.com/do/session/600382/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/company/jobs.htm -http://us.mandrakesoft.com/cgi-bin/cvsweb.cgi/kdenetwork/kppp/Rules/Poland/?only_with_tag=MAIN -http://genforum.genealogy.com/cgi-genforum/forums/flippin.cgi?30 -http://pub.chinaccm.com/23/news/200010/28/114339.asp -http://pub.chinaccm.com/23/news/200010/27/134259.asp -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=21,9,14,35,15 -http://gamesearcher.com/games/pc/returnofphantom-cheatsfaqs.html -http://ua.php.net/manual/es/function.pg-errormessage.php -http://findmail.com/group/prairydog -http://www.loria.fr/projets/dilib/DILIB_ROOT/SYSTEMS/Linux/Dilib/Data/NLM/MedLine/ -http://www.daysinn.com/ctg/cgi-bin/DaysInn/programs/AAAksrACwAAACEaAAQ -http://www.leo.org/leoclick/35dd60550f1ba90ed5bb7952eebae0d3+L+1__ -http://members.fortunecity.com/abbalink/songs/lyrics/wg.htm -http://chat.sportsline.com/u/football/nfl/xword/answers/091500.htm -http://210.173.172.13/entertainments/sports/sydney/kanrenkiji/0924/0925m096-500.html -http://210.173.172.13/entertainments/sports/sydney/kanrenkiji/0924/0925m094-500.html -http://www.private-immobilien-boerse.de/nordrhein-Westfalen/Muehlheim-ruhr/Verkauf/3d-service/Gemeinsam/Inserieren/3d-service/Gemeinsam/versicherungen/gebaeude/deckungsumfang.htm -http://www.private-immobilien-boerse.de/nordrhein-Westfalen/Muehlheim-ruhr/Verkauf/3d-service/Gemeinsam/Inserieren/3d-service/Gemeinsam/IIMMitglieder.htm -http://www.realize.com/amcf7781.htm,qt=e784fe2f=2a38a234-4-7cf2ef-80000000-0-0-3-- -http://family.go.com/Categories/Features/family_1998_12/penn/penn128urban/ -http://www.loria.fr/projets/dilib/DILIB_ROOT/ApplicationsTest/Dilib/newBD/Prog/?N=D -http://www.loisirs.ch/xfeoav/7/kqbmsh.html -http://tucows.tu-graz.ac.at/herdwin0807.html -http://www-d0.fnal.gov/cgi-bin/cvsweb.cgi/gtr_htf/dat/?sortby=log -http://www.buybuddy.com/sleuth/17/1/2006/32619/ -http://www.aelita.net/products/Reg/QuoteRegister/products/library/products/company/Privacy.htm -http://www.refdag.nl/bui/990803bui08.html -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=3,0+9,6-14,0+0,2 -http://www.aelita.net/products/services/support/sitemap/news/solutions/default.htm -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=26,5,30,16,12 -http://www.ericsson.cl/gsmpro/contact.shtml -http://members.tripodasia.com.cn/maolin_photo/maolin_suzuki/maolin_suzuki/maheuitu/ -http://members.tripodasia.com.cn/maolin_photo/maolin_suzuki/maolin_suzuki/mangoo333/ -http://members.tripodasia.com.cn/maolin_photo/maolin_suzuki/maolin_suzuki/maomizhijia/ -http://members.tripodasia.com.cn/maolin_photo/maolin_suzuki/maolin_suzuki/masaki_hamada/ -http://members.tripodasia.com.cn/maolin_photo/maolin_suzuki/maolin_suzuki/maxiaofei/ -http://members.tripodasia.com.cn/maolin_photo/maolin_suzuki/maolin_suzuki/maz0503/ -http://members.tripodasia.com.cn/maolin_photo/maolin_suzuki/maolin_suzuki/menghuanboy/ -http://members.tripodasia.com.cn/maolin_photo/maolin_suzuki/maolin_suzuki/michealshen/ -http://members.tripodasia.com.cn/maolin_photo/maolin_suzuki/maolin_suzuki/mike717/ -http://members.tripodasia.com.cn/maolin_photo/maolin_suzuki/maolin_suzuki/mikeshang_2/ -http://members.tripodasia.com.cn/maolin_photo/maolin_suzuki/maolin_suzuki/mingyueyaze/ -http://members.tripodasia.com.cn/maolin_photo/maolin_suzuki/maolin_suzuki/mm3/ -http://members.tripodasia.com.cn/maolin_photo/maolin_suzuki/maolin_suzuki/mnbv89/ -http://members.tripodasia.com.cn/maolin_photo/maolin_suzuki/maolin_suzuki/morsia/ -http://members.tripodasia.com.cn/maolin_photo/maolin_suzuki/maolin_suzuki/move/ -http://members.tripodasia.com.cn/maolin_photo/maolin_suzuki/maolin_suzuki/mslug/ -http://members.tripodasia.com.cn/maolin_photo/maolin_suzuki/maolin_suzuki/msshi/ -http://members.tripodasia.com.cn/maolin_photo/maolin_suzuki/maolin_suzuki/muwei/ -http://members.tripodasia.com.cn/maolin_photo/maolin_suzuki/maolin_suzuki/my1799/ -http://members.tripodasia.com.cn/maolin_photo/maolin_suzuki/maolin_suzuki/mychat2000/ -http://members.tripodasia.com.cn/maolin_photo/maolin_suzuki/maolin_suzuki/myesky/ -http://members.tripodasia.com.cn/maolin_photo/maolin_suzuki/maolin_suzuki/mzlzq/ -http://www.ring.gr.jp/pub/linux/Vine/VineSeed/alpha/mnt/source/sbin/loader -http://www.nrk.no/finnmark/x8_5_96/nyh7.htm -http://202.99.23.245/rmrb/200001/27/no_txb_6.html -http://www-d0.fnal.gov/d0dist/dist/releases/test/smt_hit/test/?N=D -http://www-d0.fnal.gov/d0dist/dist/releases/test/smt_hit/test/LIBRARIES -http://jupiter.u-3mrs.fr/~msc41www/releves/13440405.HTM -http://ftp.univie.ac.at/packages/perl/modules/by-category/15_World_Wide_Web_HTML_HTTP_CGI/CGI/ANDK/Apache-correct_headers.readme.html -http://www.linux.com/networking/network/networking/free/windows_nt/distro/ -http://www.linux.com/networking/network/networking/free/windows_nt/tip/ -http://australia-holiday-guide.com/Englisch/Queensland_1/QLD_Furher_North_1/qld_further_north_1.html -http://australia-holiday-guide.com/Englisch/Queensland_1/QLD_Great_Barrier_Reef_1/qld_great_barrier_reef_1.html -http://ftp.uni-paderborn.de/aminet/aminet/demo/aga/Ayrton.readme -http://ftp.uni-paderborn.de/aminet/aminet/demo/aga/Deadline_1.readme -http://ftp.uni-paderborn.de/aminet/aminet/demo/aga/DiamondPPC.readme -http://ftp.uni-paderborn.de/aminet/aminet/demo/aga/Gravity2_inv.readme -http://ftp.uni-paderborn.de/aminet/aminet/demo/aga/HJB-BCFix.readme -http://ftp.uni-paderborn.de/aminet/aminet/demo/aga/ImpPos.readme -http://ftp.uni-paderborn.de/aminet/aminet/demo/aga/Nat-AutF.readme -http://ftp.uni-paderborn.de/aminet/aminet/demo/aga/PSB-Desperado2.readme -http://ftp.uni-paderborn.de/aminet/aminet/demo/aga/PSB-PUK_final.readme -http://genforum.genealogy.com/cgi-genforum/forums/kilroy.cgi?34 -http://genforum.genealogy.com/cgi-bin/print.cgi?kilroy::34.html -http://content.health.msn.com/ef/message/803324/content.health.msn.com%2fmessage_board_message%2f803324/803324 -http://de.excite.de/gesundheit/katalog/6107 -http://de.excite.de/gesundheit/katalog/4909 -http://de.excite.de/gesundheit/katalog/5941 -http://de.excite.de/gesundheit/katalog/4924 -http://de.excite.de/gesundheit/katalog/5898 -http://de.excite.de/gesundheit/katalog/4949 -http://de.excite.de/gesundheit/katalog/5987 -http://de.excite.de/gesundheit/katalog/5855 -http://de.excite.de/gesundheit/katalog/39862 -http://de.excite.de/gesundheit/katalog/5852 -http://de.excite.de/gesundheit/katalog/5645 -http://de.excite.de/gesundheit/katalog/6078 -http://de.excite.de/gesundheit/katalog/5834 -http://yp.gates96.com/11/26/80/31.html -http://yp.gates96.com/11/26/80/47.html -http://yp.gates96.com/11/26/80/91.html -http://yp.gates96.com/11/26/81/61.html -http://yp.gates96.com/11/26/81/86.html -http://yp.gates96.com/11/26/82/37.html -http://yp.gates96.com/11/26/82/49.html -http://yp.gates96.com/11/26/83/38.html -http://yp.gates96.com/11/26/83/52.html -http://yp.gates96.com/11/26/83/58.html -http://yp.gates96.com/11/26/83/84.html -http://yp.gates96.com/11/26/84/0.html -http://yp.gates96.com/11/26/84/59.html -http://yp.gates96.com/11/26/84/75.html -http://yp.gates96.com/11/26/84/99.html -http://yp.gates96.com/11/26/85/37.html -http://yp.gates96.com/11/26/85/63.html -http://yp.gates96.com/11/26/85/78.html -http://yp.gates96.com/11/26/86/36.html -http://yp.gates96.com/11/26/86/40.html -http://yp.gates96.com/11/26/87/66.html -http://yp.gates96.com/11/26/87/87.html -http://yp.gates96.com/11/26/89/7.html -http://yp.gates96.com/11/26/89/21.html -http://yp.gates96.com/11/26/89/38.html -http://providenet.tukids.tucows.com/mac/9-12/macspell912_license.html -http://providenet.tukids.tucows.com/mac/9-12/adnload/25805_25780.html -http://www04.u-page.so-net.ne.jp/zb3/eiji-m/dog6.htm -http://school.educities.org/card/jou0731.html -http://school.educities.org/card/ke234.html -http://school.educities.org/card/aaaaaqqqqqqq.html -http://school.educities.org/card/cso.html -http://school.educities.org/card/g40203.html -http://school.educities.org/card/h123915388.html -http://school.educities.org/card/k1084211.html -http://www.cigar-pipe.de/SP/dhuc3112.htm -http://www.newquestcity.com/cities/MA///news/3675.htm -http://caowei_814.home.chinaren.com//wenxue/wenxue-mood/love147.htm -http://www.amulation.com/md-l-archive/199805/msg00065.html -http://in.egroups.com/messages/conventions/51?viscount=-30 -http://yp.gates96.com/11/63/20/4.html -http://yp.gates96.com/11/63/20/21.html -http://yp.gates96.com/11/63/20/51.html -http://yp.gates96.com/11/63/21/29.html -http://yp.gates96.com/11/63/21/41.html -http://yp.gates96.com/11/63/21/74.html -http://yp.gates96.com/11/63/22/4.html -http://yp.gates96.com/11/63/22/29.html -http://yp.gates96.com/11/63/22/80.html -http://yp.gates96.com/11/63/22/86.html -http://yp.gates96.com/11/63/23/7.html -http://yp.gates96.com/11/63/23/24.html -http://yp.gates96.com/11/63/23/39.html -http://yp.gates96.com/11/63/24/1.html -http://yp.gates96.com/11/63/25/35.html -http://yp.gates96.com/11/63/25/78.html -http://yp.gates96.com/11/63/25/83.html -http://yp.gates96.com/11/63/26/37.html -http://yp.gates96.com/11/63/27/3.html -http://yp.gates96.com/11/63/27/9.html -http://yp.gates96.com/11/63/27/14.html -http://yp.gates96.com/11/63/28/16.html -http://yp.gates96.com/11/63/28/26.html -http://yp.gates96.com/11/63/28/54.html -http://yp.gates96.com/11/63/28/55.html -http://yp.gates96.com/11/63/29/13.html -http://yp.gates96.com/11/63/29/64.html -http://yp.gates96.com/11/63/29/69.html -http://spaceports.tucows.com/winnt/httpservernt_license.html -http://www.affiliate.hpstore.hp.co.uk/do/session/380848/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/FR/REGISTRATION/entry.asp -http://incrediblegolfsavings.subportal.com/sn/Games/Simulation_Games/11310.html -http://incrediblegolfsavings.subportal.com/sn/Games/Simulation_Games/12064.html -http://www.linux.com/networking/linux/industry/gnu/operating_system/Corel/ -http://www.linux.com/networking/linux/industry/gnu/operating_system/Updates/ -http://www.fogdog.com/cedroID/ssd3040183307418/womens/ -http://www.fogdog.com/cedroID/ssd3040183307418/nav/products/featured_brands/1o/casual_sunglasses/ -http://www.fogdog.com/cedroID/ssd3040183307418/nav/products/featured_brands/1o/hockey_skates/ -http://www.fogdog.com/cedroID/ssd3040183307418/nav/products/featured_brands/1o/sweatshirts_fleece/ -http://www.fogdog.com/cedroID/ssd3040183307418/crs/nvCZ/wld/fogdog_sports/nike/football/equipment/500r_series_football.html -http://www.seoul.co.kr/dmaeil/199908/0820j015.htm -http://www-trn.bards.ru/Lobanovskiy/part13.htm -http://www-trn.bards.ru/Vahnuk/part27.htm -http://www-trn.bards.ru/Vetrova_Svetlana/part9.htm -http://www-trn.bards.ru/Tretiyakov/part22.htm -http://www-trn.bards.ru/Okoudjava/part202.htm -http://www-trn.bards.ru/Panyushkin/part100.htm -http://www-trn.bards.ru/Gorodnicky/part287.htm -http://yumemi.ne.jp/bbs/ky/view/f/forum9/1_jpbshj_vvvzil.html -http://yumemi.ne.jp/bbs/ky/view/f/forum9/1_xxosis_czhmrb.html -http://yumemi.ne.jp/bbs/ky/view/f/forum9/1_yikriy_qjvins.html -http://www.peopledaily.co.jp/shch/199907/28/newfiles/D103.html -http://legalminds.lp.findlaw.com/list/newlawbooks-l/frm00336.html -http://tucows.sp-plus.nl/winme/phoneme.html -http://ustlib.ust.hk/search*chi/dalcoholic+beverages+china/dalcoholic+beverages+china/7,-1,0,E/2browse -http://ustlib.ust.hk/search*chi/dalcoholic+beverages+china/dalcoholic+beverages+china/-5,-1,0,E/frameset&F=dalcoholic+beverages+great+britain&1,,0 -http://www.canit.se/(k10,k13,k16,k6)/support/faq/faq.html -http://aecjobbank.com/texis/script/jobbank/+Owwrmwxeri2wBV6evNVpwwwF6eWYqkwwwn6eXmcOwwwn6ekmyjwwwn6eULpOwwqn6eUCBZwwwn6e22QuwwwefPY9GepmwwmeiP46eczdwwmeOTB6eXhzwwwnmBVve89AHwwxeY44Ie-pxwww+vejWRhwwxealYTeXjzwwwhvep9q9wwwxveoA6kwwqe0PYieqFzwwwv6eFRFrwwwt6eSGxDwwwetNY1e8drwwqeT53Amwww0h7mwww1tzmwwweb-3qmwwww/jobdirectory.html -http://www9.hmv.co.uk:5555/do/session/1347780/vsid/199/tid/199/cid/1061396/mid/1020/rid/1052/chid/1029/parser/yes/imref/eqqLmwlGltt5tkeHjskKZlkKrhlK/url/http://www.hmv.co.uk/hmv/newmenu.html -http://www9.hmv.co.uk:5555/do/session/1347780/vsid/199/tid/199/cid/1061396/mid/1020/rid/1052/chid/1029/parser/yes/imref/eqqLmwlGltt5tkeHjskKZlkKrhlK/url/http://www.hmv.co.uk/hmv/departments/d30_sd0_pt0.html -http://www9.hmv.co.uk:5555/do/session/1347780/vsid/199/tid/199/cid/1061396/mid/1020/rid/1052/chid/1029/parser/yes/imref/eqqLmwlGltt5tkeHjskKZlkKrhlK/url/http://www.hmv.co.uk/hmv/departments/d70_sd0_pt0.html -http://www9.hmv.co.uk:5555/do/session/1347780/vsid/199/tid/199/cid/1061396/mid/1020/rid/1052/chid/1029/parser/yes/imref/eqqLmwlGltt5tkeHjskKZlkKrhlK/url/http://www.hmv.co.uk/hmv/departments/d90_sd0_pt0.html -http://www9.hmv.co.uk:5555/do/session/1347780/vsid/199/tid/199/cid/1061396/mid/1020/rid/1052/chid/1029/parser/yes/imref/eqqLmwlGltt5tkeHjskKZlkKrhlK/url/http://www.hmv.co.uk/hmv/departments/d120_sd0_pt0.html -http://www.hbdaily.com.cn/hbrb/20000622/BIG5/hbrb^18323^12^0622h016.htm -http://excite.de/immobilien/katalog/6877 -http://excite.de/immobilien/katalog/7012 -http://www.globalmart.com/housewares/appliances/household/irons/blackanddecker/S680.htm -http://mediate.magicbutton.net/do/session/625631/vsid/4385/tid/4385/cid/88138/mid/1702/rid/2114/chid/3393/url/http://www.worldgallery.co.uk/frameset-artc.html -http://ddb.libnet.kulib.kyoto-u.ac.jp/exhibit/mt3/image/mt3shf/mt3sh0192.html -http://us.parsimony.net/forum26166/messages/410.htm -http://linux.tnc.edu.tw/CPAN/authors/id/A/AZ/AZEMGI/?M=A -http://linux.tnc.edu.tw/CPAN/authors/id/A/AZ/AZEMGI/CHECKSUMS -http://launchbase.com/Shopping/Visual_Arts/communication/entertainment/Pictures_&_Images.htm -http://launchbase.com/Shopping/Visual_Arts/communication/shopping/Gifts.htm -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/programs/simple/music/midi/lit/lit/quizz/quizz1.html -http://home02.wxs.nl/~nash0002/amber-94.htm -http://www.redrocksports.com/sports/webSession/shopper/RR972959711-31098/store/dept-5/department/dept-5/item/52400 -http://www.redrocksports.com/sports/webSession/shopper/RR972959711-31098/store/dept-5/department/dept-5/item/52550 -http://www.redrocksports.com/sports/webSession/shopper/RR972959711-31098/store/dept-5/department/dept-5/item/50900 -http://gnu.archive.sunet.se/software/sather/ICSI_Sather/Documentation/Compiler/CompilerBrowser/shortflat-FLIST{_}.html -http://mailman.real-time.com/rte-crossfire/1992/Dec/mail1.html -http://de.nedstat.net/viewstat.asp?name=larsen -http://ftp.ring.gr.jp/archives/pc/gnu-win32/latest/man/?S=A -http://src.openresources.com/debian/src/graphics/HTML/D/S_ISSOCK.html -http://www.perotech.ch/d/securedb/html/listtopic.php?4277 -http://web.health.aol.thriveonline.oxygen.com/medical/library/article/003558res.html -http://cn.egroups.com/message/Website_Warez/346 -http://adex3.flycast.com/server/socket/127.0.0.1:2800/click/OnlineCitiesSM/OnlineCitiesInteractiveCityGuides/bd510213891 -http://ring.nii.ac.jp/pub/pack/x68/personal/calendar/ -http://www.zeal.com/Government/U_S__Government/State___Local_Governments/South_Carolina/Politics/Elections/State_wide/ -http://ftp.unina.it/pub/TeX/macros/latex209/contrib/manual/?S=A -http://www.perotech.ch/d/securedb/html/listtopic.php?5376 -http://polygraph.ircache.net:8181/lci/https_-2ssl.galaxy-net.net/jazzee/http_-2www.microsoft.com/truetype/fontpack/win.htm -http://python.konbib.nl/dutchess.ned/83/00/info-1592.html -http://www.excite.com/lifestyle/cultures_and_groups/world_cultures/regions/north_america/ethnic_communities/african_american/history/military_history/ -http://www.bluemonutain.com/engy/david/CHI1-educk.html -http://www.bluemonutain.com/engy/susie/CHI1-edaddog.html -http://cn.egroups.com/messages/childhoodepilepsy/3349 -http://cn.egroups.com/messages/childhoodepilepsy/648 -http://cn.egroups.com/messages/childhoodepilepsy/1189 -http://polygraph.ircache.net:8181/services/design/http_-2www.swnebr.net/~cambridg/http_-2www.bikininet.com/climate.htm -http://www.annuairefrancais.com/54/France/I/INTERNET/Fournisseurs-d'acces/Fournisseurs-d -http://polygraph.ircache.net:8181/http_-2www.monarchcom.net/http_-2www.netscape.com/comprod/mirror/http_-2bible.gospelcom.net/http_-2www.rehablinks.com/ptlinks.htm -http://findmail.com/message/studentdoctor/4312?source=1 -http://mediate.magicbutton.net/do/session/625624/vsid/4385/tid/4385/cid/88138/mid/1702/rid/2114/chid/3393/url/http://www.worldgallery.co.uk/frameset-cart.html -http://ring.htcn.ne.jp/archives/lang/perl/CPAN/authors/id/P/PG/?M=A -http://www.buybuddy.com/sleuth/33/1/10601/526343/ -http://www1.zdnet.com/products/stories/reviews/0,4161,2470142,00.html -http://www1.zdnet.com/companyfinder/filters/products/0,9996,2256-82,00.html -http://webcvs.kde.org/cgi-bin/cvsweb.cgi/kdeutils/ark/doc/en/Attic/index-2.html?only_with_tag=MAIN -http://tv.thevines.com/leaf/AA0000364048/45///&act=24-1-11&bref=1601 -http://link.fastpartner.com/do/session/600384/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/local/redirect.php -http://www.excite.com/lifestyle/politics_and_society/community_and_cultures/world_cultures/diaspora/jewish/judaism/congregations/humanistic_judaism/ -http://biblio.cesga.es:81/search*gag/aXove,+Xosé/axove+xose/7,-1,0,B/frameset&F=axuntanza&1,,3 -http://biblio.cesga.es:81/search*gag/aXove,+Xosé/axove+xose/7,-1,0,B/frameset&F=axuntanza&3,,3 -http://db.zaq.ne.jp/asp/bbs/jttk_baasc506_1/article/36 -http://db.zaq.ne.jp/asp/bbs/jttk_baasc506_1/article/37 -http://db.zaq.ne.jp/asp/bbs/jttk_baasc506_1/article/35 -http://db.zaq.ne.jp/asp/bbs/jttk_baasc506_1/article/21 -http://www.tiroler-adler.com/1Root/Kontinent/6/Staat/7/Bundesland/16/Ort/691/Homepage/f_homepage...1.html -http://yp.gates96.com/4/52/90/87.html -http://yp.gates96.com/4/52/90/95.html -http://yp.gates96.com/4/52/91/4.html -http://yp.gates96.com/4/52/91/39.html -http://yp.gates96.com/4/52/91/42.html -http://yp.gates96.com/4/52/92/33.html -http://yp.gates96.com/4/52/92/93.html -http://yp.gates96.com/4/52/93/6.html -http://yp.gates96.com/4/52/93/98.html -http://yp.gates96.com/4/52/94/8.html -http://yp.gates96.com/4/52/94/14.html -http://yp.gates96.com/4/52/95/92.html -http://yp.gates96.com/4/52/96/16.html -http://yp.gates96.com/4/52/96/32.html -http://yp.gates96.com/4/52/96/72.html -http://yp.gates96.com/4/52/96/90.html -http://yp.gates96.com/4/52/97/1.html -http://yp.gates96.com/4/52/97/53.html -http://yp.gates96.com/4/52/98/34.html -http://yp.gates96.com/4/52/98/84.html -http://yp.gates96.com/4/52/98/97.html -http://yp.gates96.com/4/52/99/55.html -http://yp.gates96.com/4/52/99/68.html -http://yp.gates96.com/14/40/10/3.html -http://yp.gates96.com/14/40/10/86.html -http://yp.gates96.com/14/40/11/53.html -http://yp.gates96.com/14/40/12/74.html -http://yp.gates96.com/14/40/13/11.html -http://yp.gates96.com/14/40/13/34.html -http://yp.gates96.com/14/40/13/45.html -http://yp.gates96.com/14/40/13/79.html -http://yp.gates96.com/14/40/14/3.html -http://yp.gates96.com/14/40/14/6.html -http://yp.gates96.com/14/40/14/25.html -http://yp.gates96.com/14/40/14/84.html -http://yp.gates96.com/14/40/14/88.html -http://yp.gates96.com/14/40/15/39.html -http://yp.gates96.com/14/40/15/40.html -http://yp.gates96.com/14/40/16/64.html -http://yp.gates96.com/14/40/16/92.html -http://yp.gates96.com/14/40/17/69.html -http://yp.gates96.com/14/40/18/42.html -http://yp.gates96.com/14/40/18/82.html -http://yp.gates96.com/14/40/19/36.html -http://www.4positiveimages.com/4positiveimages/727410225/IconBar -http://www.teacherformation.org/html/od/facilitators.cfm/task1,login/discussion_id,2/xid,6559/yid,6157439 -http://www.secinfo.com/dSU5m.74.htm -http://www.secinfo.com/dSU5m.7v.htm -http://www.secinfo.com/dSU5m.6y.htm -http://www.secinfo.com/dSU5m.5c.htm -http://linux.softhouse.com.cn/linux/knowledge/tech/qs/linux5.htm -http://linux.softhouse.com.cn/linux/knowledge/tech/qs/linux10.htm -http://freesoftware.subportal.com/sn/Programming/Visual_Basic_Components_H-P/993.html -http://dk.egroups.com/message/NGHILUAN/2881 -http://dk.egroups.com/message/NGHILUAN/2889 -http://www.cga.state.ct.us/ps98/cbs/H/hj-0084.htm -http://apple.excite.com/entertainment/music/artists_and_genres/jazz/new_world_jazz/afro_cuban/ -http://www.euronet.nl/users/hiroshi/ksweb/interest.htm -http://library.bangor.ac.uk/search/aMollica,+Anthony/amollica+anthony/-5,-1,0,B/browse -http://www.fogdog.com/cedroID/ssd3040183308040/nav/products/featured_brands/14t/all/ -http://www.brio.de/BRIO.catalog/39fe2f8d0912d4962740d472aa780701/UserTemplate/9 -http://www.hig.se/(accessed,autoformat,referrer,sqloutput,tablify)/~jackson/roxen/ -http://www.newstimescybermall.com/Mall/Catalog/Product/ASP/product-id/206059/store-id/1000010991.html -http://www6.163.com/news/p-item/0,1587,economy_1916,00.html -http://ftp.uni-stuttgart.de/pub/systems/sgi/graphics/lib/?D=A -http://preview.egroups.com/message/abdou3/152 -http://ch.php.net/manual/it/function.pg-loimport.php -http://yp.gates96.com/1/94/30/39.html -http://yp.gates96.com/1/94/30/78.html -http://yp.gates96.com/1/94/31/11.html -http://yp.gates96.com/1/94/31/72.html -http://yp.gates96.com/1/94/31/85.html -http://yp.gates96.com/1/94/32/25.html -http://yp.gates96.com/1/94/32/45.html -http://yp.gates96.com/1/94/32/74.html -http://yp.gates96.com/1/94/33/20.html -http://yp.gates96.com/1/94/33/68.html -http://yp.gates96.com/1/94/34/92.html -http://yp.gates96.com/1/94/35/1.html -http://yp.gates96.com/1/94/35/50.html -http://yp.gates96.com/1/94/35/60.html -http://yp.gates96.com/1/94/37/0.html -http://yp.gates96.com/1/94/37/46.html -http://yp.gates96.com/1/94/37/47.html -http://yp.gates96.com/1/94/37/61.html -http://yp.gates96.com/1/94/38/19.html -http://yp.gates96.com/1/94/39/49.html -http://yp.gates96.com/1/94/39/57.html -http://www.gartenfachmarkt.de/beratung_garten/duengen_und_kompostieren/anlage_und_vorarbeiten/fertig.htm -http://support.dell.com/docs/storage/4955r/en/Hw/setup.htm -http://www.hig.se/(clientname,header,sort,sqlquery,sqltable)/~jackson/roxen/ -http://www.mic.hr/PGBURZA:423870 -http://www.mic.hr/PGNEWS:423870 -http://members.tripod.com/Tess_Tom/my_photoalbum/page12.html -http://legalminds.lp.findlaw.com/list/courtinterp-spanish/nav05815.html -http://www.fogdog.com/cedroID/ssd3040183239698/crs/pn__/wld/fogdog_sports/pearl_izumi/road_cycling/apparel/classic_vest.html -http://www.fogdog.com/cedroID/ssd3040183239698/nav/stores/wakeboarding/ -http://troy.lib.sfu.ca/search/slogos/slogos/-5,-1,0,E/frameset&F=slogistics+and+transportation+review&1,,0 -http://themes.tucows.dia.dk/skins/icq/preview/54718.html -http://php.nic.fi/manual/html/function.shm_open.html -http://ftp.fi.debian.org/debian/dists/woody/non-free/binary-m68k/misc/?S=A -http://www.csupomona.edu/reference/java/jdk1.2/docs/api/org/omg/CORBA/class-use/CompletionStatus.html -http://www.trax.nilex.co.uk/trax.cgi/A1C/B1U/A1D/C1R/A1D/B1R/ -http://www.uni-duesseldorf.de/ftp/ftp/software/opt/cpio-2.4.2/?M=A -http://ep.com/js/about/c9079/b0/250918.html -http://polygraph.ircache.net:8181/busi/html/http_-2www.dirtsports.com/index.html-ssi -http://www.chabadlibrary.org/ecatalog/EC06/EC06232.HTM -http://chat.hani.co.kr/NetBBS/Bbs.dll/brief/lst/qqa/f/qqo/PRMY/zka/B23qB2Bm -http://209.207.239.212/bkindex/c1047/f1128.html -http://tv.thevines.com/leaf/AA0000364429/4/1 -http://tv.thevines.com/leaf/AA0000364429/4//&order_by=WORST -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=12,17,20,5,16 -http://yp.gates96.com/4/4/40/22.html -http://yp.gates96.com/4/4/40/29.html -http://yp.gates96.com/4/4/41/11.html -http://yp.gates96.com/4/4/42/0.html -http://yp.gates96.com/4/4/42/27.html -http://yp.gates96.com/4/4/42/89.html -http://yp.gates96.com/4/4/42/99.html -http://yp.gates96.com/4/4/43/40.html -http://yp.gates96.com/4/4/43/69.html -http://yp.gates96.com/4/4/43/85.html -http://yp.gates96.com/4/4/44/27.html -http://yp.gates96.com/4/4/44/28.html -http://yp.gates96.com/4/4/44/36.html -http://yp.gates96.com/4/4/44/86.html -http://yp.gates96.com/4/4/45/76.html -http://yp.gates96.com/4/4/45/82.html -http://yp.gates96.com/4/4/45/86.html -http://yp.gates96.com/4/4/46/61.html -http://yp.gates96.com/4/4/47/1.html -http://yp.gates96.com/4/4/47/41.html -http://yp.gates96.com/4/4/47/42.html -http://yp.gates96.com/4/4/48/66.html -http://people.freebsd.org/~knu/cgi-bin/cvsweb.cgi/ports/misc/geekcode/pkg-descr?only_with_tag=RELEASE_3_4_0 -http://perso.wanadoo.fr/genealogie.aubert.jm/geweb/ff100.htm -http://www.securitiestimes.com.cn/199904/29/data/newfiles/0060080.htm -http://autos.yahoo.co.jp/ucar/m1015/k10152012199906/g21/a101520120210248821003520208199906.html -http://dg.galaxy.com/galaxy/Community/United-States/States/Connecticut/Cities-and-Regions/Guilford/Education/K--12/Middle.html -http://carriage.de/Schoner/info-e/literature/collections/models/ -http://www.amcity.com/orlando/stories/1998/06/29/weekinbiz.html?t=email_story -http://www.icopyright.com/1.1655.94549 -http://biblio.cesga.es:81/search*gag/dMicrosoft+Visual+BASIC+(Archivo+de+ordenador)/dmicrosoft+visual+basic+archivo+de+ordenador/-5,1,1,B/frameset&F=dmicrosoft+project+archivo+de+ordenador&1,1, -http://www.jamba.de/KNet/_KNet-AzI8j1-tGd-13d56/browse.de/node.0/cde7f1uou -http://www.jamba.de/KNet/_KNet-AzI8j1-tGd-13d5e/browse.de/node.0/cde7f1uou -http://www.ioppublishing.com/PEL/help/article/ja30010l2/refs/?topic=refs -http://members.tripod.lycos.co.kr/uuujsh/?N=D -http://www.wlu.ca/~wwwregi/95-96/cal/ucourses/CP/CP417.html -http://books.hyperlink.co.uk/bookinfo/Essential_Papers_on_Messianic_Movements_and_Personalities_in_Jewish_History/0814779433 -http://generalstore.everdream.com/kore/catalog/Office_Supplies/Furniture_&_Accessories/File_Cabinets/Vertical/GRP-US747/product.html -http://satlink.tucows.com/winnt/adnload/54136_29678.html -http://dc.web.aol.com/myrtlebeacharea/penpals/browse.dci?cat=twenties&sort=m -http://itcareers.careercast.com/texis/it/itjs/+nwwBme4WD86e4rwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewDthDo5O5apGdtGwMaBGnDBdDaqd1DBGon5aoDqc1moDtax15oDn55amnVncdpoDta5dc1BodD5adppdGB1DoBon5aqdMpnBoBoVnaMFqtuNfIjIDzmYqwwpBme68D86eihwww5rmerdwwwBrmeZpwww/jobpage.html -http://ring.yamanashi.ac.jp/pub/linux/debian/debian-jp/dists/hamm-jp/hamm/disks-i386/current/base14-3.bin.2.0.11.2-i386 -http://www.ibm.co.jp/pc/thinkpad/pt110/look110.html -http://retailer.gocollect.com/do/session/1912720/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/postcards/index.asp -http://www-rn.informatik.uni-bremen.de/home/X11R6/xc/doc/hardcopy/XProtocol/?N=D -http://cafe3.daum.net/Cafe-bin/bbsList?bbsgrp=SIXTEEN&bbscode=SIXTEENbbs -http://allmacintosh.arrakis.es/adnload/12140.html -http://allmacintosh.arrakis.es/adnload/2476.html -http://www.msb.malmo.se/search*swe/dSkönlitteratur/dskz~cnlitteratur/-5,-1,0,B/2exact&F=dskz~cnliteratur&1,2 -http://tucows.syix.com/winme/preview/137803.html -http://pages.prodigy.net/patotoole/musicman/page6.htm -http://yp.gates96.com/14/43/0/39.html -http://yp.gates96.com/14/43/0/78.html -http://yp.gates96.com/14/43/0/79.html -http://yp.gates96.com/14/43/0/99.html -http://yp.gates96.com/14/43/1/3.html -http://yp.gates96.com/14/43/1/57.html -http://yp.gates96.com/14/43/1/86.html -http://yp.gates96.com/14/43/2/74.html -http://yp.gates96.com/14/43/2/80.html -http://yp.gates96.com/14/43/3/2.html -http://yp.gates96.com/14/43/3/97.html -http://yp.gates96.com/14/43/3/99.html -http://yp.gates96.com/14/43/4/37.html -http://yp.gates96.com/14/43/4/51.html -http://yp.gates96.com/14/43/4/72.html -http://yp.gates96.com/14/43/6/4.html -http://yp.gates96.com/14/43/7/20.html -http://yp.gates96.com/14/43/7/39.html -http://yp.gates96.com/14/43/7/45.html -http://yp.gates96.com/14/43/9/41.html -http://yp.gates96.com/14/43/9/58.html -http://yp.gates96.com/14/43/9/60.html -http://ftp.support.compaq.com/public/dunix/v3.2g/ASE_V1.3/ReleaseNotes.htm -http://seniorfriendfinder.com/cgi-bin/w3com/pws/ffsenior/mchI1k9vDw6DGJ19bljzJPwhHhJYxAcnAIKgudPEJtzjiTWMWT4U-YMr4m-AccPn7sEIqMzfFTZnQEQBZNx-lh8DEr_c1F3DXpcc4PzhALzHJ76GytRWNCSauwtfVocYmy_RKsP-H9T-UhQgoc9_uexBhD4a -http://seniorfriendfinder.com/cgi-bin/w3com/pws/ffsenior/IqtI3V1hdRxfYW_4AHOzeXZkuTzyKfveVl4qdYM_2WFldvLDKFgK8SvYa0mSlrWDVodDERGv2jvb2dEN1-mRmY3TBKURFCsqneanb8BNMBeBfqmSnBYuou5RMCmHxXCedHy3TQnL51n3TYbg5exYBWl9FJTcQEIJt2wyyrfB66jP -http://seniorfriendfinder.com/cgi-bin/w3com/pws/ffsenior/Hk1ILVbQbFwze5TrhlBima0MylJ0gTqcnVeTbMTcn7Gy5GkelYKhUQ7m8P8_K3IkOWfIWbpGOJEuHqJLX5jY_7ygFevbtkNXPvb1yztdy9qzCTsCJvS5uaHN3cZd0LtuoMX3lX7d_-L_PrwRXSfTE3TNvWl-RHiY4Xmxk1fXhD_uwwjDvC7DDsxz66j6 -http://seniorfriendfinder.com/cgi-bin/w3com/pws/ffsenior/T41IiB449vZ7nrOl2Z_klJHCHQZhigz52e9YVMztVI-K01klBYQrw4VmiKN8JDs9xaeMSWopQs1euSbr6BAiyuqpbSFiiVWObVmWHv031jtdQ1y93wnHhx8PkbrA4hkNhjTPs2mUhBF9wIAJSPCYLkf6W7mCB8ObikqLTuIwBfRtSgMK4Hz9e7Bp -http://seniorfriendfinder.com/cgi-bin/w3com/pws/ffsenior/CI1IlJNaoNrBcwJYSEcjLyxBnpQHK3wpRPeCR_0u07GznNXQ3Ug57ciOqlfXKlYM1HbRfcvrF5s214yaEHiIizneyWrbSEW_xal49NjQDbWj6R2nEZvDQdDMQEMoTuQlSetyUwMidLBmJJ5v5w9m066en6Yxuzt3RkGIyoHKaVmXgVIYD2Fc40eA -http://www.secinfo.com/dSm4r.997.htm -http://www.secinfo.com/dSm4r.68c.htm -http://www.secinfo.com/dSm4r.69c.htm -http://mirror.cc.utsunomiya-u.ac.jp/mirror/CPAN/modules/by-module/MD5/GAAS/HTML-Parser-3.04.readme -http://polygraph.ircache.net:8181/Game+Controllers/http_-2www.real-e-video.com/price-abuse.html -http://ecomonly.shop.goto.com/z/netadp/search/matches.jhtml?MANUF=Linksys -http://ecomonly.shop.goto.com/z/netadp/search/matches.jhtml?MANUF=Madge -http://freesoftware.subportal.com/sn/Web_Authoring/Misc__Programming_Tools/3100.html -http://www.sam.hi-ho.ne.jp/m-saka/stepwgn/himeji/6scene/ -http://ftp.unina.it/pub/Unix/linux/SuSE/ftp.suse.com/projects/3d/kernel/?N=D -http://www.ld.com/cbd/archive/1999/08(August)/10-Aug-1999/61awd001.htm -http://www.ld.com/cbd/archive/1999/08(August)/10-Aug-1999/61awd004.htm -http://statweb.byu.edu/sasdoc/sashtml/stat/chap2/sect5.htm -http://www.diogenes.de/4DACTION/web_rd_aut_show_authorlist/ID=483367&chr=F -http://web1.localbusiness.com/Story/Email/1,1198,RDU_461041,00.html -http://www.clientwire.com/A55697/tmr.nsf/vwApprovedResumesbyDate!OpenView&Start=55&Count=50&Collapse=48 -http://cpan.nitco.com/modules/by-module/Mail/JWIED/SNMP-Monitor-0.1011.readme -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=237&discrim=178,16,10 -http://www6.compaq.com/products/quickspecs/10135_na/10135_na.PDF -http://www.suk2.com/user/777/20001012.html -http://www.jamba.de/KNet/_KNet-vAy8j1-iFd-13az6/browse.de/node.0/cde7f2elw -http://www.imagesofengland.org.uk/41/69/416915.htm -http://ocean.ntou.edu.tw/search*chi/aLaplante,+Phillip+A./alaplante+phillip+a/7,-1,0,B/frameset&F=alappe+frances+moore&1,,2 -http://ocean.ntou.edu.tw/search*chi/aLaplante,+Phillip+A./alaplante+phillip+a/7,-1,0,B/frameset&F=alappe+frances+moore&2,,2 -http://wap.jamba.de/KNet/_KNet-6Fz8j1-oFd-13b3x/admLogin.de/node.0/cde7f1uou -http://yp.gates96.com/14/49/20/26.html -http://yp.gates96.com/14/49/20/37.html -http://yp.gates96.com/14/49/20/39.html -http://yp.gates96.com/14/49/20/86.html -http://yp.gates96.com/14/49/20/94.html -http://yp.gates96.com/14/49/20/97.html -http://yp.gates96.com/14/49/21/19.html -http://yp.gates96.com/14/49/21/43.html -http://yp.gates96.com/14/49/21/68.html -http://yp.gates96.com/14/49/21/78.html -http://yp.gates96.com/14/49/24/6.html -http://yp.gates96.com/14/49/24/62.html -http://yp.gates96.com/14/49/24/77.html -http://yp.gates96.com/14/49/24/83.html -http://yp.gates96.com/14/49/25/30.html -http://yp.gates96.com/14/49/25/41.html -http://yp.gates96.com/14/49/26/17.html -http://yp.gates96.com/14/49/26/53.html -http://yp.gates96.com/14/49/27/21.html -http://yp.gates96.com/14/49/27/27.html -http://yp.gates96.com/14/49/27/45.html -http://yp.gates96.com/14/49/27/65.html -http://yp.gates96.com/14/49/28/71.html -http://www.boston.digitalcity.com/orangecounty/entertainment/article.dci?aid=1293&start=10 -http://tucows.allnet.it/winme/adnload/143-006-005-021.html -http://tucows.allnet.it/winme/adnload/143-006-005-030.html -http://www.trax.nilex.co.uk/trax.cgi/A1C/B1U/A1D/C1R/A2D/A1U/ -http://www.crosswinds.net/~klinnia/DragonsDomain/Nest/nest.htm -http://mirrors.valueclick.com/backup.pause/modules/by-category/99_Not_In_Modulelist/Memoize/?S=A -http://www.tgw.com/EJr.5ajd/customer/category/product.html?SUBCATEGORY_ID=557 -http://www.sohu.com/business_economy/Company/Computer_Internet/Network_System/Network/ -http://china-water.51.net/oicq/oicq_down.htm -http://ftp.lip6.fr/pub/FreeBSD/development/FreeBSD-CVS/ports/math/plplot/patches/Attic/patch-ac,v -http://library.cuhk.edu.hk/search*chi/cHC427.92.C59/chc++427.92+c59/-5,-1,,E/browse -http://yp.gates96.com/4/8/60/2.html -http://yp.gates96.com/4/8/60/19.html -http://yp.gates96.com/4/8/62/9.html -http://yp.gates96.com/4/8/62/23.html -http://yp.gates96.com/4/8/62/59.html -http://yp.gates96.com/4/8/63/26.html -http://yp.gates96.com/4/8/63/41.html -http://yp.gates96.com/4/8/64/48.html -http://yp.gates96.com/4/8/65/0.html -http://yp.gates96.com/4/8/65/42.html -http://yp.gates96.com/4/8/66/13.html -http://yp.gates96.com/4/8/66/88.html -http://yp.gates96.com/4/8/67/23.html -http://yp.gates96.com/4/8/67/51.html -http://yp.gates96.com/4/8/68/11.html -http://yp.gates96.com/4/8/68/16.html -http://yp.gates96.com/4/8/68/78.html -http://www.outpersonals.com/cgi-bin/w3com/pws/out/CehIaxpSN7cGOeOUjXx_FtrylkakPWisW0DYq0MYmHwGxLBo7shB2XGSeXyvbnsBzHMJTZtmYOUK-XaaAW0Yh88wTY-Mms-hxw67Xaw8WMk3-vUJ4sXm4U7yIGdiN9XoPOqfnODrkqXYztjU6Var -http://www.brd.net/brd-cgi/brd_netzwerk?mailto&router&BZ85G0IL -http://power.luneng.com/power/library/jxgcs/jxgc99/jxgc9912/991204.htm -http://www.egroups.com/messages/Creative_Teaching/72?viscount=-30 -http://www.egroups.com/message/Creative_Teaching/85 -http://ftp.eecs.umich.edu/.1/people/elta/cusm-Javajae-elta/?D=A -http://polygraph.ircache.net:8181/cagliari/WHOWOULD.HTM -http://www.tiscover.ch/1Root/Kontinent/6/Staat/30/Bundesland/33/Ort/1564/Homepage/h_homepage...2.html -http://t-online.de/computer/haupt/intcoh87.htm -http://prodigy-sports.excite.com/ncaab/news/025uwire1 -http://wwwold.ifi.uni-klu.ac.at/Manuals/jdk1.1b3/docs/guide/awt/designspec/graphics/imagescale.html -http://www.taconet.com.tw/a6983/ -http://www.mapion.co.jp/custom/AOL/admi/13/13107/higashimukojima/3chome/index-3.html -http://www.mapion.co.jp/custom/AOL/admi/13/13107/higashimukojima/3chome/index-13.html -http://caller-times.com/autoconv/kickoff98/kickoff30.html -http://www.incestpornstories.com/bisexualbisexual/big-bonedmen/beautiesslanted-eyes/plus-sizeoverweight/{teenlink} -http://qcardsccg.safeshopper.com/8/359.htm?923 -http://qcardsccg.safeshopper.com/8/429.htm?923 -http://qcardsccg.safeshopper.com/8/433.htm?923 -http://lib1.nippon-foundation.or.jp/1997/0486/contents/011.htm -http://commerce.was-inc.com/cgi-bin/abtwsam.dll/LbkWebCommerceOrderStatusOverview-BBC709F1_97EF_F357031944376B6D965FDC23BED4C6F4 -http://in.egroups.com/subscribe/muovimallit -http://multichat.de/fp/talk/cb-funk/4.htm -http://multichat.de/fp/talk/cb-funk/5.htm -http://www.jamba.de/KNet/_KNet-zfB8j1-EFd-13bkr/browse.de/node.0/cde7f2elw -http://www.jamba.de/KNet/_KNet-zfB8j1-EFd-13bl7/showInfo-jobs.de/node.0/cenv0b09a -http://152.80.49.210/PUBLIC/WXMAP/GLOBAL/AVN/2000103000/avn.prp.00-36.swasia.htm -http://retailer.gocollect.com/do/session/1912741/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/help/site_tour/index.asp -http://retailer.gocollect.com/do/session/1912741/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/product_display/top_ten.asp?pagenum=2 -http://www.fogdog.com/cedroID/ssd3040183248168/nav/products/winter_sports/1b/shell_jackets/ -http://www.fogdog.com/cedroID/ssd3040183248168/nav/products/featured_brands/3c/all/ -http://kutschen.de/Schoner/literature/Sammlungen/modelle/collections/ -http://el-mundo.es/1999/06/04/television/04N0121.html -http://bitwise.tucows.com/win2k/htmlval2k_license.html -http://bbs.ee.ntu.edu.tw/boards/Saturn/3/7/12/5.html -http://ustlib.ust.hk/search*chi/deconomic+conditions+cameroon+to+1960/deconomic+conditions+cameroon+to+1960/-5,-1,0,B/browse -http://excite.de/kunst/katalog/865 -http://www2.hindustantimes.com/ht/nonfram/280498/detFRO07.htm -http://yp.gates96.com/11/69/0/60.html -http://yp.gates96.com/11/69/1/60.html -http://yp.gates96.com/11/69/1/72.html -http://yp.gates96.com/11/69/2/80.html -http://yp.gates96.com/11/69/3/7.html -http://yp.gates96.com/11/69/3/54.html -http://yp.gates96.com/11/69/3/66.html -http://yp.gates96.com/11/69/3/90.html -http://yp.gates96.com/11/69/3/91.html -http://yp.gates96.com/11/69/4/13.html -http://yp.gates96.com/11/69/4/18.html -http://yp.gates96.com/11/69/4/26.html -http://yp.gates96.com/11/69/4/70.html -http://yp.gates96.com/11/69/5/45.html -http://yp.gates96.com/11/69/5/77.html -http://yp.gates96.com/11/69/6/10.html -http://yp.gates96.com/11/69/6/80.html -http://yp.gates96.com/11/69/7/43.html -http://yp.gates96.com/11/69/7/76.html -http://yp.gates96.com/11/69/8/17.html -http://yp.gates96.com/11/69/8/33.html -http://yp.gates96.com/11/69/8/98.html -http://yp.gates96.com/11/69/9/3.html -http://yp.gates96.com/11/69/9/41.html -http://yp.gates96.com/11/69/9/92.html -http://store.peoplestour.com/kore/catalog/Music/R&B/G_by_artist/104757/product.html -http://free.prohosting.com/~seikyo/speak2.htm -http://pub.chinaccm.com/12/news/200009/16/160724.asp -http://pub.chinaccm.com/12/news/200008/11/155448.asp -http://www.fogdog.com/cedroID/ssd3040183305379/nav/products/featured_brands/12r/spa_products/ -http://itcareers.careercast.com/texis/it/itjs/+EwwBmev6D86ebtwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewGtmoBGnaqdGpdGwBodDacnwmaADdicnmtnaMwDwtnMnDBanDtoDnnGaMw55wqr15nBB5aqwpB1GnaoDhdGMwBodDaBnqrDdcdton5aMFqhTfR20DzmewrwwwpBmGeP0-dmwww5rmeNDwwwBrmeZpwww/jobpage.html -http://www.outdoorwire.com/content/lists/dirt/200004/msg00354.html?{LoadingFrameset} -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=5&discrim=186,22,8 -http://www.teleparc.com/sports/funski/02/03.htm -http://cn.egroups.com/post/safrica_bridge?act=reply&messageNum=43 -http://www.dfae.diplomatie.gouv.fr/culture/france/cinema/documentaires/recherche/francais/ethique.html -http://ring.toyama-ix.net/archives/mac/info-mac/_Communication/ctb/?D=A -http://www.eveclub.com/cgi-bin/eveclub.front/972959528284/Catalog/11000155 -http://www.eveclub.com/cgi-bin/eveclub.front/972959528284/Catalog/2000019 -http://cometweb01.comet.co.uk/do!session=132005&vsid=700&tid=20&cid=37030&mid=1000&rid=1060&chid=1713&url=eqqLmwlGltt5tkZHljbLqkZHlkrHhlZHdfjKYfkLlkZ5ljjLboZLbplG5ubLZDXLZolLl3l5jbqLljX5fkkKaotHlob5mloLq1 -http://cometweb01.comet.co.uk/do!session=132005&vsid=700&tid=20&cid=37030&mid=1000&rid=1060&chid=1713&url=eqqLmwlGltt5tkZHljbLqkZHlkrHhlZHdfjKYfkLlkZ5ljjLboZLbplG3XqLbdlLov4LfpmLiXvL-Zd5jbkLYozKvot0cZd5ockLYozKvsm0uts0cZX5qkXLjbzKKbiLbsfLpflLkp5 -http://www.ualberta.ca/CNS/RESEARCH/Software/SAS/cms/zfor-hex.htm -http://www.ualberta.ca/CNS/RESEARCH/Software/SAS/os390/zlibname.htm -http://genforum.genealogy.com/cgi-bin/print.cgi?hanrahan::175.html -http://library.bangor.ac.uk/search/dAIDS+(Disease)+--+Risk+factors+--+Psychological+aspects+--+Periodicals/daids+disease+risk+factors+psychological+aspects+periodicals/-5,1,1,B/frameset&F=daids+disease+research&1,1, -http://www.rismedia.com/consumer/27/12194/ -http://www.hole.kommune.no/hole/journweb.nsf/weboffjournal!OpenView&Start=39&Count=50&Expand=38 -http://www.etoys.com/prod/toy/53097261 -http://www.outpersonals.com/cgi-bin/w3com/pws/out/J6tI5danl1CaEvxOmyBVl8pzyaGqhs1RWIGq0aJ2_fwvzv4y9T7bHlxQKPzsrhMRN5HEI_Y9ZKrSvboCZvKhdwPPYK2klPp0EqNMO7Mb8fDTcz6xykQv8YQCQ2dy_iLZjbXwrknXqcH32HVSXAq7iUr4yIVG66IK -http://www.amcity.com/jacksonville/stories/1999/11/22/daily16.html?t=printable -http://moviestore.zap2it.com/browse/MOVIES/BOXERSHO/s.F0FWmEHm -http://moviestore.zap2it.com/browse/MOVIES/SHIRT/s.F0FWmEHm -http://moviestore.zap2it.com/browse/MOVIES/TIE/s.F0FWmEHm -http://moviestore.zap2it.com/browse/MOVIES/WATCH/s.F0FWmEHm -http://yp.gates96.com/11/25/30/0.html -http://yp.gates96.com/11/25/30/47.html -http://yp.gates96.com/11/25/31/87.html -http://yp.gates96.com/11/25/32/3.html -http://yp.gates96.com/11/25/32/61.html -http://yp.gates96.com/11/25/32/97.html -http://yp.gates96.com/11/25/33/6.html -http://yp.gates96.com/11/25/33/81.html -http://yp.gates96.com/11/25/33/83.html -http://yp.gates96.com/11/25/34/10.html -http://yp.gates96.com/11/25/34/35.html -http://yp.gates96.com/11/25/34/88.html -http://yp.gates96.com/11/25/34/90.html -http://yp.gates96.com/11/25/35/95.html -http://yp.gates96.com/11/25/36/19.html -http://yp.gates96.com/11/25/36/98.html -http://yp.gates96.com/11/25/37/61.html -http://yp.gates96.com/11/25/37/74.html -http://yp.gates96.com/11/25/38/2.html -http://yp.gates96.com/11/25/38/62.html -http://yp.gates96.com/11/25/39/1.html -http://yp.gates96.com/11/25/39/25.html -http://yp.gates96.com/11/25/39/85.html -http://yp.gates96.com/11/25/39/95.html -http://www.linux.com/networking/network/industry/server/community/Red_Hat/ -http://www.linux.com/networking/network/industry/server/community/Slashdot/ -http://www.linux.com/networking/network/industry/server/community/growth/ -http://mirror.cc.utsunomiya-u.ac.jp/mirror/CPAN/modules/by-category/16_Server_and_Daemon_Utilities/Server/DRUOSO/Server-FastPL-1.0.0.readme -http://ftp.nacamar.de/pub/NetBSD/NetBSD-current/pkgsrc/parallel/clusterit/pkg/DESCR -http://dk.egroups.com/login.cgi?login_target=%2Fgroup%2FGravesrus -http://www.maxfunds.com/MF1000.nsf/FUNDanalysisPrint/FGOAX -http://www.gbnf.com/genealog2/brothers/html/d0065/I12666.HTM -http://office.net/benelux/nld/downloadcatalog/dldpowerpoint.asp -http://yam.com/en/rand/ent/music/minfo/ -http://kernel2.adver.com.tw/Counter/log/kernel2.adver.com.tw/Collect_DB_Advers2/2000-09-28/23/?N=D -http://www.arm.com/sitearchitek/support.ns4/html/cores_faq!OpenDocument&ExpandSection=22,11,35 -http://dk.egroups.com/messages/lafz/6 -http://www.online.kokusai.co.jp/Words/V0043555/wrd/G700/words/kana_main.html -http://adelaida.net/music/texts/pink75.html -http://support.tandy.com/support_audio/doc40/40914.htm -http://www.nutritionblvd.com/426162.html -http://www.nutritionblvd.com/426121.html -http://www.nutritionblvd.com/426117.html -http://www.fogdog.com/cedroID/ssd3040183301450/boutique/aaron_chang/ -http://www.fogdog.com/cedroID/ssd3040183301450/boutique/moving_comfort/ -http://www.fogdog.com/cedroID/ssd3040183301450/fly/ -http://in.egroups.com/login.cgi?login_target=%2Fmessage%2Finfogiappone%2F81 -http://in.egroups.com/post/infogiappone?act=reply&messageNum=81 -http://cn.egroups.com/message/1800list/5416 -http://smb.slac.stanford.edu/cgi-bin/nph-proxy.cgi/000/http/www.slac.stanford.edu/grp/arb/tn/arbvol1/ARDB011.pdf -http://crrstv.tucows.com/winnt/adnload/135146_46908.html -http://syix.tucows.com/win2k/adnload/61785_28334.html -http://ftp.ccu.edu.tw/pub/language/tcl/sorted/packages-7.6/sound/xmpeg_0.5/ -http://www.eos.ncsu.edu/linux/LDP/LDP/khg/HyperNews/get/fs/fs/3.html -http://polygraph.ircache.net:8181/http_-2www.tvguide.com/sports/football/http_-2home.netscape.com/http_-2www.premaonline.com/http_-2www.ionet.net/~burndragon/form1.html -http://se.egroups.com/group/MyLuminaGoezBoom -http://www.diogenes.ch/4DACTION/web_rd_aut_show_author/a_id=7056553&tmpl=AUT_00&ID=483371 -http://www3.newstimes.com/archive97/apr0497/tvg.htm -http://dic.empas.com/show.tsp/?q=edger&f=B -http://www.brio.de/BRIO.catalog/39fe2f570905fb6a2740d472aa7806aa/UserTemplate/2 -http://itcareers.careercast.com/texis/it/itjs/+uwwBme7WD86eYtwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewGtmoBGnaqdGpdGwBodDaoDhdGMwBodDa5nq1GoBOanDtoDnnGaiw5roDtBdDanDBnGpGo5naGn31oGnmawGqroBnqB1Gna5O5BnM5aMFqhTfR20DzmehrwwwpBmeZWD86Nwww5rmekdwwwBrmeZpwww/jobpage.html -http://itcareers.careercast.com/texis/it/itjs/+pwwBmet5986twwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewGtmoBGnaqdGpdGwBodDaoDhdGMwBodDa5nq1GoBOanDtoDnnGaiw5roDtBdDanDBnGpGo5naGn31oGnmawGqroBnqB1Gna5O5BnM5aMFqhTfR20DzmehrwwwpBmeZWD86Nwww5rmekdwwwBrmeZpwww/morelike.html -http://biblioteca.upv.es/bib/doc/doc_fisbd/180/132317//C/1825784/0////25/S/MLTPAI -http://www.stanford.edu/~sevls/files/?M=D -http://library.bangor.ac.uk/search/dSystem+analysis+--+Periodicals/dsystem+analysis+periodicals/-17,-1,0,B/browse -http://mirror.ox.ac.uk/Mirrors/ftp.redhat.com/roughcuts/m68k/misc/src/install/pci-probing/CVS/ -http://yp.gates96.com/0/13/10/17.html -http://yp.gates96.com/0/13/11/26.html -http://yp.gates96.com/0/13/12/20.html -http://yp.gates96.com/0/13/12/24.html -http://yp.gates96.com/0/13/12/49.html -http://yp.gates96.com/0/13/13/22.html -http://yp.gates96.com/0/13/13/80.html -http://yp.gates96.com/0/13/15/8.html -http://yp.gates96.com/0/13/16/4.html -http://yp.gates96.com/0/13/16/18.html -http://yp.gates96.com/0/13/16/64.html -http://yp.gates96.com/0/13/17/15.html -http://yp.gates96.com/0/13/18/11.html -http://yp.gates96.com/0/13/18/18.html -http://yp.gates96.com/0/13/19/5.html -http://yp.gates96.com/0/13/19/22.html -http://yp.gates96.com/0/13/19/60.html -http://library.cuhk.edu.hk/search*chi/aYen-shou,+Shih,+904-975./ayen+shou+shih++904++975/-5,-1,0,E/2browse -http://china.sydney2000.com/StaticNews/2000-07-29/News372a86.htm -http://www.fujian-window.com/Fujian_w/news/mzrb1/20000724/3_1.html -http://www.fujian-window.com/Fujian_w/news/mzrb1/20000724/3_2.html -http://legalminds.lp.findlaw.com/list/law-lib/nav07807.html -http://ftp.fi.debian.org/debian/dists/woody/contrib/binary-sparc/tex/?N=D -http://community.webshots.com/photo/3635718/3636284GcTotmmONR -http://www.power2lead.com/Global/English.nsf/pgWWLocations!OpenPage&ExpandSection=23,24,25,17,10 -http://spaindustry.com/por/exp/911.html -http://niagara.tucows.com/winme/preview/10464.html -http://niagara.tucows.com/winme/adnload/138750_30032.html -http://niagara.tucows.com/winme/adnload/138743_30025.html -http://niagara.tucows.com/winme/adnload/138740_30023.html -http://retailer.gocollect.com/do/session/1912780/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/product_display/advanced_search.asp -http://preview.egroups.com/messages/UKMatrix -http://fi.egroups.com/login.cgi?login_target=%2Fmessage%2Fhecates_news%2F21 -http://pub.chinaccm.com/02/news/200005/31/133146.asp -http://pub.chinaccm.com/02/news/200005/31/133212.asp -http://localhost/test, -http://kuyper.calvin.edu/fathers2/ANF-02/anf02-25.htm -http://kuyper.calvin.edu/fathers2/ANF-02/anf02-56.htm -http://totalsports.aol.com/stats/bbo/mlb/mlb/990910.cle.AT.cws.box.html -http://totalsports.aol.com/stats/bbo/mlb/mlb/990915.nym.AT.col.box.html -http://totalsports.aol.com/stats/bbo/mlb/mlb/990919.cws.AT.tor.box.html -http://totalsports.aol.com/stats/bbo/mlb/mlb/990926.hou.AT.mil.box.html -http://totalsports.aol.com/stats/bbo/mlb/mlb/991003.nyy.AT.tam.box.html -http://totalsports.aol.com/stats/bbo/mlb/mlb/991006.bos.AT.cle.box.html -http://totalsports.aol.com/stats/bbo/mlb/mlb/ALscores.html -http://totalsports.aol.com/stats/bbo/mlb/mlb/CAT.ROS.pit.html -http://totalsports.aol.com/stats/bbo/mlb/mlb/NYY.CLE.pit.html -http://totalsports.aol.com/stats/bbo/mlb/mlb/mlb.ARI.recap.html -http://totalsports.aol.com/stats/bbo/mlb/mlb/mlb.atl.vs.hou.stat.html -http://www.jpc-music.com/2241771.htm -http://sunsite.org.uk/packages/TeX/uk-tex/macros/latex/contrib/supported/europs/?M=A -http://mitglied.tripod.de/blueblood/forum.html -http://kuyper.calvin.edu/fathers2/NPNF1-06/npnf1-06-92.htm -http://garbage.sonicnet.com/classical/features/Thomas,_Tilson/060500/index04.jhtml -http://dk.egroups.com/post/danish?act=forward&messageNum=6 -http://www.bornloser.com/comics/peanuts/f_profiles/html/f4b1.html -http://www.online.kokusai.co.jp/Home/V0043517/wrd/G100/ -http://www.affiliate.hpstore.hp.co.uk/do/session/380823/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.france.hp.com/Main/acheterhp/ -http://www.bemi-immobilien.de/Landhaus-Bordeaux/Gemeinsam/versicherungen/lebensversicherung/Gemeinsam/Startseite/Top-Darlehens-Konditionen/Gemeinsam/erreichenPartner/email3d.htm -http://sunsite.org.uk/public/pub/Mirrors/ftp.hpc.uh.edu/pub/?D=A -http://genforum.genealogy.com/cgi-bin/print.cgi?tillery::418.html -http://ring.omp.ad.jp/archives/lang/perl/CPAN/authors/id/MSCHWARTZ/?M=A -http://montxsuz.all-hotels.com/usa/massachusetts/plymouth_e1.htm -http://montxsuz.all-hotels.com/usa/massachusetts/brewster_e1.htm -http://montxsuz.all-hotels.com/usa/massachusetts/edgartown_e1.htm -http://montxsuz.all-hotels.com/usa/massachusetts/north_dartmouth_e1.htm -http://montxsuz.all-hotels.com/usa/massachusetts/washington_e1.htm -http://romeo.univ-savoie.fr/winnt/adnload/51179_28892.html -http://www.dispatch.co.za/1998/12/02/sport/FALDO.HTM -http://www.dispatch.co.za/1998/12/02/sport/RACE2.HTM -http://store1.europe.yahoo.com/brink2/2000074707407.html -http://www34.yahoo.co.jp/horse/1999/tokyo/0530/result_08.html -http://members.tripod.co.jp/suiha_izumi/gallery-taikoubou-.htm -http://linuxberg.vol.at/gnomehtml/adnload/020-008-002-004_6145.html -http://books.hyperlink.com/bookdetails/Nuclear_Power_Plants_Worldwide/0810388804 -http://www.hudecek.de/gen/gen57.htm -http://www.hudecek.de/gen/gen61.htm -http://unofficial.capital.edu/students/kralph/ -http://web6.peopledaily.com.cn/gjjrb/200004/home.htm -http://www.gov.hk/hkma/eng/public/sccr/toc.htm -http://www4.50megs.com/johnphil29/86week3injury.htm -http://www4.50megs.com/johnphil29/86week3loupitlog.htm -http://naver22.juniornaver.co.kr/Entertainment_and_Arts/Performing_Arts/Theater/Musical/ -http://198.103.152.100/search*frc/dInfrastructure+(Economics)+--+Canada/dinfrastructure+economics+canada/-5,-1,0,B/frameset&F=dinfrastructure+economics&3,,0 -http://198.103.152.100/search*frc/dInfrastructure+(Economics)+--+Canada/dinfrastructure+economics+canada/-5,-1,0,B/frameset&F=dinfrastructure+economics&5,,0 -http://www.playgirl.dk/oncampus/feature/collegemovies/06.html -http://www.linux.com/networking/support/red_hat/internet/consumer/growth/ -http://www.linux.com/networking/support/red_hat/internet/consumer/mainstream/ -http://no.egroups.com/message/tengu-l/224 -http://no.egroups.com/message/tengu-l/229 -http://oss.sgi.com/cgi-bin/cvsweb.cgi/linux-2.3-4/linux/Documentation/filesystems/romfs.txt?only_with_tag=LINUX-2_3_24 -http://oss.sgi.com/cgi-bin/cvsweb.cgi/linux-2.3-4/linux/Documentation/filesystems/romfs.txt?only_with_tag=LINUX-2_3_22 -http://oss.sgi.com/cgi-bin/cvsweb.cgi/linux-2.3-4/linux/Documentation/filesystems/romfs.txt?only_with_tag=LINUX-2_3_16 -http://sunsite.informatik.rwth-aachen.de/LinuxArchives/slackware/slackware/source/a/e2fsprog/?M=A -http://bbs.syu.ac.kr/NetBBS/Bbs.dll/ipspds018/lst/qqa/f/qqo/008A/zka/B2-kB2-p -http://stulchik.list.ru/catalog/13346.html -http://katalog.wp.pl/www/Biznes_i_Ekonomia/Firmy_Podzial_wg_Branz/Elektrotechnika_i_Energetyka/index25.html -http://www.fogdog.com/cedroID/ssd3040183313356/nav/stores/tennis/ -http://www.fogdog.com/cedroID/ssd3040183313356/customer_service/shop_by_catalog.html -http://193.207.57.3/cgi-win/hiweb.exe/a2/d13/b4,4,1f,4,4,, -http://ring.omp.ad.jp/archives/lang/perl/CPAN/modules/by-authors/id/JPRIT/Envy-2.45.readme -http://193.207.57.3/cgi-win/hiweb.exe/a2/d1342/b4,4,1f,e,e,, -http://library.wuhee.edu.cn/dzsy/military/china/army/002.htm -http://library.wuhee.edu.cn/dzsy/military/china/army/006.htm -http://library.wuhee.edu.cn/dzsy/military/china/army/059.htm -http://library.wuhee.edu.cn/dzsy/military/china/army/095.htm -http://polygraph.ircache.net:8181/http_-2www.geocities.com/TimesSquare/Maze/2075/http_-2www.yahoo.com/Science/Engineering/Mechanical_Engineering/corporate.htm -http://198.103.152.100/search*frc/aGundavaram,+Shishir/agundavaram+shishir/-17,-1,0,B/frameset&F=aguirdham+maureen&1,1 -http://findmail.com/message/geewhiz/21 -http://sound-dist.secured.co.uk/cgi-bin/psProdDet.cgi/19P02|972959597|Luggage|user|0|1,0,0,1 -http://sound-dist.secured.co.uk/cgi-bin/psShop.cgi/add|19P03|972959597|Luggage|user|0|1,0,0,1 -http://nme.com/AST/Discussion_Groups/CDA/Message_Search/1,1105,37_92-0-0-7,00.html -http://namviet.subportal.com/sn/Programming/Visual_Basic_Components_H-P/5638.html -http://www2.so-net.ne.jp/cinet/board/log/200001/messages/4963.html -http://www2.so-net.ne.jp/cinet/board/log/200001/messages/4810.html -http://www2.so-net.ne.jp/cinet/board/log/200001/messages/4735.html -http://www2.so-net.ne.jp/cinet/board/log/200001/messages/3294.html -http://www2.so-net.ne.jp/cinet/board/log/200001/messages/3329.html -http://www2.so-net.ne.jp/cinet/board/log/200001/messages/4689.html -http://www2.so-net.ne.jp/cinet/board/log/200001/messages/4646.html -http://www2.so-net.ne.jp/cinet/board/log/200001/messages/4582.html -http://www2.so-net.ne.jp/cinet/board/log/200001/messages/4587.html -http://www2.so-net.ne.jp/cinet/board/log/200001/messages/4154.html -http://www2.so-net.ne.jp/cinet/board/log/200001/messages/4607.html -http://www2.so-net.ne.jp/cinet/board/log/200001/messages/4600.html -http://www2.so-net.ne.jp/cinet/board/log/200001/messages/4571.html -http://www.gotocity.com/local/2/us/KS/g/67455/shopping/ -http://www.mapion.co.jp/custom/AOL/admi/13/13115/ogikubo/1chome/index-1.html -http://www.mapion.co.jp/custom/AOL/admi/13/13115/ogikubo/1chome/index-21.html -http://neuro-www.mgh.harvard.edu/forum_2/ChronicPainF/Capornottocapthatisthe.html -http://www.yagoo.co.kr/stats/pitching.asp?Mlbmanid=MIGDEL7299 -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=50&discrim=165,233,7 -http://www.mirror.edu.cn/res/sunsite/pub/academic/literature/book-reviews/1994/8-August/?N=D -http://www.ferien-immobilien.de/ungarn/verkauf/Versteigerungen-IB/Startseite/Allgemeine-IB/Gemeinsam/versicherungen/gebaeude/Gemeinsam/vertriebspartner.htm -http://www.ferien-immobilien.de/ungarn/verkauf/Versteigerungen-IB/Startseite/Allgemeine-IB/Gemeinsam/versicherungen/gebaeude/Gemeinsam/feedback.html -http://www.bjd.com.cn/BJWB/20000401/GB/BJWB^10199^1^01W136.htm -http://pluto.beseen.com/boardroom/u/49766/ -http://amadeus.siba.fi/doc/bitchx/documentation/color.txt -http://www.ealingcommon.londonengland.co.uk/pensions.htm -http://pub8.ezboard.com/fthecriticalpoetsmessageboartheartofcritiquing.showMessage?topicID=11.topic&index=13 -http://pub8.ezboard.com/fthecriticalpoetsmessageboareverythingelse.showMessage?topicID=223.topic&index=10 -http://www.endocrine.ru/Meln_09_10_00/_vti_bin/shtml.exe/meln_post.htm?79 -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=9,0+9,3-12,0+18,0 -http://www.jobvillage.com/channel/jobs/media_communication/b.9255.g.1733.html -http://www.teenplatinum.com/barelylegal/no-boundarieshardcore/flashingbarely-legal/sweatingendurance/cuntamateur/chinesepetite/bootygay-bar/lubricationfellatio.html -http://www.babyheirlooms.com/catalog/htmlos.cat/001222.1.5246799112 -http://src.openresources.com/debian/src/utils/HTML/R/change_cur_jutil.html -http://genforum.genealogy.com/caudill/messages/389.html -http://www.allkorea.co.jp/cgi-bin/allkorea.front/972959928076/Catalog/1000003 -http://www.allkorea.co.jp/cgi-bin/allkorea.front/972959928076/ContentView/1000188/1/1201981 -http://www.marketingtool.com/contribute/webfirm/b.435.r.2416.html -http://dell.excite.co.jp/member_encounters/mailing_list/ml_for_women -http://www.angeredsgymn.se/doc/sdb/en/html/keylist.SIGNSET.html -http://map.ipc.co.jp/asp/onmap/r/new/g-27/f-525628/ -http://www.jpc-music.com/2549026.htm -http://www.egroups.com/message/nandscarolina/324?source=1 -http://www.jpc-music.com/2226499.htm -http://www.jpc-music.com/2226480.htm -http://tucows.bigskysoft.com/winnt/miscaudiont_rating.html -http://tucows.bigskysoft.com/winnt/adnload/69355_28370.html -http://www.hole.kommune.no/hole/journweb.nsf/weboffjournal!OpenView&Start=115.23&Count=50&Expand=130 -http://personal.atl.bellsouth.net/mia/a/j/ajcubas/ -http://yp.gates96.com/7/49/21/96.html -http://yp.gates96.com/7/49/22/39.html -http://yp.gates96.com/7/49/22/60.html -http://yp.gates96.com/7/49/22/70.html -http://yp.gates96.com/7/49/22/75.html -http://yp.gates96.com/7/49/23/8.html -http://yp.gates96.com/7/49/23/30.html -http://yp.gates96.com/7/49/23/43.html -http://yp.gates96.com/7/49/24/7.html -http://yp.gates96.com/7/49/24/8.html -http://yp.gates96.com/7/49/24/27.html -http://yp.gates96.com/7/49/24/49.html -http://yp.gates96.com/7/49/25/92.html -http://yp.gates96.com/7/49/26/56.html -http://yp.gates96.com/7/49/26/77.html -http://yp.gates96.com/7/49/28/23.html -http://yp.gates96.com/7/49/28/34.html -http://yp.gates96.com/7/49/29/56.html -http://yp.gates96.com/7/49/29/60.html -http://sound-dist.secured.co.uk/cgi-bin/psShop.cgi/add|38P08B|972959501|Communications|user|0|1,0,0,1 -http://193.207.57.3/cgi-win/hiweb.exe/a2/d170/b9,4,1f,1c,1c,, -http://wuarchive.wustl.edu/systems/linux/replay/debian/dists/unstable/non-US/binary-hurd-i386/?M=D -http://www.private-immobilien-boerse.de/friesland/verkauf/Ferien-IB/Startseite/Gemeinsam/MarketingStrategie/Allgemeine-IB/Startseite/Exklusiv-IB/Startseite/ -http://citeseer.nj.nec.com/update/269184 -http://citeseer.nj.nec.com/cidcontext/3266491 -http://citeseer.nj.nec.com/cidcontext/3266502 -http://genforum.genealogy.com/cgi-genforum/forums/hinkle.cgi?786 -http://eagle.synet.edu.cn/mirror/www.wisc.edu/grad/catalog/cals/biometry.html -http://cisne.sim.ucm.es/search*spi/cCDR7(035)TRA/ccdr7(035)tra/-5,-1,0,B/frameset&F=ccdr7(058)may&1,1 -http://www.wfg-rhein-lahn.de/goldenes-fass/schrott2.htm -http://www.jamba.nl/KNet/_KNet-6Aw8j1-pC4-ptt0/browse.nl/node.0/cdn40t70v -http://www.dcc.ufmg.br/Entnet/estrem/tsld018.htm -http://sites.uol.com.br/knaumann/DorstnerDrahtwerke.html -http://64.209.212.162/learnlots/step/0,2891,9+47+95+23413+12412_0,00.html -http://www.on-semiconductor.com/pub/prod/0,1824,productsm_ProductSummary_BasePartNumber=LM337A,00.html -http://jxi.gov.cn/yw-gn001.nsf/view!OpenView&Start=39.19&Count=30&Expand=53 -http://systemlogic.neoseeker.com/Games/Products/PC/dropship/dropship_reviews.html -http://link.fastpartner.com/do/session/600373/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/smartguy.php -http://www.bsv.ch/ch/d/sr/0_211_222_1/a10.html -http://smb.slac.stanford.edu/cgi-bin/nph-proxy.cgi/000/http/contact.netscape.com/contact -http://smb.slac.stanford.edu/cgi-bin/nph-proxy.cgi/000/http/entertainment.netscape.com/entertainment/ -http://smb.slac.stanford.edu/cgi-bin/nph-proxy.cgi/000/http/games.netscape.com/computing/games/features/ -http://smb.slac.stanford.edu/cgi-bin/nph-proxy.cgi/000/http/home.netscape.com/finance/taxes/ -http://link.fastpartner.com/do/session/600379/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/brleksaker.php -http://itcareers.careercast.com/texis/it/itjs/+TwwBmeOWD86eDhwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewPXwotoBwcaqconDBahoDwDqnaqddGmoDwBdGaqdMpwDon5aBnwMax1mtnBoDtaMwoDBnDwDqnapGdqn55n5aGn51MnaMFqryfHfREIDzmUwwwpBme+9D86Exww5rme7dwwwBrmeZpwww/jobpage.html -http://fi.egroups.com/message/handebol_aaagm/5?source=1 -http://www.crutchfield.com/cgi-bin/S-SHC3792E7De/viewcart.asp -http://www.links2go.org/more/www.asle.umn.edu/ -http://yp.gates96.com/7/69/10/58.html -http://yp.gates96.com/7/69/10/64.html -http://yp.gates96.com/7/69/10/76.html -http://yp.gates96.com/7/69/10/91.html -http://yp.gates96.com/7/69/11/31.html -http://yp.gates96.com/7/69/11/67.html -http://yp.gates96.com/7/69/11/70.html -http://yp.gates96.com/7/69/11/88.html -http://yp.gates96.com/7/69/11/96.html -http://yp.gates96.com/7/69/12/25.html -http://yp.gates96.com/7/69/12/29.html -http://yp.gates96.com/7/69/12/61.html -http://yp.gates96.com/7/69/12/65.html -http://yp.gates96.com/7/69/12/73.html -http://yp.gates96.com/7/69/13/30.html -http://yp.gates96.com/7/69/13/36.html -http://yp.gates96.com/7/69/14/8.html -http://yp.gates96.com/7/69/14/32.html -http://yp.gates96.com/7/69/14/54.html -http://yp.gates96.com/7/69/14/62.html -http://yp.gates96.com/7/69/14/83.html -http://yp.gates96.com/7/69/15/34.html -http://yp.gates96.com/7/69/15/87.html -http://yp.gates96.com/7/69/16/18.html -http://yp.gates96.com/7/69/17/5.html -http://yp.gates96.com/7/69/17/22.html -http://yp.gates96.com/7/69/17/44.html -http://yp.gates96.com/7/69/17/86.html -http://yp.gates96.com/7/69/17/88.html -http://yp.gates96.com/7/69/18/16.html -http://yp.gates96.com/7/69/18/83.html -http://yp.gates96.com/7/69/18/88.html -http://yp.gates96.com/7/69/19/0.html -http://yp.gates96.com/7/69/19/1.html -http://yp.gates96.com/7/69/19/97.html -http://213.36.119.69/do/session/152995/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/FR/jeux/jeux_himalaya.html -http://www.egroups.com/post/sikhstudent?act=forward&messageNum=77 -http://ca.yahoo.com/Regional/U_S__States/Wisconsin/Metropolitan_Areas/Milwaukee_Metro/Business_and_Shopping/Shopping_and_Services/Food_and_Drink/Beverages/ -http://www.aelita.net/products/services/library/~archive/Download_redirect/company/news/default.htm -http://mindex.tucows.com/winme/preview/430.html -http://coda.nctu.edu.tw/vendors/DBMaker/DBMaker/driver/PHP/?S=A -http://www.streetprices.com/Electronics/Computer_Hardware_PC/Switches/Monitor/MAKE+BELKIN+COMPONENTS/sortproductbydesc/SP151043.html -http://wynnsystems.com/y9I_5aVd/careerlink.html -http://www.volny.cz/alik/akordy/zizen.htm -http://www.houses-apartment-listings.com/Michigan/city_search_criteria.asp?state=MI&City=CHAMPION -http://pub9.ezboard.com/fpyro1394pyro1394.showAddReplyScreenFromWeb?topicID=345.topic -http://www.maastrek.de/maas/01851471b455eff5cd01/1/0/1 -http://beta.mkn.co.uk/wine/order/champ2?what-mnw9=1 -http://beta.mkn.co.uk/wine/order/champ2?what-mnw14=1 -http://sunsite.org.uk/public/pub/packages/andrew/auis-6.3/overhead/ -http://www.ferien-immobilien.de/Spanien/Verkauf/GmbH-Kauf-Verkauf-Insolvenz-konkurs/Startseite/Gemeinsam/Exklusiv-IB/Startseite/Gemeinsam/geschaeftsbedingungen.htm -http://www.trax.nilex.co.uk/trax.cgi/A1S/A2S/A3S/1AL/A2D/A1S/ -http://www.trax.nilex.co.uk/trax.cgi/A1S/A2S/A3S/1AL/A2D/C2S/ -http://tv.thevines.com/leaf/AA0000369148/3/1 -http://tv.thevines.com/leaf/AA0000369148/37/0/&favorite[join]=yes -http://www.centc251.org/forums/aca-1/dispatch.cgi/isowg4/showFolder/100001/1304571 -http://freebsd.ntu.edu.tw/perl/modules/by-module/FileCache/ILYAZ/?D=A -http://www.highwired.net/Sport/Player/0,2291,2037-46698,00.html -http://www.nl.sco.com/unixware/adminguide/qs-11-32.html -http://www.online.kokusai.co.jp/Service/V0043502/wrd/G200/service/service.html -http://www.realize.com/ambe7581.htm,qt=e784fe2f=2a38a234-14-26557ed-80000000-0-0-3-- -http://www.realize.com/am9a7d81.htm,qt=e784fe2f=2a38a234-14-26557ed-80000000-0-0-3-- -http://www.geocities.co.jp/Colosseum/7952/dragon3.html -http://uk.dir.clubs.yahoo.com/Entertainment___Arts/Magic/~other/~White_Pages/2.html -http://yp.gates96.com/13/9/60/95.html -http://yp.gates96.com/13/9/60/97.html -http://yp.gates96.com/13/9/61/12.html -http://yp.gates96.com/13/9/61/42.html -http://yp.gates96.com/13/9/61/52.html -http://yp.gates96.com/13/9/62/13.html -http://yp.gates96.com/13/9/62/19.html -http://yp.gates96.com/13/9/62/32.html -http://yp.gates96.com/13/9/62/44.html -http://yp.gates96.com/13/9/62/75.html -http://yp.gates96.com/13/9/63/71.html -http://yp.gates96.com/13/9/63/89.html -http://yp.gates96.com/13/9/64/16.html -http://yp.gates96.com/13/9/64/64.html -http://yp.gates96.com/13/9/64/83.html -http://yp.gates96.com/13/9/65/15.html -http://yp.gates96.com/13/9/65/39.html -http://yp.gates96.com/13/9/65/81.html -http://yp.gates96.com/13/9/66/19.html -http://yp.gates96.com/13/9/66/51.html -http://yp.gates96.com/13/9/67/72.html -http://yp.gates96.com/13/9/67/75.html -http://yp.gates96.com/13/9/67/93.html -http://yp.gates96.com/13/9/67/94.html -http://yp.gates96.com/13/9/68/9.html -http://yp.gates96.com/13/9/68/14.html -http://yp.gates96.com/13/9/68/23.html -http://yp.gates96.com/13/9/68/39.html -http://yp.gates96.com/13/9/68/68.html -http://yp.gates96.com/13/9/69/22.html -http://yp.gates96.com/13/9/69/62.html -http://shop.intouch.de/cgi-bin/Eternit-Shop/1678827467/IconBar -http://www.jango.com/home_and_garden/outdoor_and_garden/gardening/outdoor_furniture/miscellaneous/?num=1&prod=7 -http://ring.omp.ad.jp/archives/lang/perl/CPAN/authors/id/SHERWOOD/CHECKSUMS -http://www.acad.polyu.edu.hk/spkg/sas8/sasdoc/hrddoc/indfiles/57263.htm -http://ftp.te.fcu.edu.tw/cpatch/system/mbm/source/?D=A -http://web1.localbusiness.com/Story/0,1118,SAN_11751,00.html -http://www.amulation.com/md-l-archive/199902/msg00357.html -http://ads3.zdnet.com/c/g=r1517&c=a53585&camp=c13878&idx=2000.10.30.21.32.11/www.sega.com/seganet -http://pub.chinaccm.com/23/news/200009/30/111206.asp -http://www.online.kokusai.co.jp/Service/V0043534/wrd/G200/service/service.html -http://www.buybuddy.com/sleuth/27/1/1060204/2992/ -http://www.friend4life.com/foreign-affair/infopage/info12655.htm -http://www.friend4life.com/women/info7867.htm -http://www.friend4life.com/women/info11637.htm -http://www.chabadlibrary.org/ecatalog/EC07/EC07328.HTM -http://tulips.ntu.edu.tw/search*chi/cJC311+S275+1992/cjc++311+s275+1992/7,-1,0,E/2browse -http://stationradio.subportal.com/sn/Network_and_Internet/Misc__Networking_Tools/866.html -http://www.canlii.org/ca/regu/sor88-278/sec2.html -http://www.rottentomato.com/movies/titles/traffic/click.php?review=1 -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=4,26,16,35,15 -http://www.staroriental.net/nav/soeg/ihf,aai,n2,169,Electric+Wave+Girl+1998.html -http://www.staroriental.net/nav/soeg/ihf,aai,n2,176,Electric+Wave+Girl+1998.html -http://www.teenplatinum.com/barelylegal/bellyovary/parkingjail-bait/oral-sexoral-sex/big-bonedmen/sex/main.html -http://troy.lib.sfu.ca/search/snewsinc/snewsinc/-5,1,1,B/frameset&F=snewsbrief&1,,2 -http://biblio.cesga.es:81/search*gag/dLó%3Bpez+de+Medina,+Juan/dlopez+de+medina+juan/-5,-1,0,B/frameset&F=dlopez+de+ayala+pedro+critica+e+interpretacion&1,,2 -http://proxy.rmcnet.fr/udsp68/commissions.htm -http://proxy.rmcnet.fr/udsp68/csp_colmar.htm -http://yp.gates96.com/4/0/70/88.html -http://yp.gates96.com/4/0/71/51.html -http://yp.gates96.com/4/0/71/57.html -http://yp.gates96.com/4/0/71/84.html -http://yp.gates96.com/4/0/71/85.html -http://yp.gates96.com/4/0/72/84.html -http://yp.gates96.com/4/0/72/94.html -http://yp.gates96.com/4/0/73/15.html -http://yp.gates96.com/4/0/73/92.html -http://yp.gates96.com/4/0/74/96.html -http://yp.gates96.com/4/0/75/23.html -http://yp.gates96.com/4/0/75/94.html -http://yp.gates96.com/4/0/76/41.html -http://yp.gates96.com/4/0/76/82.html -http://yp.gates96.com/4/0/77/64.html -http://yp.gates96.com/4/0/78/93.html -http://yp.gates96.com/4/0/79/72.html -http://yp.gates96.com/4/0/79/82.html -http://fi.egroups.com/message/morehealth/13?source=1 -http://cn.egroups.com/message/Multicultural/489 -http://cn.egroups.com/message/Multicultural/495 -http://cn.egroups.com/message/Multicultural/497 -http://yp.gates96.com/4/1/60/54.html -http://yp.gates96.com/4/1/60/69.html -http://yp.gates96.com/4/1/61/83.html -http://yp.gates96.com/4/1/62/68.html -http://yp.gates96.com/4/1/63/13.html -http://yp.gates96.com/4/1/63/42.html -http://yp.gates96.com/4/1/63/61.html -http://yp.gates96.com/4/1/63/73.html -http://yp.gates96.com/4/1/64/15.html -http://yp.gates96.com/4/1/64/49.html -http://yp.gates96.com/4/1/64/54.html -http://yp.gates96.com/4/1/65/19.html -http://yp.gates96.com/4/1/65/26.html -http://yp.gates96.com/4/1/65/69.html -http://yp.gates96.com/4/1/65/98.html -http://yp.gates96.com/4/1/66/57.html -http://yp.gates96.com/4/1/66/62.html -http://yp.gates96.com/4/1/66/79.html -http://yp.gates96.com/4/1/66/86.html -http://yp.gates96.com/4/1/66/88.html -http://yp.gates96.com/4/1/67/6.html -http://yp.gates96.com/4/1/67/49.html -http://yp.gates96.com/4/1/67/76.html -http://yp.gates96.com/4/1/67/78.html -http://yp.gates96.com/4/1/68/57.html -http://yp.gates96.com/4/1/69/10.html -http://yp.gates96.com/4/1/69/47.html -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=blich&l=de -http://www.secinfo.com/d17xw.53m.htm -http://www.cs.unm.edu/sheppard-bin/igmdesc.cgi/n=shep/I1475 -http://home.pchome.com.tw/computer/54915491/data/data2.htm -http://forum.rai.it/aca-finestre/dispatch.cgi/FORUM/folderFrame/100001/0/author/3910318 -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=215&discrim=164,80,165 -http://library.bangor.ac.uk/search/cHN582+.R45+1991/chn++582+r45+1991/-5,-1,0,B/bibandlinks&F=chn++573+h313&1,1 -http://mai.flora.org/forum/new-2110 -http://www.tucows.telia.no/winnt/adnload/68747_30295.html -http://www.tucows.telia.no/winnt/adnload/135780_47081.html -http://www.annotate.net/html/Annotate_Directory/Top/Regional/North_America/United_States/Louisiana/Localities/C/Coushatta -http://wine.cc.chuo-u.ac.jp/home/pub/TeX/CTAN/support/mctex/?D=A -http://pub21.ezboard.com/ujaletheadmin.showPublicProfile?language=EN -http://ftp.lip6.fr/pub11/NetBSD/NetBSD-current/src/usr.sbin/quot/Makefile -http://www.hrdc.gc.ca/socpol/cfs/bulletins/jan97/man_f.shtml -http://www.loveme.com/infopage/info23899.htm -http://polygraph.ircache.net:8181/http_-2www.fsa.org/MutareMap.asp -http://www.sdrt.com.cn/tiyuzhichuang/wangqiu/mingxingdangan/4/gelafu.htm -http://home.netvigator.com/~raympoon/digital7.htm -http://www.bemi-immobilien.de/Startseite/www.allgemeine-immobilien-boerse.de/allgemeine-ib/landkreiszwickau/Verkauf/29109700708107kirchbergvillamü/Gemeinsam/3d-service/Top-Darlehens-Konditionen/Startseite/Gemeinsam/immolink/Startseite/froben.htm -http://www.hum.auc.dk/~magnus/MHonArc/NTSEC/frm00999.html -http://www.hum.auc.dk/~magnus/MHonArc/NTSEC/frm09255.html -http://www.affiliate.hpstore.hp.co.uk/do/session/380849/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/entry.asp -http://genforum.genealogy.com/cgi-genforum/forums/skeen.cgi?265 -http://wiem.onet.pl/wiem/00f59f.html -http://www2.ipc.pku.edu.cn/scop/data/scop.1.007.033.001.002.000.html -http://splitrock.themes.tucows.com/cursors/adnload/15789.html -http://splitrock.themes.tucows.com/cursors/adnload/15884.html -http://www.cpami.gov.tw/ymsnp/animal/insect/34654text.htm -http://lateline.muzi.net/ll/fanti/89027.shtml -http://www.hig.se/(accessed,comment,date,header,quote)/~jackson/roxen/ -http://ftpsearch.belnet.be/ftp/packages/Linux-RedHat/up2date/rhl-6.0/alpha/README -http://ftpsearch.belnet.be/ftp/packages/Linux-RedHat/up2date/rhl-6.0/alpha/etc/ -http://ftpsearch.belnet.be/ftp/packages/Linux-RedHat/up2date/rhl-6.0/alpha/lib/ -http://polygraph.ircache.net:8181/services/define/http_-2www.microsoft.com/http_-2www.microsoft.com/ntserver/http_-2www.netscape.com/comprod/mirror/http_-2gateway.olympcfunding.com/products.html -http://polygraph.ircache.net:8181/services/define/http_-2www.microsoft.com/http_-2www.microsoft.com/ntserver/http_-2www.netscape.com/comprod/mirror/http_-2gateway.olympcfunding.com/products/ -http://f7.parsimony.net/forum9177/messages/638.htm -http://f7.parsimony.net/forum9177/messages/594.htm -http://japan.medscape.com/medscape/HIV/journal/1998/v04.n03/expert1098/expert1098.html -http://golfonline.comfluent.net/cgi.pan$advsts&Dicky_Pride&102&lwfth&pga?golfstats -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=93&discrim=5,200,183 -http://girls.4gee.com/japan/azumi_kawashima/big_page/0023.htm -http://www.jobvillage.com/channel/jobs/travel/travel_guide/b.4899.g.37.html -http://www.chaos.dk/sexriddle/b/o/q/p/ -http://www.osiris.978.org/~brianr/mirrors/olga/cowpie/m/mellencamp_john/?N=D -http://www.jpc-music.com/1695294.htm -http://sunsite.org.uk/packages/TeX/uk-tex/macros/latex/contrib/supported/t-angles/?D=A -http://www.shopworks.com/index.cfm/action/info/userid/000B34B5-2F17-19FE-9038010B0A0ADCF2 -http://www.bemi-immobilien.de/Startseite/www.ferien-immobilien.de/ferien-ib/startseite/Top-Darlehens-Konditionen/Gemeinsam/Startseite/Gemeinsam/Gemeinsam/versicherungen/gebaeude/Gemeinsam/Inserieren/onlineInserieren.htm -http://www.idgnet.com/crd_playstation_254384.html -http://www.3wbooks.de/BauerGunter/BauerGunter3406402798.htm -http://library.cwu.edu/search/dSports+--+Washington+(State)+--+Periodicals/dsports+washington+state+periodicals/-5,-1,0,B/request&F=dsports+university+of+michigan&1,,2 -http://www.aelita.net/products/library/sitemap/Reg/Subscribe/sitemap/Reg/QuoteRegister/Default.htm -http://topcu.tucows.com/winme/preview/76604.html -http://tonet.com.cn/zhuanyejihua/kaoshijihua/ligonglei/dianzizhuanyezhuanke.htm -http://tonet.com.cn/zhuanyejihua/kaoshijihua/falv2001.htm -http://tonet.com.cn/zhuanyejihua/kaoshijihua/caijinglei/gongshangqiyeguanlibenke.htm -http://ftp.univ-lyon1.fr/faq/by-name/cats-faq/breeds/american-curl -http://www.videos-erotism.com/xhuge/1/hardMid3.html -http://www.zope.org/Wikis/DevSite/Projects/CoreSessionTracking/WikiWikiWeb/map -http://www.v2music.com/Scripts/WebObjects-ISAPI.dll/V2_New_Publisher.woa/74461000003304200000112720000087451/Labels.wo/603110000077451/2.0.0.5.0/3/Webobjects1 -http://books.hyperlink.co.uk/bookinfo/Willa_Cathers_Transforming_Vision/Brienzo/Gary_W./0945636660 -http://ftp.darenet.dk/tucows/winme/adnload/137112_28604.html -http://l-infonet.phkk.fi/fi/TIETOPALVELUT/TEKNIIKKA/korkeakoulukirjastot/yliopisto-+ja+korkeakoulukirjastot/insin%F6%F6rit/kirjastot/ -http://www.pokers.com/asp/sp-asp/_/SZ--2/PD--10017288/posters.htm -http://itcareers.careercast.com/texis/it/itjs/+RwwBmelXD86elmwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewhXwotoBwcaMnmowamoGnqBdGaDntdBowBodD5aqconDBaMwGAnBoDtapd5oBodDaMwDwtnainxawqqd1DBaMFqryfHfREIDzmbwwwpBmezWD86Wwww5rme9cwwwBrmeZpwww/jobpage.html -http://berlin-charlottenburg.de/deutsch/politik/ma/062.htm -http://www.ericsson.cl/cables/protection/index.shtml -http://209.207.239.212/bkindex/c1007/f1401.html -http://209.207.239.212/bkindex/c1007/f1418.html -http://www.neoseeker.com/forums/index.php?function=edit_message&messageid=1037 -http://www.neoseeker.com/forums/index.php?function=edit_message&messageid=1199 -http://www.geocities.co.jp/SweetHome-Green/3692/PROFILE.HTML -http://www.geocities.co.jp/SweetHome-Green/3692/MELINDEX.HTML -http://myhome.naver.com/bora1234/photo.html -http://www.magicvillage.de/magicvillage/computercenter/Grafik%20%26%20Layout/Software/Macintosh/Hotline/PowerBooks/ -http://student.monterey.edu/nr/panditharatnesha/world/ -http://in.egroups.com/message/Michelles__Miracles/657 -http://www.babyheirlooms.com/catalog/htmlos.cat/001248.1.5492769465 -http://republika.pl/raduczulu/counter.html -http://adex3.flycast.com/server/socket/127.0.0.1:2800/click/OnlineCitiesSM/OnlineCitiesInteractiveCityGuides/bd378258019 -http://www.8848.net/fjnews/200007/0728/2000072811393979.htm -http://www.chaos.dk/sexriddle/m/n/x/t/ -http://www.maastrek.de/maas/01eea86f59dac641c053/1/0/4 -http://yp.gates96.com/14/79/82/8.html -http://yp.gates96.com/14/79/82/95.html -http://yp.gates96.com/14/79/82/98.html -http://yp.gates96.com/14/79/83/10.html -http://yp.gates96.com/14/79/83/16.html -http://yp.gates96.com/14/79/83/48.html -http://yp.gates96.com/14/79/84/4.html -http://yp.gates96.com/14/79/84/96.html -http://yp.gates96.com/14/79/85/34.html -http://yp.gates96.com/14/79/85/96.html -http://yp.gates96.com/14/79/86/9.html -http://yp.gates96.com/14/79/86/11.html -http://yp.gates96.com/14/79/86/28.html -http://yp.gates96.com/14/79/86/32.html -http://yp.gates96.com/14/79/86/86.html -http://yp.gates96.com/14/79/86/96.html -http://yp.gates96.com/14/79/87/96.html -http://yp.gates96.com/14/79/88/38.html -http://yp.gates96.com/14/79/88/74.html -http://yp.gates96.com/14/79/88/95.html -http://yp.gates96.com/14/79/89/57.html -http://autos.yahoo.co.jp/ucar/m1010/k10102006199904/g24/a101020060240158710008510205199904_4.html -http://www02.geocities.co.jp/HeartLand-Keyaki/7483/ -http://online.excite.de/wirtschaft/katalog/32476 -http://www9.hmv.co.uk:5555/do/session/1347777/vsid/199/tid/199/cid/1061396/mid/1020/rid/1052/chid/1029/parser/yes/imref/eqqLmwlGltt5tkeHjskKZlkKrhlK/url/http://www.hmv.co.uk/hmv/Top_Navigation_Bar/top_navbar.html -http://www9.hmv.co.uk:5555/do/session/1347777/vsid/199/tid/199/cid/1061396/mid/1020/rid/1052/chid/1029/parser/yes/imref/eqqLmwlGltt5tkeHjskKZlkKrhlK/url/http://www.hmv.co.uk/hmv/departments/d90_sd0_pt0.html -http://infoserv2.ita.doc.gov/efm/efm.nsf/Sources!OpenView&Start=5&Count=30&Collapse=54 -http://users.ai-lab.fh-furtwangen.de/for_local_use_only/CD-TMFUMV/daten/beisp/05321/?D=A -http://www.babyheirlooms.com/catalog/htmlos.cat/011629.1.0871727476 -http://www.fogdog.com/cedroID/ssd3040183241146/cgi-bin/MyFogdog -http://www.3w-geschichte.de/OReillyJamesT/OReillyJamesT0471287237.htm -http://www.annotate.net/html/Annotate_Directory/Top/Arts/Movies/Titles/W/World_According_to_Garp,The/ -http://dandini.cranfield.ac.uk/vl=-39536559/cl=151/nw=1/rpsv/cw/web/nw1/bargen.htm -http://cgi.superonline.com/cgi-bin/sworld43/thread.pl/forums/sworld43/oss2000/45.html?dir=nextResponse -http://cgi.superonline.com/cgi-bin/sworld43/get/forums/sworld43/oss2000/45.html?admin -http://dogbert.bizit.net/debian/dists/unstable/non-US/non-free/binary-sparc/?M=A -http://ftp.eecs.umich.edu/debian/dists/potato/main/binary-i386/misc/?D=A -http://fi.egroups.com/message/girlscouting/3383 -http://dk.egroups.com/group/scaleauto -http://members.tripod.lycos.co.kr/SM4/paper.htm -http://www.jamba.nl/KNet/_KNet-BqE8j1-JC4-pv4w/browse.nl/node.0/cde7f2elw -http://yp.gates96.com/4/6/10/47.html -http://yp.gates96.com/4/6/10/52.html -http://yp.gates96.com/4/6/10/96.html -http://yp.gates96.com/4/6/11/25.html -http://yp.gates96.com/4/6/11/61.html -http://yp.gates96.com/4/6/11/67.html -http://yp.gates96.com/4/6/11/93.html -http://yp.gates96.com/4/6/12/11.html -http://yp.gates96.com/4/6/12/28.html -http://yp.gates96.com/4/6/12/66.html -http://yp.gates96.com/4/6/12/81.html -http://yp.gates96.com/4/6/12/93.html -http://yp.gates96.com/4/6/13/86.html -http://yp.gates96.com/4/6/13/94.html -http://yp.gates96.com/4/6/14/17.html -http://yp.gates96.com/4/6/14/76.html -http://yp.gates96.com/4/6/15/61.html -http://yp.gates96.com/4/6/16/47.html -http://yp.gates96.com/4/6/16/71.html -http://yp.gates96.com/4/6/17/62.html -http://yp.gates96.com/4/6/18/1.html -http://yp.gates96.com/4/6/18/24.html -http://yp.gates96.com/4/6/18/28.html -http://158.169.50.70/eur-lex/it/lif/dat/1994/it_294D1217_09.html -http://158.169.50.70/eur-lex/it/lif/dat/1995/it_295D0928_02.html -http://158.169.50.70/eur-lex/it/lif/dat/1997/it_297D0904_03.html -http://www.irishnews.com/k_archive/181299/local4.html -http://www.irishnews.com/k_archive/181299/local14.html -http://www.irishnews.com/k_archive/181299/local16.html -http://uk.dir.yahoo.com/Regional/U_S__States/North_Carolina/Cities/Charlotte/Business_and_Shopping/Business_to_Business/Manufacturing/Casting__Moulding__and_Machining/ -http://www.uwec.edu/Academic/English/Projects/VonHaden/ -http://www.playease.com/et/beauty/img/jijinglian/jjl054.htm -http://www.digitaldrucke.de/(aktuell,für,marktplatz,metamorphose,raum,sense)/_fort/html/themen/kultur/digital/digital.htm -http://pub6.ezboard.com/fzfreesubmissiondirectoryplacestosubmitforfree.showMessage?topicID=35.topic -http://pub6.ezboard.com/fzfreesubmissiondirectoryplacestosubmitforfree.showMessage?topicID=12.topic -http://www.emerchandise.com/browse/DISNEY/TOY/b.FAVORITES%20COMICS%20CARTOONS%20DISNEY/s.CgJlPxcV -http://www.centc251.org/forums/aca-1/dispatch.cgi/hsi/showNextUnseen/fol/100001/1302769 -http://911codes.com/games/platform/gameboy/sect/div/cont/list_cheat/spray/y/id/0000010187/gid/0000003974/_cheats/_walkthroughs/_codes/_pc/_n64/_psx/_gameboy/_playstation/ -http://library.bangor.ac.uk/search/dPolice+regulations+--+Great+Britain/dpolice+regulations+great+britain/7,-1,0,E/frameset&F=dpolice+social+work+great+britain+congresses&1,1 -http://www02.u-page.so-net.ne.jp/ta2/grosh/Training/Training9.html -http://ring.shibaura-it.ac.jp/archives/linux/RedHat/redhat/code/i18n/trans/?D=A -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=15,35,22,28,26 -http://ftp.nacamar.de/pub/NetBSD/NetBSD-current/pkgsrc/graphics/ruby-gl/?S=A -http://www.academyfloral.com/state/aliro/flowers/birthdaybouquet1.html -http://l-infonet.phkk.fi/fi/TIETOPALVELUT/KIRJASTO-+JA+TIETOPALVELUT/ammattikorkeakoulukirjastot/ammattikorkeakoulut/p%E4ij%E4t-h%E4meen+koulutuskonserni/kirjastot/ -http://www.jpc-music.com/1409509.htm -http://chat.sportsline.com/u/ce/feature/0,1518,2565545_56,00.html -http://chat.sportsline.com/u/ce/feature/0,1518,1675610_56,00.html -http://www.affiliate.hpstore.hp.co.uk/do/session/380831/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hpstore.hewlett-packard.fr/gp -http://209.207.239.212/bkindex/c1016/f1419.html -http://209.207.239.212/bkindex/c1016/f1424.html -http://www.sports.aol.fr/Jo/Perec_2.html -http://www.citybrazil.com.br/go/smiguelaraguaia/transporte.htm -http://www.fileamerica.com/states/texas/local/cameron/ptax.html -http://www.angelfire.com/nv/bellea -http://school.educities.org/card/a4711862.html -http://school.educities.org/card/a60902.html -http://school.educities.org/card/amy60630.html -http://school.educities.org/card/aney1.html -http://school.educities.org/card/christinelee.html -http://school.educities.org/card/grace3721.html -http://school.educities.org/card/jj1245j.html -http://school.educities.org/card/jyik.html -http://school.educities.org/card/k3813813.html -http://school.educities.org/card/k78780606.html -http://school.educities.org/card/kitty1snoopy.html -http://school.educities.org/card/landy1.html -http://school.educities.org/card/m0522.html -http://school.educities.org/card/mark747.html -http://school.educities.org/card/okdh.html -http://school.educities.org/card/poppybaby.html -http://school.educities.org/card/ry21.html -http://www.secinfo.com/dvtBm.7a.htm -http://www.craft-supplies.co.uk/cgi-bin/psProdDet.cgi/HT206|972959537|Deluxe_Dividers|user|0|0,0,1,1 -http://in.egroups.com/post/book-readers?act=forward&messageNum=3829 -http://www.nacion.co.cr/ln_ee/2000/enero/31/mundo10.html -http://www.bigstar.com/news/sb/index.cfm/4ae0978g371d907g1?fa=today -http://www.bigstar.com/cs/index.cfm/4ae0978g371d907g1?fa=privacy -http://v2.bdnet.com/I/Cailleaux/I/Cannabissimo/fiche_serie.htm -http://ftp.darenet.dk/tucows/winnt/adnload/12475_29978.html -http://ftp.darenet.dk/tucows/winnt/adnload/1879_29966.html -http://www.canit.se/(h1,k15,mail,unix,www)/support/ -http://byron17.home.chinaren.com/lit/novle/maio.htm -http://www.emerchandise.com/browse/PAGEANTS/MUG/b.FAVORITES%20PAGEANTS/s.Q8q0znEj -http://stulchik.list.ru/catalog/10310.html -http://stulchik.list.ru/catalog/10967.2.html -http://dada.tucows.com/adnload/70717_30131.html -http://forum.rai.it/aca-finestre/dispatch.cgi/FORUM/folderFrame/100001/0/alpha/7677890 -http://webraft.its.unimelb.edu.au/196024/students/cabong/pub/?M=A -http://www.crutchfield.com/S-fFFHlZKyKNq/shop/ -http://www.earthsystems.org/gopher/seacnet/announce97-08-03-14/1994/aug94/94-08-25-18:%20Violence%20in%20Indian%20Country%20Over%20Waste -http://www.brio.de/BRIO.catalog/39fdb65f08c44c28273fd472aa7806e3/UserTemplate/10 -http://www.qsl.net/hj3ufa -http://www-jl.jl.cninfo.net/jlweb/book/wxtd/gu_long/chuliuxiang/bat/009.htm -http://www.intel.fr/support/netport/pro/21402.htm -http://shopping.lycos.co.kr/cgi-bin/LCWB.cgi/957423999/957522544/Catalog/1375/001 -http://www01.u-page.so-net.ne.jp/qc4/sam-ft/gallerycraftspace.html -http://rpmfind.net/linux/RPM/mandrake/usr_src_linux-2.2.16_pcmcia-cs-3.1.14_doc_Tree.html -http://www.chrisgraef.de/chg/webdesigner_medien.html -http://www.opengroup.com/trbooks/186/1864501634.shtml -http://moviestore.zap2it.com/shopcart/s.1GUFVsoF -http://moviestore.zap2it.com/browse/MOVIES/ACTIONFI/s.1GUFVsoF -http://moviestore.zap2it.com/browse/MOVIES/PUPPET/s.1GUFVsoF -http://ocean.ntou.edu.tw/search*chi/m387.224+M178t/m387.224+m178+t/-5,-1,0,E/buttonframe&F=m387.224+m178+m&1,,0 -http://www.egroups.com/message/BalletBuds/25 -http://link.fastpartner.com/do/session/600375/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/create/learn.htm -http://www.vedomosti.spb.ru/2000/arts/spbved-2180-art-27.html -http://www.vedomosti.spb.ru/2000/arts/spbved-2180-art-42.html -http://www.vedomosti.spb.ru/2000/arts/spbved-2180-art-45.html -http://www.vedomosti.spb.ru/2000/arts/spbved-2180-art-46.html -http://www2.ipc.pku.edu.cn/scop/rsgen.cgi?pd=3nla -http://www.allkorea.co.jp/cgi-bin/allkorea.front/972959900763/Catalog/1000006 -http://www.allkorea.co.jp/cgi-bin/allkorea.front/972959900763/Catalog/1000031 -http://fi.egroups.com/message/gailporter/199 -http://fi.egroups.com/message/gailporter/222 -http://www.egroups.com/messages/X-Air_Ultralight_Aircraft/359 -http://dia.tucows.com/winme/adnload/136838_28375.html -http://dia.tucows.com/winme/adnload/136846_28383.html -http://www.letsmusic.co.kr/directory/weblink/weblink_list/1,1011,100000000186810,00.html -http://www.smcworld.com/smcworld/bp/large/0744_2_1611_2_1611b.html -http://news.pchome.com.tw/ettoday/entertainment/20001028/index-20001028155543020439.html -http://www2.stas.net/lostlane/J.html -http://allmacintosh.arrakis.es/utilsmac_rating.html -http://novel.hichinese.net/zt/zpj/k/kelisidi/kill/008.htm -http://194.174.50.23/cgi-bin/FisRun/InsertExhibitorIntoNotebook/1/interpack99/d/2891 -http://www.loisirs.ch/jifmuf/14/roedrz.html -http://www.linux.com/networking/server/business/operating_system/learning/consumer/ -http://dandini.cranfield.ac.uk/vl=-39685335/cl=158/nw=1/rpsv/cw/www/faqs.htm -http://blisty.internet.cz/1250/9901/19990108a.html -http://www.staroriental.net/nav/soeg/ihf,aai,n2,247,Electric+Wave+Girl+1998.html -http://www.multimania.com/excave/vicking.html -http://students.lsu.edu/students/main.nsf/Pages/CSISAJ1!OpenDocument&ExpandSection=5,14,21,12 -http://www.secinfo.com/dWXc8.bz.htm -http://www.secinfo.com/dWXc8.9d.htm -http://bbs.ee.ntu.edu.tw/boards/RomanceNovel/11/2/9/2/ -http://ftp.nacamar.de/pub/NetBSD/packages/1.4/amiga/emulators/?M=A -http://no.egroups.com/subscribe/windows98 -http://ftp.dei.uc.pt/pub/netscape/communicator/english/4.76/unix/unsupported/linux20_libc5/?D=A -http://smb.slac.stanford.edu/cgi-bin/nph-proxy.cgi/000/http/www.gsb.stanford.edu/sloan/sloan_fellows.html -http://apple.excite.com/entertainment/music/artists_and_genres/alternative_rock/grunge/stone_temple_pilots/merchandise/ -http://home.sprynet.com/~tales/asw2.html -http://fi.egroups.com/post/audiovision?act=reply&messageNum=145 -http://www.zema.ru/post/forum/komi_respublika/usinsk/messages/712 -http://opac.lib.rpi.edu/search/ddesert+ecology/-5,-1,0,B/browse -http://www.arm.com/sitearchitek/support.ns4/html/sdt_debug!OpenDocument&ExpandSection=6,32,7,5 -http://www.linux.com/networking/network/technology/security/community/open_source/ -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=9,33,15,36,22 -http://isbn.nu/0505523892/borders -http://www.informika.ru/text/database/geom/Draw/ris/ris34_1.htm -http://caselaw.lp.findlaw.com/casecode/uscodes/42/chapters/77/subchapters/iii/parts/h/sections/section_6374_notes.html -http://www.cyd.com.cn/zqb/19991104/GB/9672^Q805.htm -http://providenet.tukids.tucows.com/win95nt/9-12/adnload/132963_46167.html -http://www.chaos.dk/sexriddle/e/o/g/k/i/ -http://www2.brent.gov.uk/planning.nsf/013459d30f2ad00680256623005fcc0a/8af30b42469a1215802568720046524a!OpenDocument&ExpandSection=16,13,11,9,15 -http://jje.subportal.com/sn/Multimedia_and_Graphics/MPEG_Audio_Players_and_Editors/9126.html -http://www.ropnet.ru/HyperNews/edit-response.pl/case/2856.html -http://www.eveclub.com/cgi-bin/eveclub.front/972959508447/Catalog/1000045 -http://itcareers.careercast.com/texis/it/itjs/+rwwBmeO9D86MwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewDXnnqrDoqwcaiGoBnapd5oBodDaxw5nmamdq1MnDBwBodDawppcoqwBodD5a15naM15BapGdm1qBodDawxcnaMFqtPfRRZNDzme8xwwwpBme7WD86eLrwww5rm-mwwBrmeZpwww/jobpage.html -http://www.iucr.ac.uk/iucr-top/journalsonline/iucr-top/cif/software/hiccup/prods/?M=A -http://lists.omnipotent.net/mysql/199707/msg00381.html -http://www.yescall.co.kr/kyungheein/ -http://minyos.its.rmit.edu.au/~s9763278/sparks/sparks.html -http://www.movieguide.com/pressroom/events/nbcpresstour/festival_nbcpresstour9.html -http://www.gamers.net/game/190940/reviews -http://www.staroriental.net/nav/soeg/ihf,aai,n2,198,Electric+Wave+Girl+1998.html -http://marysz.freeservers.com/cgi-bin/c/736/64/dXNlcmJhbm5lcg==/gn/6616/ -http://subversion.tigris.org/source/browse/subversion/subversion/libsvn_delta/delta.h?annotate=1.34&sortby=rev -http://subversion.tigris.org/source/browse/subversion/subversion/libsvn_delta/delta.h?annotate=1.28&sortby=rev -http://sunsite.org.uk/public/public/packages/WWW/spinner/?D=A -http://sunsite.org.uk/public/public/packages/WWW/spinner/untared/ -http://www.realbig.com/miata/miata/1998-01/1635.html -http://cky.8k.com/cgi-bin/framed/1359/info/jess.html -http://cky.8k.com/cgi-bin/framed/1359/info/bran.html -http://www.loisirs.ch/jifmuf/10/bhcqud.html -http://naver22.jrnaver.co.kr/Entertainment_and_Arts/Design_Arts/Architecture/Organizations/ -http://www.zing.com/member/?name=birchpole&c=1 -http://student.monterey.edu/nr/porrasjohnny/campus/ -http://ftp.lip6.fr/pub/FreeBSD/development/FreeBSD-CVS/ports/misc/peq/files/patch-ab,v -http://www.multimania.com/lesoir2/news/sept99/quake4.htm -http://www.multimania.com/lesoir2/news/sept99/2309-12.txt -http://www.multimania.com/lesoir2/news/sept99/0609-06.txt -http://www.multimania.com/lesoir2/news/sept99/1309-13.txt -http://homepage1.nifty.com/shiraishi/school/school2.htm -http://ring.htcn.ne.jp/pub/NetBSD/NetBSD-current/pkgsrc/mbone/sdr/pkg/PLIST -http://www.chaos.dk/sexriddle/m/c/z/b/ -http://www.chaos.dk/sexriddle/m/c/z/p/ -http://map.ipc.co.jp/asp/onmap/r/new/g-26/f-523824/ -http://www.nissan.co.jp/RENAULT-DEALERS/PASSPORT/view.cgi/admission/972959650-- -http://novel.hichinese.net/xd/gt/zpj/l/liangfengyi/jingrong/010.htm -http://www.tvstore.com/browse/TV/MAGNET/s.l03qOWiP -http://www.tvstore.com/browse/TV/KEYCHAIN/s.l03qOWiP -http://www.gbnf.com/genealog2/burt/html/d0002/I1199.HTM -http://www.gbnf.com/genealog2/burt/html/d0006/I1187.HTM -http://www.gbnf.com/genealog2/burt/html/d0004/I1521.HTM -http://src.openresources.com/debian/src/graphics/HTML/R/HVcreate.html -http://yomama.tgm.ac.at/doc/susehilf/gnu/vip/Changing.html -http://www.science.uva.nl/pub/NetBSD/NetBSD-current/pkgsrc/sysutils/gmc/pkg/ -http://news.fm365.com/zonghe/20001009/156610.htm -http://homepage1.nifty.com/tojo/shin13.htm -http://www.sf.digitalcity.com/naplesfl/personals/browse.dci?cat=wsw&sort=t -http://plat.debian.or.jp/debian/dists/woody/non-free/binary-hppa/otherosfs/?M=A -http://people.freebsd.org/~knu/cgi-bin/cvsweb.cgi/ports/databases/gdbm/distinfo?only_with_tag=RELEASE_4_1_0 -http://bbs.csie.ntu.edu.tw/txt/Emprisenovel/ebooks/mystery/alisanderla/wsyz/013.txt -http://www.legis.state.ia.us/GA/78GA/Legislation/SCR/00000/SCR00018/?M=D -http://www.mapion.co.jp/custom/AOL/admi/23/23104/kaminagoya/2chome/index-2.html -http://ciscom.cnet.com/hardware/member/entry/0,10285,0-1069-419-1544825,00.html -http://wow-online.vhm.de/Regional/Grossbritannien/Kunst.html -http://www.cs.rit.edu/~hpb/Man/_Man_Openwin_html/html2/sigaction.2.html -http://in.egroups.com/message/talksigncreate/287 -http://rainforest.parentsplace.com/dialog/thread.pl/newclubfoot8/19.html?dir=nextThread -http://ftp.jp.debian.org/debian-non-US/dists/potato/non-US/main/binary-arm/?N=D -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=baumelte&l=de -http://www.chaos.dk/sexriddle/i/f/p/k/h/ -http://unionsoft.narod.ru/3d/anatomy/pages/head1.htm -http://src.openresources.com/debian/src/electronics/acs_021.orig/acs-021.orig/ -http://www.mapion.co.jp/custom/AOL/admi/23/23111/takagicho/2chome/index-45.html -http://dennou-q.geo.kyushu-u.ac.jp/library/Linux/debian-jp/dists/unstable/contrib-jp/binary-m68k/tex/?N=D -http://rapidus.tucows.com/winnt/adnload/54123_28460.html -http://193.207.119.193/MV/gazzette_ufficiali/303-99/8.htm -http://www.emerchandise.com/help_security/b.TV%20FRASIER/s.LoO0xS99 -http://gpul.org/ftp/os/linux/cd-images/other/ISO/suse/?M=A -http://opac.lib.rpi.edu/search/arush+sean+c/-17,-1,0,E/frameset&arush+homer+f&1,,0 -http://genforum.genealogy.com/cgi-genforum/forums/griffin.cgi?3823 -http://www.leo.org/leoclick/dce2b1c893db6a8193428ecad9ecd878+L+1__ -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=55&discrim=178,230,174 -http://www.msb.malmo.se/search*swe/aKling,+Rolf/akling+rolf/7,-1,0,B/browse -http://retailer.gocollect.com/do/session/1912785/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/checkout/shopping_cart.asp -http://st3.yahoo.co.jp/nihondo/k4932828003023.html -http://webtools.familyeducation.com/whatworks/review/front/0,2562,1-10641-2316_-7233-3,00.html -http://www.bretagne-online.com/telegram/htdocs/archive/1997/19970618/sommaire/stpoldeleon.htm -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=234&discrim=235,230,183 -http://www.yagoo.co.kr/stats/batting.asp?Mlbmanid=HAMPAT7709 -http://www.linux.com/networking/network/new/website/suse/SAP/ -http://www.linux.com/networking/network/new/website/suse/security/ -http://javatest.a-net.nl/servlet/pedit.Main/http://www.cdc.gov/ncidod/dpd/parasiticpathways/drinkingwater.htm -http://www.across.or.jp/shizuoka/nbbs.cgi/seibu:n52/post -http://www.across.or.jp/shizuoka/nbbs.cgi/seibu:n52/450 -http://www.across.or.jp/shizuoka/nbbs.cgi/seibu:n52/607 -http://dangerous.co.kr/www.sony.co.jp/ProductsPark/Consumer/Peripheral/MDData/page6.html -http://www2.sega.co.jp/bbs/article/s/sports/47/xvwixh/jlvcgk.html -http://troy.lib.sfu.ca/search/alondon+mathematical+society/alondon+mathematical+society/-5,-1,0,B/frameset&F=alondon+m+c+s&2,,3 -http://pub14.ezboard.com/fbrlproductionsfrm10.showAddTopicScreenFromWeb -http://rex.skyline.net/html/Computers_-_Monitors.html?16,computers,radio,electronics,communication -http://rex.skyline.net/html/Software_-_Developers.html?20,computers,radio,electronics,communication -http://ftp.cwi.nl/static/publications/reports/abs/MAS-R9815.html -http://www.jt.com.br/noticias/98/09/28/sd2.htm -http://www.kentuckyconnect.com/heraldleader/news/080899/sportsdocs/08chuck.htm -http://pix.egroups.com/post/ipe?act=forward&messageNum=5302 -http://tulips.ntu.edu.tw/search*chi/cHT392+Un3/cht++392+un3/-5,-1,,B/browse -http://magazines.sina.com/gourmet/contents/199912/199912-006_3_gb.html -http://collection.nlc-bnc.ca/100/201/300/january/2000/00-06-05/sanctuary.html -http://collection.nlc-bnc.ca/100/201/300/january/2000/00-06-05/blue1.html -http://www.vorlesungen.uni-osnabrueck.de/informatik/pt/code/DiagramPalettes/Components.dpalette2/Image45 -http://www.vorlesungen.uni-osnabrueck.de/informatik/pt/code/DiagramPalettes/Components.dpalette2/Image5 -http://playsite.top263.net/software/hh-13.htm -http://www.dispatch.co.za/1998/12/21/sport/MISS.HTM -http://www.allhealth.com/parentsplace/send/0,3288,14-844-1-fertility-INFERTILITY,00.html -http://www.tucows.telia.no/win2k/preview/37705.html -http://www.peopledaily.co.jp/9803/09/current/newfiles/j1020.html -http://shopping.lycos.co.kr/cgi-bin/LCWB.cgi/957424007/957522556/Catalog/1320/001 -http://shopping.lycos.co.kr/cgi-bin/LCWB.cgi/957424007/957522556/Catalog/1321/001 -http://shopping.lycos.co.kr/cgi-bin/LCWB.cgi/957424007/957522556/Catalog/1328/001 -http://shopping.lycos.co.kr/cgi-bin/LCWB.cgi/957424007/957522556/Catalog/1350/001 -http://shopping.lycos.co.kr/cgi-bin/LCWB.cgi/957424007/957522556/Catalog/1359/001 -http://shopping.lycos.co.kr/cgi-bin/LCWB.cgi/957424007/957522556/ProductView/26897 -http://www.uftree.com/UFT/WebPages/Don_MacFarlane/FEB99/d1/i0001285.htm -http://wap.jamba.de/KNet/_KNet-n4B8j1-DFd-13bgt/showInfo-jambabanner.de/node.0/cde7f1uou -http://launchbase.com/Shopping/Visual_Arts/entertainment/information/Politics.htm -http://launchbase.com/Shopping/Visual_Arts/entertainment/shopping/Electronics.htm -http://www.aoyun.sina.com.cn/news/sports/table/2000-09-15/1/4622.shtml -http://www.eggerwirt.at/1Root/Kontinent/6/Staat/7/Bundesland/21/Ort/129509/Homepage/m_homepage...1.html -http://198.103.152.100/search*frc/dSociologie+rurale+--+Ontario/dsociologie+rurale+ontario/-5,-1,0,B/frameset&F=dsociologie+religieuse+islam&1,,0 -http://msn.excite.co.jp/travel/the_country/kinki/wakayama/hot_spring_of_accommodations/inn_tourist_home_in_wakayama?summary=false -http://search.ibm.co.jp/as400/year2000/v3r2.html -http://www.allgemeine-immobilien-boerse.de/nordrhein-Westfalen/Muehlheim-ruhr/Verkauf/Allgemeine-IB/Startseite/3d-service/Private-IB/Startseite/Gemeinsam/Super-Zins-Konditionen/anforderungsformular.htm -http://spaceports.tucows.com/winnt/adnload/78908_28797.html -http://www.trax.nilex.co.uk/trax.cgi/A1S/A2R/A3R/B1S/A1D/A1S/ -http://www.babyheirlooms.com/catalog/htmlos.cat/041130.1.3206884924 -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/music/misc/thoughts/lit/misc/colorart/misc/freespeech.html -http://www.cs.rit.edu/~hpb/Lectures/2000/JRMS_590/all-2.7.html -http://www.cs.rit.edu/~hpb/Lectures/2000/JRMS_590/all-4.11.html -http://www.refdag.nl/kl/990615klfo01.html -http://pub20.ezboard.com/ftheimperiumknightsfrm11.showMessage?topicID=9.topic -http://retailer.gocollect.com/do/session/1912767/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/product_display/advanced_search.asp -http://www.thestateofcolorado.com/saudealersnew.html -http://awelymor.weblogs.co.uk/sdb/en/html/ftp://ftp.suse.com/pub/suse/i386/6.2/suse/n1/ -http://www.mirror.kiev.ua:8083/paper/2000/21/1251/text/21-13-3.htm -http://www.recipezaar.com/browse/0110FC1070110A301109901109E00F06D -http://www.linux.com/networking/network/vpn/server/Unix/ -http://www.gasex.com/main.html?m4m.gallery.twinks -http://www.xtdnet.nl/listarch/linux-router/1998-05-01/nav00046.html -http://www.fogdog.com/cedroID/ssd3040183325831/cgi-bin/CedroCommerce?func=EditBasket -http://www.totalmarketing.com/an/basket.pl/cancel/xwxm6773.94076 -http://ciaoweb.tucows.com/winnt/adnload/56695_29112.html -http://www.brio.de/BRIO.catalog/39fe2f6006e4fc48273fd472aa7806e0/UserTemplate/1 -http://retailer.gocollect.com/do/session/1912715/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/product_display/top_ten.asp?pagenum=2 -http://retailer.gocollect.com/do/session/1912715/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/company_info/dealer_lookup.asp -http://www.streetprices.com/Electronics/Computer_Hardware_PC/Motherboards/ATX/Slot1/Via_Pro133/sortproductbymake/sortcategorybylowprice/ -http://www.streetprices.com/Electronics/Computer_Hardware_PC/Projectors/MAKE+CTX/sortdetailbystock/sortproductbyhighprice/sortcategorybycount/SP318392.html -http://www.multimania.com/egypt95/img0017.htm -http://dic.empas.com/show.tsp/?q=fourteenthly&f=B -http://linux2.ipc.pku.edu.cn/scop/pdb.cgi?sid=d1repc2 -http://www.schlagertempel.de/RobertPayer/B00000B8D2.htm -http://www.cricinfo.com/link_to_database/INTERACTIVE/MAGAZINE/1996-97/SL_IN_NZ/SL_IN_NZ_FEEDBACK_1.html -http://mediate.magicbutton.net/do/session/625637/vsid/4385/tid/4385/cid/88138/mid/1702/rid/2114/chid/3393/url/http://www.worldgallery.co.uk/frameset-top50.html -http://www.clickm.dk/Clickmusic_Web_Guide/Bands_and_Artists/B/Better_Than_Ezra/ -http://www.clickm.dk/Clickmusic_Web_Guide/Bands_and_Artists/B/Breeders,_The/ -http://www.maastrek.de/maas/71eb3baf4c78ed98ef94/1/0/4 -http://www.trnonline.com/archives/1999archives/07221999/obits/24620.shtml -http://www.recipezaar.com/browse/0110FC1070110A100F06D0110A00110A3 -http://www.areaguide.net/addlisting.asp?book=box&CatID=516 -http://webraft.its.unimelb.edu.au/196023/students/lucym/ -http://sunsite.org.uk/public/0-Most-Packages/quake/utils/frontends/qshel15b.txt -http://pub14.ezboard.com/flfiaglarafabianisagoddess.emailToFriend?topicID=858.topic -http://www.realize.com/am4d0481.htm,qt=e784fe2f=2a38a234-4-7cf2ef-1-1-0-3-- -http://www.realize.com/am7bcd81.htm,qt=e784fe2f=2a38a234-4-7cf2ef-1-10-0-3-- -http://mailman.real-time.com/rte-crossfire/1993/Dec/msg00022.html -http://mailman.real-time.com/rte-crossfire/1993/Dec/msg00000.html -http://mailman.real-time.com/rte-crossfire/1993/Dec/msg00009.html -http://www.eallinfo.com/A55782/sameeron.nsf/homeFood!OpenPage&ExpandSection=8,4,3,6 -http://www.ami.dk/udgivelser/emne/36.html -http://www-x500-1.uni-giessen.de:8890/Lcn%3dKai%20Cheong%20HO,ou%3dEstates%20Management%20Office,o%3dHong%20Kong%20University%20of%20Science%20and%20Technology,c%3dHK -http://ftp.telepac.pt/pub/cpan/modules/by-module/DBD/DMOW/?D=A -http://members.se.tripod.de/aah/jochumsen/per02614.htm -http://www.academyfloral.com/state/cacat/flowers/funeralofferingshare.html -http://www.hotelboulevard.com/fr/paris/standard/htmlb877e62937802c0678f4638130be1ef0/sessionLang/ANG/prov/browse/cp/75013/resultatSearch.html -http://www.alsapresse.com/jdj/00/03/24/AK/article_4.html -http://www.mairie-montreuil93.fr/ville_pratique/environ/democrat/printemps/_vti_cnf/interstice.htm -http://variety.studiostore.com/help/b.FAVORITES%20COMICS%20CARTOONS%20POWERPUFF/s.UAREyMtL -http://ftp.sektornet.dk/tucows/winme/adnload/137341_28799.html -http://www.eveclub.com/cgi-bin/eveclub.front/972959532302/Catalog/1000046 -http://www.eveclub.com/cgi-bin/eveclub.front/972959532302/ClubBoard/list/1000022 -http://findmail.com/post/geewhiz?act=reply&messageNum=2039 -http://orders.mkn.co.uk/toy/rattles/order/now.en$NOK?what-bells=1 -http://www.buybuddy.com.au/sleuth/26/1/502/10134/ -http://spokesmanreview.sportshuddle.com/sports/baseball/playbetter/ask-expert/vincent3.asp -http://ant.i.hosei.ac.jp/Ant.WWW/PCD0420/HTMLE/29.html -http://ant.i.hosei.ac.jp/Ant.WWW/PCD0420/HTMLE/34.html -http://builder.hw.net/frmRestDir/0,1112,'1~21~325~1~S~074800~90270',00.html -http://builder.hw.net/frmRestDir/0,1112,'1~21~325~1~S~074800~09890',00.html -http://dennou-h.ees.hokudai.ac.jp/library/Linux/debian-jp/dists/hamm-jp/non-free/binary-i386/games/?M=A -http://www.peopledaily.com.cn/GB/paper68/1469/236625.html -http://us.mandrakesoft.com/cgi-bin/cvsweb.cgi/koffice/kformula/BracketElement.cc?hideattic=1&sortby=rev -http://us.mandrakesoft.com/cgi-bin/cvsweb.cgi/koffice/kformula/FractionElement.cc?hideattic=1&sortby=rev -http://us.mandrakesoft.com/cgi-bin/cvsweb.cgi/koffice/kformula/MIMETYPE-Format?hideattic=1&sortby=rev -http://linuxberg.ii.net/conhtml/preview/7963.html -http://213.36.119.69/do/session/152992/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/FR/reserver/hotels.html -http://213.36.119.69/do/session/152992/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.spycamera.com/webcam/ -http://ftp.netc.pt/pub/idgames/levels/doom/d-f/deathme.txt -http://ftp.netc.pt/pub/idgames/levels/doom/d-f/dork.txt -http://ustlib.ust.hk/search*chi/dsea+stories/dsea+stories/-5,-1,0,B/browse -http://members.fortunecity.com/skinweaver/nf/nfpin01.htm -http://se.egroups.com/group/French_ -http://www.gencat.es/cgi-bin/bc/drawer.cgi/LD/0074/L00465?101 -http://oss.sgi.com/cgi-bin/cvsweb.cgi/projects/ogl-sample/main/gfx/lib/glut/glut_shapes.c?sortby=author -http://www.teacherformation.org/html/od/facilitators.cfm/task1,about/discussion_id,2/xid,9456/yid,7276398 -http://genforum.genealogy.com/cgi-genforum/forums/getchell.cgi?230 -http://www9.hmv.co.uk:5555/do/session/1347795/vsid/199/tid/199/cid/1061396/mid/1020/rid/1052/chid/1029/parser/yes/imref/eqqLmwlGltt5tkeHjskKZlkKrhlK/url/http://www.hmv.co.uk/hmv/departments/d100_sd0_pt0.html -http://www.brd.net/brd-cgi/brd_multimedia/bildbearbeitung/WZ01K0DJ/beurteilung/ci=972850465.htm -http://retailer.gocollect.com/do/session/1912745/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/company_info/affiliate_network.asp -http://www.fao.org/icatalog/orders/basket.asp?prev2=yes&aries_id=1310 -http://www.realestate-mls.com/list.cgi/VACANT_LAND|WATERFRONT|Edenville!Midland!MI -http://www.geocities.co.jp/SilkRoad-Desert/1661/profile/profile.html -http://hp-partner.whowhere.lycos.com/hp/chick/com/nj/ -http://hp-partner.whowhere.lycos.com/hp/chick/com/next/ -http://hp-partner.whowhere.lycos.com/hp/chick/com/nightflight/ -http://www.emerchandise.com/browse/FRIENDS/TSHIRT/20/10/b.TV%20FRIENDS/s.kGIgjr5i -http://dk.egroups.com/group/anarchymcgill -http://bbs.gznet.edu.cn/cgi-bin/getannounce//groups/GROUP_3/WinNT_Win2k/smthbbs/Dir002 -http://de.excite.de/computer/katalog/12947 -http://www.bizline.co.kr/library/data/002/001/007/008/020/002/000017.html -http://www.bizline.co.kr/library/data/002/001/007/008/020/002/000046.html -http://saleonall.com/cat/OPTOMA/6492/video/projectors/145336/oneprod.html -http://sun1.rrzn-user.uni-hannover.de/jgaertner/matlab/help/techdoc/newfeat/ch213.html -http://sun1.rrzn-user.uni-hannover.de/jgaertner/matlab/help/techdoc/newfeat/newfeat.html -http://excite.de/wirtschaft/katalog/37737 -http://www.digitaldrucke.de/(aktuell,kino,kultur,werbung)/_fort/html/themen/aktuell/events/events.htm -http://www.digitaldrucke.de/(aktuell,kino,kultur,kunst)/suche/uebersicht.html -http://www.online.kokusai.co.jp/Stock_corner/V0043566/wrd/G500/stock_corner/stock_corner.html -http://yp.gates96.com/4/37/0/92.html -http://yp.gates96.com/4/37/1/3.html -http://yp.gates96.com/4/37/1/38.html -http://yp.gates96.com/4/37/1/58.html -http://yp.gates96.com/4/37/2/21.html -http://yp.gates96.com/4/37/3/56.html -http://yp.gates96.com/4/37/3/68.html -http://yp.gates96.com/4/37/3/79.html -http://yp.gates96.com/4/37/4/1.html -http://yp.gates96.com/4/37/4/48.html -http://yp.gates96.com/4/37/4/99.html -http://yp.gates96.com/4/37/5/27.html -http://yp.gates96.com/4/37/6/1.html -http://yp.gates96.com/4/37/6/7.html -http://yp.gates96.com/4/37/6/80.html -http://yp.gates96.com/4/37/7/0.html -http://yp.gates96.com/4/37/7/5.html -http://yp.gates96.com/4/37/7/9.html -http://yp.gates96.com/4/37/7/12.html -http://yp.gates96.com/4/37/7/49.html -http://yp.gates96.com/4/37/7/97.html -http://yp.gates96.com/4/37/8/15.html -http://yp.gates96.com/4/37/8/32.html -http://yp.gates96.com/4/37/8/62.html -http://yp.gates96.com/4/37/8/76.html -http://yp.gates96.com/4/37/8/96.html -http://yp.gates96.com/4/37/9/12.html -http://yp.gates96.com/4/37/9/14.html -http://yp.gates96.com/4/37/9/23.html -http://yp.gates96.com/4/37/9/78.html -http://yp.gates96.com/4/37/9/80.html -http://cgi.cnn.com/US/9601/state_union_poll/state_union_speech/pm/ -http://freethemes.netc.pt/cursors/adnload/16904.html -http://freethemes.netc.pt/cursors/preview/16926.html -http://freethemes.netc.pt/cursors/adnload/16953.html -http://library.bangor.ac.uk/search/dTelevision+broadcasting+of+news+--+Wales/dtelevision+broadcasting+of+news+wales/-17,-1,0,B/frameset&F=dtelevision+broadcasting+moral+and+ethical+aspects&1,1 -http://home.baoding.cn.net/~snowcxm/photoshop/newpage6tp.htm -http://home.baoding.cn.net/~snowcxm/photoshop/newpage6xq2.htm -http://dennou-q.geo.kyushu-u.ac.jp/library/Linux/debian-jp/dists/woody/non-free-jp/binary-sparc/otherosfs/?D=A -http://www.tucows.ch/winnt/toolnt_size.html -http://www.sdinfonet.com.cn/379/26/379269983.htm -http://www.sdinfonet.com.cn/379/26/379269980.htm -http://www.egroups.com/message/wdf/3368 -http://de.excite.de/bildung/katalog/35821 -http://kidneyfailure.shn.net/content/article/1677.57596 -http://kidneyfailure.shn.net/content/article/1677.57625 -http://kidneyfailure.shn.net/content/article/1677.57517 -http://kidneyfailure.shn.net/content/article/1677.57456 -http://kidneyfailure.shn.net/content/article/1677.57562 -http://dia.tucows.com/winme/adnload/138490_29803.html -http://www.nhic.or.kr/netbbs/Bbs.cgi/nhic31062/lst/qqo/004A -http://www.nhic.or.kr/netbbs/Bbs.cgi/nhic31062/qry/zka/B2-kB23p/pno/0/qqatt/^ -http://www.nhic.or.kr/netbbs/Bbs.cgi/nhic31062/qry/zka/B2-kB2-n/pno/0/qqatt/^ -http://www.nhic.or.kr/netbbs/Bbs.cgi/nhic31062/qry/zka/B2-kB2-o/pno/0/qqatt/^ -http://dk.egroups.com/message/tw2002/3626 -http://dk.egroups.com/message/tw2002/3644 -http://www.spiral.at/Katalog/Artikel/8908435/ -http://www.spiral.at/Katalog/Artikel/8908842/ -http://168.160.224.62/insurance/200006/10/114941.asp -http://168.160.224.62/insurance/200006/10/114219.asp -http://tucows.soneraplaza.nl/termnt_license.html -http://pub13.ezboard.com/ubelegruin.showPublicProfile?language=EN -http://troy.lib.sfu.ca/search/tbiometrics/tbiometrics/-5,-1,0,B/exact&F=tbiometrical+genetics+the+study+of+continuous+variation&1,2/limit -http://futures.homeway.com.cn/lbi-html/news/content/20001013/172026.shtml -http://jproxy.uol.es/jproxy/http://www.channel6000.com/sh/sports/columnist/stories/columnists-20001030-154321.html -http://www.linux.com/networking/network/free/release/community/development/ -http://pub17.ezboard.com/fskysurfingskysurfersubb.showAddReplyScreenFromWeb?topicID=4.topic -http://ring.tains.tohoku.ac.jp/pub/linux/debian/debian-jp/dists/woody/contrib-jp/binary-m68k/oldlibs/?D=A -http://10000downloads.subportal.com/sn/Network_and_Internet/Misc__Communications_Tools/12507.html -http://www.hbdaily.com.cn/ctdsb/19991101/GB/ctdsb^1042^06^Ct06b08.htm -http://cytobase.cnusc.fr:8101/textes/PURDmail/1998-12/nav00129.html -http://www.brio.de/BRIO.catalog/39fe2f73050d53aa2741d472aa7806d2/UserTemplate/9 -http://www.anekdot.ru:8084/an/an0007/t000731.html -http://statweb.byu.edu/sasdoc/sashtml/gref/z0265802.htm -http://oss.sgi.com/cgi-bin/cvsweb.cgi/linux/drivers/char/ftape/Makefile?only_with_tag=davem-cvs-merge -http://www.intellicast.com/Golf/World/UnitedStates/Southeast/NorthCarolina/Hawksnest/WINDcast/d1_00/bannerAd.shtml -http://dailynews.sina.com.hk/sinaNews/wiser/hkStock/2000/0720/1418727.html -http://ftp.dti.ad.jp/pub/lang/CPAN/authors/id/A/AG/AGUL/?S=A -http://link.fastpartner.com/do/session/600392/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/jobpilot.php -http://link.fastpartner.com/do/session/600392/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/smartguy.php -http://citeseer.nj.nec.com/cidcontext/1024594 -http://www.burstnet.com/ads/ad4820b-map.cgi/1395444997 -http://us.mandrakesoft.com/cgi-bin/cvsweb.cgi/kdeutils/kpm/proc.h?r1=1.6&only_with_tag=HEAD -http://www.uftree.com/UFT/WebPages/JenHawkins/ALL/d0/i0001501.htm -http://www.uftree.com/UFT/WebPages/JenHawkins/ALL/d0/i0000641.htm -http://www.uftree.com/UFT/WebPages/JenHawkins/ALL/d1/i0000932.htm -http://www.uftree.com/UFT/WebPages/JenHawkins/ALL/d1/i0000762.htm -http://www.uftree.com/UFT/WebPages/JenHawkins/ALL/d1/i0000997.htm -http://www.uftree.com/UFT/WebPages/JenHawkins/ALL/d1/i0001325.htm -http://www.uftree.com/UFT/WebPages/JenHawkins/ALL/nindex.htm -http://www.primenet.com/~g-lady/Farewell/_borders/ -http://imasy.or.jp/~iwao/hokkaido/kushiro.html -http://citeseer.nj.nec.com/nrelated/0/208436 -http://www.zeal.com/Arts___Entertainment/Literature/Authors/Lovecraft__H_P_/Books/Cthulhu_Campus_Crusade_for_Cthulhu/ -http://ftp1.se.debian.org/debian/dists/woody/contrib/binary-mipsel/mail/?M=A -http://ftp1.se.debian.org/debian/dists/woody/contrib/binary-mipsel/mail/?S=A -http://webtools.familyeducation.com/whatworks/item/front/0,2551,1-10698-1981-,00.html -http://www.affiliate.hpstore.hp.co.uk/do/session/380859/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/REGISTRATION/entry.asp -http://www.collectingnation.com/cgi-bin/bn/view_feedback.mod/pn?HANDLE=pokeweed -http://www.egroups.com/messages/Future-History-L/213 -http://www.egroups.com/message/Future-History-L/192 -http://www.burstnet.com/ads/cb7826a-map.cgi/1384588733 -http://www.cs.com.cn/csnews/articles/142_23823.htm -http://search.yam.com.tw/en/new/edu/hs/voca/tpc_vs/ -http://ftp.univie.ac.at/packages/tex/macros/latex2e/contrib/supported/vmargin/?D=A -http://citeseer.nj.nec.com/cidcontext/3145269 -http://yp.gates96.com/11/72/80/34.html -http://yp.gates96.com/11/72/80/36.html -http://yp.gates96.com/11/72/80/76.html -http://yp.gates96.com/11/72/81/26.html -http://yp.gates96.com/11/72/81/67.html -http://yp.gates96.com/11/72/83/68.html -http://yp.gates96.com/11/72/84/29.html -http://yp.gates96.com/11/72/84/39.html -http://yp.gates96.com/11/72/85/56.html -http://yp.gates96.com/11/72/85/63.html -http://yp.gates96.com/11/72/85/96.html -http://yp.gates96.com/11/72/86/3.html -http://yp.gates96.com/11/72/86/28.html -http://yp.gates96.com/11/72/86/59.html -http://yp.gates96.com/11/72/86/63.html -http://yp.gates96.com/11/72/88/43.html -http://yp.gates96.com/11/72/89/8.html -http://yp.gates96.com/11/72/89/13.html -http://yp.gates96.com/11/72/89/20.html -http://cometweb01.comet.co.uk/do!session=132039&vsid=700&tid=20&cid=37030&mid=1000&rid=1060&chid=1713&url=eqqLmwlGltt5tkkHbqpLZXmLbkZHljlKaltLkilLXalKfkaLbukKeqjLi1 -http://iworld.freethemes.com/savers/adnload/77213.html -http://iworld.freethemes.com/savers/adnload/35420.html -http://www.questlink.com/QL/CDA/Research/ProductBrief/1,1768,0_11201_353170_43264,00.html -http://www.questlink.com/QL/CDA/Research/ProductBrief/1,1768,0_11201_353170_43305,00.html -http://www2.eunet.lv/library/iso/HISTORY/RUSSIA/Mirrors -http://nathanael.upi.jussieu.fr/tele6.nsf/autres+centres+de+formations!OpenPage&ExpandSection=10,3,5,16,14,6 -http://nathanael.upi.jussieu.fr/tele6.nsf/autres+centres+de+formations!OpenPage&ExpandSection=17,3,5,16,14,6 -http://opac.lib.rpi.edu/search/dnatural+history+united+states+historiography+dictionaries/-17,-1,0,B/browse -http://opac.lib.rpi.edu/search/dnatural+history+united+states+historiography+dictionaries/7,-1,0,B/browse -http://www.sportinggreen.com/news/20001014/fbo/fbc/abb/001014.0391.html -http://yp.gates96.com/0/14/10/63.html -http://yp.gates96.com/0/14/10/80.html -http://yp.gates96.com/0/14/11/32.html -http://yp.gates96.com/0/14/11/37.html -http://yp.gates96.com/0/14/11/80.html -http://yp.gates96.com/0/14/13/21.html -http://yp.gates96.com/0/14/13/23.html -http://yp.gates96.com/0/14/13/38.html -http://yp.gates96.com/0/14/13/49.html -http://yp.gates96.com/0/14/13/90.html -http://yp.gates96.com/0/14/14/53.html -http://yp.gates96.com/0/14/14/63.html -http://yp.gates96.com/0/14/14/77.html -http://yp.gates96.com/0/14/15/12.html -http://yp.gates96.com/0/14/15/88.html -http://yp.gates96.com/0/14/15/96.html -http://yp.gates96.com/0/14/16/27.html -http://yp.gates96.com/0/14/16/62.html -http://yp.gates96.com/0/14/16/67.html -http://yp.gates96.com/0/14/16/86.html -http://yp.gates96.com/0/14/16/92.html -http://yp.gates96.com/0/14/17/15.html -http://yp.gates96.com/0/14/17/22.html -http://yp.gates96.com/0/14/17/44.html -http://yp.gates96.com/0/14/18/27.html -http://yp.gates96.com/0/14/18/29.html -http://yp.gates96.com/0/14/18/83.html -http://yp.gates96.com/0/14/19/35.html -http://yp.gates96.com/0/14/19/58.html -http://www.123bestphonerates.com/q/001p/vn/ZWUdEJwdxM.htm -http://www.trax.nilex.co.uk/trax.cgi/A1C/B1U/A2S/B3L/A4S/B1L/ -http://www.trax.nilex.co.uk/trax.cgi/A1C/B1U/A2S/B3L/A4S/C2D/ -http://southwind.themes.tucows.com/skins/icq/preview/68532.html -http://southwind.themes.tucows.com/skins/icq/adnload/77797.html -http://southwind.themes.tucows.com/skins/icq/preview/55623.html -http://southwind.themes.tucows.com/skins/icq/adnload/51324.html -http://southwind.themes.tucows.com/skins/icq/adnload/26609.html -http://southwind.themes.tucows.com/skins/icq/adnload/48629.html -http://southwind.themes.tucows.com/skins/icq/adnload/48628.html -http://www.webcom.com.mx/cronica/1999/mar/09/neg01.html -http://jproxy.uol.es/jproxy/http://mars.jpl.nasa.gov/msp98/news/mpl000207.html -http://jproxy.uol.es/jproxy/http://mars.jpl.nasa.gov/msp98/news/news61.html -http://jproxy.uol.es/jproxy/http://mars.jpl.nasa.gov/msp98/ds2/fact.html -http://jproxy.uol.es/jproxy/http://mars.jpl.nasa.gov/mgs/sci/mola/98lander.html -http://jproxy.uol.es/jproxy/http://mars.jpl.nasa.gov/msp98/news/status990123.html -http://ustlib.ust.hk/search*chi/dmarriage/dmarriage/-5,-1,0,B/exact&F=dmarriage+china&1,4/limit -http://mediate.magicbutton.net/do/session/625641/vsid/4385/tid/4385/cid/88138/mid/1702/rid/2114/chid/3393/url/http://www.worldgallery.co.uk/frameset-artc.html -http://www.scifi.com/cgi-bin/rbox/articles.pl?1&6&1721&20 -http://www.areteoutdoors.com/contribute/earth/b.97.r.54.g.1706.html -http://members.tripod.lycos.co.kr/ifoo6981/?M=A -http://link.fastpartner.com/do/session/600395/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/bol.php -http://link.fastpartner.com/do/session/600395/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/mediatransfer.php -http://link.fastpartner.com/do/session/600395/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/smartguy.php -http://www.safrex.com/catalog/elite08/elite084c.html -http://www.911codes.com/games/platform/psx/sect/div/cont/list_cheat/spray/y/id/0000005511/gid/0000003893/_cheats/_walkthroughs/_codes/_pc/_n64/_psx/_gameboy/_playstation/ -http://yp.gates96.com/7/44/10/4.html -http://yp.gates96.com/7/44/10/15.html -http://yp.gates96.com/7/44/10/30.html -http://yp.gates96.com/7/44/10/32.html -http://yp.gates96.com/7/44/10/36.html -http://yp.gates96.com/7/44/11/1.html -http://yp.gates96.com/7/44/11/41.html -http://yp.gates96.com/7/44/11/44.html -http://yp.gates96.com/7/44/12/29.html -http://yp.gates96.com/7/44/12/76.html -http://yp.gates96.com/7/44/12/81.html -http://yp.gates96.com/7/44/13/56.html -http://yp.gates96.com/7/44/14/19.html -http://yp.gates96.com/7/44/15/14.html -http://yp.gates96.com/7/44/15/52.html -http://yp.gates96.com/7/44/15/62.html -http://yp.gates96.com/7/44/15/72.html -http://yp.gates96.com/7/44/15/78.html -http://yp.gates96.com/7/44/15/81.html -http://yp.gates96.com/7/44/15/82.html -http://yp.gates96.com/7/44/16/78.html -http://yp.gates96.com/7/44/16/93.html -http://yp.gates96.com/7/44/17/51.html -http://yp.gates96.com/7/44/17/75.html -http://yp.gates96.com/7/44/18/43.html -http://yp.gates96.com/7/44/18/92.html -http://yp.gates96.com/7/44/19/26.html -http://www3.newstimes.com/archive2000/oct17/bze.htm -http://member.aol.co%20m/askmo/ -http://home.excite.co.uk/directory/categories/528195 -http://www.scifi.com/bboard/browse.cgi/1/5/545/11566?pnum=1 -http://member.shangdu.net/home1/havdone/game/gonglue/ljcq.htm -http://member.shangdu.net/home1/havdone/game/gonglue/lishou.htm -http://archiv.leo.org/cgi-bin/leo-md5.pl/pub/comp/usenet/comp.sources.misc/dostrace/ -http://yp.gates96.com/8/70/91/12.html -http://yp.gates96.com/8/70/91/20.html -http://yp.gates96.com/8/70/91/45.html -http://yp.gates96.com/8/70/92/29.html -http://yp.gates96.com/8/70/92/40.html -http://yp.gates96.com/8/70/92/74.html -http://yp.gates96.com/8/70/93/9.html -http://yp.gates96.com/8/70/93/11.html -http://yp.gates96.com/8/70/94/10.html -http://yp.gates96.com/8/70/94/90.html -http://yp.gates96.com/8/70/95/4.html -http://yp.gates96.com/8/70/95/13.html -http://yp.gates96.com/8/70/95/58.html -http://yp.gates96.com/8/70/95/74.html -http://yp.gates96.com/8/70/95/80.html -http://yp.gates96.com/8/70/96/34.html -http://yp.gates96.com/8/70/96/65.html -http://yp.gates96.com/8/70/97/0.html -http://yp.gates96.com/8/70/97/16.html -http://yp.gates96.com/8/70/97/75.html -http://yp.gates96.com/8/70/98/27.html -http://yp.gates96.com/8/70/98/60.html -http://www.icopyright.com/1.1638.306154 -http://www.zeal.com/category/be_zealous.jhtml?cid=828 -http://lib1.nippon-foundation.or.jp/1996/0621/contents/004.htm -http://www.haikou.hainan.gov.cn/pandect/nj/n96jada.htm -http://www.chaos.dk/sexriddle/s/e/x/p/b/m/s/ -http://www.symantec.ca/region/uk/resources/mobile/nav.html -http://retailer.gocollect.com/do/session/1912798/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/product_display/products/product_lines.asp -http://polygraph.ircache.net:8181/services/define/http_-2www.microsoft.com/ie/Tabitha/http_-2www.adultlinks.net/gallery.shtml -http://f22.parsimony.net/forum42460/messages/1.htm -http://www.greenleaves.com/bookcat/gb_0722530986.html -http://www.classiccmp.org/mail-archive/classiccmp/1998-06/0638.html -http://www1.onelist.com/dir/Society/Paranormal/UFOs/Biblical_Perspectives -http://home.hiwaay.net/~bjacobs/genealogy/laster/html/d0055/g0000045.html -http://link.fastpartner.com/do/session/600374/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/netmaling.php -http://big5.peopledaily.com.cn/haiwai/200003/03/newfiles/A104.html -http://ustlib.ust.hk/search*chi/achang+chieh+mei/achang+chieh+mei/-5,-1,0,B/frameset&F=achang+chieh+fu&1,,2 -http://teleline.terra.es/personal/mgsair/chtml/ejemplos/marcos1.html -http://myhome.naver.com/toktok01/bbs.php3?p_work=admin&p_page=1 -http://netway.pda.tucows.com/palm/adnload/34443_22051.html -http://netway.pda.tucows.com/palm/adnload/34930_22057.html -http://netway.pda.tucows.com/palm/adnload/34435_22044.html -http://us.mandrakesoft.com/cgi-bin/cvsweb.cgi/kmusic/brahms/qtWaveTrack.h?sortby=rev&only_with_tag=HEAD -http://sinr.net/book/content/39/8411.html -http://www.egroups.com/post/gvocsa?act=reply&messageNum=145 -http://www.diogenes.ch/4DACTION/web_rd_aut_prview/a_id=7056669&area=&ID=483352 -http://www.brio.de/BRIO.catalog/39fe2f7d06fe4a08273fd472aa7806a9/UserTemplate/1 -http://www3.newstimes.com/archive2000/sep01/rgd.htm -http://community.webshots.com/photo/5886633/5886821zAagKCgZhs -http://community.webshots.com/photo/5886633/5917061PxBHHqElgV -http://www.dnai.com/~mbaum/anita/html/eng/art/images/image38.html -http://www.houses-apartment-listings.com/Michigan/city_search_criteria.asp?state=MI&City=CLINTON -http://www.brio.de/BRIO.catalog/39fdb87c09896af6273fd472aa78076c/UserTemplate/10 -http://www.expressindia.com/ie/daily/19990129/02950495p.html -http://www.linux.com/networking/web/unix/internet/project/security/ -http://www.linux.com/networking/web/unix/internet/project/Red_Hat/ -http://www.linux.com/networking/web/unix/internet/project/freshmeat/ -http://www.linux.com/networking/web/unix/internet/project/?kw_offset=50 -http://ring.yamanashi.ac.jp/pub/linux/debian/debian/dists/Debian2.2r0/non-free/binary-i386/science/?N=D -http://ftp.task.gda.pl/pub/games/idgames/utils/level_edit/acaddoom.txt -http://www.affiliate.hpstore.hp.co.uk/do/session/380864/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/FR/REGISTRATION/entry.asp -http://fi.egroups.com/post/allianc?act=reply&messageNum=2305 -http://polygraph.ircache.net:8181/services/design/company/http_-2burn.ucsd.edu/~abcf -http://polygraph.ircache.net:8181/services/design/company/miami.htm -http://www.utexas.edu/ftp/admin/AI_ATTIC/ATW/Mosaic.instruct/?D=A -http://ftp.du.se/disk3/redhat/updates/powertools/current/alpha/ -http://www.multicosm.com/facade/demo.multicosm.com/facade/www.informationweek.com/mediakit/00/default.html -http://www.multicosm.com/facade/demo.multicosm.com/facade/www.informationweek.com/mediakit/00/about_overview.html -http://www7.tok2.com/home/maki67/menu.htm -http://www.mapion.co.jp/custom/AOL/admi/23/23103/tsujicho/2chome/index-24.html -http://sunsite.org.uk/public/computing/networks/internet/ietf/printmib/printmib-attendees-97apr.txt -http://ftp.univie.ac.at/packages/tex/macros/latex2e/contrib/supported/nomencl/?N=D -http://spaceports.tucows.com/winme/adnload/137993_30287.html -http://habenix.uni-muenster.de/Rektorat/Forschungsberichte-1997-1998/fo05acd01.htm -http://www.power2lead.com/Global/English.nsf/pgWWLocations!OpenPage&ExpandSection=2,25,7,32,18 -http://www.teacherformation.org/html/od/facilitators.cfm/task1,help/discussion_id,2/xid,6155/yid,3651726 -http://itcareers.careercast.com/texis/it/itjs/+IwwBmeS9D867xwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqew7hmwGAnBoDtapGdtGwMamnVncdpa51ppdGBaqconDBaqdMM1DoqwBodDaoDVn5BMnDBapGdm1qBaMwDwtnaqGnwBoVnaMFqhgfHNEDzm7wwwpBmeg9D86exqwww5rmeqDwwwBrmeZpwww/morelike.html -http://itcareers.careercast.com/texis/it/itjs/+XwwBmie0B-deaqwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqew7hmwGAnBoDtapGdtGwMamnVncdpa51ppdGBaqconDBaqdMM1DoqwBodDaoDVn5BMnDBapGdm1qBaMwDwtnaqGnwBoVnaMFqhgfHNEDzm7wwwpBmeg9D86exqwww5rm-mwwBrmeZpwww/morelike.html -http://members.iinet.net.au/~scott3/legacy/matt.html -http://cn.egroups.com/post/bastardimage?act=forward&messageNum=11 -http://ftp.nodomainname.net/pub/mirrors/.2/gnu/tasks/?N=D -http://ftp.nodomainname.net/pub/mirrors/.2/gnu/tasks/standards.text -http://10000downloads.subportal.com/sn/Utilities/Misc__Utilities/11320.html -http://mindit.netmind.com/proxy/http://www.altera.com/html/tools/swupdates.html -http://www.next.com.hk/mag/419/news/an06.htm -http://www.areteoutdoors.com/channel/air/b.283.g.3871.html -http://troop485.tripod.com/documents/johnwayne.htm -http://troop485.tripod.com/documents/bp-churchhill.htm -http://sound-dist.secured.co.uk/cgi-bin/psProdDet.cgi/22P03|972959558|Security|user|0|1,0,0,1 -http://www9.hmv.co.uk:5555/do/session/1347794/vsid/199/tid/199/cid/1061396/mid/1020/rid/1052/chid/1029/parser/yes/imref/eqqLmwlGltt5tkeHjskKZlkKrhlK/url/http://www.hmv.co.uk/hmv/departments/d120_sd0_pt0.html -http://ftp.du.se/debian/dists/Debian2.2r0/main/disks-m68k/2.2.16-2000-07-14/mac/images-1.44/?S=A -http://opac.lib.ntnu.edu.tw/search*chi/++ftlist/bp20043193/-5,-1,0,B/buttonframe&F=bp20043190&1,1 -http://www.parlament.ch/internet98/Poly/Suchen_amtl_Bulletin/ce98/ete/275.HTM -http://in.egroups.com/messages/svpvril/5195?viscount=-30 -http://in.egroups.com/messages/svpvril/?expand=1 -http://retailer.gocollect.com/do/session/1912744/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/checkout/shopping_cart.asp -http://retailer.gocollect.com/do/session/1912744/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/clubhouse/suggestions.asp -http://www18.freeweb.ne.jp/sports/imamako/ -http://www.cs.ucc.ie/javadocs/jdk1.2.2/docs/api/java/awt/geom/class-use/QuadCurve2D.Double.html -http://click-to.tell-a-friend.boardhost.com/tell-a-friend-confirm.cgi?stigmaonline&msg=172 -http://www.emerchandise.com/aboutus/b.TV%20ANGEL/s.2YYjVOgH -http://www.leyou.com/product/ShowResult.php?LY_Category=0531&page=3 -http://cafe6.daum.net/Cafe-bin/Bbs.cgi/rest114pds/qry/zka/B2-kB23o/qqatt/^ -http://sunsite.informatik.rwth-aachen.de/LinuxArchives/sunsite.unc.edu/distributions/linux-router/dists/2.9.6/base/?N=D -http://www-uk5.cricket.org/link_to_database/ARCHIVE/1999-2000/PAK_IN_SL/FANTASY/ -http://findmail.com/message/sangersreview/99 -http://phase.etl.go.jp/mirrors/netlib/utk/people/JackDongarra/SLIDES/osu-498/sld011.htm -http://tucows.datasync.com/winme/preview/75261.html -http://secure.danysoft.com/asp/dany.tienda/1266636789/Catalog -http://www.birding.about.com/hobbies/birding/cs/placesecuador/index_2.htm -http://www.cpami.gov.tw/ymsnp/animal/fauna/nospc385text.htm -http://www.fh-telekom-leipzig.de/hilfe/pak_e/paket_inhalt_jade_dsl.html -http://home.vicnet.net.au/~nunayl/feedback.html -http://www.expage.com/nibina -http://www.expage.com/virtuaalisiittolantallivihko -http://www.expage.com/muittentallijenkisoja -http://www.arm.com/sitearchitek/support.ns4/html/cores_faq!OpenDocument&ExpandSection=9,39,33 -http://retailer.gocollect.com/do/session/1912707/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/product_display/top_ten.asp?pagenum=2 -http://www.streetprices.com/Electronics/Other/MAKE+SYMANTEC/sortdetailbystock/SP322647.html -http://www.peopledaily.co.jp/haiwai/199810/09/no_981009003024_6.html -http://mediate.magicbutton.net/do/session/625622/vsid/4385/tid/4385/cid/88138/mid/1702/rid/2114/chid/3393/url/http://www.worldgallery.co.uk/frameset-artc.html -http://mediate.magicbutton.net/do/session/625622/vsid/4385/tid/4385/cid/88138/mid/1702/rid/2114/chid/3393/url/http://www.worldgallery.co.uk/frameset-top50.html -http://www.nada.kth.se/systemgruppen/docs/javadoc/jdk-1.3/docs/api/javax/swing/plaf/basic/class-use/BasicSliderUI.ChangeHandler.html -http://kernel2.adver.com.tw/Counter/log/kernel2.adver.com.tw/Collect_DB_Advers2/2000-09-10/08/?N=D -http://yp.gates96.com/12/57/30/53.html -http://yp.gates96.com/12/57/32/14.html -http://yp.gates96.com/12/57/32/97.html -http://yp.gates96.com/12/57/33/1.html -http://yp.gates96.com/12/57/33/37.html -http://yp.gates96.com/12/57/37/91.html -http://yp.gates96.com/12/57/37/98.html -http://yp.gates96.com/12/57/38/23.html -http://yp.gates96.com/12/57/38/34.html -http://yp.gates96.com/12/57/38/51.html -http://yp.gates96.com/12/57/38/53.html -http://yp.gates96.com/12/57/39/43.html -http://yp.gates96.com/12/57/39/56.html -http://yp.gates96.com/12/57/39/68.html -http://yp.gates96.com/12/57/39/70.html -http://www3.sympatico.ca/jacques.m.boisvert/Data_Distribution.html -http://www.garekiya.com/female/female02-25.html -http://www.brio.de/BRIO.catalog/39fe2f6c06f4cd8e273fd472aa780734/UserTemplate/5 -http://202.99.23.195/GB/channel1/13/20001030/291723.html -http://db.bbc.co.uk/education/gcsebitesize/maths/shape_and_space_i_h/loci_rev.shtml -http://commerce.was-inc.com/cgi-bin/abtwsam.dll/LbkWebCommerceStoreCategories-BBC709F9_97F3_1F2D7EFC4CA45617D914720977E88400 -http://commerce.was-inc.com/cgi-bin/abtwsam.dll/LbkWebCommerceShoppingCartPage-BBC709F9_97F3_1F2D7EFC4CA45617D914720977E88400 -http://polygraph.ircache.net:8181/http_-2www.microsoft.com/frontpage/http_-2www.hercules.com/history.htm -http://www.jbc.org/cgi/content/short/275/36/27501 -http://brazil.mit.edu/sdb/de/html/keylist.NNTP.html -http://ads3.zdnet.com/c/g=r771&c=a53605&idx=2000.10.30.21.30.57/www.micronpc.com/zd/max1299 -http://webtools.familyeducation.com/whatworks/item/front/0,2551,22-9696-6689-473-46499,00.html -http://www.dispatch.co.za/2000/04/08/business/HIGHLOW.HTM -http://generalstore.everdream.com/kore/catalog/Office_Supplies/Forms,_Record_Keeping_&_Reference/Human_Resources/Motivational/brand.html?sort=price&count=0 -http://www.laria.u-picardie.fr/docs/www.linux-france.org/article/securite/intro.html -http://ftp.uni-stuttgart.de/pub/netscape/communicator/slovenian/4.51/windows/windows95_or_nt/ -http://cafe4.daum.net/Cafe-bin/Bbs.cgi/monjatingpds/lst/qqeq/1/zka/B2-kBnNt -http://myhome.shinbiro.com/~funky27/novel18.htm -http://www.apcmag.com/apcweb/reviewsdisc.nsf/aac7d56ca8fd884b852563be00610639/25858e2d9c878e294a2567060015364d!EditDocument -http://www.private-immobilien-boerse.de/nordrhein-Westfalen/luedinghausen/Verkauf/3d-service/Gemeinsam/Immolink/Gemeinsam/erreichenPartner/Private-IB/ -http://www.eos.dk/archive/swing/msg00405.html -http://www.jobvillage.com/channel/jobs/human_resources/benefits_analysis/b.2807.g.1757.html -http://www.hanaga.com.cn/gbjc/tc/jq.htm -http://www.multimap.com/wi/33747.htm -http://www.multimap.com/wi/143959.htm -http://home.freeuk.net/jdl/Left_Navigate.htm -http://www.crit.org/nph-edit.cgi/http://crit.org/pub/ifi.unizh.ch/wagner/just-testing.html -http://www.interessengemeinschaft-musik.de/catalog%20data/body_22.html -http://aleph.tau.ac.il:4500/ALEPH/ENG/ATA/AAS/AAS/FIND-ACC/0333501 -http://www.mojahedin.org/Pages/Mojahed/Mojahed451/rp/rp09.html -http://genforum.genealogy.com/cgi-genforum/forums/lenhart.cgi?158 -http://carriage.de/Schoner/collections/Geschichte/Sammlungen/info-e/ -http://cafe4.daum.net/Cafe-bin/Bbs.cgi/pflhs11pds/rnw/zka/B2-kB2-s -http://ftp.lip6.fr/pub11/NetBSD/arch/hpcmips/pkgstat/20001008.0536/textproc/xerces-j-current/ -http://dk.egroups.com/message/scotdisinfo/306 -http://groups.haas.berkeley.edu/hcs/Docs/SASv8/sasdoc/sashtml/proc/z0360708.htm -http://www.legend-net.com/news/tiyu/messages/474.html -http://www.legend-net.com/news/tiyu/messages/466.html -http://tv.thevines.com/leaf/AA0000373887/3/0/0/&hmode=on -http://vorg1.subportal.com/sn/Business/Enhanced_Calculators/5511.html -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=7,28,31,24,35 -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=24,5,17,30,11 -http://ftp.gwdg.de/pub/eff/Global/USA/Legislation/gtda_export.regulations -http://www.dein-schicksal.de/Fotoanzeigen/April_2000/7/17/27/body_57.html -http://www.fujian-window.com/Fujian_w/news/mzrb1/20000630/2_14.html -http://www.webswap.com/shelf/2/17559/sell.html -http://search.leg.wa.gov/wslrcw/RCW%20%2036%20%20TITLE/RCW%20%2036%20.100%20%20CHAPTER/RCW%20%2036%20.100%20.060.htm -http://www.doc.ic.ac.uk/lab/labsrc_area/firstyear/submissions/1997-98/jmc1/labs/Ex02/icc97/?M=A -http://school.educities.org/card/abc0609.html -http://school.educities.org/card/huangmei.html -http://school.educities.org/card/a126457822.html -http://school.educities.org/card/a8911.html -http://school.educities.org/card/aa5117.html -http://school.educities.org/card/b3575610.html -http://school.educities.org/card/c5625.html -http://school.educities.org/card/h1230997.html -http://school.educities.org/card/h224153937.html -http://school.educities.org/card/julie9.html -http://school.educities.org/card/lefe135.html -http://school.educities.org/card/nl123.html -http://school.educities.org/card/s5802.html -http://school.educities.org/card/s58120.html -http://school.educities.org/card/s5931.html -http://school.educities.org/card/s6197.html -http://school.educities.org/card/vov.html -http://school.educities.org/card/xx5331.html -http://darkwing.uoregon.edu/~cblanksh/GeneratedItems/?M=A -http://ciscom.gamecenter.com/Tipcheat/PC/Item/0,128,0-202,00.html -http://rotten-tomatoes.com/movies/browse/1010942/video.php -http://rotten-tomatoes.com/movies/browse/1076825/reviews.php -http://archive.soccerage.com/s/fr/09/98335.html -http://www.ferien-immobilien.de/nordrhein-Westfalen/aachen/Verkauf/GmbH-Kauf-Verkauf-Insolvenz-konkurs/Startseite/3d-service/Gemeinsam/erreichenPartner/Gemeinsam/impressum.htm -http://www.ebigchina.com/tool_tellfriend.phtml?code=msg&mid=3174 -http://people.freebsd.org/~knu/cgi-bin/cvsweb.cgi/src/libexec/rpc.rwalld/Makefile?only_with_tag=RELENG_3 -http://people.freebsd.org/~knu/cgi-bin/cvsweb.cgi/src/libexec/rpc.rwalld/Makefile?only_with_tag=MAIN -http://people.freebsd.org/~knu/cgi-bin/cvsweb.cgi/src/libexec/rpc.rwalld/Makefile?only_with_tag=RELENG_3_BP -http://ring.jec.ad.jp/pub/linux/debian/debian/dists/unstable/contrib/binary-sh/admin/?M=A -http://www2.eunet.lv/library/alt/URIKOVA/FORTUNE_D/Mirrors -http://www.hermes.dk/departments/om/publica.shtml -http://208.194.150.10/Ski/Articles/DrDewpoint/001/bannerAd.shtml -http://us.mandrakesoft.com/cgi-bin/cvsweb.cgi/quanta/quanta/widgets/?sortby=log&only_with_tag=start -http://biblio.cesga.es:81/search*gag/aSempere+Navarro,+Antonio-Vicente/asempere+navarro+antonio+vicente/-5,-1,0,E/frameset&F=asempere+y+guarinos+juan+trad&1,1 -http://www.fractal.com.ru/Component/Toshiba/74Cxx/TC74HC74DS.pdf -http://www.staroriental.net/nav/soeg/ihf,aai,n3,7,Electric+Wave+Girl+1998.html -http://excite.de/auto/katalog/11803 -http://gatekeeper.dec.com/pub/BSD/NetBSD/NetBSD-current/pkgsrc/sysutils/amanda-client/pkg/ -http://www.smcworld.com/smcworld/bp_e/large/0524_2301_002x2301_003x2301_004x2301_005x2301_006x2301_007_2301_005b.html -http://www.kaos.dk/sexriddle/x/j/t/z/d/ -http://www.kaos.dk/sexriddle/x/j/t/z/e/ -http://spartanburg2.edgate.com/blgspringes/school_athletics/parent/ -http://www-personal.engin.umich.edu/~mhaanpaa/?S=D -http://www.amcity.com/jacksonville/stories/2000/05/15/story8.html?t=email_story -http://yp.gates96.com/7/47/40/13.html -http://yp.gates96.com/7/47/42/7.html -http://yp.gates96.com/7/47/43/2.html -http://yp.gates96.com/7/47/43/22.html -http://yp.gates96.com/7/47/43/54.html -http://yp.gates96.com/7/47/44/0.html -http://yp.gates96.com/7/47/45/3.html -http://yp.gates96.com/7/47/45/30.html -http://yp.gates96.com/7/47/45/78.html -http://yp.gates96.com/7/47/45/89.html -http://yp.gates96.com/7/47/46/41.html -http://yp.gates96.com/7/47/46/71.html -http://yp.gates96.com/7/47/48/1.html -http://yp.gates96.com/7/47/48/68.html -http://yp.gates96.com/7/47/48/92.html -http://yp.gates96.com/7/47/49/6.html -http://yp.gates96.com/7/47/49/43.html -http://yp.gates96.com/7/47/49/86.html -http://yp.gates96.com/7/47/49/97.html -http://de.excite.de/bildung/katalog/24692 -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=90&discrim=226,20,231 -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=90&discrim=226,20,4 -http://www.affiliate.hpstore.hp.co.uk/do/session/380862/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/search.asp -http://www1.zdnet.co.uk/news/news1/ns-1511.html -http://bellona.itworld.com:8080/cwi/reprint/0,1926,NAV63-128-1357-1367_STO48730,00.html -http://wwwhome.cs.utwente.nl/~zwiers/projects/docs/jdk/api/java/util/class-use/SortedMap.html -http://cgi.cnnsi.com/football/nfl/players/Ed.McCaffrey/ -http://fi.egroups.com/messages/philmusic/12006 -http://fi.egroups.com/messages/philmusic/12123 -http://fi.egroups.com/messages/philmusic/213 -http://fi.egroups.com/messages/philmusic/1826 -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=22,0+20,0-9,2-~ -http://my.egroups.com/message/gps4gis/164 -http://www.bemi-immobilien.de/Startseite/www.allgemeine-immobilien-boerse.de/allgemeine-ib/landkreiszwickau/Verkauf/29109700708107kirchbergvillamü/Gemeinsam/MarketingStrategie/Gemeinsam/Inserieren/Startseite/Startseite/Gemeinsam/versicherungen/gebaeude/anforderungsformular.htm -http://apple.excite.com/entertainment/fine_arts/classical_music/composers/baroque_composers/albinoni_tomaso/works/ -http://www.lithoquoter.com/Scripts/WebObjects.exe/Printers.woa/609420000046582000001552000000949302/main.wo/7834100000849302/4/-/prime -http://yp.gates96.com/11/75/40/25.html -http://yp.gates96.com/11/75/40/38.html -http://yp.gates96.com/11/75/40/88.html -http://yp.gates96.com/11/75/40/91.html -http://yp.gates96.com/11/75/42/1.html -http://yp.gates96.com/11/75/42/74.html -http://yp.gates96.com/11/75/42/81.html -http://yp.gates96.com/11/75/43/45.html -http://yp.gates96.com/11/75/43/51.html -http://yp.gates96.com/11/75/46/25.html -http://yp.gates96.com/11/75/46/72.html -http://yp.gates96.com/11/75/46/89.html -http://yp.gates96.com/11/75/46/91.html -http://yp.gates96.com/11/75/47/5.html -http://yp.gates96.com/11/75/48/67.html -http://yp.gates96.com/11/75/49/89.html -http://users.telerama.com/~mross/jenny/forsale.html -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=14&discrim=212,57 -http://ring.htcn.ne.jp/archives/NetBSD/NetBSD-1.4.2/atari/binary/security/?N=D -http://library.bangor.ac.uk/search/dCanada+--+Agricultural+resources+--+19th+century/dcanada+agricultural+resources+++19th+century/-5,-1,0,B/exact&F=dcanaanites&1,3 -http://www.brio.de/BRIO.catalog/39fe2f6406e8eec4273fd472aa780738/UserTemplate/5 -http://kuyper.calvin.edu/fathers2/NPNF1-05/npnf1-05-04.htm -http://kuyper.calvin.edu/fathers2/NPNF1-05/npnf1-05-08.htm -http://kuyper.calvin.edu/fathers2/NPNF1-05/npnf1-05-20.htm -http://polygraph.ircache.net:8181/http_-2www.sgi.net/http_-2www.itools.com/research-it/http_-2www.aardvarkclay.com/Themes/http_-2www.snapsite.com/guests/sk8ctrl/public/html/sitemap/sitemap.htm -http://www.genexchange.com/cemlist.cfm?state=mo&county=webster -http://newsone.net/nnr/showart/alt.current-events.haiti/911 -http://212.11.11.62/voyages_degriffes/MEXIQUE/PARIS+-+MEXICO+A%2FR/SAI00511790/ -http://bitwise.linux.tucows.com/x11html/adnload/131942_45932.html -http://www.brio.de/BRIO.catalog/39fe2f740910301a2740d472aa7806aa/UserTemplate/1 -http://singles-ads.theshoppe.com/cgi-bin/c/736/64/dXNlcmJhbm5lcg==/gn/3585/ -http://www.chaos.dk/sexriddle/j/l/v/y/t/ -http://www.interlog.com/~prandall/relations/d0003/g0000795.html -http://ftp.jp.debian.org/debian/dists/woody/non-free/binary-arm/oldlibs/?M=A -http://biblioteca.upv.es/bib/doc/doc_fisbd/129/97268//V/1828099/6////25/N/MLTPAID -http://biblioteca.upv.es/bib/doc/doc_fisbd/129/147168//V/1828099/11////25/N/MLTPAID -http://biblioteca.upv.es/bib/doc/doc_fisbd/129/124846//V/1828099/24////25/N/MLTPAID -http://mirrortucows.technet.it/winme/htmlbeginnerme_size.html -http://www.bcbsal.org/Provider_Dir/pharmacy/state/Georgia/HAWKINSVILLE/index_10201.html -http://www.incestpornstories.com/tinkerbellbeard/ac/plus-sizehealthy/petitevietnamese/slanted-eyes/cuntschoolgirls/high-schoolteenager/cherryunderage.html -http://www.0563.net/imode2/hazu/play/outdoor/nature/nature1.htm -http://www.launch.com/music/songpage/pvn_content/0,5259,1074221,00.html -http://ftp.jp.debian.org/debian/dists/unstable/main/binary-alpha/tex/?S=A -http://iceberg.adhomeworld.com/cgi-win/redirect.exe/896425026 -http://www.nrc-handelsblad.nl/W2/Lab/Baan/000726-a.html -http://www.nrc-handelsblad.nl/W2/Lab/Baan/000718-a.html -http://members.tripod.co.jp/muzyaki/?M=A -http://alfa.nic.in/lsdeb/ls12/ses4/0413039930.htm -http://excite.de/immobilien/katalog/26640 -http://excite.de/immobilien/katalog/27591 -http://excite.de/immobilien/katalog/28370 -http://excite.de/immobilien/katalog/28376 -http://excite.de/immobilien/katalog/26426 -http://excite.de/immobilien/katalog/28458 -http://www.emerchandise.com/aboutus/b.TV%20THE60S/s.qxmvd5Gr -http://www.computerworld.com.cn/99/week/9920/9920c13.asp -http://www.stud.ntnu.no/~oystena/oystena/cache/dvx70a.html -http://nealet.subportal.com/sn/Shell_and_Desktop/Holiday_Screen_Savers/ -http://dk.egroups.com/message/ugm/40?source=1 -http://www1.bdaserver.de/bda/nat/pzt/formel1/gp/mon.html -http://www17.freeweb.ne.jp/diary/t-soken/love-love.htm -http://kernel2.adver.com.tw/Counter/log/kernel2.adver.com.tw/SaveCounter/2000-10-12/14/971332013437.txt -http://pub3.ezboard.com/f80sxchangegeneraldiscussion.showMessage?topicID=60.topic -http://www.northampton.ac.uk/cgi-bin/liberation/betsie/betsie.pl/0005/www.nene.ac.uk/ncr/enrol/sectn4/pdf/4-5.pdf -http://www.xmission.com/~dkenison/cgi/lwgate.cgi/LDS-BOOKSHELF/archives/v01.n676/Date/article-15.html -http://www.eos.dk/archive/swing/nav08574.html -http://nathanael.upi.jussieu.fr/tele6.nsf/autres+centres+de+formations!OpenPage&ExpandSection=1,4,11,18,5,17 -http://nathanael.upi.jussieu.fr/tele6.nsf/autres+centres+de+formations!OpenPage&ExpandSection=6,4,11,18,5,17 -http://cn.egroups.com/message/highlanderswaps/3351 -http://cn.egroups.com/message/highlanderswaps/3356 -http://www.mobygames.com/user/sheet/view/havelist/so,game_title(game_id)+DESC,game_havelist_id+DESC/userHaveListId,18/userSheetId,832/offset,15/ -http://www.mobygames.com/user/sheet/view/havelist/so,game_title(game_id)+DESC,game_havelist_id+DESC/userHaveListId,18/userSheetId,832/offset,60/ -http://gettosdownloads.subportal.com/sn/Palm_Pilot/Home_and_Hobby/12385.html -http://biblio.cesga.es:81/search*gag/aOurense+(Di%26oacute%3Bcesis).+Obispado+de+Ourense,+ed./aourense+diocesis+obispado+de+ourense+ed/-5,-1,0,B/browse -http://www.beneteau-owners.com/beneteau.nsf/userlistbyboat!OpenView&Start=21.24&Count=45&Expand=39 -http://www.geocities.com/Yosemite/8908/ -http://www.geocities.com/Yosemite/3295/ -http://lists.insecure.org/linux-kernel/2000/Apr/4105.html -http://www.telematik.informatik.uni-karlsruhe.de/osf/sw/v5.0x/lp2/dna500/ -http://atlas.web.cern.ch/Atlas/GROUPS/SOFTWARE/OO/dist/0.0.28/graphics/TreeBuilder/TreeMaker/CVS/?M=A -http://www.21hk.com/book/zt/zt/zpj/c/chichuancilang/txmoxj/012.htm -http://chat.hani.co.kr/NetBBS/Bbs.dll/brief/rcm/zka/B23lBn-t/qqatt/^ -http://www3.buch-per-sms.de/impressum.jsp$ID=To7770mC6889218603037781At0.41865389376542195 -http://mayu.sourceforge.net/cgi-bin/nph-ml.cgi/000/http/www.geocrawler.com/archives/3/151/1997/7/0/904457/ -http://www.mets.com/gameinfo/990504-recap.htm -http://www.mets.com/Video/990709-PiazzaHR_lr.asp -http://www.people.zeelandnet.nl/cn.atlas/compatlasw1.html -http://www.digitaldrucke.de/(aktuell,bekanntschaften,hilfe,marktplatz,nuernberg)/_fort/html/themen/markt/bekannt/bekannt.htm -http://www.staroriental.net/nav/soeg/ihf,acf,s0,359,Gigi+Leung+Wing-Kay.html -http://rapidus.tucows.com/winme/adnload/137435_28887.html -http://library.bangor.ac.uk/search/aBerthoff,+Ann+E/aberthoff+ann+e/-5,-1,0,B/frameset&F=aberthier+rene&1,1 -http://www.teenplatinum.com/barelylegal/underagevirgin/abductionbondage/amateurco-ed/chijapanese/{gaylink} -http://www.paisvirtual.com/informatica/freeware/cltorres/contra.htm -http://library.cuhk.edu.hk/search*chi/aInstitution+of+Civil+Engineers+(Great+Britain)/ainstitution+of+civil+engineers+great+britain/-5,-1,0,B/browse -http://www.digitaldrucke.de/(aktuell,computer,hersteller,hilfe)/_fort/html/themen/computer/hard/links/dell.htm -http://www.angelfire.com/ar/jimbowles/weekofoct3.html -http://www.dtic.mil/envirodod/derpreport95/vol_2/b2_1991.html -http://www.dtic.mil/envirodod/derpreport95/vol_2/b2_2010.html -http://kobe.cool.ne.jp/heartisland/y_top0004.html -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=146&discrim=10,97,3 -http://www.channel7000.com/partners/tv/consumer/partners-tv-consumer-20000207-231308.html -http://www.channel7000.com/partners/tv/consumer/partners-tv-consumer-19991206-195152.html -http://www.channel7000.com/partners/tv/consumer/partners-tv-consumer-990920-105620.html -http://www.channel7000.com/partners/tv/consumer/partners-tv-consumer-990810-082554.html -http://gallery2.simplenet.com/lobby/main/videocaps/lalbrght/conair/laca26.htm -http://www.ld.com/cbd/archive/1999/09(September)/30-Sep-1999/Bawd007.htm -http://www.ld.com/cbd/archive/1999/09(September)/30-Sep-1999/Bawd013.htm -http://chunma.yeungnam.ac.kr/~j4390071/ -http://www.chaos.dk/sexriddle/h/y/z/m/ -http://www.maas.ccr.it/cgi-win/hiweb.exe/a18/d262/b190,8,be,29,29,,b,,be,b, -http://pub17.ezboard.com/fanimesandrpgslinkstositesandotherforums.showMessage?topicID=2.topic -http://www.hotelboulevard.com/fr/riviera/standard/htmled1e03872682f66e105b3c38b4506d50/sessionLang/ANG/search.html -http://bbs.msquare.or.kr/list.bbs/course/old/DiscMath95/9.html -http://www.rezel.enst.fr/ftp/linux/distributions/debian/CD-1/dists/unstable/main/binary-all/mail/?N=D -http://www.ee/epbe/pangandus/9910/0.2.txt -http://shitty.10pics.com/buttfucking/rear/ -http://www.thestateofcolorado.com/hsiwindowdoorlettering.html -http://www.generation-formation.fr/brevesc.htm---o21zAo0UtDo0Ol9A074fo6Td4ezyr6feZJPAPfVbNyqruePl9neNHhIeOkatAhcgNA074wNV8XzAhcgNAPfVbdsNhJI.htm -http://netscape.digitalcity.com/boston/sports/standings.dci?league=NBA&team=BOS -http://netscape.digitalcity.com/boston/sports/attcompare.dci?league=NBA&team=BOS -http://retailer.gocollect.com/do/session/1912752/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/clubhouse/suggestions.asp -http://mindit.netmind.com/proxy/http://www.skepdic.com/sympathetic.html -http://mindit.netmind.com/proxy/http://faculty.washington.edu/chudler/moon.html -http://itcareers.careercast.com/texis/it/itjs/++wwBmeE_D86esmwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqew8Qwo5qda5dc1BodDawGnwaGn31oGnmaoDmnpBraADdicnmtnapGdm1qBaBnqrDoqwcatGd1pamnVncdpaMFqoET02fgENDzmezxwwwpBmeC_D86Qwww5rmkmwwBrmeyDwww/morelike.html -http://retailer.gocollect.com/do/session/1912762/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/company_info/terms_and_conditions.asp -http://retailer.gocollect.com/do/session/1912762/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/clubhouse/suggestions.asp -http://www.writtenbyme.com/cgi-bin/rw_readarticle.cgi/141339880.shtml -http://www.writtenbyme.com/cgi-bin/rw_readarticle.cgi/410769654.shtml -http://www.writtenbyme.com/cgi-bin/rw_readarticle.cgi/190045923.shtml -http://tucows.megalink.com/winme/preview/76155.html -http://www.buybuddy.com/sleuth/17/1/2006/32184/ -http://www.affiliate.hpstore.hp.co.uk/do/session/380853/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/FR/REGISTRATION/entry.asp -http://pchome.net:81/ch/Hw/CAMERA/canoneosd30/canoneosd30.htm -http://pchome.net:81/ch/Hw/CAMERA/kodaknew.htm -http://pchome.net:81/ch/Hw/MODEM/twluc562w2k.htm -http://pchome.net:81/ch/Hw/MONITOR/mag796fd.htm -http://pchome.net:81/ch/Hw/cool/anquanshuileng/anquanshuileng.htm -http://pchome.net:81/ch/Hw/DISPLAY/3dbenchmarks/3dbenchmarks.htm -http://pchome.net:81/ch/Hw/CAMERA/Microdrive.htm -http://pchome.net:81/ch/Hw/harddisk/niyaomaishime.htm -http://www.civila.com/guitar/desenredada/chat/logos/index.html-ssi -http://members.xoom.it/scialpinismo/gitaappenparm/PreviewPages/PreviewPage7.htm -http://cpan.nitco.com/modules/by-module/Mail/ASPIERS/URI-Bookmarks-0.92.readme -http://polygraph.ircache.net:8181/services/design/http_-2www.swnebr.net/~cambridg/http_-2www.cauce.org/Malcolm/ -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/16_aswkit_aswkit.html -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/16_nbilwv_rbpobu.html -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/16_jkawvi_messod.html -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/16_jkawvi_otdbms.html -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/16_jkawvi_hoktlo.html -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/16_uhfkhdn_ilaeh.html -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/16_xyhsj_pfepjoa.html -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/16_alkqaay_mogsts.html -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/16_ighrg_ighrg.html -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/16_cbfjod_parbe.html -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/16_dqnlq_jfspcj.html -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/16_phcro_bwlah.html -http://www.asahi-net.or.jp/~yd7k-itu/sbbsindex/old/16_phcro_xoxchqb.html -http://seniorfriendfinder.com/cgi-bin/w3com/pws/ffsenior/IkhI2h2UISFGhSJ4dK-jGu69npNFUTS7n0SO4q6b8rSzWq_RIDBJOsj9QRxPcb3IZgZlQ5jvjGikzJWNeK-85DucH1Ag5dhhL0czi-GMxyHC1dmfKc0hW5TzqJpnm938SIT3xNrWgjZN66P6 -http://seniorfriendfinder.com/cgi-bin/w3com/pws/ffsenior/oo1IpLu33emgRiskeudWkzY7LxFY35wz6EqyQ42lguNadi_4qnt4FhGUPOob_C5Wt99hQSEKEuRTRevsau9UYJ9lySivV-u51_OF4aSEhYXTt98QpjnIOFYPV6acMb20In922uOHMyYdC8HXvwhIP-8o8oM4wLBMdll6aW8xe922WllgXE1F5qlvFqyA -http://msdn.microsoft.com/library/devprods/vs6/visualj/vjref/java.sql.DatabaseMetaData136.html -http://msdn.microsoft.com/library/devprods/vs6/visualj/vjref/java.sql.DatabaseMetaData090.html -http://romulus.ehs.uiuc.edu/cgi-bin/lwgate/RADSAFE/archives/radsafe9902/Date/article-572.html -http://spaceports.tucows.com/winme/preview/76400.html -http://www.telecombroker.com/q/001p/ppc3/qG4gs1ewhU.htm -http://ftp.nodomainname.net/pub/mirrors/.2/gnu/graphics/?N=D -http://retailer.gocollect.com/do/session/1912813/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/help/site_tour/index.asp -http://retailer.gocollect.com/do/session/1912813/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/news/index.asp -http://retailer.gocollect.com/do/session/1912813/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/company_info/privacy_policy.asp -http://202.101.106.19/dir/100/10a/zzgk/bszn/111.htm -http://www.eveclub.com/cgi-bin/eveclub.front/972959538910/Catalog/1000084 -http://www.eveclub.com/cgi-bin/eveclub.front/972959538910/Club/start/1000000 -http://www.slis.ua.edu/cgi-bin/clickthrough.cgi/CT=http_3a_2f_2fwww_2edermis_2enet_2fbilddb_2fdiagnose_2fenglisch_2fi697015_2ehtm -http://forum.rai.it/aca-finestre/dispatch.cgi/FORUM/folderFrame/100001/0/rnumber/8467604 -http://www-personal.engin.umich.edu/~vernage/teamweb/team.building/effective.meetings/effective.meetings.facilitation.htm -http://www4.law.cornell.edu/uscode/42/ch87subchIV.head.html -http://yp.gates96.com/7/27/90/10.html -http://yp.gates96.com/7/27/90/11.html -http://yp.gates96.com/7/27/90/30.html -http://yp.gates96.com/7/27/91/72.html -http://yp.gates96.com/7/27/91/76.html -http://yp.gates96.com/7/27/91/85.html -http://yp.gates96.com/7/27/91/92.html -http://yp.gates96.com/7/27/92/61.html -http://yp.gates96.com/7/27/92/72.html -http://yp.gates96.com/7/27/93/10.html -http://yp.gates96.com/7/27/93/17.html -http://yp.gates96.com/7/27/93/30.html -http://yp.gates96.com/7/27/93/65.html -http://yp.gates96.com/7/27/93/76.html -http://yp.gates96.com/7/27/93/99.html -http://yp.gates96.com/7/27/94/37.html -http://yp.gates96.com/7/27/94/85.html -http://yp.gates96.com/7/27/95/5.html -http://yp.gates96.com/7/27/95/14.html -http://yp.gates96.com/7/27/95/55.html -http://yp.gates96.com/7/27/95/57.html -http://yp.gates96.com/7/27/96/21.html -http://yp.gates96.com/7/27/96/49.html -http://yp.gates96.com/7/27/96/50.html -http://yp.gates96.com/7/27/96/55.html -http://yp.gates96.com/7/27/96/92.html -http://yp.gates96.com/7/27/97/24.html -http://yp.gates96.com/7/27/97/73.html -http://yp.gates96.com/7/27/97/98.html -http://yp.gates96.com/7/27/98/26.html -http://yp.gates96.com/7/27/98/62.html -http://yp.gates96.com/7/27/99/15.html -http://yp.gates96.com/7/27/99/52.html -http://www.nrk.no/finnmark/x2_9_98/nyh11.htm -http://www.excelsior.com.mx/9701/970105/nac18.html -http://www.symantec.co.kr/sabu/igear/igear_educ/stories.html -http://www.smcworld.com/smcworld/bp/pre/0204_1_1070.html -http://www.cpami.gov.tw/ymsnp/animal/fauna/nospc708choice.htm -http://pub9.ezboard.com/fdawsonscreek50374helpwanted -http://pub9.ezboard.com/fdawsonscreek50374frm17 -http://www.happychannel.it/turismo/europa/top_news/schede/scheda_991209110434.shtml -http://www.happychannel.it/turismo/europa/top_news/schede/scheda_991111111106.shtml -http://dirs.educationamerica.net/New_York/Localities/N/New_York_City/Manhattan/Business_and_Economy/ -http://dirs.educationamerica.net/New_York/Localities/N/New_York_City/Manhattan/Government/ -http://china-water.51.net/life/life_20.htm -http://china-water.51.net/life/life_22.htm -http://www.egroups.com/message/ramtalk/17801 -http://www.usahardware.com/inet/webSession/shopper/US972959720-31113/store/dept-1 -http://www.usahardware.com/inet/webSession/shopper/US972959720-31113/store/specials -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=97&discrim=2,68,201 -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/quizz/legendes/misc/music/lit/hasard.html -http://findmail.com/group/ken2061 -http://www.affiliate.hpstore.hp.co.uk/do/session/380852/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-photoworld.com/photoworld.asp?lang=f -http://www.affiliate.hpstore.hp.co.uk/do/session/380852/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/SMARTTIPS/traveljournal.asp -http://smb.slac.stanford.edu/cgi-bin/nph-proxy.cgi/000/http/www-med.stanford.edu/school/banner.html -http://smb.slac.stanford.edu/cgi-bin/nph-proxy.cgi/000/http/www-med.stanford.edu/school/neurosurgery.html -http://hotop.on.net.cn/diguo/club/disp.asp?owner=A201&ID=894 -http://hotop.on.net.cn/diguo/club/disp.asp?owner=A201&ID=846 -http://interbaun.tucows.com/winme/preview/577.html -http://www.ferien-immobilien.de/ungarn/verkauf/Gemeinsam/Immolink/Exklusiv-IB/Startseite/3d-service/Private-IB/Startseite/Default.htm -http://www.eos.dk/archive/swing/msg10936.html -http://www.egroups.com/message/ICSIA-PublicForum/138 -http://www.online.kokusai.co.jp/Service/V0043601/wrd/G200/service/service.html -http://debian.tod.net/debian/dists/unstable/main/source/libs/?N=D -http://www.maas.ccr.it/cgi-win/hiweb.exe/a17/d79/b77,e,4d,51,51,819,819,,2,,51,2,4e,,4d,4e, -http://www.redhat.com/mirrors/LDP/LDP/khg/HyperNews/get/fs/fs/9/?N=D -http://ftp.oleane.net/pub/CTAN/systems/knuth/local/man1/?D=A -http://www.jamba.de/KNet/_KNet-_UA8j1-xFd-13bat/browse.de/node.0/cde7f1uou -http://www.jamba.de/KNet/_KNet-_UA8j1-xFd-13bbg/showInfo-jambabanner.de/node.0/cenv0b09a -http://www.tente.de/us/produkte/artikel/af000000736.htm -http://dwp.bigplanet.com/bloomingprairie/look/sitemap.nhtml -http://www.kfh-mainz.de/Organisationen/Ketteler/pf/ws0001.html -http://extreme-dm.com/tracking/reports/dj/nph-reloads.cgi?tag=agmusik -http://www.chaos.dk/sexriddle/c/v/m/v/y/ -http://ring.jec.ad.jp/pub/linux/debian/debian/dists/woody/non-free/binary-i386/electronics/?D=A -http://tongbang-gh.ed.taejon.kr/1998대전시/math/olym/function/m103_003/html/m103_003h01.html -http://www.company-product.com/23063/ -http://members.tripod.lycos.co.kr/re22/CPUCOOL5195/uni2k15/?N=D -http://209.52.189.2/print_message.cfm/stepparents/8279/173602 -http://216.33.87.17/sports/baseball/sba/sba04r.htm -http://www.mc99.co.jp/mvp/member/new/honda/16kr3fj2/search.cgi?_file=038 -http://www.emerchandise.com/browse/EMERCH/COASTERS/s.cU6lmV05 -http://www.emerchandise.com/browse/CHARMED/s.cU6lmV05 -http://www.across.or.jp/nbbs/nbbs.cgi/talk:n18/replyto/462 -http://www.vins-siffert-scea.fr/lycee-seijo/guide/staff/yoshida.htm -http://www.egroups.com/messages/grebel-list/2305 -http://polygraph.ircache.net:8181/services/design/http_-2www.abcjewelry.com/http_-2www.1045fm.com/http_-2www.4sitedesign.com/stp/nbm.html -http://bsd.sinica.edu.tw/cgi-bin/cvsweb.cgi/ports/astro/wmmoonclock/pkg/Attic/DESCR?only_with_tag=RELEASE_4_0_0 -http://biblio.cesga.es:81/search*gag/tMariposas+negras.+1:08,50+min/tmariposas+negras++++1+++08+++50+min/-5,-1,0,B/frameset&F=tmariposa+y+la+hormiga&1,1 -http://polygraph.ircache.net:8181/Cameras/order/rr962.htm -http://polygraph.ircache.net:8181/Cameras/order/dfwmap.htm -http://support.tandy.com/support_audio/doc45/45827.htm -http://image.tulips.tsukuba.ac.jp:70/fif=picture/ECWP/001.fpx&init=-0.23170732,0.0,1.2317073,1.0&rect=0.5,0.25,0.6829269,0.375&wid=600&hei=600&lng=ja&enablePastMaxZoom=OFF&page=uv1-en.html&obj=uv,1.0&cmd=NW -http://pub23.ezboard.com/fcaribbeanvoiceforumsfrm3.showAddTopicScreenFromWeb -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=9,1+0,0-19,0+9,4 -http://vipnet.tucows.com/win2k/adnload/51108_28465.html -http://vipnet.tucows.com/win2k/adnload/38782_28482.html -http://www4.50megs.com/tstazer/edhtms/edbeats.htm -http://www.unterhaltungs-cd.de/ObervellacherBuam/B000025KMT.htm -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=bocarderont&l=fr -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=146&discrim=10,3,211 -http://variety.studiostore.com/help_security/b.TV%20HERCULES/s.cD15jQkr -http://variety.studiostore.com/help_shipping/b.TV%20HERCULES/s.cD15jQkr -http://variety.studiostore.com/product/TSHER0001/b.TV%20HERCULES/s.cD15jQkr -http://variety.studiostore.com/aboutus/b.TV%20HERCULES/s.cD15jQkr -http://www.redrocksports.com/sports/webSession/shopper/RR972959753-31163/store/dept-5/department/dept-5/item/51530 -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=135&discrim=165,71,194 -http://www.kagtech.com/SpitfrireKennels -http://www.expage.com/page/thekatshow -http://www.jobvillage.com/channel/jobs/cleaning/gardener/b.4255.g.3878.html -http://www.xmwb.sh.cn/xmwb/20000704/BIG5/14016^6070408.htm -http://www.xmwb.sh.cn/xmwb/20000704/BIG5/14016^7070414.htm -http://dennou-t.ms.u-tokyo.ac.jp/arch/cc-env/Linux/debian-jp/dists/woody-jp/contrib/binary-all/tex/?S=A -http://genforum.genealogy.com/ny/monroe/messages/350.html -http://genforum.genealogy.com/ny/monroe/messages/296.html -http://genforum.genealogy.com/ny/monroe/messages/306.html -http://genforum.genealogy.com/ny/monroe/messages/213.html -http://otenet.themes.tucows.com/fonts/preview/18792.html -http://otenet.themes.tucows.com/fonts/adnload/18828.html -http://otenet.themes.tucows.com/fonts/adnload/18876.html -http://otenet.themes.tucows.com/fonts/preview/18877.html -http://otenet.themes.tucows.com/fonts/adnload/18894.html -http://otenet.themes.tucows.com/fonts/adnload/18910.html -http://otenet.themes.tucows.com/fonts/adnload/18941.html -http://otenet.themes.tucows.com/fonts/adnload/18949.html -http://otenet.themes.tucows.com/fonts/adnload/25945.html -http://ww.egroups.com/message/schoolnet_sadc/96 -http://ww.egroups.com/message/schoolnet_sadc/98 -http://www6.pasta.cs.uit.no/ietf/ietf45/proceedings/I-D/webdav-dublin-core-01.txt -http://www-uk9.cricket.org/link_to_database/INTERACTIVE/SURVEYS/POLLS_DEC1998.html -http://www.ucp.org/ucp_generaldsc.cfm/151/8/35/ucp_disctpc/292/263 -http://www.ucp.org/ucp_generaldsc.cfm/151/8/35/ucp_disctpc/79/79 -http://se.egroups.com/message/DBA/1700 -http://mayu.sourceforge.net/cgi-bin/nph-ml.cgi/000/http/www.geocrawler.com/archives/3/138/2000/6/0/ -http://mayu.sourceforge.net/cgi-bin/nph-ml.cgi/000/http/www.geocrawler.com/archives/3/138/2000/7/0/ -http://www.inf.fu-berlin.de/lehre/WS00/SWT/material/rosebeispiele/interaccess/logicalview/cat32862112022a/cat36e7162c0192/msg343269780227.htm -http://www.private-immobilien-boerse.de/leipzig/verkauf/Gemeinsam/erreichenPartner/IIM-Teil/Startseite/Gemeinsam/versicherungen/gebaeude/Allgemeine-IB/Startseite/ -http://www.private-immobilien-boerse.de/leipzig/verkauf/Gemeinsam/erreichenPartner/IIM-Teil/Startseite/Gemeinsam/versicherungen/gebaeude/Gemeinsam/Immolink/link.htm -http://freetravel.bedandbreakfast.com/Canada/Prince%20Edward%20Island/Little%20Sands.asp -http://freetravel.bedandbreakfast.com/Canada/Prince%20Edward%20Island/Miscouche.asp -http://freetravel.bedandbreakfast.com/Canada/Prince%20Edward%20Island/O'Leary.asp -http://www.buybuddy.com/sleuth/15/1/1070306/519432/ -http://l-infonet.phkk.fi/fi/TIETOPALVELUT/KIRJASTO-+JA+TIETOPALVELUT/ammattikorkeakoulukirjastot/ammattikorkeakoulut/lahti/p%E4ij%E4t-h%E4me/ -http://www.3w-buecher.de/GravesRobert/GravesRobert0140171991.htm -http://www.3w-buecher.de/GravesRobert/GravesRobert1559948345.htm -http://www.3w-buecher.de/GravesRobert/GravesRobert1850897506.htm -http://members.theglobe.com/heliox2/pokepages/ninepic.htm -http://taiwan.vh.org//////Providers/Textbooks/MuscleInjuries/Fig2.html -http://www.globalgarden.com/Tomato/Archives/vol.1/1147.html -http://www.mojahedin.org/Pages/Mojahed/Mojahed442/articles/articlesftx03.html -http://216.34.146.180/161000reu/16hlth6.htm -http://moshkow.sstu.samara.ru/win/BESTER/Encoding_koi -http://in.egroups.com/message/Girl-Scout-Swaps/9 -http://in.egroups.com/message/Girl-Scout-Swaps/31 -http://members.tripod.com/floydechoes/more.htm -http://nanjingnews.jlonline.com/nanjingnews/njrb/20000222/08dushi.htm -http://www.egroups.com/messages/archery/38?expand=1 -http://retailer.gocollect.com/do/session/1912759/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/index.asp -http://home.dqt.com.cn/~ying_jia/wangwen/new/111.htm -http://canoe.com/MLB97FLASF/sep30_fla_sf.html -http://pub2.ezboard.com/fespguitarsmessageboardltdguitarandbassreviews.subscribeUnregisteredToTopic?topicID=8.topic -http://www.catholicstore.com/search/index.cfm/FuseAction/largeImage/SKU/2558/category/Bo/subCategory/AE/subject/17 -http://www.allgemeine-immobilien-boerse.de/bayern/augsburg/Verkauf/Private-IB/Startseite/Gemeinsam/Inserieren/Private-IB/IIM-Teil/Startseite/froben.htm -http://www.infoscape.com.cn:8171/nf/0004/18/nfga1801.htm -http://www.infoscape.com.cn:8171/nf/0004/18/nfga1809.htm -http://www.linux.com/networking/network/kernel/apache/applications/HTTP/ -http://www.linux.com/networking/network/kernel/apache/applications/Linuxcare/ -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=exacerbate&l=en -http://dopey.rediris.es/ftp/mirror/CPAN/modules/by-module/overload/GSAR/Archive-Tar-0.071.readme -http://dopey.rediris.es/ftp/mirror/CPAN/modules/by-module/overload/GSAR/Tie-IxHash-1.21.readme -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=207&discrim=3,201,226 -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=207&discrim=3,201,85 -http://www.gsnet.com/bdltg/es/1_136243.html?num=2 -http://www.pinoycentral.com/img/UBB.nsf/e39d540ca6a9104b4825694d006ed185/6668efca7b60518648256966000fd202?Navigate&To=Prev -http://www.academyfloral.com/state/cabel/flowers/harmony.html -http://trading.rakuten.co.jp/items001/4c/0d/10138895/bidlist.html -http://www.cs.uwa.edu.au/programming/jdk1.2.2/api/javax/swing/event/class-use/TableColumnModelListener.html -http://secure.danysoft.com/asp/dany.tienda/803039052/IconBar -http://ftp-stud.fht-esslingen.de/pub/Mirrors/CPAN/modules/by-authors/id/L/LH/LHS/?S=A -http://genforum.genealogy.com/ga/messages/6297.html -http://genforum.genealogy.com/ga/messages/7843.html -http://genforum.genealogy.com/ga/messages/7281.html -http://www.jsinc.com/dd/destnat/sep00/fromcol10090800.asp -http://www.secinfo.com/$/SEC/Filing.asp?T=nDA3.7c_9i4 -http://www.secinfo.com/$/SEC/Filing.asp?T=nDA3.7c_b19 -http://www.sd.digitalcity.com/maconga/penpals/browse.dci?cat=teens -http://www.sd.digitalcity.com/maconga/penpals/browse.dci?cat=seniors&sort=f -http://www.picktips.com/category-1031-1172_1170_1174-4_1_3 -http://www-us6.semiconductors.com/acrobat/datasheets/CR6627_1.pdf -http://ftp.netc.pt/pub/idgames/levels/doom2/deathmatch/p-r/pimp.txt -http://ftp.netc.pt/pub/idgames/levels/doom2/deathmatch/p-r/radiated.txt -http://commerce.was-inc.com/cgi-bin/abtwsam.dll/LbkWebCommerceMallCategories-BBC709FC_97F7_9E91E7C8C7066684B664C77C8575B940 -http://commerce.was-inc.com/cgi-bin/abtwsam.dll/LbkWebCommerceOrderStatusOverview-BBC709FC_97F7_9E91E7C8C7066684B664C77C8575B940 -http://ads.puntopartenza.com/cgi-bin/redirect.cgi/31033638 -http://mediate.magicbutton.net/do/session/625642/vsid/4385/tid/4385/cid/88138/mid/1702/rid/2114/chid/3393/url/http://www.worldgallery.co.uk/frameset-top50.html -http://link.fastpartner.com/do/session/600388/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/netmaling.php -http://www.egroups.com/message/RecipeCollectors2/3785 -http://plat.debian.or.jp/debian/dists/woody/contrib/binary-alpha/admin/?S=A -http://198.103.152.100/search*frc/aFILIPPELLI,+R.L/afilippelli+r+l/-5,-1,0,B/frameset&F=afilion+louis+jacques&1,,0 -http://de.excite.de/wetter/katalog/4206 -http://www.burstnet.com/ads/ad8386a-map.cgi/973225252.925077 -http://www.branchenfuehreronline.de/A/hauptteil_a.html -http://www.linux.com/networking/support/red_hat/internet/test/simple/ -http://www.shopworks.com/ccfarm/index.cfm/action/search/userid/00061450-2F40-19FE-9038010B0A0ADCF2 -http://www.shopworks.com/index.cfm/userid/00061450-2F40-19FE-9038010B0A0ADCF2 -http://pelit.saunalahti.fi/.1/tucows/preview/144491.html -http://pelit.saunalahti.fi/.1/tucows/preview/52377.html -http://www.teacherformation.org/html/od/facilitators.cfm/xid,7238/yid,4053212 -http://tw.yahoo.com/Regional/Countries_and_Regions/China/Provinces__Regions_and_Municipalities/Tianjin/Business/Companies/Utilities/ -http://brain.brent.gov.uk/WebPages.nsf/vWebAllPagesByKey!OpenView&Start=174&Count=60&Expand=194 -http://brain.brent.gov.uk/WebPages.nsf/vWebAllPagesByKey!OpenView&Start=174&Count=60&Expand=227 -http://www.bemi-immobilien.de/Landhaus-Bordeaux/Gemeinsam/versicherungen/unfall/Gemeinsam/erreichenPartner/Startseite/Gemeinsam/MarketingStrategie/Startseite/froben.htm -http://www.bemi-immobilien.de/Landhaus-Bordeaux/Gemeinsam/versicherungen/unfall/Gemeinsam/erreichenPartner/Startseite/Gemeinsam/MarketingStrategie/Gemeinsam/versicherungen/gebaeude/deckungsumfang.htm -http://www.3wposter.com/hake/hkg1701.htm -http://www.citybrazil.com.br/go/mossamedes/utilpub.htm -http://oss.software.ibm.com/developerworks/opensource/cvs/icu4j/icu4j/src/com/ibm/demo/translit/Attic/?sortby=date -http://www.linux.com/networking/network/management/operating_system/enterprise/research/ -http://www.angelfire.com/pq/Prophetess/Prophetess.page3.html -http://www.3w-nostalgie.de/ZeigerMimi/ZeigerMimi007072833X.htm -http://www.excelsior.com.mx/9801/980128/for01.html -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=11&discrim=49,235,5 -http://retailer.gocollect.com/do/session/1912802/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/company_info/contact.asp -http://citeseer.nj.nec.com/track/64292/4220924 -http://citeseer.nj.nec.com/correct/318910 -http://citeseer.nj.nec.com/correct/249393 -http://www.chaos.dk/sexriddle/h/y/r/k/ -http://www.hig.se/(aconf,date,doc,insert,return)/~jackson/roxen/ -http://www.hig.se/(aconf,date,doc,gtext,insert)/~jackson/roxen/ -http://mediate.magicbutton.net/do/session/625608/vsid/4573/tid/4573/cid/88043/mid/2247/rid/2383/chid/3527/url/http://www.winesmart.com/expert.asp -http://magazines.sina.com/education/renbun/93/13.html -http://www6.freeweb.ne.jp/art/cilter/kamijo02.htm -http://yp.gates96.com/11/25/50/28.html -http://yp.gates96.com/11/25/50/41.html -http://yp.gates96.com/11/25/50/65.html -http://yp.gates96.com/11/25/50/74.html -http://yp.gates96.com/11/25/50/91.html -http://yp.gates96.com/11/25/50/93.html -http://yp.gates96.com/11/25/50/94.html -http://yp.gates96.com/11/25/51/59.html -http://yp.gates96.com/11/25/51/93.html -http://yp.gates96.com/11/25/52/66.html -http://yp.gates96.com/11/25/54/46.html -http://yp.gates96.com/11/25/54/68.html -http://yp.gates96.com/11/25/54/83.html -http://yp.gates96.com/11/25/54/95.html -http://yp.gates96.com/11/25/54/98.html -http://yp.gates96.com/11/25/55/1.html -http://yp.gates96.com/11/25/55/6.html -http://yp.gates96.com/11/25/55/96.html -http://yp.gates96.com/11/25/56/83.html -http://yp.gates96.com/11/25/56/89.html -http://yp.gates96.com/11/25/57/30.html -http://yp.gates96.com/11/25/57/68.html -http://yp.gates96.com/11/25/58/56.html -http://yp.gates96.com/11/25/58/67.html -http://yp.gates96.com/11/25/59/7.html -http://yp.gates96.com/11/25/59/40.html -http://yp.gates96.com/11/25/59/58.html -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/lit/misc/legendes/lit/misc/quizz/quizz2.html -http://excite.de/kleinanzeigen/katalog/7100 -http://www.egroups.org/messages/stepup/97 -http://sunsite.org.uk/pub/packages/proftpd/misc/?S=A -http://ring.htcn.ne.jp/archives/lang/perl/CPAN/modules/by-module/CGI/DOUGM/?M=A -http://ring.htcn.ne.jp/archives/lang/perl/CPAN/modules/by-module/CGI/DOUGM/Apache-Scoreboard-0.10.readme -http://ring.htcn.ne.jp/archives/lang/perl/CPAN/modules/by-module/CGI/DOUGM/B-Size-0.04.readme -http://herndon1.sdrdc.com/cgi-bin/can_ind/S8NY00082/1/Y/ -http://in.egroups.com/message/msu-foi/20?source=1 -http://www.worldstocks.de/htm/boersen/asien/indonesien_boerse.htm -http://members.xoom.com/pvmnieuws/movies/movies.html -http://gb.toget.com.tw/article/screensaver/index_a_2.html -http://www.emis.de/journals/EJDE/Volumes/Monographs/Volumes/2000/64/?N=D -http://bsd.wj.o3.net/8/1/18/4.html -http://www.ftp.uni-erlangen.de/pub/mirrors/_other/afterstep.foo.net/apps/asprint/?S=A -http://citeseer.nj.nec.com/cidcontext/3597768 -http://m4.findmail.com/dir/Sports/Soccer/Academic_Study_of_Soccer/History -http://genforum.genealogy.com/cgi-bin/print.cgi?westerman::121.html -http://www-koi.bards.ru/Egorov/part84.htm -http://www-koi.bards.ru/Egorov/part29.htm -http://www-koi.bards.ru/Egorov/part127.htm -http://www-koi.bards.ru/Egorov/part68.htm -http://www.loisirs.ch/emjius/10/brglll.html -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/quizz/music/computers/legendes/lit/hellequin.html -http://www.redrival.com/dejanss/muzika/exploited/themassacre.html -http://kernel2.adver.com.tw/Counter/log/kernel2.adver.com.tw/SaveCounter/2000-08-31/13/967698323786.txt -http://kernel2.adver.com.tw/Counter/log/kernel2.adver.com.tw/SaveCounter/2000-08-31/13/967699453627.txt -http://kernel2.adver.com.tw/Counter/log/kernel2.adver.com.tw/SaveCounter/2000-08-31/13/967699813970.txt -http://www.chaos.dk/sexriddle/c/v/w/l/o/ -http://www.chaos.dk/sexriddle/c/v/w/l/x/ -http://www.allgemeine-immobilien-boerse.de/Oesterreich/verkauf/IIM-Teil/Startseite/Allgemeine-IB/Gemeinsam/3d-service/info.htm -http://www.marktplatz-hs.de/cgi-bin/ChioEditionShop.s/39fe2eeb0239a4a4273fd47540f806ea/IconBar -http://www.jamba.nl/KNet/_KNet-sDD8j1-GC4-puzu/browse.nl/node.0/cde7f1uou -http://www.icopyright.com/1.1635.66362 -http://www.ld.com/cbd/archive/1999/05(May)/07-May-1999/Vsol004.htm -http://www.infoscape.com.cn:8171/nf/0007/05/nfgz0517.htm -http://209.207.239.212/bkindex/c1034/f1392.html -http://www.gbnf.com/genealogy/rockwel4/html/d0007/I1584.HTM -http://www.gbnf.com/genealogy/rockwel4/html/d0023/I3700.HTM -http://www.hornchurch.londonengland.co.uk/designersgraphic.htm -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/computers/computers/lit/misc/colorart/lit/quizz/ -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/computers/computers/lit/misc/colorart/lit/misc/orders_mag.html -http://www.multimap.com/wi/141313.htm -http://www.multimap.com/wi/141326.htm -http://www.thestateofcolorado.com/aconplumbing.html -http://www.thestateofcolorado.com/aconstairs.html -http://ftp.netc.pt/pub/idgames/levels/doom2/0-9/10level.txt -http://members.tripod.com.br/Magoo13/musicas.htm -http://tucows.bigskysoft.com/winme/adnload/137256_30133.html -http://www.houses-apartment-rentals.com/Texas/city_search_criteria.asp?state=TX&City=CHICOTA -http://se.egroups.com/message/trabalhoseguro/186 -http://www.daysinn.com/ctg/cgi-bin/DaysInn/financial_support/AAAksrACwAAABvyAAQ -http://www.long-life.de/lt040.htm -http://smartnet.tucows.com/winme/meditme_rating.html -http://smartnet.tucows.com/winme/meditme_size.html -http://www.kmoviefc-jp.com/db/prod/pd/k1000003.htm -http://ftp.rge.com/pub/usenet/readers/mac/Mews/?S=A -http://fi.egroups.com/messages/lasermail/298 -http://fi.egroups.com/message/lasermail/295 -http://www.voter.com/home/message/post/1,1559,24-60_2976_2473-,00.html -http://se.egroups.com/message/rv8list/1122 -http://www.ferien-immobilien.de/Rhein-Sieg-kreis/verkauf/GmbH-Kauf-Verkauf-Insolvenz-konkurs/Startseite/3d-service/Gemeinsam/Inserieren/Private-IB/Startseite/Default.htm -http://library.bangor.ac.uk/search/aUnited+Kingdom+Reading+Association/aunited+kingdom+reading+association/-17,-1,0,B/exact&F=aunited+kingdom+environmental+law+association&1,2/limit -http://webcenter.travelocity-leisure.netscape.com/DestGuides/0,1840,TRAVELOCITY|1987|5|2,00.html -http://yokohama.cool.ne.jp/michirur/dragon/maria/m2.htm -http://ring.omp.ad.jp/archives/NetBSD/packages/pkgsrc/graphics/Ngraph/patches/?D=A -http://mitglied.tripod.de/argewesterwald/jr/jrfo3.htm -http://www.arm.com/sitearchitek/support.ns4/html/cores_faq!OpenDocument&ExpandSection=3,16,10 -http://www.arm.com/sitearchitek/support.ns4/html/cores_faq!OpenDocument&ExpandSection=28,16,10 -http://avdistrict.edgate.com/hhs/pa_rc_gre.html -http://pub26.ezboard.com/fdysfuctionalrealityfrm2.showAddReplyScreenFromWeb?topicID=32.topic&index=1 -http://www.geocities.co.jp/Playtown-Domino/5245/guti.html -http://www.haikou.hi.cn/Pandect/hknj98/nj98d1.html -http://retailer.gocollect.com/do/session/1912800/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/help/site_tour/index.asp -http://ftp.unina.it/pub/Pcibm/pcdemos/ftp.hornet.org/graphics/images/1998/b/?M=A -http://variety.studiostore.com/browse/ABUGSLIFE/FIGURINE/s.qjEoNLlG -http://yp.gates96.com/11/76/10/13.html -http://yp.gates96.com/11/76/10/18.html -http://yp.gates96.com/11/76/11/63.html -http://yp.gates96.com/11/76/14/45.html -http://yp.gates96.com/11/76/14/65.html -http://yp.gates96.com/11/76/14/77.html -http://yp.gates96.com/11/76/15/1.html -http://yp.gates96.com/11/76/15/68.html -http://yp.gates96.com/11/76/15/97.html -http://yp.gates96.com/11/76/16/2.html -http://yp.gates96.com/11/76/16/59.html -http://yp.gates96.com/11/76/16/64.html -http://yp.gates96.com/11/76/16/79.html -http://yp.gates96.com/11/76/17/10.html -http://yp.gates96.com/11/76/17/52.html -http://yp.gates96.com/11/76/19/9.html -http://yp.gates96.com/11/76/19/11.html -http://yp.gates96.com/11/76/19/17.html -http://yp.gates96.com/11/76/19/19.html -http://www.debian.org.cn/Bugs/db/67/67207-b.html -http://www.bemi-immobilien.de/Exklusiv-IB/Startseite/Gemeinsam/immolink/Gemeinsam/Inserieren/Startseite/Gemeinsam/versicherungen/unfall/Gemeinsam/3d-service/info.htm -http://www.private-immobilien-boerse.de/baden-wuertemberg/calw/Verkauf/Gemeinsam/versicherungen/gebaeude/Gemeinsam/erreichenPartner/Private-IB/IIM-Teil/Startseite/frinfo.htm -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=21,0-(14,0)+9,5 -http://www.thesite.msnbc.com/tlkbck/comment/2100652/0,7436,80913-291181,00.html -http://202.109.72.57:8077/article/19991130/1741.htm -http://www.mit.edu/afs/athena.mit.edu/astaff/project/eolcdev/arch/sgi_62/ -http://www.metromix.com/top/1,1419,M-Metromix-Home-reviews!PlaceDetail-13623,00.html -http://ring.jec.ad.jp/pub/linux/debian/debian/dists/woody/non-free/binary-powerpc/news/?M=A -http://commerce.was-inc.com/cgi-bin/abtwsam.dll/LbkWebCommerceStoreCategories-BBC70A07_97FC_42E663949129E2030ACC2E97E71CD8B3 -http://grwy.online.ha.cn/paoe/about/aoe2.htm -http://www.2pl.com/b/ar/to/1/01/01/v1/1010178470-3.htm -http://www.digitaldrucke.de/(aktuell,marktplatz,nuernberg,sense,werbung)/suche/uebersicht.html -http://ustlib.ust.hk/search*chi/aswiss+radio+symphony+orchestra/aswiss+radio+symphony+orchestra/-5,-1,0,B/frameset&F=aswiss+society+for+soil+and+rock+mechanics&1,1 -http://www.ecatsbridge.com/BiB/static/sims/bbljuly99/00000101843221172F1.htm -http://www.videogames.com/psx/sports/freestyle99/screen.html?page=19 -http://www.mojahedin.org/Pages/Mojahed/Mojahed474/sci/sci02.html -http://www.shopworks.com/bigmountain/index.cfm/action/cart/userid/000E50D6-1185-19FE-A703010D0A0A8CF2 -http://polygraph.ircache.net:8181/http_-2www.horizonfinance.com/~xionthia/as/ -http://yp.gates96.com/14/76/30/16.html -http://yp.gates96.com/14/76/30/81.html -http://yp.gates96.com/14/76/31/12.html -http://yp.gates96.com/14/76/31/37.html -http://yp.gates96.com/14/76/31/68.html -http://yp.gates96.com/14/76/32/11.html -http://yp.gates96.com/14/76/32/50.html -http://yp.gates96.com/14/76/32/68.html -http://yp.gates96.com/14/76/33/26.html -http://yp.gates96.com/14/76/33/53.html -http://yp.gates96.com/14/76/35/11.html -http://yp.gates96.com/14/76/35/26.html -http://yp.gates96.com/14/76/35/47.html -http://yp.gates96.com/14/76/35/74.html -http://yp.gates96.com/14/76/36/16.html -http://yp.gates96.com/14/76/37/23.html -http://yp.gates96.com/14/76/37/56.html -http://yp.gates96.com/14/76/37/82.html -http://yp.gates96.com/14/76/38/76.html -http://yp.gates96.com/14/76/39/20.html -http://yp.gates96.com/14/76/39/25.html -http://yp.gates96.com/14/76/39/28.html -http://yp.gates96.com/14/76/39/33.html -http://yp.gates96.com/14/76/39/61.html -http://yp.gates96.com/14/76/39/69.html -http://yp.gates96.com/14/76/39/91.html -http://www-usa8.cricket.org/link_to_database/ARCHIVE/ARTICLES/JAN-JUN_1996/PRESS_REACTIONS_AUS_18MAR1996 -http://www-usa8.cricket.org/link_to_database/ARCHIVE/ARTICLES/JAN-JUN_1996/LOSS_WI_CRICKET_11MAR1996.html -http://www-usa8.cricket.org/link_to_database/ARCHIVE/ARTICLES/JAN-JUN_1996/SPINNERS_TALES_11JAN1996 -http://hurweb01.hurriyetim.com.tr/hur/turk/98/11/19/gundem/31gun.htm -http://library.cuhk.edu.hk/search*chi/aKuan,+Jui-hsuan./akuan+jui+hsuan/-5,-1,0,E/exact&F=akuan+jui+hsuan&1,22 -http://library.cuhk.edu.hk/search*chi/aKuan,+Jui-hsuan./akuan+jui+hsuan/-5,-1,0,E/frameset&F=akuan+jung&1,,0 -http://ring.toyama-ix.net/archives/pc/winsock-l/Windows95/Finger/fing32l.txt -http://cometweb01.comet.co.uk/do!tid=20&rtid=1&vsid=700&session=132044&mid=1000&rid=1060&cid=37030&chid=1713&url=eqqLmwlGltt5tkZHljbLqkZHlkrHhlZHdfjKYfkLlkZ5ljjLboZLbplGGolLarZLq4fLpmiLXv-KmooLckYLoznGmpq0qsc0mojLbkYLozvGotc0ZdoLckYLozvGsmv0qmc0jXfLkVZLdocLkYoLzcj1XfkLVZXLqkXLjbzKcob5qroLkVrLoizKlZd5fjYHfklKkZlLjjbLoZbLpl51ubZLDXZLollK3ljLbqlKjXfLkkaHotl4obmLloqL -http://student.monterey.edu/nr/riveradebranepom/campus/ -http://forum.rai.it/aca-finestre/dispatch.cgi/FORUM/listUnseen/fol/100001/20,0/5170254 -http://www.ibiblio.org/pub/Linux/distributions/debian/contrib/binary-all/otherosfs/?D=D -http://www.ilmessaggero.it/hermes/19980909/01_NAZIONALE/SPETTACOLI/E.htm -http://ayasii.virtualspace.net/html/1207/12071611_himemiya02.htm -http://retailer.gocollect.com/do/session/1912732/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/company_info/about.asp -http://retailer.gocollect.com/do/session/1912732/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/exclusives/newintros.asp -http://retailer.gocollect.com/do/session/1912732/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/company_info/dealer_lookup.asp -http://se.egroups.com/subscribe/pretty_of_five -http://home.neo.rr.com/keeter/pics.html -http://www.peopledaily.co.jp/haiwai/199910/12/newfiles/E108.html -http://www.telematik.informatik.uni-karlsruhe.de/osf/sw/v4.0x/lp2/snt100/?M=A -http://www.alyon.org/perso/1001-sciences/sciences_citoyens/agronomie/agronomie/intervenants.htm -http://www.2pl.com/b/no/fi/3/02/24/b1/3022400016-11131.htm -http://channel.nytimes.com/indexes/2000/07/21/sports/hockey/ -http://space.tin.it/io/fivird/REM/eng/albums/lyrics/documentfr.html -http://www.kurit.com/girls/galleryf.cgi?mp_code=7332&service=girls -http://store.efunctional.com/nokia.html -http://dk.egroups.com/login.cgi?login_target=%2Fmessage%2Fbonsai-cz%2F274 -http://bbs.kcm.co.kr/NetBBS/Bbs.dll/boliviabbs/opn/zka/B2-kB2Fq/qqo/007D/qqatt/^ -http://www.loisirs.ch/cvljnq/10/yrespd.html -http://www.primenet.com/~trakker/events/abcforum.htm -http://www.primenet.com/~trakker/events/frame_abcforum.htm -http://www.fogdog.com/cedroID/ssd3040183253760/nav/products/featured_brands/12r/gift_packs/ -http://www.fogdog.com/cedroID/ssd3040183253760/nav/products/featured_brands/12r/windshirts/ -http://www.oreilly.com/homepages/dtdparse/docbook/3.0/dtdent/simmod02.htm -http://dk.egroups.com/group/SCMHCSC -http://www.ycwb.com.cn/gb/2000/01/11/ycwb/dsxw/9.html -http://dk.egroups.com/message/teenhealth/1620 -http://nbzhuhq1.top263.net/htm/y/y14-5.htm -http://adserver.latimes.com/editions/orange/20001030/t000103739.html -http://adserver.latimes.com/editions/orange/20001030/t000103751.html -http://library.bangor.ac.uk/search/cWS+200+G4655+1999/cws++200+g4655+1999/-17,-1,0,B/frameset&F=cws++141+j74+h+1989&2,,2 -http://ftpsearch.belnet.be/pub/os/linux/SuSE-Linux/i386/6.4/disks/rescue -http://www.rarf.riken.go.jp/archives/tex-archive/macros/latex//contrib/supported/elsevier/model-harv.pdf -http://www.diogenes.ch/4DACTION/web_glob_showhtml/path=leser/verlag/index.html&ID=483373 -http://crn.com/Components/emailArticle.asp?ArticleID=2114 -http://link.fastpartner.com/do/session/600410/vsid/1970/tid/1970/cid/135878/mid/1060/rid/1488/chid/1970/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/speednames.php -http://link.fastpartner.com/do/session/600410/vsid/1970/tid/1970/cid/135878/mid/1060/rid/1488/chid/1970/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/nordicliving.php -http://ftp.gigabell.net/pub/FreeBSD/FreeBSD-stable/packages/emulators/ -http://ftp.gigabell.net/pub/FreeBSD/FreeBSD-stable/packages/print/ -http://emplois.fr.net/archive062000/2348.html -http://variety.studiostore.com/browse/ANASTASIA/_/b.FAVORITES%20COMICS%20ANIMFEAT/s.eKoxAPfo -http://www.geocities.co.jp/HeartLand-Gaien/3163/choko.htm -http://members.tripod.com/~moviemaniac1/moviesR/Rocketman.html -http://wiem.onet.pl/wiem/0006ac-sp1.html -http://msdn.microsoft.com/library/devprods/vs6/visualj/vjref/java.net.UnknownHostException001.html -http://www.tiscover.ch/1Root/Kontinent/6/Staat/30/Bundesland/31/Ort/1732/Homepage/m_homepage...2.html -http://power.luneng.com/power/library/jzjs/jzjs99/jzjs9903/990311.htm -http://citeseer.nj.nec.com/cidcontext/1976718 -http://in.egroups.com/messages/srcg/2 -http://sunsite.informatik.rwth-aachen.de/cgi-bin/ftp/ftpshow/pub/comp/Linux/debian/dists/potato/main/disks-sparc -http://pd.shiseido.co.jp/s9701unt/html/unt00025.htm -http://www.kame.tadaima.com/9721036/taro1.html -http://www.kame.tadaima.com/9721036/taro8.html -http://www.unc.edu/courses/chem41/classnotes/41s6/sld008.htm -http://a1sexpics.com/butts/buttfucking/ -http://moundoflove.com/buttfucking/butts/asslickinganal.html -http://www.digitaldrucke.de/(arbeitsvermittlung,hilfe,nuernberg)/_fort/html/themen/hilfe/hilfe.htm -http://freethemes.netc.pt/preview/15221.html -http://freethemes.netc.pt/preview/51972.html -http://freethemes.netc.pt/preview/74442.html -http://cn.tech.yahoo.com/000913/23/1dpl.html -http://cn.tech.yahoo.com/000913/23/1dp2.html -http://wap.jamba.de/KNet/_KNet-JgK8j1-FGd-13di8/browse.de/node.0/cde7f1uou -http://imageserver2.tibetart.com:8087/fif=fpxbuddhist/43.fpx&init=0.0,0.0,1.0,1.0&rect=-0.25,0.25,0.25,0.75&wid=280&hei=400&lng=en_US&enablePastMaxZoom=OFF&page=image.html&obj=uv,1.0&cmd=S -http://www.ozemail.com.au/~pballard/gnt_hidden123/mar12.htm -http://www.ozemail.com.au/~pballard/gnt_hidden123/act9.htm -http://www.ozemail.com.au/~pballard/gnt_hidden123/rom7.htm -http://www.ozemail.com.au/~pballard/gnt_hidden123/2co13.htm -http://www.ozemail.com.au/~pballard/gnt_hidden123/heb12.htm -http://www.ozemail.com.au/~pballard/gnt_hidden123/jam4.htm -http://ftp.darenet.dk/tucows/winnt/adnload/1449_29554.html -http://www.chaos.dk/sexriddle/w/j/u/o/ -http://www.chaos.dk/sexriddle/w/j/u/v/ -http://opac.lib.rpi.edu/search/tmcgraw+hill+series+in+advanced+chemistry/-5,-1,0,B/frameset&tmcgraw+hill+series+in+advanced+chemistry&9,,42 -http://www.zcu.cz/ftp/mirrors/pgp/6.5/6.5.1/win/ -http://webpolitik.subportal.com/sn/Multimedia_and_Graphics/Misc__Graphics_Tools/12852.html -http://ftp.lip6.fr/pub2/perl/CPAN/doc/manual/html/lib/SysV/SysV.html -http://bbs.gznet.edu.cn/cgi-bin/getannounce//groups/GROUP_9/Telecom/friend/fbf/ewqtr -http://www.infomedia.it/cgi-bin/lwgate/JAVA-IT/archives/java-it.log.9709/date/article-10.html -http://www.infomedia.it/cgi-bin/lwgate/JAVA-IT/archives/java-it.log.9709/date/article-88.html -http://www.infomedia.it/cgi-bin/lwgate/JAVA-IT/archives/java-it.log.9709/date/article-92.html -http://www.infomedia.it/cgi-bin/lwgate/JAVA-IT/archives/java-it.log.9709/date/article-177.html -http://www.infomedia.it/cgi-bin/lwgate/JAVA-IT/archives/java-it.log.9709/date/article-178.html -http://www.infomedia.it/cgi-bin/lwgate/JAVA-IT/archives/java-it.log.9709/date/article-229.html -http://www.infomedia.it/cgi-bin/lwgate/JAVA-IT/archives/java-it.log.9709/date/article-288.html -http://www.infomedia.it/cgi-bin/lwgate/JAVA-IT/archives/java-it.log.9709/date/article-293.html -http://www.usq.edu.au/unit-1997/fullspec/54081s2x.htm -http://sound-dist.secured.co.uk/cgi-bin/psProdDet.cgi/15P04|972959617|Helmet|user|0|1,0,0,0 -http://www.buybuddy.com.au/sleuth/8/1/5010204/40843/ -http://www.maxpages.com/vote.cgi?site=pokemonyellow1&pg=Home -http://rex.skyline.net/html/Automobiles_-_Dealers_-_Used.html?64,outdoor,transportation,collectibles,transportation -http://www.linux.com/networking/network/communications/management/updates/Windows_NT/ -http://retailer.gocollect.com/do/session/1912735/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/product_display/top_ten.asp?pagenum=1 -http://amarilloglobenews.com/stories/031000/ -http://www.egroups.com/post/swish?act=reply&messageNum=275 -http://www.apcmag.com/apcweb/reviewsdisc.nsf/aac7d56ca8fd884b852563be00610639/af5bb64432e7f9444a2565240026bbbf!Navigate&To=PrevMain -http://best.netease.com/guestbook/personal/zhuirinew3.html -http://best.netease.com/cgi-bin/view/viewbasic.cgi?japanboy4 -http://www.ftp.uni-erlangen.de/cgi-bin/view/pub/mirrors/redhat/current/i386/doc/gsg/ch-basics.htm -http://www.ftp.uni-erlangen.de/cgi-bin/view/pub/mirrors/redhat/current/i386/doc/gsg/p5202.htm -http://splitrock.themes.tucows.com/preview/77000.html -http://splitrock.themes.tucows.com/preview/25855.html -http://splitrock.themes.tucows.com/preview/134493.html -http://splitrock.themes.tucows.com/preview/14722.html -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=13,0-22,0+15,0-0,2 -http://www.icopyright.com/1.1634.64625 -http://mvweb.de/olympia/nachrichten/sportarten/ergebnisse/bdt-190900-438-dpa_153140.html -http://www.rge.com/pub/tex/fonts/armtex/v2.0/examples/plain/ -http://www.club-internet.fr/cgi-bin/h?Antibes -http://www.caprili.it/santantimo.htm -http://dic.empas.com/show.tsp/?q=%C3%EB%C8%EF%20%F6%AD%FD%E9&f=B -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=98&discrim=2,38 -http://www.artex.firenze.it/_qualitart/articoli/zoom/02235.htm -http://home.powertech.no/huftis/w3c/TR/WAI-WEBCONTENT-NO-NYN/checkpoint-list.txt -http://mtlab.biol.tsukuba.ac.jp/WWW/PDB2/PCD0467/htmls/07.html -http://library.cuhk.edu.hk/search*chi/aShu,+Tien-min./ashu+tien+min/-5,-1,0,B/exact&F=ashu+tsung+chiao&1,6 -http://www.trnonline.com/archives/2000archives/05242000/how_now_joe_brown/23506.shtml -http://www.bemi-immobilien.de/Exklusiv-IB/Startseite/Gemeinsam/versicherungen/gebaeude/Gemeinsam/MarketingStrategie/Gemeinsam/erreichenPartner/Gemeinsam/versicherungen/lebensversicherung/Startseite/frinfo.htm -http://santabarbarashops.com/Mall/Stores/StoreInfo/asp/store-id/1000007121.html -http://www.angelfire.com/ok/americassweetheart/UNique.html -http://ukinvest.ukwire.com/articles/199909070731000375A.html -http://www.streetprices.com/Electronics/Consumer/Camcorders/Digital/sortproductbylowprice/SP374033.html -http://www.streetprices.com/Electronics/Consumer/Camcorders/Digital/sortproductbylowprice/SP363722.html -http://www.streetprices.com/Electronics/Consumer/Camcorders/Digital/sortproductbylowprice/SP288187.html -http://www.streetprices.com/Electronics/Consumer/Camcorders/Digital/sortproductbylowprice/SP288192.html -http://www.bemi-immobilien.de/Startseite/www.ferien-immobilien.de/ferien-ib/startseite/Gemeinsam/Gemeinsam/versicherungen/gebaeude/Startseite/Gemeinsam/Gemeinsam/immolink/Top-Darlehens-Konditionen/anforderungsformular.htm -http://celes.subportal.com/sn/Business/Standard_Calculators/index1.html -http://www.linux.com/networking/network/networking/it/future/firewall/ -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=198&discrim=87,19,3 -http://www.hig.se/(append,define,language,quote,tablify)/~jackson/roxen/ -http://www.guba.com/114/236/12fE/index-3.phtml -http://genforum.genealogy.com/tn/messages/7906.html -http://207.138.41.133/message/BienestarCalifornia/16 -http://207.138.41.133/message/BienestarCalifornia/26 -http://chasnaz.freeyellow.com/email.html -http://genforum.genealogy.com/cgi-bin/print.cgi?mcevoy::217.html -http://www.civila.com/brasil/fov/ -http://www.emerchandise.com/associates/b.FAVORITES%20PAGEANTS/s.oAq5vp1w -http://www.emerchandise.com/help_security/b.FAVORITES%20PAGEANTS/s.oAq5vp1w -http://www.z-plus.de/freizeit/kino/galerie/roula/kritikwelt.html -http://www.angelfire.com/mo2/MrMime2000/wewon.html -http://www.gazeta.com/Iso/Regiony/Lodz/Raporty/Jedzenie/Jedz/020jed.html -http://www.sportas.de/ddsup00.htm -http://muc-zvs-web1.goethe.de/an/mel/wabhorst/dtourism.htm -http://www.cardina.net/~erps -http://www.polbox.com/p/paruwa/spec.html -http://ww2.comune.fe.it/cgi-win/hiweb.exe/a2/d72/b31,e,1f,b,b,50,50,,3,,1f,3,9,,1f,9, -http://www.ld.com/cbd/archive/1999/03(March)/29-Mar-1999/15awd002.htm -http://dk.egroups.com/post/cbradio?act=reply&messageNum=823 -http://aecjobbank.com/texis/script/newjobs/+lww7mwww0xBV6e52iHwwwesPBB2eZmwwwt6erV0Vwwwh6er6Gswwwt6er6bgwwwt6etDL-www+6ethrCwwxeRT43eR4mwwwt6etrvuwwwn6KeU-wwwmcmrmwxerjmx7mwww1hzmww-eHxww/jobdirectory.html -http://www.envy.nu/summerslip/past.html -http://www.envy.nu/summerslip/leave.html -http://home.pacific.net.sg/~kinnkinn/ -http://www.bluesapphires.net/ladies/lv0444.shtml -http://www.freerepublic.com/forum/a4148bd.htm -http://www.sdinfonet.com.cn/024/32/024329969.htm -http://www.sdinfonet.com.cn/024/32/024329953.htm -http://www.jpc-music.com/8754347.htm -http://www.jpc-music.com/5183511.htm -http://www.jamba.nl/KNet/_KNet-ytO8j1-7D4-pwef/browse.nl/node.0/cde7f38ny -http://dk.egroups.com/message/noholdsbarred/210 -http://uoi.tucows.com/winme/preview/75912.html -http://207.197.132.133/lobbyists/98profiles/556.htm -http://www.jobvillage.com/channel/jobs/protective_services/private_investigator/g.4.html -http://www.jobvillage.com/channel/jobs/protective_services/private_investigator/b.8946.g.4179.html -http://aleph.tau.ac.il:4500/ALEPH/eng/ATA/AAS/AAS/SET-MAIL/381462/11/ -http://www-rn.informatik.uni-bremen.de/home/X11R6/xc/lib/font/Speedo/?D=A -http://www.brio.de/BRIO.catalog/39fe2f7006f69fb6273fd472aa78073d/UserTemplate/6 -http://cardiology.medscape.com/IMNG/ClinPsychNews/1998/v26.n07/cpn2607.34.01.html -http://www.incestpornstories.com/hot-hardcore-fuckingbanging/plus-sizewhale/slutspretty/slutsbest-friends/erectionfellatio/bisexualtinkerbell.html -http://yp.gates96.com/7/65/10/40.html -http://yp.gates96.com/7/65/11/15.html -http://yp.gates96.com/7/65/11/34.html -http://yp.gates96.com/7/65/11/69.html -http://yp.gates96.com/7/65/11/88.html -http://yp.gates96.com/7/65/12/95.html -http://yp.gates96.com/7/65/13/82.html -http://yp.gates96.com/7/65/13/91.html -http://yp.gates96.com/7/65/13/93.html -http://yp.gates96.com/7/65/14/2.html -http://yp.gates96.com/7/65/14/8.html -http://yp.gates96.com/7/65/15/31.html -http://yp.gates96.com/7/65/15/38.html -http://yp.gates96.com/7/65/15/51.html -http://yp.gates96.com/7/65/15/95.html -http://yp.gates96.com/7/65/15/96.html -http://yp.gates96.com/7/65/16/4.html -http://yp.gates96.com/7/65/16/20.html -http://yp.gates96.com/7/65/16/58.html -http://yp.gates96.com/7/65/17/22.html -http://yp.gates96.com/7/65/17/66.html -http://yp.gates96.com/7/65/18/37.html -http://yp.gates96.com/7/65/18/69.html -http://yp.gates96.com/7/65/18/97.html -http://yp.gates96.com/7/65/19/0.html -http://yp.gates96.com/7/65/19/12.html -http://yp.gates96.com/7/65/19/16.html -http://yp.gates96.com/7/65/19/28.html -http://yp.gates96.com/7/65/19/37.html -http://yp.gates96.com/7/65/19/44.html -http://dyade.inrialpes.fr/aaa/public/java/jdk1.3/docs/api/javax/swing/plaf/basic/class-use/BasicSplitPaneUI.KeyboardUpLeftHandler.html -http://l-infonet.phkk.fi/fi/TIETOPALVELUT/asiasanahaku/kalatalous/ty%F6voimapolitiikka/pienet+ja+keskisuuret+yritykset/maatilatalous/ -http://www.ferien-immobilien.de/ungarn/verkauf/Gemeinsam/MarketingStrategie/Allgemeine-IB/Private-IB/Private-IB/Startseite/Default.htm -http://ftp.du.se/disk2/CPAN/modules/by-category/15_World_Wide_Web_HTML_HTTP_CGI/WWW/libwww-perl-5.43.readme -http://ftp.du.se/disk2/CPAN/modules/by-category/15_World_Wide_Web_HTML_HTTP_CGI/WWW/libwww-perl-5.46.readme -http://ftp.du.se/disk2/CPAN/modules/by-category/15_World_Wide_Web_HTML_HTTP_CGI/WWW/webchat-0.05.readme -http://209.0.220.240/biz/541519/541-389-1493.htm -http://www.shsu.edu/wcb/schools/SHSU/sed/rmzoubi/12/forums/forum54/wwwboard.html -http://retailer.gocollect.com/do/session/1912768/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/news/index.asp -http://romulus.ehs.uiuc.edu/cgi-bin/lwgate/RADSAFE/archives/radsafe9610/Date/article-33.html -http://romulus.ehs.uiuc.edu/cgi-bin/lwgate/RADSAFE/archives/radsafe9610/Date/article-31.html -http://www.acfas.ca/congres/congres67/S408.htm -http://pub1.ezboard.com/fthehawkeyehotspotfrm16.showMessage?topicID=178.topic -http://archives.marshall.edu/~mccomas/cd315-spring00-list/1549.html -http://www.asiastockwatch.com/AsiaStockWatch_-_Cached/Articles/asw_recommend_friend_con/1,1145,617_1_1:3,00.html -http://wiem.onet.pl/wiem/014a7e.html -http://linux99.inrialpes.fr/linux/RPM/kondara/1.2/errata/bugfixes/i586/System_Environment_Daemons.html -http://linux99.inrialpes.fr/linux/RPM/kondara/1.2/errata/bugfixes/i586/User_Interface_X.html -http://cn.egroups.com/login.cgi?login_target=%2Fmessage%2FWeb_Holidays%2F35 -http://library.bangor.ac.uk/search/aEuropean+Academy+of+Allergology+and+Clinical+Immunology/aeuropean+academy+of+allergology+and+clinical+immunology/7,-1,0,B/bibandlinks&F=aeuropean+association+for+animal+production+commission+on+animal+management&1,1 -http://www4.freeweb.ne.jp/art/fujiso/gehp/pge222.html -http://pnews.jcc.co.jp/scoop/9905/990506kk2-3ss.html -http://ring.nii.ac.jp/archives/linux/Vine/Vine-1.1/kernel-2.2.x-kit/RPMS/ -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=81&discrim=8,230,214 -http://www.emerchandise.com/browse/BUFFYTHEVAMP/KEYCHAIN/b.TV%20BUFFYTHEVAMP/s.DfgPpLQw -http://www.emerchandise.com/browse/BUFFYTHEVAMP/MAGNET/s.DfgPpLQw -http://www.koms.de/I-Data/Upgrades/HostCom/Cx/isp/?S=A -http://www.back2roots.org/Aminet/Forums/Util--Wb--Amero36/ -http://www.hig.se/(autoformat,define,en,modified,referrer)/~jackson/roxen/ -http://216.35.79.131/sites/gunits/052302u.html -http://216.35.79.131/sites/gunits/052303u.html -http://216.35.79.131/sites/gunits/032883u.html -http://itcareers.careercast.com/texis/it/itjs/+4wwBmecXD86ExwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewShwAwMwoacnwmamnpcdOMnDBaMwoDBnDwDqnanDtoDnnGaDnBidGAaoDqc1mna5BGdDtaADdicnmtnaGn31oGnmaMFqtwAwMwoDzmeZxwwwpBmIe0B-decrwww5rmeAdwwwBrmeZpwww/morelike.html -http://troy.lib.sfu.ca/search/tadvocate+vanc/tadvocate+vanc/7,-1,0,B/browse -http://210.159.30.200:8080/-_-http://www2s.biglobe.ne.jp/~proton/kokuritu/ -http://210.159.30.200:8080/-_-http://www2s.biglobe.ne.jp/~proton/mituzawa/mitusta.html -http://config.tucows.com/win2k/monitor2k_size.html -http://config.tucows.com/win2k/adnload/136674_47327.html -http://www.thisisyork.com/york/news/YORK_NEWS_CAMPAIGNS_POSTOFFICE5.html -http://yp.gates96.com/5/78/0/35.html -http://yp.gates96.com/5/78/0/41.html -http://yp.gates96.com/5/78/0/65.html -http://yp.gates96.com/5/78/0/79.html -http://yp.gates96.com/5/78/0/81.html -http://yp.gates96.com/5/78/1/33.html -http://yp.gates96.com/5/78/1/76.html -http://yp.gates96.com/5/78/2/0.html -http://yp.gates96.com/5/78/2/65.html -http://yp.gates96.com/5/78/3/37.html -http://yp.gates96.com/5/78/4/31.html -http://yp.gates96.com/5/78/4/60.html -http://yp.gates96.com/5/78/4/73.html -http://yp.gates96.com/5/78/5/28.html -http://yp.gates96.com/5/78/5/65.html -http://yp.gates96.com/5/78/6/12.html -http://yp.gates96.com/5/78/6/38.html -http://yp.gates96.com/5/78/6/99.html -http://yp.gates96.com/5/78/7/48.html -http://yp.gates96.com/5/78/8/49.html -http://yp.gates96.com/5/78/8/55.html -http://yp.gates96.com/5/78/8/71.html -http://yp.gates96.com/5/78/9/19.html -http://yp.gates96.com/5/78/9/94.html -http://link.fastpartner.com/do/session/600420/vsid/2870/tid/2870/cid/136966/mid/1060/rid/1926/chid/2870/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/fastpartner.php -http://www.highwired.net/Guidance/UniversalNav/Redirect/0,5314,15089-15089-728,00.html -http://ring.tains.tohoku.ac.jp/archives/lang/perl/CPAN/modules/by-module/Math/ILYAZ/os2/?S=A -http://www.outpersonals.com/cgi-bin/w3com/pws/out/DzRIZER-v0LffJEf3raIMcG3_vXLUQncNB0JHLK7Xt_XcNu5W9Xwg3bnK7e0BWrbchX2jMSNnK6eY6UuDPq6GFLMrzB0DcydY5VgMGVRUFbdksWiDCuTI0LBo3psuJxBJjEd -http://www.outpersonals.com/cgi-bin/w3com/pws/out/vihIvBk0g-CdjheZ4MILAcJAB--YtsE3nzjAldQSrSojV9JzVQJV-1yVbCi9rsPamZBGc9GfXE6dq1sCz-CnrfwDCHqr_nfUtl2qUN5oWAHphPSuuQXCc2fjfBv3EI-W4XBgp-ANhxEJS0536665 -http://www.outpersonals.com/cgi-bin/w3com/pws/out/VihIDgZ6TF6W8zfPesIFMiw-CNzcKPLyYr5OXnsaqepOa1j4Wz2V-pVOhRfX5lUkxRpYs_BkTdpvjf7zUAk3RdhEaXDfmzm4RA2CLjQ84zSbEZ_Vil1cFFmY0FFZr5oIErljk11AnTlYM6y066jO -http://www.outpersonals.com/cgi-bin/w3com/pws/out/dRhIQJ3pEIfD5uG_JFeaP3_7Bke37Z5pJi0A-hZ_-kxEK4Z1jl3HNb6d3hgJ7UZ34jMQGSNzhYuMNxB-oyBon62h9GWx3Xt1Zk_o4kS3s9ybikCpzetMwprVGDCC-YzllwvEWxmP66jF -http://www.v2music.com/Scripts/WebObjects-ISAPI.dll/V2_New_Publisher.woa/24161000003783000000741030000081551/v2tvindex.wo/810000000071551/1.0.4/3/Webobjects1 -http://www.maas.ccr.it/cgi-win/hiweb.exe/a17/d3345/b77,c,4d,469,469,46e,46e,168e,168e,,51,,4d,51, -http://findmail.com/messages/themcse/102 -http://netcon.tucows.com/winme/adnload/136907_28427.html -http://netcon.tucows.com/winme/adnload/136906_30076.html -http://www.jyu.fi/~heili/tietoverkot/?S=A -http://www1.onelist.com/dir/1/16/483/32773?st=10 -http://www1.onelist.com/messages/animadores -http://seussville.com/teachers/authors/ayre.html -http://seussville.com/teachers/authors/corm.html -http://www.tente.de/sw/produkte/rubriksuche/aa000001461.htm -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=57&discrim=165,57,164 -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=57&discrim=165,57,207 -http://jars.developer.com//classes/jresout.cgi?resource=2897 -http://members.tripod.co.jp/spirits/?S=A -http://homepages.go.com/homepages/i/u/g/iuguy22/ -http://www.arm.com/sitearchitek/support.ns4/html/cores_faq!OpenDocument&ExpandSection=21,5,24 -http://www.arm.com/sitearchitek/support.ns4/html/cores_faq!OpenDocument&ExpandSection=31,5,24 -http://troy.lib.sfu.ca/search/delectrolytes+periodicals/delectrolytes+periodicals/-5,-1,0,B/exact&F=delectrolytes+congresses&1,3 -http://www.rdg.ac.uk/ITS/Topic/Stats/StGSAS8_01/SAS8/af/z0254912.htm -http://www.rdg.ac.uk/ITS/Topic/Stats/StGSAS8_01/SAS8/af/z0254924.htm -http://ring.jec.ad.jp/local/mirror/FreeBSD-current/snapshots/i386/5.0-20000902-CURRENT/compat20/ -http://ring.jec.ad.jp/local/mirror/FreeBSD-current/snapshots/i386/5.0-20000902-CURRENT/dict/ -http://ring.jec.ad.jp/local/mirror/FreeBSD-current/snapshots/i386/5.0-20000902-CURRENT/manpages/ -http://www.xmission.com/~dkenison/cgi/lwgate.cgi/KLR650/archives/v02.n1682/date/article-7.html -http://ring.toyama-ix.net/pub/linux/Vine/Vine-2.0/ppc/?S=A -http://romulus.ehs.uiuc.edu/cgi-bin/lwgate/RADSAFE/archives/radsafe9907/Date/article-80.html -http://www.officeqmart.com/cgi-bin/qmart.front/972959552267/Catalog/3000033 -http://www.checkout.com/member/movies/title/member_reviews_form/1,7722,882122,00.html -http://mindit.netmind.com/proxy/http://www.siennasoft.com/english/order/orders_retail.shtml -http://pelit.saunalahti.fi/.1/tucows/adnload/267_29529.html -http://pelit.saunalahti.fi/.1/tucows/adnload/7574_29534.html -http://zenha.myrice.com/2/23.htm -http://zenha.myrice.com/2/20.htm -http://citeseer.nj.nec.com/cachedpage/62677/1 -http://citeseer.nj.nec.com/check/248055 -http://www.3wbooks.de/BrackRuth/BrackRuth3258053200.htm -http://preview.egroups.com/group/u_exactus -http://preview.egroups.com/group/ticovista -http://www.linux.com/networking/linux/support/va_linux_systems/price/sales/ -http://kulichki-mac.rambler.ru/moshkow/akm/zercalo/kosmix/03.html -http://innopac.lib.tsinghua.edu.cn:2080/search*chi/tStructure+and+bonding+&%2359%3B+70/tstructure+and+bonding+++70/19,-1,0,B/browse -http://www.science.uva.nl/pub/NetBSD/NetBSD-current/pkgsrc/archivers/gcpio/files/ -http://www-d0.fnal.gov/d0dist/dist/releases/pmc04.00.00/calibration_management/?S=A -http://mvweb.de/olympia/nachrichten/sportarten/news/bdt-290900-158-dpa_173282.html -http://www.scifi.com/bboard/browse.cgi/3/1/69/57?pnum=2 -http://www.diogenes.ch/4DACTION/web_rd_aut_prview/a_id=7056459&area=&ID=483365 -http://mirror.cc.utsunomiya-u.ac.jp/mirror/CPAN/authors/id/L/LA/LAXEN/?D=A -http://www.affiliate.hpstore.hp.co.uk/do/session/380856/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.france.hp.com/Main/acheterhp/ -http://library.cuhk.edu.hk/search*chi/aLu,+Li,+1914-/alu+li+1914/-5,-1,0,B/frameset&F=alu+li+chun&1,1 -http://www-usa4.cricket.org/link_to_database/ARCHIVE/2000-01/IND_LOCAL/WOMEN/OTHERS/KLCA-SL/SQUADS/ -http://www.babyheirlooms.com/catalog/htmlos.cat/041141.1.4425650346 -http://193.207.57.3/cgi-win/hiweb.exe/a2/d9/b1305,4,5,,1f,5, -http://www.icopyright.com/1.1664.228033 -http://www.trax.nilex.co.uk/trax.cgi/A1C/B1S/1AR/A2S/A1S/D1L/ -http://www.trax.nilex.co.uk/trax.cgi/A1C/B1S/1AR/A2S/A1S/A2S/ -http://www.ferien-immobilien.de/baden-wuertemberg/calw/Verkauf/Gemeinsam/Inserieren/Private-IB/Gemeinsam/Super-Zins-Konditionen/3d-service/info.htm -http://sunsite.informatik.rwth-aachen.de/LinuxArchives/redhat/releases/guinness/i386/en/dosutils/fips15c/restorrb/ -http://213.36.119.69/do/session/153002/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/FR/connaitre/revue-presse_titres.html -http://pub19.ezboard.com/uvinylangel.showPublicProfile?language=EN -http://boeing_dude.tripod.com/id125_m.htm -http://members.fortunecity.com/greatway1/gallery-pageother-0.htm -http://www.searchtraffic.com/wsignup.php3?owor12 -http://www.staroriental.net/nav/soeg_c/ihf,acv,s0,194,陳慧ç³.html -http://www.jpc-music.com/5864555.htm -http://oaziz.narod.ru/kuhn/uzb/sal_f1.html -http://preview.egroups.com/message/4aromatherapy/1112 -http://www.luecos.de/webguides/reisen/travelpictures/europe -http://www.maas.ccr.it/cgi-win/hiweb.exe/a18/d47/b47,8,be,29,29,,38,,be,38, -http://www.chaos.dk/sexriddle/k/u/u/a/ -http://www.chaos.dk/sexriddle/k/u/u/d/ -http://student.monterey.edu/nr/nielsenadamp/campus/ -http://excite.de/gesundheit/katalog/3727 -http://www.ozemail.com.au/~jcai/page19.html -http://www.ozemail.com.au/~jcai/page24.html -http://www.hantsnet.co.uk/scrmxn/c23173.html -http://www.fogdog.com/cedroID/ssd3040183334784/content/fan/subway_series/ -http://www.fogdog.com/cedroID/ssd3040183334784/boutique/arnette/ -http://www.fogdog.com/cedroID/ssd3040183334784/boutique/hi-tec/ -http://www.fogdog.com/cedroID/ssd3040183334784/boutique/marmot/ -http://ftpsearch.belnet.be/packages/CPAN/modules/by-module/Stat/ENNO/ -http://go1.163.com/_NTES/~yejingsong/03/y18/506.htm -http://sinr.net/book/content/343/26710.html -http://www.ramada.com/ctg/cgi-bin/Ramada/progpack/AAAksrACwAAABtrAAV -http://library.bangor.ac.uk/search/aBoer,+J.+H.+de+(Jan+Hendrik),+1899-/aboer+j+h+de+jan+hendrik+1899/-5,-1,0,B/buttonframe&F=aboer+dirk+jan+den&1,1 -http://library.cuhk.edu.hk/search*chi/a三çœå ‚(åƒä»£ç”°å€,+Tokyo,+Japan)/a%7B213024%7D%7B214d49%7D%7B213840%7D+%7B213458%7D%7B213073%7D%7B214c24%7D%7B213455%7D+tokyo+japan/-5,-1,0,B/browse -http://ibm1.cicrp.jussieu.fr/ibmc/classref/ref/ISetCanvas--Style_DSC.htm -http://amateur-alley.porncity.net/169/ -http://www.teacherformation.org/html/od/facilitators.cfm/task1,about/discussion_id,2/xid,1989/yid,5768630 -http://www.shopworks.com/index.cfm/action/mallcat/mallcatlevel/2/parentmallcat/6/userid/000056F0-2E26-19FE-AF65010C0A0A8CF2 -http://retailer.gocollect.com/do/session/1912760/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/company_info/shipping_policy.asp -http://news.novgorod.ru/news/2001/4/1/8/-1 -http://news.novgorod.ru/news/2001/4/3/8/-1 -http://sp201.unige.ch:49213/cxxdoc/classref/ref/ITimingTestStopwatch_DSC.htm -http://netscape.digitalcity.com/boston/localexperts/profile.dci?screenName=PSYWU -http://netscape.digitalcity.com/boston/localexperts/profile.dci?screenName=Mende67 -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=17,2,26,33,23 -http://www.multicosm.com/facade/www.isinet.com/isilinks/isilinks.html -http://kutschen.de/Schoner/Info-d/history/history/literature/ -http://troy.lib.sfu.ca/search/dengineering+research+periodicals/dengineering+research+periodicals/-5,-1,0,B/frameset&F=dengineering+research+grants+canada&3,,4 -http://member.nifty.ne.jp/y-shibata/pc/pch2.htm -http://stocks.tradingcharts.com/stocks/charts/iops-bb/m -http://www.kaos.dk/sexriddle/x/j/c/s/z/ -http://www.bioimages.org.uk/HTML/R138925.HTM -http://pub22.ezboard.com/fawolpaintballfrm1.threadControl?topicID=82.topic -http://www.incestpornstories.com/hot-hardcore-fuckingbanging/plus-sizewhale/body-shotstounge/fuckinghardcore/barely-legalbackseat/{gaylink} -http://www.buybuddy.com/sleuth/27/1/1060904/5811/ -http://www.loisirs.ch/gtfmjv/9/nkrlua.html -http://vorg1.subportal.com/sn/Utilities/File_Maintenance_and_Repair_Utilities/6387.html -http://smartnet.tucows.com/winme/adnload/138584_30392.html -http://ftpsearch.belnet.be/mirrors/src.doc.ic.ac.uk/usenet/usenet-by-hierarchy/comp/emacs/?D=A -http://genforum.genealogy.com/cgi-genforum/forums/green.cgi?7578 -http://cio.cisco.com/warp/public/789/33.html -http://www7.freeweb.ne.jp/diary/bru_dog/tk/ -http://www.chinabyte.com/staticpages/software/software_download/GRBA/software_download_23274_GRBA.html -http://www.chinabyte.com/staticpages/software/software_download/GRBA/software_download_9599_GRBA.html -http://www.seekon.com/L/US/IL/Abingdon -http://freethemes.arrakis.es/skins/winamp/adnload/25359.html -http://www.hig.se/(accessed,modified,remove_cookie,smallcaps,sqlquery)/~jackson/roxen/ -http://cn.egroups.com/message/SF-users/218 -http://cn.egroups.com/message/SF-users/235 -http://www.chaos.dk/sexriddle/r/f/y/c/ -http://www.chaos.dk/sexriddle/r/f/y/e/ -http://www.chaos.dk/sexriddle/r/f/y/g/ -http://yp.gates96.com/13/50/10/33.html -http://yp.gates96.com/13/50/10/49.html -http://yp.gates96.com/13/50/10/55.html -http://yp.gates96.com/13/50/10/98.html -http://yp.gates96.com/13/50/11/35.html -http://yp.gates96.com/13/50/11/73.html -http://yp.gates96.com/13/50/11/94.html -http://yp.gates96.com/13/50/12/39.html -http://yp.gates96.com/13/50/13/8.html -http://yp.gates96.com/13/50/13/67.html -http://yp.gates96.com/13/50/14/8.html -http://yp.gates96.com/13/50/14/11.html -http://yp.gates96.com/13/50/14/47.html -http://yp.gates96.com/13/50/16/18.html -http://yp.gates96.com/13/50/16/58.html -http://yp.gates96.com/13/50/17/33.html -http://yp.gates96.com/13/50/18/13.html -http://yp.gates96.com/13/50/18/49.html -http://yp.gates96.com/13/50/18/54.html -http://yp.gates96.com/13/50/19/0.html -http://cn.egroups.com/post/romtrade?act=reply&messageNum=3851 -http://members.fortunecity.com/toleransi/sorbonne.html -http://ring.htcn.ne.jp/pub/lang/perl/CPAN/modules/by-module/PPM/MURRAY/?S=A -http://sunsite.berkeley.edu/PhiloBiblon/BITAGAP/BIB/BIB5648.html -http://sunsite.berkeley.edu/PhiloBiblon/BITAGAP/BIB/BIB7392.html -http://www.kfi640.com/shared/mod_perl/looksmart/looksmart/eus1/eus53940/eus53960/eus54753/eus543189/eus550516/ -http://www.kfi640.com/shared/mod_perl/looksmart/looksmart/eus1/eus53940/eus53960/eus54753/eus543189/eus550528/ -http://shn.webmd.com/roundtable_printing/774674 -http://www.zi.unizh.ch/software/unix/statmath/sas/sasdoc/lgref/z0205140.htm -http://www.hblb.org.uk/hblbweb.nsf/$Pages/NewsArchive1!OpenDocument&ExpandSection=16,12,3,13,5,6,9 -http://www.uni-duesseldorf.de/ftp/ftp/pf/share/fvwm-2.0.45/?S=A -http://members.tripod.com/~PhyrePhox/mcse/70-088.htm -http://extreme-dm.com/tracking/reports/dj/nph-ref1.cgi?tag=nimrood -http://opac.lib.ntnu.edu.tw/search*chi/++ftlist/bp20040397/-5,-1,0,B/frameset&F=bp20040402&1,1 -http://209.0.220.240/spec/txve.htm -http://209.0.220.240/spec/tyai.htm -http://ftp.up.pt/Linux/Linus/net-source/www/clients/netscape/?M=A -http://ftp.up.pt/Linux/Linus/net-source/www/clients/netscape/?D=A -http://www.jobvillage.com/channel/jobs/health_care/nursing/licensed_practical_nurse/b.9505.g.1766.html -http://www.zope.org/Members/stevea/CoadObjectModels/BackLinks/backlinks -http://www.mairie-montreuil93.fr/ville_pratique/environ/energie/mve/media/?D=A -http://member.shangdu.net/home2/chr/jishang/hongkong/inxg-6.html -http://www.wild-dog.com/activity/touring/idx/page_18_1.html -http://members.tripod.co.jp/susu/?M=A -http://www.dulux.co.uk/UKRETAIL:623356687:DFinity.1QJiP4jMLco -http://www.kordic.re.kr/~trend/Content326/agriculture04.html -http://www.kordic.re.kr/~trend/Content326/agriculture09.html -http://ftp.lip6.fr/pub12/OpenBSD/src/gnu/egcs/config/mh-aix43 -http://ftp.lip6.fr/pub12/OpenBSD/src/gnu/egcs/config/mh-elfalphapic -http://ftp.lip6.fr/pub12/OpenBSD/src/gnu/egcs/config/mt-x86pic -http://www.ecatsbridge.com/BiB/static/sims/bbljuly99/00000101758612773F1.htm -http://pub20.ezboard.com/faustralianslotcarreviewhoracing.showMessage?topicID=2.topic&index=47 -http://ring.omp.ad.jp/archives/NetBSD/packages/pkgsrc/games/exchess/pkg/DESCR -http://homepage.renren.com/sandybay/help.htm -http://no.egroups.com/post/oslosynth?act=reply&messageNum=634 -http://www.brio.de/BRIO.catalog/39fe2f940703266c273fd472aa7806a8/UserTemplate/2 -http://www.50megs.com/prettysenshi/captures/ep3/SMep3.html -http://www.thisislancashire.co.uk/lancashire/archive/1999/11/05/CHORNEWS5VQ.html -http://au.yahoo.com/Regional/U_S__States/California/Metropolitan_Areas/San_Francisco_Bay_Area/Entertainment_and_Arts/Restaurants/Coffee_and_Tea_Houses/ -http://www.niwl.se/WAIS/30002/30002360.htm -http://www.infoscape.com.cn:8178/gb/content/2000-08/16/content_6082.htm -http://link.fastpartner.com/do/session/600419/vsid/2870/tid/2870/cid/136966/mid/1060/rid/1926/chid/2870/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/mondosoft.php -http://www.canit.se/(c1,f3,ftp,generellt,irc,mail)/support/ -http://citeseer.nj.nec.com/cidcontext/3787443 -http://www.affiliate.hpstore.hp.co.uk/do/session/380878/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/entry.asp -http://www.usq.edu.au/unit-1997/fullspec/51129s3x.htm -http://worldres.lycos.com/script/gen_mr.asp?hotel_id=6354&n=1518 -http://www.members.aon.at/~kleindlp/neue_seite_4.htm -http://210.169.76.95/html/tai_0043/bat_1180.html -http://oneplace.adbureau.net/accipiter/adclick/site=ONEPLACE/area=INDEX/POSITION=FOOTER/AAMSZ=468x60/ACC_RANDOM=262411779164 -http://www.service911.com/mvu/step/0,2632,6+34+90+23506+13880_4,00.html -http://ftp.lip6.fr/pub11/NetBSD/NetBSD-current/src/usr.sbin/kvm_mkdb/Makefile -http://www.bemi-immobilien.de/Private-IB/Startseite/Startseite/Gemeinsam/versicherungen/unfall/Gemeinsam/immolink/Startseite/www.ferien-immobilien.de/ferien-ib/startseite/Gemeinsam/versicherungen/gebaeude/anforderungsformular.htm -http://wap.jamba.de/KNet/_KNet-BOC8j1-LFd-13bpy/showInfo-hilfe.de/node.0/cenv0b09a -http://wap.jamba.de/KNet/_KNet-BOC8j1-LFd-13bq0/browse.de/node.0/cde7f1uou -http://cnnews.sina.com/kwongzhou/china/2000/1026/2083022_2.html -http://www.msb.malmo.se/search*swe/dFlygplanskonstruktion/dflygplanskonstruktion/-5,-1,0,B/frameset&F=dflygolyckor&4,,6 -http://home.hanmir.com/~100sun/joo4.htm -http://www.szed.com/szsb/19990629/GB/default.htm -http://www.szed.com/szsb/19990629/GB/4-NPCLASS.HTM -http://www.szed.com/szsb/19990629/GB/7-NPCLASS.HTM -http://www2.kbank.no/Web/nlpublish.nsf/Published/ord_og_uttrykk!OpenDocument&ExpandSection=15,24,26,25 -http://movies.exit.de/lichtsammler/images/tunnel/gross/sw_kb/?D=A -http://www.arm.com/sitearchitek/support.ns4/html/cores_faq!OpenDocument&ExpandSection=5,34,38 -http://www.arm.com/sitearchitek/support.ns4/html/cores_faq!OpenDocument&ExpandSection=21,34,38 -http://www.arm.com/sitearchitek/support.ns4/html/cores_faq!OpenDocument&ExpandSection=31,34,38 -http://fi.egroups.com/login.cgi?login_target=%2Fmessage%2Fgamp%2F1734 -http://de.excite.de/katalog/katalog/9231 -http://www-win.rusf.ru/esli/rubr/books/es0500di.htm -http://www.jamba.de/KNet/_KNet-yjF8j1-8Gd-13cj6/browse.de/node.0/cde7f1uou -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/misc/lit/programs/misc/math/lit/athalie.html -http://ftp.fi.debian.org/debian/dists/Debian2.2r0/contrib/binary-powerpc/interpreters/?S=A -http://jupiter.u-3mrs.fr/~msc41www/releves/04350110.HTM -http://ocean.ntou.edu.tw/search*chi/dDigital+modulation/ddigital+modulation/7,-1,0,E/frameset&F=ddigital+techniques+signal+processing&4,,0 -http://pub20.ezboard.com/fcharmingtailsresourcetradeyoursportscardshere.unsubscribeUnregisteredToTopic?topicID=43.topic -http://www.kaos.dk/sexriddle/x/w/k/u/q/ -http://www.kaos.dk/sexriddle/x/w/k/u/t/ -http://216.205.158.3/smm/programs/CDG_Player/wwwboard/messages/27.html -http://216.205.158.3/smm/programs/CDG_Player/wwwboard/messages/60.html -http://fen.com/whatworks/review/edit/1,2560,1-9696-5539-0-45394,00.html -http://yp.gates96.com/8/74/30/30.html -http://yp.gates96.com/8/74/31/1.html -http://yp.gates96.com/8/74/32/12.html -http://yp.gates96.com/8/74/32/60.html -http://yp.gates96.com/8/74/32/92.html -http://yp.gates96.com/8/74/33/41.html -http://yp.gates96.com/8/74/33/55.html -http://yp.gates96.com/8/74/33/57.html -http://yp.gates96.com/8/74/33/95.html -http://yp.gates96.com/8/74/34/21.html -http://yp.gates96.com/8/74/34/23.html -http://yp.gates96.com/8/74/34/79.html -http://yp.gates96.com/8/74/35/3.html -http://yp.gates96.com/8/74/35/22.html -http://yp.gates96.com/8/74/35/79.html -http://yp.gates96.com/8/74/36/31.html -http://yp.gates96.com/8/74/36/84.html -http://yp.gates96.com/8/74/37/58.html -http://yp.gates96.com/8/74/37/77.html -http://yp.gates96.com/8/74/37/89.html -http://yp.gates96.com/8/74/37/97.html -http://yp.gates96.com/8/74/39/43.html -http://yp.gates96.com/8/74/39/63.html -http://yp.gates96.com/8/74/39/88.html -http://www9.hmv.co.uk:5555/do/session/1347828/vsid/199/tid/199/cid/1061396/mid/1020/rid/1052/chid/1029/parser/yes/imref/eqqLmwlGltt5tkeHjskKZlkKrhlK/url/http://www.hmv.co.uk/hmv/newmenu.html -http://www9.hmv.co.uk:5555/do/session/1347828/vsid/199/tid/199/cid/1061396/mid/1020/rid/1052/chid/1029/parser/yes/imref/eqqLmwlGltt5tkeHjskKZlkKrhlK/url/http://www.hmv.co.uk/hmv/departments/d80_sd0_pt0.html -http://gladstone.uoregon.edu/~sme28057/arch181-202/assign2/?M=A -http://cco.cisco.com/univercd/cc/td/doc/product/core/7206/7206ig/trble6ug.pdf -http://210.32.1.18/goldbook/humor/mh/c/changgu/1/028.htm -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=17,28,24,31,11 -http://www.spiral.at/Katalog/Artikel/7561032/ -http://www.crutchfield.com/cgi-bin/S-Ql7dbZlSZa2/viewcart.asp -http://www.fogdog.com/cedroID/ssd3040183327788/nav/products/winter_sports/1b/shell_pants/ -http://www.fogdog.com/cedroID/ssd3040183327788/nav/products/winter_sports/1j/oakley/ -http://www.fogdog.com/cedroID/ssd3040183327788/nav/products/winter_sports/1l/day_packs/ -http://www.thestateofcolorado.com/pglblock.html -http://www.staroriental.net/nav/soeg/ihf,adj,s0,259,Kristy+Yeung+Gung-Yu.html -http://pcmcia.sourceforge.org/cgi-bin/HyperNews/get/pcmcia/toshiba/38.html -http://sunsite.org.uk/public/public/packages/Dr-Fun/df9412/?N=D -http://nt.mortgage101.com/partner-scripts/1144.asp?p=mig&pw=600 -http://biblioteca.upv.es/bib/doc/doc_fisbd/17/87050//C/1828104/3////25/N/MLTPAI -http://130.80.29.3/content/houston/k-12/hanc/ -http://javatest.a-net.nl/exhibits/default.htm -http://javatest.a-net.nl/museum_info/job_opportunities.asp -http://books.hyperlink.co.uk/booklist/Alphabet_Workbook/Cheney/Martha/1565658396 -http://kobe.cool.ne.jp/orera/guestbook.html -http://ftp.eecs.umich.edu/pub/NetBSD/packages/1.4.1/vax/audio/ -http://ftp.eecs.umich.edu/pub/NetBSD/packages/1.4.1/vax/editors/ -http://ftp.eecs.umich.edu/pub/NetBSD/packages/1.4.1/vax/tk80/ -http://www.zdnet.de//news/artikel/1999/03/09001-wc.html -http://neptune.guestworld.com/gear/gateway.cfm?action=private&owner=sitonga7 -http://www.de.lycos.de/dir/Reisen_und_Regionen/L%E4nder_und_St%E4dte/Deutschland/Schleswig-Holstein/St%E4dte_und_Orte/St%E4dte_und_Orte_P_bis_S/ -http://www.mirror.edu.cn/res/sunsite/pub/academic/music/album-reviews/1995/9-September/?M=A -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=213&discrim=176,11,57 -http://europa.eu.int/abc/doc/off/bull/el/9705/x085.htm -http://europa.eu.int/abc/doc/off/bull/el/9705/x209.htm -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=15,0+17,0-3,0-9,0 -http://www.ferien-immobilien.de/baden-wuertemberg/stuttgart/Verkauf/Gemeinsam/MarketingStrategie/Ferien-IB/Startseite/Gemeinsam/Super-Zins-Konditionen/GmbH-Kauf-Verkauf-Insolvenz-konkurs/Startseite/indexbeginn.htm -http://www.ferien-immobilien.de/baden-wuertemberg/stuttgart/Verkauf/Gemeinsam/MarketingStrategie/Ferien-IB/Startseite/Gemeinsam/Super-Zins-Konditionen/Gemeinsam/impressum.htm -http://www.chaos.dk/sexriddle/s/e/x/v/i/a/w/ -http://pub4.ezboard.com/fscarletstreethorroritalianstyle.showAddReplyScreenFromWeb?topicID=15.topic -http://ftp.dti.ad.jp/pub/lang/CPAN/authors/id/P/PJ/PJF/ -http://www.highwired.net/Paper/EmailToFriend/1,2102,302-183023,00.html -http://ftpsearch.belnet.be/mirror3/ftp.kde.org/pub/kde/Incoming/Attic/old/1.1.2/apps/ide/?D=A -http://www.affiliate.hpstore.hp.co.uk/do/session/380877/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-creativeworld.com/creativeworld.asp?lang=f -http://expert.cc.purdue.edu/~steinfoc/assignment3/assig3.html -http://www.wyborcza.com/Ascii/Raporty/Filmowa/277rap.html -http://www.redhat.com/mirrors/LDP/LDP/LG/issue50/misc/pollman/?D=A -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=148&discrim=142,11,200 -http://www.marktplatz-hs.de/cgi-bin/ChioEditionShop.s/39fe2ee602379b7e273fd47540f806e1/Catalog -http://www.affiliate.hpstore.hp.co.uk/do/session/380836/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/SMARTTIPS/createbroch.asp -http://joy1.alpha-g.ne.jp/tree/user/a/amuro/2_index.shtml -http://time.188.net/movie/star/taiwan/2/pic/image36.htm -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=25,1,36,31,11 -http://bsd.sinica.edu.tw/cgi-bin/cvsweb.cgi/ports/audio/kdemultimedia11-i18n/Attic/pkg-comment?only_with_tag=RELEASE_2_2_7 -http://www.landfield.com/ftp/usenet/news.answers/bicycles-faq/?S=A -http://wap.jamba.de/KNet/_KNet-puF8j1-aGd-13clg/browse.de/node.0/cenv0b09a -http://www.empas.com/search/all.html?q=%C0%CC%B7%D3%B4%D9 -http://www.linux.com/networking/server/install/howto/website/developers/ -http://aecjobbank.com/texis/script/newjobs/+NwxBm6ev7I1wwwhmrmwxetiAw/jobdirectory.html -http://www.egroups.com/message/ijtihadmk/5 -http://www.egroups.com/message/ijtihadmk/11 -http://www.realize.com/am67bd81.htm,qt=e784fe2f=2a38a234-7-da6e2d-0-0-0-3-- -http://www.realize.com/p643c81.htm,qt=e784fe2f=2a38a234-7-da6e80-0-0-0-3-- -http://moneysaver.net/netcall/?almktng -http://www.agria.hu/bikersmeeting/archivum/talalkozo/foto/taj.cgi?15n -http://link.fastpartner.com/do/session/600401/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/company/ -http://198.103.152.100/search*frc/aDidsbury,+Howard+F.,+1924-/adidsbury+howard+f+1924/-5,-1,0,B/frameset&F=adidier+marcel&1,,0 -http://198.103.152.100/search*frc/aDidsbury,+Howard+F.,+1924-/adidsbury+howard+f+1924/-5,-1,0,B/frameset&F=adidier+michel&1,,0 -http://www.medoc-ias.u-psud.fr:81/synoptic/gif/001020/?D=A -http://shop.goto.com/compperiph/periph/cdrom/search/sidexside.jhtml?s=1&sort_up=LOW_PRICE -http://excite.de/wirtschaft/katalog/1356 -http://excite.de/wirtschaft/katalog/2631 -http://www.areteoutdoors.com/channel/earth/caving/b.89.g.473.html -http://www.areteoutdoors.com/channel/earth/caving/b.91.g.473.html -http://bo.ole.com/actualidad/articulo/html/act13873.htm -http://www.dulux.co.uk/UKRETAIL:446033260:DFinity.1QJiP4jMomdoclfieh -http://www.linux.com/networking/network/release/sap/hardware/firewall/ -http://genforum.genealogy.com/cgi-genforum/forums/hendrix.cgi?430 -http://www.chaos.dk/sexriddle/s/p/w/c/ -http://198.103.152.100/search*frc/tCanada+in+the+21st+century.+II,+Resources+and+technology/tcanada+in+the+21st+century+ii+resources+and+technology/-5,-1,0,B/frameset&F=tcanada+in+the+21st+century+no+01&1,1 -http://books.hyperlink.co.uk/bookinfo/Sunk_Costs_and_Market_Structure/Sutton/John/0262193051 -http://members.tripod.com/theshavedbeaver/site2/s2laststand.html -http://members.tripod.com/theshavedbeaver/site2/s2s1ep21.html -http://www.ytmag.com/cgi-bin/redirect.cgi/602479760 -http://www18.freeweb.ne.jp/school/syodou/you005.htm -http://www.fogdog.com/cedroID/ssd3040183334500/nav/products/featured_brands/2h/replica_jerseys/ -http://www.fogdog.com/cedroID/ssd3040183334500/nav/products/featured_brands/2h/replica_jerseys/4.html -http://www.fogdog.com/cedroID/ssd3040183334500/crs/nvCZ/wld/fogdog_sports/champion/fan_memorabilia/apparel/vlade_divac_replica_jersey.html -http://www.jobvillage.com/channel/jobs/travel/travel_guide/b.4897.g.5299.html -http://www.bcbsal.org/Provider_Dir/pharmacy/state/Oregon/HILLSBORO/index_29061.html -http://www.maas.ccr.it/cgi-win/hiweb.exe/a17/d2066/b77,c,4d,469,469,1b65,1b65,,51,811,4d,51,811,, -http://www.loisirs.ch/bbewxu/2/wofyff.html -http://mitglied.tripod.de/Jag3/jag3b.htm -http://linuxberg.starhub.net.sg/x11html/preview/9016.html -http://linuxberg.starhub.net.sg/x11html/preview/9062.html -http://linuxberg.starhub.net.sg/x11html/preview/9103.html -http://linuxberg.starhub.net.sg/x11html/preview/9820.html -http://linuxberg.starhub.net.sg/x11html/preview/10370.html -http://linuxberg.starhub.net.sg/x11html/preview/9965.html -http://linuxberg.starhub.net.sg/x11html/preview/10117.html -http://linuxberg.starhub.net.sg/x11html/preview/10129.html -http://linuxberg.starhub.net.sg/x11html/preview/10152.html -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=150&discrim=251,11,3 -http://totalsports.aol.com/stats/bbo/int/20000624/tol.at.swb.game.html -http://excite.de/gesundheit/katalog/41575 -http://bbs.csie.ntu.edu.tw/txt/Emprisenovel/ebooks/other/hsiao_yi/jqhy/007.txt -http://www.memorialcup99.com/HockeyStLouisArchive/nov17_stl.html -http://www.letsmusic.com/directory/theme/genre_each/1,1137,Z-ã„´-124-2-2,00.asp -http://rainforest.parentsplace.com/dialog/get/bedwetting/29/2.html?outline=-1 -http://www.volny.cz/j_medkova/p05.html -http://www.maas.ccr.it/cgi-win/hiweb.exe/a17/d2072/b77,c,4d,51,51,815,815,818,7d9,,51,7d9,818,, -http://collection.nlc-bnc.ca/100/200/301/ccmd-ccg/ccmd_report-e/rpt1e.pdf -http://cn.egroups.com/post/export-import-indonesia?act=forward&messageNum=595 -http://www.secinfo.com/$/SEC/Filing.asp?T=1zBgb.6t_9yc -http://www.realize.com/am81.htm,qt=4619dc8c=279e650e-c-16fba7d-1-0-0-0-- -http://amadeus.siba.fi/doc/php3-ldap/html/features.html -http://amadeus.siba.fi/doc/php3-ldap/html/function.ada-fetchrow.html -http://amadeus.siba.fi/doc/php3-ldap/html/function.array-pop.html -http://amadeus.siba.fi/doc/php3-ldap/html/function.current.html -http://amadeus.siba.fi/doc/php3-ldap/html/function.ftp-size.html -http://amadeus.siba.fi/doc/php3-ldap/html/function.getmyinode.html -http://amadeus.siba.fi/doc/php3-ldap/html/function.gmdate.html -http://amadeus.siba.fi/doc/php3-ldap/html/function.hw-getusername.html -http://amadeus.siba.fi/doc/php3-ldap/html/function.icap-list-alarms.html -http://amadeus.siba.fi/doc/php3-ldap/html/function.ifx-free-char.html -http://amadeus.siba.fi/doc/php3-ldap/html/function.imap-reopen.html -http://amadeus.siba.fi/doc/php3-ldap/html/function.is-link.html -http://amadeus.siba.fi/doc/php3-ldap/html/function.is-string.html -http://amadeus.siba.fi/doc/php3-ldap/html/function.mcal-event-set-recur-monthly-wday.html -http://amadeus.siba.fi/doc/php3-ldap/html/function.mhash-get-block-size.html -http://wwws.br-online.de/geld/boerse/980420/110001.html -http://family.go.com/Categories/reviews/Features/family_2000_01/dony/dony0100craftapple/ -http://family.go.com/Categories/reviews/Features/family_2000_01/dony/dony0100craftcactus/ -http://family.go.com/Categories/reviews/Features/family_2000_01/dony/dony0100petvetticks/ -http://www.maastrek.de/maas/d49da6854db9e797f212/1/0/1 -http://astro1.chungnam.ac.kr/NetBBS/Bbs.dll/astromov/lst/qqadm/1/zka/B2-kB2Bl/qqo/004D -http://channel.cnnsi.com/basketball/college/2000/ncaa_tourney/west/news/2000/03/25/keady_ap/lg_keady_ap.html -http://incmagazine.com/articles/details/0,3532,AGD5_ART13806_CNT56_GDE30,00.html -http://incmagazine.com/research/details/0,3470,AGD5_CNT49_GDE30_RSC16754,00.html -http://gatekeeper.dec.com/pub/linux/lorax/i386/misc/src/anaconda/balkan/CVS/ -http://adex3.flycast.com/server/socket/127.0.0.1:2800/click/OnlineCitiesSM/OnlineCitiesInteractiveCityGuides/bd720350329 -http://www.proviser.co.uk/regional/towns/alford/street_maps/alpha_b.html -http://www.fogdog.com/cedroID/ssd3040183255203/ -http://www.columbia.edu/~wl158/OCD.htm -http://www.irishnews.com/Archive2000/29052000/international.html -http://www.irishnews.com/Archive2000/29052000/sportinter.html -http://38scbshop.freeyellow.com/download.html -http://news.dinf.ne.jp/news/fj/rec/animation/msg01441.html -http://datastore.tucows.com/winnt/adnload/5372_28388.html -http://pages.infinit.net/limal/visage/chap17.htm -http://www.hotelboulevard.com/fr/paris/standard/htmlc258073cfbe254c1722c86e0aec5f5da/sessionLang/ANG/search.html -http://www.icopyright.com/1.1642.213678 -http://wiem.onet.pl/wiem/012aa2.html -http://www.secinfo.com/dRRsz.9e.htm -http://lily.nju.edu.cn/literature/cangshu/wx/wra/ysz/16.htm -http://home.swipnet.se/~w-15978/ -http://smb.slac.stanford.edu/cgi-bin/nph-proxy.cgi/000/http/www.stanford.edu/dept/EIS/moral_responsibility.htm -http://smb.slac.stanford.edu/cgi-bin/nph-proxy.cgi/000/http/www.stanford.edu/dept/EIS/hardin_review.htm -http://www.uni-duesseldorf.de/ftp/pf/share/flex-2.5.2/man/man1/?S=A -http://mindit.netmind.com/proxy/http://www.ninds.nih.gov/health_and_medical/pubs/chronic_pain_htr.htm -http://mindit.netmind.com/proxy/http://www.smalltime.com/notvictims/cutting.html -http://www.peopledaily.co.jp/zdxw/7/19991231/19991231001085.html -http://pokemonothin.8m.com/cgi-bin/c/736/64/dXNlcmJhbm5lcg==/gn/4638/ -http://www.chaos.dk/sexriddle/s/e/x/u/y/n/d/ -http://www.bestinfo.net.cn/bsti_kjhy/kyys/bjkyys/arim/technical.html -http://www.leicos.de/webguides/fun_lifestyle/unterhaltung/43101.html -http://209.207.239.212/bkindex/c1047/f1423.html -http://cylis.lib.cycu.edu.tw/search*chi/tEncyclopaedia+of+mathematical+sciences+&%2359%3B+v.+65/tencyclopaedia+of+mathematical+sciences+v+++65/-17,-1,0,B/frameset&F=tencyclopaedia+of+mathematical+sciences+v+++48&1,1 -http://www.sanxia.net/beauty/Nanako/313.htm -http://www.sanxia.net/beauty/Nanako/323.htm -http://mirrortucows.technet.it/winme/adnload/138469_29790.html -http://www.fogdog.com/cedroID/ssd3040183321970/nav/stores/walking/ -http://www.fogdog.com/cedroID/ssd3040183321970/customer_service/employment.html -http://mirror.pku.edu.cn/www.berkeley.edu/ls.berkeley.edu/lscr/services/backups/UCBackup.html -http://retailer.gocollect.com/do/session/1912804/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/postcards/index.asp -http://www.uni-duesseldorf.de/ftp/pf/share/ddd-1.4d/man/man1/?M=A -http://www.uni-duesseldorf.de/ftp/pf/share/ddd-1.4d/man/man1/?S=A -http://javatest.a-net.nl/servlet/pedit.Main/http://www.zdnet.com/special/stories/wireless/0,10676,2557092-8,00.html -http://ftp.sunet.se/pub/os/FreeBSD/development/FreeBSD-CVS/ports/archivers/makeself/ -http://www.jamba.nl/KNet/_KNet-QYL8j1-2D4-pw4k/browse.nl/node.0/cde7f1uou -http://www.discoveromaha.com/shared/health/adam/ency/imagepage/1090.000233.html -http://home.dqt.com.cn/cgi-bin/push/setluntan?luntan=64 -http://sjsulib1.sjsu.edu:81/search/dbusiness+periodicals/-5,-1,1,B/frameset&dbusiness+vocational+guidance&2,,3 -http://www-d0.fnal.gov/d0dist/dist/releases/psim01.01.00/cft_tuple/VERSION -http://pub3.ezboard.com/fmcdonaldscollectorsclubauctions.subscribeUnregisteredToTopic?topicID=136.topic -http://shopping.lycos.co.kr/cgi-bin/LCWB.cgi/957424027/957522583/Catalog/1301/001 -http://www.cs.kuleuven.ac.be/~java/docs/jdk1.3/docs/api/java/sql/class-use/DriverPropertyInfo.html -http://www.buybuddy.com/sleuth/27/1/1060701/505427/ -http://web4.sportsline.com/u/football/nfl/players/splits/4451_split.htm -http://mirror.cc.utsunomiya-u.ac.jp/mirror/FreeBSD/ports/alpha/packages-5-current/japanese/?M=A -http://no.egroups.com/login.cgi?login_target=%2Fgroup%2Ftkd-full -http://www.bemi-immobilien.de/Ferien-IB/Startseite/Gemeinsam/MarketingStrategie/Gemeinsam/immolink/Gemeinsam/3d-service/Startseite/www.ferien-immobilien.de/ferien-ib/startseite/Gemeinsam/MarketingStrategie/Strategie.htm -http://www.bemi-immobilien.de/Ferien-IB/Startseite/Gemeinsam/MarketingStrategie/Gemeinsam/immolink/Gemeinsam/3d-service/Startseite/www.ferien-immobilien.de/ferien-ib/startseite/Gemeinsam/versicherungen/gebaeude/deckungsumfang.htm -http://www.3wposter.com/czaja/czj2002.htm -http://pub19.ezboard.com/fallamericanbaseballleagueplayersneeded.showMessage?topicID=6.topic -http://ftp.uni-mannheim.de/info/OReilly/nutshell/practcpp/disk/doit/?N=D -http://www02.geocities.co.jp/HeartLand-Kaede/4970/index2.htm -http://www.selbstmachen.de/shops/pop/infotext/8008.htm -http://dennou-t.ms.u-tokyo.ac.jp/arch/cc-env/Linux/debian-jp/dists/unstable/contrib-jp/binary-alpha/doc/?D=A -http://genforum.genealogy.com/cgi-genforum/forums/flynn.cgi?1004 -http://www.iwon.com/home/movies/movies_filmography_page/0,13178,Marguerite+Hickey,00.html -http://cometweb01.comet.co.uk/do!tid=20&rtid=2&vsid=700&session=132028&mid=1000&rid=1060&cid=37030&chid=1713&url=eqqLmwlGltt5tkZHljbLqkZHlkrHhlZHdfjKYfkLlkZ5ljjLboZLbplG5ubLZDXLZolLl3l5jbqLlci5XqVLkXsLkao4tloHbmlLoq5 -http://www.kfi640.com/shared/mod_perl/looksmart/looksmart/eus1/eus65300/eus65303/eus77824/eus541028/eus168664/ -http://user.chollian.net/~iipuni/pds1/?M=A -http://tucows.ciaoweb.it/winnt/adnload/73935_29937.html -http://home2.keyciti.com/x2001/ -http://www.amateurplatinum.com/teenagerclique/fagbodyshots/elbow-greaseac/plus-sizemen/butt-fuckpartner/actionextreme/hitting-itendurance.html -http://oss.sgi.com/cgi-bin/cvsweb.cgi/linux-2.3-4/linux/Documentation/filesystems/vfs.txt?only_with_tag=LINUX-2_3_99_pre4 -http://oss.sgi.com/cgi-bin/cvsweb.cgi/linux-2.3-4/linux/Documentation/filesystems/vfs.txt?only_with_tag=LINUX-2_3_17 -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=3,0+18,0-0,0-3,0 -http://www.skaninforma.no/nord-troendelag/leksvik-h.htm -http://194.128.65.4/pa/cm199798/cmwib/wb971115/nil.htm -http://www.on.fuchu.or.jp/~oimatudo/englishmisomanzyu.htm -http://map.ipc.co.jp/asp/onmap/connect/g-2/a-719/ -http://cherokee1.edgate.com/goucheres/ed_current.html -http://www.online.kokusai.co.jp/Service/V0043594/wrd/G200/service/service.html -http://www.arm.com/sitearchitek/support.ns4/html/cores_faq!OpenDocument&ExpandSection=21,16,7 -http://binary.tucows.com/winnt/adnload/70807_30160.html -http://binary.tucows.com/winnt/adnload/1422_28846.html -http://genforum.genealogy.com/cgi-genforum/forums/theroux.cgi?69 -http://rex.skyline.net/navigate.cgi?news,ice,women,resources,living -http://umweb2.unitedmedia.com/creators/rugrats/archive/rugrats-20001015.html -http://retailer.gocollect.com/do/session/1912824/vsid/2089/tid/2089/cid/621609/mid/1540/rid/1520/chid/2083/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLlmo5larLZqVLafpLmiXLvlmHolaLrZqLpl4/url/http://www.gocollect.com/product_display/products/product_lines.asp -http://retailer.gocollect.com/do/session/1912824/vsid/2089/tid/2089/cid/621609/mid/1540/rid/1520/chid/2083/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLlmo5larLZqVLafpLmiXLvlmHolaLrZqLpl4/url/http://www.gocollect.com/clubhouse/suggestions.asp -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=146&discrim=146,7,19 -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=146&discrim=146,7,231 -http://login.hq.cricinfo.org/link_to_database/ARCHIVE/1996-97/OD_TOURNEYS/SINWS/SINWS-MATCHES/SL_ZIM_SINWS_ODI5_03SEP1996_DAILY_MR.html -http://preview.egroups.com/group/God_Calling -http://www.fogdog.com/cedroID/ssd3040183340945/nav/products/outlet/1b/sunglasses_optics/ -http://www.fogdog.com/cedroID/ssd3040183340945/nav/products/outlet/1c/dc/ -http://www.fogdog.com/cedroID/ssd3040183340945/customer_service/contact_us.html -http://link.fastpartner.com/do/session/600424/vsid/2870/tid/2870/cid/136966/mid/1060/rid/1926/chid/2870/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/itjobbank.php -http://link.fastpartner.com/do/session/600424/vsid/2870/tid/2870/cid/136966/mid/1060/rid/1926/chid/2870/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/index.php -http://pub2.ezboard.com/fteamnexgenforumhelpnexgennexencodestudio.unsubscribeUnregisteredToTopic?topicID=29.topic -http://www02.geocities.co.jp/SiliconValley-PaloAlto/1763/event/ni2k/ni2k.htm -http://yp.gates96.com/7/89/60/35.html -http://yp.gates96.com/7/89/61/4.html -http://yp.gates96.com/7/89/61/38.html -http://yp.gates96.com/7/89/62/80.html -http://yp.gates96.com/7/89/63/8.html -http://yp.gates96.com/7/89/63/16.html -http://yp.gates96.com/7/89/65/10.html -http://yp.gates96.com/7/89/65/42.html -http://yp.gates96.com/7/89/65/54.html -http://yp.gates96.com/7/89/65/88.html -http://yp.gates96.com/7/89/65/98.html -http://yp.gates96.com/7/89/66/26.html -http://yp.gates96.com/7/89/66/55.html -http://yp.gates96.com/7/89/67/28.html -http://yp.gates96.com/7/89/68/67.html -http://yp.gates96.com/7/89/69/63.html -http://yp.gates96.com/7/89/69/73.html -http://www.mediko.de/news/alt.support.eating-disord/19944.html -http://www.mediko.de/news/alt.support.eating-disord/19975.html -http://www13.cplaza.ne.jp/musicnavi/i-mode/id/KICS113.html -http://home.beseen.com/community/alienpilot/AbductionTheory.html -http://www.hausbau-finder.de/festpreis/anbieter/A11/A11_05_eg.htm -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=237&discrim=10,15,200 -http://ftp.eecs.umich.edu/pub/NetBSD/packages/1.3.3/mac68k/kde/ -http://www.leg.wa.gov/pub/rcw%20-%20text/title_49/chapter_028/rcw_49_28_065.txt -http://fi.egroups.com/login.cgi?login_target=%2Fmessages%2Fdfbl%2F77 -http://ring.omp.ad.jp/pub/NetBSD/NetBSD-current/src/sys/arch/sgimips/dev/?D=A -http://retailer.gocollect.com/do/session/1912781/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/postcards/index.asp -http://providenet.tucows.com/win2k/adnload/136128_47180.html -http://providenet.tucows.com/win2k/adnload/38527_29571.html -http://no.egroups.com/dir/1/16/476/32069/32291/104313/293356 -http://www.playease.com/et/beauty/img/lingmuyamei/lmam043.htm -http://202.99.23.201/gb/special/node_484.htm -http://202.99.23.201/gb/special/node_518.htm -http://202.99.23.201/gb/special/node_531.htm -http://ring.jec.ad.jp/archives/NetBSD/NetBSD-current/pkgsrc/fonts/acroread-chsfont/README.html -http://www.gaiax.com/~dengeki/lineb.html?haru_da_pump -http://cafe2.daum.net/Cafe-bin/Bbs.cgi/naturalproductspds/qry/zka/B2-kB27p/qqatt/^ -http://cafe2.daum.net/Cafe-bin/Bbs.cgi/naturalproductspds/qry/zka/B2-kB23t/qqatt/^ -http://cafe2.daum.net/Cafe-bin/Bbs.cgi/naturalproductspds/qry/zka/B2-kB23r/qqatt/^ -http://my.egroups.com/group/uk-mac-dev -http://www.f20.parsimony.net/forum35990/archiv.htm -http://findmail.com/group/Costumers -http://variety.studiostore.com/browse/PEOPLE/b.FAVORITES%20PEOPLE/s.ZaC1r6Q6 -http://www.chinawolf.com/~warson/japan/chichuan/cat/jiangzuo/020.htm -http://www.branchen-vermittler.de/Branchen/Mecklenburg/Mecklenburg_Region_3/Neustrelitz/kopf_neustrelitz.html -http://www.xmission.com/(art,ftp,geek,music,music,caffiene,art,toys,dots,edge,misc,shopping,ftp,places,privacy,geek,cuseeme,apocalypse,people,stuffiuse,places,privacy,stuffiuse)/~bill/links.html -http://www.cs.helsinki.fi/linux/linux-kernel/Year-1999/1999-49/1283.html -http://www.ecotec.co.jp/view/arc/f/free/33/umcotk/zxlqox.html -http://www.ecotec.co.jp/view/arc/f/free/33/tgiotk/uftfwm.html -http://www.ecotec.co.jp/view/arc/f/free/33/purotk/qxxotk.html -http://www.ecotec.co.jp/view/arc/f/free/33/purotk/sewotk.html -http://www.ecotec.co.jp/view/arc/f/free/33/purotk/sjkfwm.html -http://www.ecotec.co.jp/view/arc/f/free/33/hazfwm/llhetk.html -http://www.ecotec.co.jp/view/arc/f/free/33/bvtctk/eptrik.html -http://www.ecotec.co.jp/view/arc/f/free/33/rvkptk/syurzz.html -http://library.cuhk.edu.hk/search*chi/a��頦��哨蕭嚙賢��鞈�嚙è¸ï¿½ï¿½ï¿½+1934-/a{214b33}{213021}{214451}+1934/-5,-1,0,B/frameset&F=a{214b33}{213021}{213c63}&6,,7 -http://mitglied.tripod.de/~haubentaucher/bilder.htm -http://amc.hollywood.com/maltin/v/valleyofthekings-1954.htm -http://amc.hollywood.com/maltin/v/vannuysblvd-1979.htm -http://amc.hollywood.com/maltin/v/venicevenice-1992.htm -http://amc.hollywood.com/maltin/v/vicesquad-1931.htm -http://amc.hollywood.com/maltin/v/violette-1978.htm -http://amc.hollywood.com/maltin/v/voiceofthewhistler-1945.htm -http://amc.hollywood.com/maltin/v/vulturethe-1967.htm -http://members.tripod.co.jp/hatahata/hikoki/?D=A -http://kernel2.adver.com.tw/Counter/log/kernel2.adver.com.tw/SaveCounter/2000-10-23/07/972255822718.txt -http://www.mapion.co.jp/custom/AOL/admi/23/23105/matsubaracho/5chome/index-43.html -http://search.chollian.net/cgi-bin/filter.cgi?cid=1109&g=11 -http://search.chollian.net/cgi-bin/filter.cgi?cid=1109&p=5 -http://www.linux.com/networking/network/new/website/applications/business/ -http://www.fogdog.com/cedroID/ssd3040183313598/nav/products/w_golf/1s/ball_retrievers/ -http://www.fogdog.com/cedroID/ssd3040183313598/nav/products/w_golf/1t/biographical_books/ -http://rammstein.sonicnet.com/artists/news/1090.jhtml -http://rammstein.sonicnet.com/allmusic/ai_bio.jhtml?ai_id=1090 -http://www.ycwb.com.cn/gb/2000/08/18/ycwb/gnxw/7.html -http://www.vorlesungen.uni-osnabrueck.de/informatik/c98/code/19/?D=A -http://kernel2.adver.com.tw/Counter/log/kernel2.adver.com.tw/SaveCounter/2000-10-23/11/972270515716.txt -http://www.affiliate.hpstore.hp.co.uk/do/session/380869/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/entry1.asp -http://uk.biz.yahoo.com/mutual_funds/micropal/lf/fund/008776/properf.html -http://troy.lib.sfu.ca/search/aasociacion+argentina+de+ciencias+naturales/aasociacion+argentina+de+ciencias+naturales/-5,-1,0,E/frameset&F=aasociacion+argentina+de+ciencias+naturales&1,,0 -http://uk.dir.yahoo.com/Regional/U_S__States/Virginia/Metropolitan_Areas/Charlottesville_Metro/Travel_and_Transportation/Accommodation/Caravan_Parks_and_Camp_Sites/ -http://uk.dir.yahoo.com/Regional/U_S__States/Virginia/Metropolitan_Areas/Charlottesville_Metro/Travel_and_Transportation/Accommodation/Hotels/ -http://library.cwu.edu/search/cQA76.73.A35+T75/cqa+++76.73+a35+t75/-5,-1,0,B/marc&F=cqa+++76.73+a8+j33+1985&1,1, -http://www.tages-anzeiger.ch/sport/nagano/0902/olymp_art4.htm -http://finance.sina.com.cn/globe/globe/2000-03-16/23725.html -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=9,3-9,0+0,1-0,3 -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=9,3-9,0+0,1-9,3 -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=9,3-9,0+0,1-19,0 -http://temps-libre.promovacances.net/D02/BH/BDANE/voyagealacarte.htm -http://sunsite.org.uk/public/computing/networks/internet/ietf/98aug/imapext-attendees-98aug.txt -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=124&discrim=221,178 -http://cpan.nettuno.it/authors/Ilya_Zakharevich/modules/FreezeThaw-0.41.readme -http://cpan.nettuno.it/authors/Ilya_Zakharevich/modules/Math-Pari-2.001700.readme -http://ricoh.co.jp/SHOGI/emate/tanigawa/tume0069a.html -http://troy.lib.sfu.ca/search/dlatin+america+periodicals/dlatin+america+periodicals/-5,-1,0,B/marc&F=dlatin+america+pest+control+industry&1,1, -http://moviestore.zap2it.com/browse/MOVIES/COLLECTI/s.w2bwHPkr -http://moviestore.zap2it.com/browse/MOVIES/BUNDLE/s.w2bwHPkr -http://moviestore.zap2it.com/browse/MOVIES/BOWL/s.w2bwHPkr -http://moviestore.zap2it.com/browse/MOVIES/JEWELRY/s.w2bwHPkr -http://moviestore.zap2it.com/browse/MOVIES/COMIC/s.w2bwHPkr -http://www9.hmv.co.uk:5555/do/session/1347801/vsid/199/tid/199/cid/1061396/mid/1020/rid/1052/chid/1029/parser/yes/imref/eqqLmwlGltt5tkeHjskKZlkKrhlK/url/http://www.hmv.co.uk/hmv/Top_Navigation_Bar/top_banner.html -http://www3.adobe.com/type/browser/F/P_103/F_FRAK-70005000.html -http://ftp.netc.pt/pub/idgames/levels/doom2/deathmatch/j-l/kewl.txt -http://ftp.netc.pt/pub/idgames/levels/doom2/deathmatch/j-l/ledges-z.txt -http://park.org:8888/Japan/CSK/hyakki/zukan/turezure/ue/c_tirizuka.html -http://pub4.ezboard.com/fscarletstreetfilmmusic.unsubscribeUnregisteredToTopic?topicID=54.topic -http://tucows.niagara.com/win2k/adnload/37364_29149.html -http://wap.jamba.de/KNet/_KNet-JGG8j1-eGd-13cre/showInfo-special1.de/node.0/cde7f1uou -http://www.personalmd.com/news/n0706062122.shtml -http://ds.dial.pipex.com/tmc/ConfPresentations/s2000/NetworkingJ/msconfig.htm -http://calcul.si.uji.es/Programes/SAS/proc/z0325264.htm -http://www.kaos.dk/sexriddle/x/m/k/i/i/ -http://ring.toyama-ix.net/archives/lang/perl/CPAN/clpa/1998-08/?N=D -http://ring.toyama-ix.net/archives/lang/perl/CPAN/clpa/1998-08/?S=A -http://www.spiral.at/Katalog/Artikel/0879070/ -http://homepage1.nifty.com/nao~nao/pages/profile.html -http://www.ferien-immobilien.de/friesland/verkauf/Gemeinsam/Inserieren/Allgemeine-IB/3d-service/Allgemeine-IB/Startseite/ -http://www.ferien-immobilien.de/friesland/verkauf/Gemeinsam/Inserieren/Allgemeine-IB/3d-service/Gemeinsam/erreichenPartner/email3d.htm -http://www.thestateofcolorado.com/m1jerepair.html -http://www.legis.state.pa.us/WU01/LI/BI/TI/1989/0/MNTENNIS.HTM -http://www.legis.state.pa.us/WU01/LI/BI/TI/1989/0/MNTRASH.HTM -http://www.shop4magazines.com/pg004752.htm -http://www.shop4magazines.com/pg005070.htm -http://www.shop4magazines.com/pg005084.htm -http://fi.egroups.com/login.cgi?login_target=%2Fmessage%2Fsocalscan%2F5293 -http://www.incestpornstories.com/hot-hardcore-fuckingbanging/bootsfeet-/hitting-itsmacking/{hardcorelink} -http://www.columbia.edu/~mkn12/Nominees.html -http://www.generation-formation.fr/pdetail.htm---o21zAo06Rxo0Ol9A074fo6s0Md6jIHeNHhIeOkn2ApvFFo6s5dfexiWo2W81N3OsPeaR2VeuzlEdRsR3djaPfdNjfco41qrfP6sWd6wuCoz4ZteOgKHekLVSePl8vNhiWhAhcgNAPfVbdsNhJl.htm -http://tiscover.at/1Root/Kontinent/6/Staat/7/Bundesland/20/Ort/212/Sonstige_Sportstaette/276591/Bericht/berw...1.html -http://fi.egroups.com/message/meterreader/207?source=1 -http://polygraph.ircache.net:8181/services/design/http_-2www.arthritis.org/http_-2www.alameda-vcf.org/http_-2www.microsoft.com/ie/ie.htm -http://www.fortunecity.com/lavender/deathrace/251/billy.html -http://ftpsearch.belnet.be/packages/CPAN/modules/by-module/AppleII/?N=D -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=7,34,29,16,25 -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=21,34,29,16,25 -http://www.ftp.uni-erlangen.de/pub/unix/BSD/FreeBSD/FreeBSD-current/ports/irc/tirc/ -http://retailer.gocollect.com/do/session/1912840/vsid/1696/tid/1696/cid/604361/mid/1540/rid/1420/chid/1725/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLlmo5larLZqVLafpLmiXLvlmHolaLrZqLpl4/url/http://www.gocollect.com/company_info/about.asp -http://retailer.gocollect.com/do/session/1912840/vsid/1696/tid/1696/cid/604361/mid/1540/rid/1420/chid/1725/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLlmo5larLZqVLafpLmiXLvlmHolaLrZqLpl4/url/http://www.gocollect.com/company_info/terms_and_conditions.asp -http://businessrecorder.com/story/S0024/S2401/S2401113.htm -http://arabia.com/article/0,1690,Sports|20732,00.html -http://www.worldmedicus.com/servlet/Controller/$7006041629a50000.sj_viewa/ -http://myhome.naver.com/chocobini/company.html -http://builder.hw.net/frmMessageFront/1,1079,'1~21~0~8~1~2348~9590',00.html -http://pub1.ezboard.com/fcrossstitchcorner504212000shepherdsbushretreat.showAddReplyScreenFromWeb?topicID=48.topic&index=5 -http://www.parisnights.de/fanfiction/archive/authors/andrews/stories/bright.htm -http://198.103.152.100/search*frc/cCA1+MPR+NS51+98Y25/cca1+mpr+ns51+98y25/7,-1,0,E/2browse -http://www.kfi640.com/shared/mod_perl/looksmart/looksmart/eus1/eus51605/eus147927/eus269761/eus269920/eus918452/ -http://www.kfi640.com/shared/mod_perl/looksmart/looksmart/eus1/eus51605/eus147927/eus269761/eus269920/eus918493/ -http://www.computing.net/cgi-bin/report.pl/windows95/wwwboard/forum/3119.html|21 -http://www.kiarchive.ru:8093/pub/misc/books/Camelot/Vasilyev/Forgotten_Road/ -http://yp.gates96.com/4/9/50/30.html -http://yp.gates96.com/4/9/51/1.html -http://yp.gates96.com/4/9/51/88.html -http://yp.gates96.com/4/9/51/92.html -http://yp.gates96.com/4/9/52/3.html -http://yp.gates96.com/4/9/52/53.html -http://yp.gates96.com/4/9/52/67.html -http://yp.gates96.com/4/9/53/25.html -http://yp.gates96.com/4/9/53/50.html -http://yp.gates96.com/4/9/53/96.html -http://yp.gates96.com/4/9/54/40.html -http://yp.gates96.com/4/9/54/57.html -http://yp.gates96.com/4/9/54/77.html -http://yp.gates96.com/4/9/55/57.html -http://yp.gates96.com/4/9/55/71.html -http://yp.gates96.com/4/9/56/1.html -http://yp.gates96.com/4/9/56/98.html -http://yp.gates96.com/4/9/57/6.html -http://yp.gates96.com/4/9/57/90.html -http://yp.gates96.com/4/9/58/91.html -http://yp.gates96.com/4/9/58/96.html -http://yp.gates96.com/4/9/59/29.html -http://yp.gates96.com/4/9/59/33.html -http://yp.gates96.com/4/9/59/84.html -http://yp.gates96.com/4/9/59/97.html -http://mayu.sourceforge.net/cgi-bin/nph-ml.cgi/000/http/www.geocrawler.com/archives/3/151/1997/5/0/900308/ -http://www2.odn.ne.jp/~cao20970/affair/oh/ha-342 -http://www2.odn.ne.jp/~cao20970/affair/oh/ha-346 -http://wap.jamba.de/KNet/_KNet-lvH8j1-nGd-13d1j/browse.de/node.0/cdzqggtyb -http://www.danielwebster.org//hallofusa/thestampact/HENDRICKFISHER.COM//thestampact/ -http://news.cn.tom.com/maya/cnnav/01/item/2000_09/309490.shtml -http://polygraph.ircache.net:8181/services/design/http_-2www.paducahrotary.org/pbcmap.htm -http://polygraph.ircache.net:8181/services/design/http_-2www.paducahrotary.org/mainpage.htm -http://www.debian.org.cn/Bugs/db/23/23547.html -http://www.debian.org.cn/Bugs/db/54/54172.html -http://www.adetti.iscte.pt/ADETTI/Security/HowTo/Java/jdk1.2.1/docs/guide/beans/spec/beancontext.fm7.html -http://www.users.qwest.net/~campputz/page413.htm -http://flybird.soyou.edu.cn/item/2000-07-31/164671.html -http://www.cognigen.net/corporate/trainers.cgi?full-timer -http://www.babyheirlooms.com/catalog/htmlos.cat/041143.1.1156359481 -http://ramdam.com/art/k/katerine.htm -http://ramdam.com/art/k/krapulax.htm -http://aleph.tau.ac.il:4501/ALEPH/eng/ATA/AAM/AAM/SET-MAIL///1249009 -http://online.linux.tucows.com/conhtml/adnload/8973_2294.html -http://www.arrakis.es/~lady_cel/frcontenf.htm -http://online.linux.tucows.com/conhtml/adnload/39034_1349.html -http://online.linux.tucows.com/conhtml/adnload/51651_2248.html -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=23,0+14,0-13,0-13,0 -http://www.ferien-immobilien.de/Westerwald/verkauf/GmbH-Kauf-Verkauf-Insolvenz-konkurs/Startseite/Gemeinsam/Inserieren/Private-IB/Gemeinsam/suche.htm -http://www.linux.com/networking/network/it/alternative/developers/Apple/ -http://www.sanxia.net/beauty/Nanako/418.htm -http://www-usa8.cricket.org/link_to_database/ARCHIVE/1999-2000/OTHERS+ICC/NORTHANTS_IN_WI/ARTICLES/ -http://gds.cc.va.us:8888/Mcn%3dMELISSA%20BACK,%20ou%3dSV.CC.VA.US,%20ou%3dFaculty%20%26%20Staff,%20o%3dvccs,%20c%3dUS -http://www.allgemeine-immobilien-boerse.de/nordrhein-Westfalen/luedinghausen/Verkauf/Ferien-IB/Startseite/Gemeinsam/erreichenPartner/Versteigerungen-IB/Startseite/IIM-Teil/Startseite/froben.htm -http://198.103.152.100/search*frc/dIndustrial+relations+--+Germany+(West)+--+History/dindustrial+relations+germany+west+history/-5,-1,0,B/frameset&F=dindustrial+relations+germany+dictionaries&1,,0 -http://secure.danysoft.com/asp/dany.tienda/892496425/Catalog -http://yp.gates96.com/13/57/90/23.html -http://yp.gates96.com/13/57/90/91.html -http://yp.gates96.com/13/57/91/68.html -http://yp.gates96.com/13/57/92/22.html -http://yp.gates96.com/13/57/92/49.html -http://yp.gates96.com/13/57/92/73.html -http://yp.gates96.com/13/57/93/75.html -http://yp.gates96.com/13/57/94/16.html -http://yp.gates96.com/13/57/94/62.html -http://yp.gates96.com/13/57/94/99.html -http://yp.gates96.com/13/57/95/19.html -http://yp.gates96.com/13/57/95/34.html -http://yp.gates96.com/13/57/95/84.html -http://yp.gates96.com/13/57/96/22.html -http://yp.gates96.com/13/57/96/24.html -http://yp.gates96.com/13/57/96/52.html -http://yp.gates96.com/13/57/96/70.html -http://yp.gates96.com/13/57/97/39.html -http://yp.gates96.com/13/57/97/55.html -http://yp.gates96.com/13/57/98/4.html -http://yp.gates96.com/13/57/98/41.html -http://yp.gates96.com/13/57/98/58.html -http://yp.gates96.com/13/57/98/98.html -http://yp.gates96.com/13/57/98/99.html -http://yp.gates96.com/13/57/99/79.html -http://carriage.de/Schoner/Info-d/history/literature/literature/ -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/lit/lit/computers/misc/unitest/misc/computers/programs/simple/simple.html -http://kwic.tucows.com/partners/flyswat/get_acx.html -http://sp201.unige.ch:49213/cxxdoc/ioc/concepts/c2g2rcsm.htm -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=0,2-0,1-21,0+9,1 -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=237&discrim=10,2,183 -http://firstweb.tucows.com/win2k/adnload/58783_28760.html -http://www.boerseninfos.de/dynamic/ak/mk/news/719350-20000830-104827.html -http://baseball.mainichi.co.jp/life/family/syuppan/wakaru/wakaru-j/10/01/01.html -http://helios.nlib.ee/search*est/dsÃĩjalised+blokid/dsw~ajalised+blokid/-5,-1,0,B/exact&F=dsw~ajalised+konfliktid&1,58/limit -http://helios.nlib.ee/search*est/dsÃĩjalised+blokid/dsw~ajalised+blokid/-5,-1,0,B/frameset&F=dsw~ajalised+konfliktid&11,,58 -http://lexicon.linux.tucows.com/conhtml/adnload/8642_2088.html -http://ua.php.net/manual/es/function.pg-fieldisnull.php -http://www.babyheirlooms.com/catalog/htmlos.cat/041132.1.4352706945 -http://www.civila.com/guitar/chat/desenredada/juegos/ -http://sunsite.org.uk/public/pub/packages/info-mac/pilot/?N=D -http://www.aelita.net/products/products/support/news/Reg/Subscribe/company/contact/default.htm -http://cn.egroups.com/message/newsclips/295 -http://www.jornada.unam.mx/2000/sep00/000922/oriente-y.htm -http://members.tripod.co.jp/mosokke/dubair01ghe.html -http://202.99.23.245/zdxw/21/20000217/200002172112.html -http://link.fastpartner.com/do/session/600412/vsid/2870/tid/2870/cid/136966/mid/1060/rid/1926/chid/2870/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/speednames.php -http://link.fastpartner.com/do/session/600412/vsid/2870/tid/2870/cid/136966/mid/1060/rid/1926/chid/2870/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/nordicliving.php -http://link.fastpartner.com/do/session/600412/vsid/2870/tid/2870/cid/136966/mid/1060/rid/1926/chid/2870/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/local/redirect.php -http://iant.subportal.com/sn/Utilities/System_Maintenance_and_Repair_Utilities/2128.html -http://polygraph.ircache.net:8181/client/http_-2www.scubaring.com/http_-2www.aaainvestments.com/http_-2www.primenet.com/~stmmoon/stmbik.html -http://itcareers.careercast.com/texis/it/itjs/+wwwBme89D86qxwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewGtmoBGnaqdGpdGwBodDanDtoDnnGaMw55wqr15nBB5aoDhdGMwBodDa5nq1GoBOaDnBidGAapGdBdqdc5aGn31oGnmanLpnGonDqnaMFqhTfR20DzmehrwwwpBme26D86eSqwww5rmePdwwwBrmeZpwww/morelike.html -http://itcareers.careercast.com/texis/it/itjs/+awwBme3AT+6ezqwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewGtmoBGnaqdGpdGwBodDanDtoDnnGaMw55wqr15nBB5aoDhdGMwBodDa5nq1GoBOaDnBidGAapGdBdqdc5aGn31oGnmanLpnGonDqnaMFqhTfR20DzmehrwwwpBme26D86eSqwww5rmeEdwwwBrmeZpwww/jobpage.html -http://itcareers.careercast.com/texis/it/itjs/+vwwBme26D86eSqwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewGtmoBGnaqdGpdGwBodDanDtoDnnGaMw55wqr15nBB5aoDhdGMwBodDa5nq1GoBOaDnBidGAapGdBdqdc5aGn31oGnmanLpnGonDqnaMFqhTfR20DzmehrwwwpBme26D86eSqwwwGzmwwww5rmeEdwwwBrmeZpwww/morelike.html -http://www.starcities.com/usa/ca/carlsbad/ -http://www.3w-geschichten.de/PlumptreGeorge/PlumptreGeorge1857938461.htm -http://residence.educities.edu.tw/goyen/ -http://polygraph.ircache.net:8181/http_-2www.whowhere.com/http_-2www.primenet.com/~mmfact/http_-2www.microsoft.com/ie/download/ -http://polygraph.ircache.net:8181/http_-2www.whowhere.com/http_-2www.primenet.com/~mmfact/http_-2www.infohwy.com/odframes.html -http://www.linux.com/networking/network/management/industry/internet/services/ -http://cn.egroups.com/message/ruosulista/1176 -http://ftp.jp.debian.org/debian/dists/unstable/main/binary-i386/tex/?M=A -http://de.excite.de/bildung/katalog/17722 -http://de.excite.de/bildung/katalog/17893 -http://de.excite.de/bildung/katalog/17879 -http://www.emerchandise.com/browse/BUFFYTHEVAMP/PIN/b.TV%20BUFFYTHEVAMP/s.Xpiu5LCZ -http://variety.studiostore.com/browse/VARIETY/CAMERA/s.dmZspziz -http://carriage.de/Schoner/Sammlungen/models/info-e/Info-d/ -http://www.gazeta.com/Iso/Plus/Kraj/Prezyden/Ak/700kwa.html -http://www.linux.com/networking/network/networking/developers/operating_system/Debian/ -http://online.linux.tucows.com/conhtml/adnload/8808_32695.html -http://149.221.91.10/news/lokales/wermelskirchen/ -http://opac.lib.rpi.edu/search/avirgin+vision+limited/7,-1,0,B/frameset&avirginia+cooperative+fisheries+research+unit&1,1 -http://www.emerchandise.com/browse/DISNEY-FAM/ACTIONFI/b.FAVORITES%20KIDSSTUFF%20DISNEY-FAM/s.erm2bF5K -http://polit.kulichki.net/moshkow/PXESY/GORIN/ -http://polit.kulichki.net/moshkow/COPYRIGHT/stolyarov.txt -http://www.science.uva.nl/pub/NetBSD/NetBSD-current/pkgsrc/textproc/rman/pkg/DESCR -http://cgi.www.4tourism.com/uk/wareham65426.html -http://cgi.www.4tourism.com/uk/wareham22477.html -http://www.ccnet.com/affif/_themes/sumipntg/_vti_cnf/?M=A -http://web.tin.it/regionesardegna/ital/lavpubb/bandi_contratti/schema5_1q.htm -http://ring.htcn.ne.jp/archives/text/CTAN/macros/latex/contrib/other/apa/ -http://ftpsearch.belnet.be/packages/CPAN/modules/by-module/Callback/Callback-1.02.readme -http://iant.subportal.com/sn/Utilities/Misc__Utilities/12800.html -http://yp.gates96.com/2/51/0/86.html -http://yp.gates96.com/2/51/1/72.html -http://yp.gates96.com/2/51/2/10.html -http://yp.gates96.com/2/51/3/7.html -http://yp.gates96.com/2/51/3/50.html -http://yp.gates96.com/2/51/4/90.html -http://yp.gates96.com/2/51/5/6.html -http://yp.gates96.com/2/51/5/42.html -http://yp.gates96.com/2/51/5/50.html -http://yp.gates96.com/2/51/6/49.html -http://yp.gates96.com/2/51/8/12.html -http://yp.gates96.com/2/51/8/50.html -http://yp.gates96.com/2/51/9/82.html -http://yp.gates96.com/2/51/9/94.html -http://archive.soccerage.com/s/fr/09/37602.html -http://archive.soccerage.com/s/fr/09/39203.html -http://ftp.ring.gr.jp/archives/NetBSD/NetBSD-1.4.1/pmax/binary/security/ -http://www.yorosiku.net:8080/-_-http://www.us-japan.org/otr/ -http://support.dell.com/docs/storage/dlt1/ug/sp/jumpers.htm -http://moviestore.zap2it.com/browse/MOVIES/MOUSEPAD/s.uiIfdEiW -http://moviestore.zap2it.com/browse/MOVIES/STANDUP/s.uiIfdEiW -http://focusin.ads.targetnet.com/ad/id=animeart&opt=cin&cv=210&uid=972942857 -http://www.emerchandise.com/browse/SATNIGHTLIVE/SWEATSHI/s.pJ2FFfba -http://www.realize.com/p5dee81.htm,qt=e784fe2f=2a38a234-e-1ade986-0-0-0-3-- -http://support.tandy.com/support_audio/doc30/30780.htm -http://sun1.rrzn-user.uni-hannover.de/jgaertner/matlab/help/techdoc/umg/chlabel2.html -http://sun1.rrzn-user.uni-hannover.de/jgaertner/matlab/help/techdoc/umg/chprin12.html -http://www.es.co.nz/~rotary.home.html -http://www.excelsior.com.mx/9802/980217/nac18.html -http://dante.bdp.it/cgi-bin/poseidon_v2.0/reflect/poseidon/disc/biblioteca1/1316779952/prevarticle -http://dennou-t.ms.u-tokyo.ac.jp/arch/cc-env/Linux/debian-jp/dists/stable/non-free-jp/binary-alpha/net/?D=A -http://guest/forestpatholog/diseases/annosus.html -http://guest/forestpatholog/diseases/rot.html -http://no.egroups.com/message/readbygrade3/2029 -http://www.cybercd.de/artist/Fabri,+Stafke.htm -http://www.jamba.de/KNet/_KNet-zQG8j1-hGd-13cwi/admLogin.de/node.0/cenv0b09a -http://www.digitaldrucke.de/(aktuell,computer,marktplatz,sense,tausch)/_fort/html/themen/computer/computer.htm -http://ring.tains.tohoku.ac.jp/pub/linux/debian/debian-jp/dists/potato/contrib-jp/source/news/?S=A -http://strategis.ic.gc.ca/sc_indps/recboats/frndoc/3g.html -http://ftp.eq.uc.pt/software/unix/Linux/redhat/redhat-6.2/i386/doc/gsg/figs/rpmlite/?M=A -http://www.judds-resort.com/judds/Lake-Winni-pike-lodge/upload/upload/photo/fallphoto/boat/12.html -http://ftp.eecs.umich.edu/.7/NetBSD/NetBSD-current/src/usr.sbin/cnwctl/ -http://ftp.eecs.umich.edu/.7/NetBSD/NetBSD-current/src/usr.sbin/mailwrapper/ -http://ftp.eecs.umich.edu/.7/NetBSD/NetBSD-current/src/usr.sbin/traceroute6/ -http://ftp.eecs.umich.edu/.7/NetBSD/NetBSD-current/src/usr.sbin/yppoll/ -http://pelit.saunalahti.fi/.3/linuxberg/conhtml/preview/8785.html -http://www.asahi-net.or.jp/~rz3n-snd/kitakan/kamiyosida.html -http://www.chaos.dk/sexriddle/s/e/x/q/x/k/l/ -http://www.chaos.dk/sexriddle/s/e/x/q/x/k/y/ -http://ring.jec.ad.jp/archives/text/CTAN/dviware/umddvi/libcompat/?S=A -http://seniorfriendfinder.com/cgi-bin/w3com/pws/ffsenior/OCtIhwK0_lecIJU9yN87J4DTFWqXdztVO8nfP1zxdwq79fkod_IhHN3-iHbCrlaXZ5ATMMc_Gb5Zt_RdtVOloKJ1Z7DGqz2vE9vOjESyOqryETO-lNa0NWtCoTJH_QGCfq7ss5VGa1MO3iLryKZ2gIVI_Lonfx_bC9m7 -http://seniorfriendfinder.com/cgi-bin/w3com/pws/ffsenior/D-tI2p4N__5TTgffRqVzdrKNYFZc3jj2Oatw29gt_YiNBPXUlYZaTA2ndP2CrwlrdiMS8YzPKxDR7Vp4ZBqD3d5o3MwYrYIxk31YsVtP3yFS2bLdZcBGLKdyNUc9yYgvGsGMXAMcEAUJPjtRqUVzDpuhHzS6V_U76I6G -http://my.egroups.com/subscribe/enemapix -http://yp.gates96.com/0/23/40/60.html -http://yp.gates96.com/0/23/40/82.html -http://yp.gates96.com/0/23/41/67.html -http://yp.gates96.com/0/23/43/71.html -http://yp.gates96.com/0/23/43/75.html -http://yp.gates96.com/0/23/44/64.html -http://yp.gates96.com/0/23/44/73.html -http://yp.gates96.com/0/23/44/84.html -http://yp.gates96.com/0/23/45/19.html -http://yp.gates96.com/0/23/46/9.html -http://yp.gates96.com/0/23/46/26.html -http://yp.gates96.com/0/23/46/37.html -http://yp.gates96.com/0/23/46/92.html -http://yp.gates96.com/0/23/47/39.html -http://yp.gates96.com/0/23/47/52.html -http://yp.gates96.com/0/23/48/52.html -http://yp.gates96.com/0/23/49/12.html -http://yp.gates96.com/0/23/49/90.html -http://retailer.gocollect.com/do/session/1912812/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/help/index.asp -http://retailer.gocollect.com/do/session/1912812/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/sports/index.asp -http://203.93.50.148:2222/*0110http://www.snweb.com/gb/people_daily/2000/10/20/i1020004.htm -http://cn.egroups.com/messages/romtrade/5024 -http://members.tripod.co.jp/medo/_private/ -http://dbc.copystar.com.tw/DelphiChat/200001/msg0325.htm -http://tucows.pi.be/winnt/diskcnt_license.html -http://millennium.fortunecity.com/ruthven/144/5041.htm -http://news.pchome.com.tw/ttv/finance/20000616/ -http://library.bangor.ac.uk/search/dEcology+--+Poland+--+Periodicals/decology+poland+periodicals/-17,-1,0,B/frameset&F=decology+north+america+congresses&1,1 -http://www.could.be/travel/north_america/united_states/lodge_2.htm -http://genforum.genealogy.com/cgi-bin/print.cgi?huntington::195.html -http://www.bemi-immobilien.de/Ferien-IB/Startseite/Gemeinsam/immolink/Gemeinsam/MarketingStrategie/Gemeinsam/erreichenPartner/Gemeinsam/3d-service/Top-Darlehens-Konditionen/anforderungsformular.htm -http://members.tripod.co.jp/snowmen/?D=A -http://ftp.unicamp.br/pub/FAQ/sf/alt_history/part6 -http://www.affiliate.hpstore.hp.co.uk/do/session/380884/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/REGISTRATION/entry.asp -http://grid9.linux.tucows.com/x11html/adnload/9444_3744.html -http://www.linux.com/networking/network/communications/tools/web/support/ -http://www.linux.com/networking/network/communications/tools/web/alternative/ -http://cometweb01.comet.co.uk/do!tid=20&rtid=1&vsid=700&session=132030&mid=1000&rid=1060&cid=37030&chid=1713&url=eqqLmwlGltt5tkZHljbLqkZHlkrHhlZHdfjKYfkLlkZ5ljjLboZLbplGGolLarZLq4fLpmiLXv-KmooLckYLoznGmpq0qsc0mojLbkYLozvGotc0ZdoLckYLozvGsmv0qmc0jXfLkVZLdocLkYoLzcj1XfkLVZXLqkXLjbzKcob5qroLkVrLoizKlZd5fjYHfklKkZlLjjbLoZbLpl51ubZLDXZLollK3ljLbqlKjXfLkkaHotl4obmLloqL -http://yp.gates96.com/14/77/20/1.html -http://yp.gates96.com/14/77/20/3.html -http://yp.gates96.com/14/77/20/32.html -http://yp.gates96.com/14/77/20/55.html -http://yp.gates96.com/14/77/21/7.html -http://yp.gates96.com/14/77/22/20.html -http://yp.gates96.com/14/77/22/26.html -http://yp.gates96.com/14/77/22/50.html -http://yp.gates96.com/14/77/23/63.html -http://yp.gates96.com/14/77/23/96.html -http://yp.gates96.com/14/77/25/53.html -http://yp.gates96.com/14/77/26/8.html -http://yp.gates96.com/14/77/26/32.html -http://yp.gates96.com/14/77/27/0.html -http://yp.gates96.com/14/77/27/55.html -http://yp.gates96.com/14/77/27/78.html -http://yp.gates96.com/14/77/28/8.html -http://yp.gates96.com/14/77/28/53.html -http://yp.gates96.com/14/77/28/57.html -http://yp.gates96.com/14/77/28/99.html -http://yp.gates96.com/14/77/29/96.html -http://mirror.nucba.ac.jp/mirror/FreeBSD/FreeBSD-stable/ports/cad/xcircuit/files/?D=A -http://pub3.ezboard.com/BBSForum.showForumSearch?boardName=jenxforum&forumName=jenxforumfrm0 -http://genforum.genealogy.com/cgi-genforum/forums/hi.cgi?415 -http://elib.zib.de/pub/opt-net/msc/msc-90-xx/90c15/v93w20n4 -http://biblio.cesga.es:81/search*gag/aDittrich,+Stefan/adittrich+stefan/-5,-1,0,E/frameset&F=adittman+richard+h+coaut&1,,0 -http://biblio.cesga.es:81/search*gag/aDittrich,+Stefan/adittrich+stefan/-5,-1,0,E/frameset&F=adittmar+jorge&1,1 -http://biblio.cesga.es:81/search*gag/aDittrich,+Stefan/adittrich+stefan/-5,-1,0,E/exact&F=adivis+jan&1,4 -http://www.doc.ic.ac.uk/~gwsb98/bucket/Wine-20001026/etc/?D=A -http://news.fm365.com/xinwen/guoji/20000531/72641.htm -http://www.newquestcity.com/templates/eventout.cfm?nqc=TN0730 -http://www.rhena.de/kempinsk1.htm -http://www.jamba.de/KNet/_KNet-tkL8j1-PGd-13dss/showInfo-wir.de/node.0/cenvd8eze -http://www.jamba.de/KNet/_KNet-tkL8j1-PGd-13dsv/browse.de/node.0/ceo0fdeye -http://cpan.nitco.com/modules/by-module/String/BLCKSMTH/?N=D -http://www.digitaldrucke.de/(hilfe,nuernberg)/_fort/html/themen/computer/soft/links/intuit.htm -http://www.jeunesdocteurs.com/fplr/56/08.html -http://simf1.tripod.com/Rio.htm -http://www.mirror.kiev.ua:8083/paper/1998/17/1251/people.htm -http://web2.sportsline.com/u/baseball/mlb/2000PO_stats/tpSTLw.htm -http://www15.freeweb.ne.jp/art/charukun/yusuke.htm -http://map.ipc.co.jp/asp/onmap/r/new/g-24/f-905972/ -http://www.affiliate.hpstore.hp.co.uk/do/session/380882/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/REGISTRATION/entry.asp -http://www.webcrawler.com/education/arts_and_humanities/visual_arts/art_history/c19th/arts_and_crafts/mackintosh_cr/structures/ -http://polygraph.ircache.net:8181/wwwboard/http_-2www.microsoft.com/msoffice/frontpage/http_-2www.linkstar.com/home/partners/marketlink-international-inc -http://polygraph.ircache.net:8181/wwwboard/http_-2www.microsoft.com/msoffice/frontpage/ECA2.htm -http://polygraph.ircache.net:8181/wwwboard/http_-2www.microsoft.com/msoffice/frontpage/http_-2www.intac.com/~dversch/catalog.html -http://excite.de.netscape.com/kunst/katalog/24315 -http://www.outpersonals.com/cgi-bin/w3com/pws/out/KhhIzVYqtXJlJzGPqrqzbJbUw7ERB8P7PSm9mTaj3BkJF6tLfllGlz2yKgLweoM1LPKLdHjjKv8zfb9tb2yojpTmzt6264ZE3V9vWzxY1mZnhDOG1vlwPrnwH5OCJM6C98fbjgZX66II -http://mirror.nucba.ac.jp/mirror/Netscape/netscape6/french/6_PR2/windows/win32/?S=A -http://www.linux.com/networking/server/install/howto/red_hat/package/ -http://www.nissan.co.jp/RENAULT-DEALERS/PASSPORT/view.cgi/proof/972959618-- -http://brain.brent.gov.uk/WebPages.nsf/vWebAllPagesByKey!OpenView&Start=97&Count=60&Expand=152 -http://i-mode.kakiko.com/deaitomo/mag/magurox/1405b.html -http://www.ring.gr.jp/pub/NetBSD/arch/amiga/snapshot/20000115-1.4P/binary/security/ -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=18,0+20,0-17,0-0,0 -http://us.mandrakesoft.com/cgi-bin/cvsweb.cgi/www/anoncvs.html?annotate=1.2&sortby=rev -http://ftp.jp.debian.org/debian/dists/woody/non-free/binary-sh/hamradio/?M=A -http://netscape.complete-skier.com/resorts/survey/submit.asp?ResortID=772 -http://nathanael.upi.jussieu.fr/tele6.nsf/autres+centres+de+formations!OpenPage&ExpandSection=9,17,2,16,5,14 -http://www.egroups.com/messages/zingiber/238 -http://www.umr.edu/~rhall/class/sap/sap8/demo.html -http://209.207.239.212/bkindex/c1043/f1202.html -http://se.egroups.com/message/ackmud/104 -http://school.educities.org/card/cug55.html -http://school.educities.org/card/wgl.html -http://school.educities.org/card/a77125.html -http://school.educities.org/card/apple6128.html -http://school.educities.org/card/c369852.html -http://school.educities.org/card/cges4216.html -http://school.educities.org/card/cges6307.html -http://school.educities.org/card/eaa.html -http://school.educities.org/card/f129235832.html -http://school.educities.org/card/g1546.html -http://school.educities.org/card/h223422022.html -http://school.educities.org/card/lemon6112.html -http://school.educities.org/card/st6408.html -http://www.dulux.co.uk/UKRETAIL:1243142410:DFinity.1QJiP4jRACol -http://www.iagora.com/pages/bbaddpost/::bb_id=148:mid=43302:thread_id=8185:parent_id=43302::lang=de -http://www.iagora.com/pages/bbaddpost/::bb_id=148:mid=43431:thread_id=8185:parent_id=43431::lang=de -http://www.egroups.com/message/intelligent_humor/875 -http://club.telepolis.com/klvinbc/fotosb.htm -http://plat.debian.or.jp/debian/dists/woody/non-free/binary-mips/editors/?D=A -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=207&discrim=3,12,63 -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=207&discrim=3,12,237 -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=207&discrim=3,12,120 -http://www.jamba.de/KNet/_KNet-_tJ8j1-AGd-13ddq/browse.de/node.0/cdel3j591 -http://immihelpdownloads.subportal.com/sn/Utilities/System_Analysis_Utilities/2980.html -http://dwp.bigplanet.com/crestinginc/discussion/edit.nhtml -http://dwp.bigplanet.com/crestinginc/discussion/list.nhtml?profile=discussion -http://194.128.65.4/pa/cm199900/cmwib/wb991127/ahead.htm -http://61.128.218.34/book/hhsh/wu/wolongsheng/jiangxue/055.htm -http://gd.cnread.net/cnread1/wgwx/t/tuwen/kxj/035.htm -http://gd.cnread.net/cnread1/wgwx/t/tuwen/kxj/041.htm -http://www.redrocksports.com/sports/webSession/shopper/RR972959743-31143/store/dept-5/department/dept-5/item/50110 -http://www.redrocksports.com/sports/webSession/shopper/RR972959743-31143/store/dept-5/department/dept-5/item/51530 -http://www.redrocksports.com/sports/webSession/shopper/RR972959743-31143/store/dept-5/department/dept-5/item/51510 -http://www.yorku.ca/org/yusa/who99/wh02.html -http://www1.onelist.com/message/ar8200/3350 -http://www.kodak.se/US/en/corp/features/kern/jodi/index.shtml -http://cafe3.daum.net/Cafe-bin/Bbs.cgi/semtle15pds/rnw/zka/B2-kB27k -http://my.egroups.com/messages/dcfwriters/187?expand=1 -http://link.fastpartner.com/do/session/600414/vsid/1970/tid/1970/cid/135878/mid/1060/rid/1488/chid/1970/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/gosafe.php -http://www.tiscover.com/1Root/Kontinent/6/Staat/7/Bundesland/20/Ort/108147/Bauernhof/315126/Homepage/f_homepage...2.html -http://ring.omp.ad.jp/archives/NetBSD/packages/pkgsrc/net/gnut/patches/?D=A -http://www.mtranslations.cz/40/cs/dictionary/dictionary_index.html -http://pub10.ezboard.com/BBSSystem.handleLoginCheck?action=forgotPassword&boardName=alakazamslair -http://tour.stanford.edu/cgi/locate3.prl/139.6/jMtlo -http://www.shopworks.com/index.cfm/action/search/userid/00042DDE-2F63-19FE-9038010B0A0ADCF2 -http://thestar.com/back_issues/ED20001004/life/20000820LFE01_AH-BATH.html -http://thestar.com/back_issues/ED20001004/life/20000818LFE01_LI-DEPRESS.html -http://thestar.com/back_issues/ED20001004/life/20000806LFE01_AH-DAHLIAS.html -http://www.hole.kommune.no/hole/journweb.nsf/7e180336094ef23a412568cd004a5093/466e7592a4c6c7ccc12568e3004402e8!Navigate&To=Prev -http://mailthat.subportal.com/sn/Multimedia_and_Graphics/Graphics_Editors/3752.html -http://www.gbnf.com/genealogy/rockwel4/html/d0014/I6348.HTM -http://www.lookforforestry.com/catalog/FORSALE/FORKLIFT/JCB/930RTFL/ -http://www.espl.org/mearscol/pagendxs/stockley/d1828.htm -http://in.egroups.com/messages/eyecandy/1290 -http://in.egroups.com/message/eyecandy/1264 -http://in.egroups.com/message/eyecandy/1271 -http://www.ferien-immobilien.de/bayern/deggendorf/Verkauf/Exklusiv-IB/Startseite/3d-service/Gemeinsam/Immolink/Gemeinsam/vertriebspartner.htm -http://linux99.inrialpes.fr/linux/RPM/redhat/6.2/i386/Distribs.html -http://students.lsu.edu/students/main.nsf/Pages/CSISAJ1!OpenDocument&ExpandSection=4,13,11,10 -http://www.doc.ic.ac.uk/lab/labsrc_area/firstyear/submissions/1997-98/jmc1/labs/Ex04/jwb97/?S=A -http://www.iabusnet.org:90/forums/aca-1/dispatch.exe/survey/folderFrame/100001/0/alpha/2509069 -http://www.scifi.com/bboard/browse.cgi/1/5/545?lnum=4223 -http://www.fogdog.com/cedroID/ssd3040183304719/customer_service/ -http://www.fogdog.com/cedroID/ssd3040183304719/nav/products/winter_sports/1b/suits/ -http://www.gpul.org/ftp/lang/java/JDK/jdk1.1.6-docs/api/java.lang.Math.html -http://www.gpul.org/ftp/lang/java/JDK/jdk1.1.6-docs/api/java.lang.IncompatibleClassChangeError.html -http://www.staroriental.net/nav/soeg/ihf,aai,n2,418,Electric+Wave+Girl+1998.html -http://www.parentsplace.com/expert/lactation/basics/qa/0,3459,5757,00.html -http://www.francetrade.fr/opcvm/details/4/44200.html -http://www.francetrade.fr/opcvm/details/4/42876.html -http://genforum.genealogy.com/cgi-bin/print.cgi?phillippines::319.html -http://www.affiliate.hpstore.hp.co.uk/do/session/380860/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-photoworld.com/photoworld.asp?lang=f -http://ftp.eq.uc.pt/software/unix/Linux/docs/HOWTO/translations/italian/distributions/?M=A -http://store1.europe.yahoo.com/brink2/2000074017704.html -http://store1.europe.yahoo.com/brink2/2000073276003.html -http://www.cbe21.com.cn/xueke/dili/jiaoxuezs/ziliaojn/tupianhc/i0733.htm -http://www.networkpatternmatching.com/inventory/L/Limoges-American/Limoges-American-Tea-Rose-(Green).html -http://www.networkpatternmatching.com/inventory/L/Limoges-American/Limoges-American-Toledo-Delight-(Sand).html -http://ftp.debian.org/dists/sid/non-free/binary-hppa/games/?M=A -http://www.angelfire.com/vt/kAoZzZ -http://yp.gates96.com/14/28/60/15.html -http://yp.gates96.com/14/28/60/17.html -http://yp.gates96.com/14/28/60/41.html -http://yp.gates96.com/14/28/60/75.html -http://yp.gates96.com/14/28/60/83.html -http://yp.gates96.com/14/28/60/87.html -http://yp.gates96.com/14/28/61/96.html -http://yp.gates96.com/14/28/62/12.html -http://yp.gates96.com/14/28/62/28.html -http://yp.gates96.com/14/28/62/45.html -http://yp.gates96.com/14/28/62/74.html -http://yp.gates96.com/14/28/63/24.html -http://yp.gates96.com/14/28/63/45.html -http://yp.gates96.com/14/28/64/33.html -http://yp.gates96.com/14/28/65/84.html -http://yp.gates96.com/14/28/66/28.html -http://yp.gates96.com/14/28/66/49.html -http://yp.gates96.com/14/28/67/15.html -http://yp.gates96.com/14/28/67/17.html -http://yp.gates96.com/14/28/67/92.html -http://yp.gates96.com/14/28/67/95.html -http://yp.gates96.com/14/28/68/10.html -http://yp.gates96.com/14/28/69/20.html -http://yp.gates96.com/14/28/69/64.html -http://yp.gates96.com/14/28/69/74.html -http://www.cs.kuleuven.ac.be/documentation/Sun/WorkShop/html_docs/c-plusplus/stdlibcr/deq_4164.htm -http://no.egroups.com/message/Holiday-Best/571?source=1 -http://www.outpersonals.com/cgi-bin/w3com/pws/out/G1hIPcWIQWr-i3fHpjDuaPPPdDR9n25II-MFpjX9vR_df0A3ukwPXLd19bYe7oxRH5Zr5z3G_wJnwM6gAVSOlRUN-p5MKYEBVJa1T-GaZS44Z98yjSST2LfXzEdc9Xqp8W0jRiNL6iAX -http://msn.expedia.co.uk/wg/Asia/China/P31642.asp -http://www.angelfire.com/fl2/gulfcoastsoftball/images/?N=D -http://www.greenleaves.com/bookcat/gb_0879513802.html -http://cn.egroups.com/post/Digitrends_Daily?act=reply&messageNum=210 -http://www.bookhome.net/wuxia/hzlz/li/031.html -http://gb.toget.com.tw/intro/game_action/game_action_click/19990804_3190_dl.html -http://www.mbnet.mb.ca/gray/cgrcc.html -http://www.civila.com/noticias/chat/logos/juegos/esgratis/logos/index.html-ssi -http://www.ytmag.com/cgi-bin/redirect.cgi/1197948180 -http://debian.tod.net/debian/dists/sid/contrib/binary-arm/admin/?M=A -http://haste.co.kr/www.amaquest.com.tw/support.htm -http://www.diogenes.ch/4DACTION/web_rd_aut_frlist_az/ID=483376&chr=A -http://ads.neoseeker.com/remoteclick/GB972959289/ -http://urawa.cool.ne.jp/whoinside/cg/cgframe2.htm -http://excite.de/bildung/katalog/33148 -http://plat.debian.or.jp/debian-archive/dists/Debian-2.0/hamm/binary-m68k/news/ -http://wwwpriv.uni-koblenz.de:81/~admin/Doku/HtmlTutor/tcdkc.htm -http://platsbanken.amv.se/kap/text/62/000907,150090,120901,40,1427050362.shtml -http://216.35.79.131/sites/gunits/022140u.html -http://www.hotelboulevard.com/fr/paris/standard/htmle55cd396d0d1450ad1eddadf65bd6574/sessionLang/ANG/prov/browse/cp/75011/resultatSearch.html -http://www.ftp.uni-erlangen.de/cgi-bin/view/pub/unix/Linux/MIRROR.KDE/unstable/apps/README -http://www.ftp.uni-erlangen.de/pub/unix/Linux/MIRROR.KDE/unstable/apps/network/ -http://www.ycwb.com.cn/gb/2000/04/28/dnzk/itkx/3.html -http://polygraph.ircache.net:8181/http_-2www.microsoft.com/guestbook/http_-2www.nmpinc.com/cfiguest.htm -http://www.our-home.org/giulianovallemani/success.htm -http://retailer.gocollect.com/do/session/1912838/vsid/2312/tid/2312/cid/573127/mid/1020/rid/2147/chid/2210/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLlZe5ofpLqjXLpl4/url/http://www.gocollect.com/product_display/products/product_lines.asp -http://binary.tucows.com/win2k/adnload/60913_29719.html -http://www.allhealth.com/kickbutt/qa/0,4801,6565_168263-1,00.html -http://library.cuhk.edu.hk/search*chi/tChinese+history+series.+[Motion+picture]/tchinese+history+series/-5,1,1,B/frameset&F=tchinese+history+index+to+learned+articles+1902+1962&1,1, -http://cafe4.daum.net/Cafe-bin/Bbs.cgi/culturalistpds/lst/qqeq/1/zka/B2-kB27p -http://lib1.nippon-foundation.or.jp/1997/0012/contents/086.htm -http://members.tripod.com/~theernest/lit/long.html -http://de.excite.de/auto/katalog/13030 -http://www.szinfo.com/book/ke/fam/nk1/wlsf/001.htm -http://www.backflip.com/members/cquinn/466730/sort=1/ -http://130.158.208.53/WWW/PDB2/PCD4711/htmls/49.html -http://astronomysite.com/mapug1/15/msg15752.htm -http://astronomysite.com/mapug1/15/msg15922.htm -http://astronomysite.com/mapug1/15/msg15970.htm -http://astronomysite.com/mapug1/12/msg12909.htm -http://astronomysite.com/mapug1/9/msg9909.htm -http://astronomysite.com/mapug1/7/msg7248.htm -http://astronomysite.com/mapug1/7/msg7288.htm -http://astronomysite.com/mapug1/7/msg7300.htm -http://astronomysite.com/mapug1/7/msg7277.htm -http://astronomysite.com/mapug1/3/msg3386.htm -http://astronomysite.com/mapug1/0/msg898.htm -http://astronomysite.com/mapug1/2/msg2146.htm -http://people.freebsd.org/~knu/cgi-bin/cvsweb.cgi/ports/x11-fm/systemg/pkg/Attic/DESCR -http://www.posterwelt.de/byers/bye2506.htm -http://www.5a8.com/book/wg/zpj/f/fajieyefu/huimie/003.htm -http://www.5a8.com/book/wg/zpj/f/fajieyefu/huimie/015.htm -http://businessrecorder.com/story/S0015/S1510/top -http://sunsite.org.uk/Mirrors/ftp.microsoft.com/bussys/winnt/winnt-public/fixes/usa/nt351/hotfixes-postsp5/sec-fix/?S=A -http://sunsite.org.uk/Mirrors/ftp.microsoft.com/bussys/winnt/winnt-public/fixes/usa/nt351/hotfixes-postsp5/sec-fix/readme.txt -http://www.angelfire.com/ky/dodone/HistJ.html -http://www.cricinfo.com/link_to_database/ARCHIVE/1997-98/WI_IN_PAK/WI_IN_PAK_NOV-DEC1997_WI-SQUAD.html -http://www.egroups.com/message/-Girlhelp-/3251 -http://www.egroups.com/message/-Girlhelp-/3268 -http://202.130.244.3/wuliwangye/help/help.htm -http://ftp.gwdg.de/pub/EMIS/EMS/journals/SLC/divers/mirror.html -http://ftp.gwdg.de/pub/EMIS/EMS/journals/SLC/divers/s20ghinelli.html -http://ftp.gwdg.de/pub/EMIS/EMS/journals/SLC/divers/s25dress.html -http://ftp.gwdg.de/pub/EMIS/EMS/journals/SLC/divers/s30wen.html -http://ftp.gwdg.de/pub/EMIS/EMS/journals/SLC/divers/slc41email.html -http://guardian.co.uk/Print/0,3858,3889048,00.html -http://genforum.genealogy.com/mccallum/messages/187.html -http://genforum.genealogy.com/mccallum/messages/192.html -http://genforum.genealogy.com/mccallum/messages/133.html -http://genforum.genealogy.com/mccallum/messages/95.html -http://genforum.genealogy.com/mccallum/messages/82.html -http://genforum.genealogy.com/mccallum/messages/30.html -http://dekooi.tucows.com/win2k/adnload/37333_29427.html -http://dekooi.tucows.com/win2k/adnload/37624_29418.html -http://dekooi.tucows.com/win2k/preview/139483.html -http://www.zurich-schweiz.ch/static/it/peraziende/grandiimprese/riskmanagement/procedere_con_metodo/gestione_del_rischio/ -http://cn.egroups.com/login.cgi?login_target=%2Fmessage%2Fcertdev%2F373 -http://www.angelfire.com/pa2/DreamAvs/ -http://www.madisonmag.com/sh/entertainment/stories/entertainment-20000713-013454.html -http://variety.studiostore.com/browse/WHATSNEW/SHIRT/b.FAVORITES%20WHATSNEW/s.GqXR0UHu -http://variety.studiostore.com/browse/WHATSNEW/MUG/b.FAVORITES%20WHATSNEW/s.GqXR0UHu -http://www.ecs.soton.ac.uk/~ecc/teaching/java/ExampleCode/Chapter10/s03/ -http://ftp.nacamar.de/pub/NetBSD/packages/1.4/alpha/cross/?M=A -http://www.he.ctc.org.cn/ctc2/news/internet/develop/news0413-7.htm -http://www.he.ctc.org.cn/ctc2/news/internet/invest/news0523-4.htm -http://www.he.ctc.org.cn/ctc2/news/internet/invest/news0514-1.htm -http://www.he.ctc.org.cn/ctc2/news/internet/politics/news0518-1.htm -http://www.linux.com/networking/network/applications/industry/trade_show/internet/ -http://www.linux.com/networking/network/applications/industry/trade_show/Motorola/ -http://www.linux.com/networking/network/applications/industry/trade_show/distro/ -http://iinet.tukids.tucows.com/mac/5-8/macmulti58_license.html -http://www.leg.wa.gov/pub/rcw%20-%20text/title_48/chapter_098/rcw_48_98_005.txt -http://universal.eud.com/1999/02/28/28304AA.shtml -http://www.firstview.com/WRTWfall97/MAX_MARA/P033.html -http://l-infonet.phkk.fi/fi/TIETOPALVELUT/SOSIAALI-+JA+TERVEYSALA/tietoverkot/suositukset/tietotekniikka/sanat/getdoc.akM?document_id=479 -http://l-infonet.phkk.fi/fi/TIETOPALVELUT/SOSIAALI-+JA+TERVEYSALA/tietoverkot/suositukset/tietotekniikka/sanat/www/ -http://ns.studenti.to.it/~s86852/applets/tetris.htm -http://www.egroups.com/message/grebel-list/1014 -http://emedici.net/www.homesbyavi.com/canadian_site/communities/evergreen/evergreen.html -http://ring.toyama-ix.net/pub/net/wu-ftpd/wu-ftpd/binaries/?N=D -http://ring.nii.ac.jp/archives/text/CTAN/support/vmspell/?N=D -http://ftpsearch.belnet.be/packages/CPAN/modules/by-authors/John_Macdonald/CHECKSUMS -http://students.depaul.edu/~eephrem/piazza123 -http://students.depaul.edu/~eephrem/maqdoomi.html -http://ftp.unina.it/pub/Unix/KDE/stable/2.0/distribution/deb/?D=A -http://www.dulux.co.uk/UKRETAIL:1433075516:DFinity.1QJiP4jMofi7bof -http://yp.gates96.com/14/20/10/26.html -http://yp.gates96.com/14/20/10/34.html -http://yp.gates96.com/14/20/10/63.html -http://yp.gates96.com/14/20/11/36.html -http://yp.gates96.com/14/20/11/73.html -http://yp.gates96.com/14/20/12/93.html -http://yp.gates96.com/14/20/13/42.html -http://yp.gates96.com/14/20/13/44.html -http://yp.gates96.com/14/20/14/9.html -http://yp.gates96.com/14/20/15/62.html -http://yp.gates96.com/14/20/15/77.html -http://yp.gates96.com/14/20/16/52.html -http://yp.gates96.com/14/20/16/70.html -http://yp.gates96.com/14/20/16/83.html -http://yp.gates96.com/14/20/17/91.html -http://yp.gates96.com/14/20/17/98.html -http://yp.gates96.com/14/20/18/8.html -http://yp.gates96.com/14/20/18/73.html -http://yp.gates96.com/14/20/19/38.html -http://yp.gates96.com/14/20/19/42.html -http://yp.gates96.com/14/20/19/56.html -http://www.wco.com/~havok/wellington.html -http://opac.lib.ntnu.edu.tw/search*chi/++ftlist/bbm0019678/7,-1,0,E/frameset&F=bbm0019685&1,1 -http://cdrom.zeelandnet.nl/elfsound/archief.htm -http://businessrecorder.com/story/S0055/S5527/top -http://www.private-immobilien-boerse.de/DominikanischeRep/verkauf/Versteigerungen-IB/Startseite/Gemeinsam/GmbH-Kauf-Verkauf-Insolvenz-konkurs/Startseite/IIM-Teil/Startseite/froben.htm -http://ring.nii.ac.jp/archives/lang/perl/CPAN/doc/manual/html/pod/perlfunc/utime.html -http://yp.gates96.com/14/21/10/71.html -http://yp.gates96.com/14/21/11/15.html -http://yp.gates96.com/14/21/12/55.html -http://yp.gates96.com/14/21/12/58.html -http://yp.gates96.com/14/21/13/94.html -http://yp.gates96.com/14/21/14/7.html -http://yp.gates96.com/14/21/14/12.html -http://yp.gates96.com/14/21/14/32.html -http://yp.gates96.com/14/21/14/96.html -http://yp.gates96.com/14/21/15/3.html -http://yp.gates96.com/14/21/15/51.html -http://yp.gates96.com/14/21/16/32.html -http://yp.gates96.com/14/21/16/87.html -http://yp.gates96.com/14/21/17/19.html -http://yp.gates96.com/14/21/17/31.html -http://yp.gates96.com/14/21/18/15.html -http://yp.gates96.com/14/21/18/68.html -http://yp.gates96.com/14/21/19/56.html -http://cafe2.daum.net/Cafe-bin/Bbs.cgi/kjbugopds/lst/qqa/f/zka/B2-kB2Rt -http://legalminds.lp.findlaw.com/list/courtinterp-spanish/frm04580.html -http://legalminds.lp.findlaw.com/list/courtinterp-spanish/frm04611.html -http://genforum.genealogy.com/cgi-genforum/forums/sweden.cgi?5207 -http://variety.studiostore.com/main/b.FAVORITES%20NOSTALGI%20CLASTV%20ILOVELUCY/s.VfgR3aEr -http://variety.studiostore.com/help/b.FAVORITES%20NOSTALGI%20CLASTV%20ILOVELUCY/s.VfgR3aEr -http://bsd.sinica.edu.tw/cgi-bin/cvsweb.cgi/ports/x11-clocks/xalarm/patches/Attic/patch-aa?only_with_tag=RELEASE_2_2_8 -http://gd.cnread.net/cnread1/ztxs/h/henggouzhengshi/eld/013.htm -http://gd.cnread.net/cnread1/ztxs/h/henggouzhengshi/eld/022.htm -http://gd.cnread.net/cnread1/ztxs/h/henggouzhengshi/eld/024.htm -http://ftp.unina.it/pub/Amiga/NetBSD/NetBSD-current/xsrc/xc/lib/xkbfile/?N=D -http://202.99.23.245/zdxw/17/20000217/200002171734.html -http://sunsite.org.uk/packages/netbsd/NetBSD-current/pkgsrc/net/batchftp/files/ -http://www.highwired.net/Activity/PrintArticle/0,1640,1326-186648,00.html -http://phpbuilder.net/forum/archives/1/2000/10/1/104426?&print_mode=1 -http://www.cognos.co.uk/de/vertriebspartner/vertriebspartner_plz.html -http://citeseer.nj.nec.com/cidcontext/3974259 -http://fi.egroups.com/message/free-classifieds/4556?source=1 -http://genforum.genealogy.com/cgi-genforum/forums/epler.cgi?2 -http://no.egroups.com/post/relations_iVillage?act=reply&messageNum=5 -http://198.103.152.100/search*frc/lHD69+P75H84/lhd+++69+p75+h84/-5,-1,0,E/frameset&F=lhd+++69+p75+k47+1984&1,1 -http://www.4positiveimages.com/4positiveimages/921456486/UserTemplate/2 -http://haha.3322.net/donghua/agui/adi/6.htm -http://mediate.magicbutton.net/do/session/625591/vsid/4573/tid/4573/cid/88043/mid/2247/rid/2383/chid/3527/url/http://www.winesmart.com/CaseDetails.asp?idCase=66 -http://www.lettera.de/tp/deutsch/inhalt/lis/8676/1.html -http://www.citybrazil.com.br/sc/regioes/joinville/expressoes.htm -http://webcvs.kde.org/cgi-bin/cvsweb.cgi/www/food/worse_is_better.html?sortby=date -http://yp.gates96.com/7/45/60/13.html -http://yp.gates96.com/7/45/61/3.html -http://yp.gates96.com/7/45/61/60.html -http://yp.gates96.com/7/45/62/37.html -http://yp.gates96.com/7/45/62/48.html -http://yp.gates96.com/7/45/62/70.html -http://yp.gates96.com/7/45/64/9.html -http://yp.gates96.com/7/45/64/33.html -http://yp.gates96.com/7/45/64/43.html -http://yp.gates96.com/7/45/64/55.html -http://yp.gates96.com/7/45/65/14.html -http://yp.gates96.com/7/45/65/48.html -http://yp.gates96.com/7/45/65/57.html -http://yp.gates96.com/7/45/66/27.html -http://yp.gates96.com/7/45/67/51.html -http://yp.gates96.com/7/45/68/12.html -http://yp.gates96.com/7/45/68/78.html -http://yp.gates96.com/7/45/69/25.html -http://www.msb.malmo.se/search*swe/aHarley,+Robert/aharley+robert/-5,-1,0,B/browse -http://www.superdownloads.com.br/linkinvalido.cfm?ID=748 -http://linuz.sns.it/doc/howto/en/html/AI-Alife-HOWTO-6.html -http://www.linux.com/networking/network/market/tools/applications/ -http://www.linux.com/networking/network/market/tools/frame_relay/ -http://www.linux.com/networking/network/market/tools/e-commerce/ -http://opac.lib.ntnu.edu.tw/search*chi/aUnited+Nations.+Dept.+of+Economic+and+Social+Affairs/aunited+nations+dept+of+economic+and+social+affairs/7,-1,0,B/frameset&F=aunited+nations+economic+and+social+commission+for+asia+and+the+pacific&6,,7 -http://www.affiliate.hpstore.hp.co.uk/do/session/380863/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/assistance/entry.asp -http://www.affiliate.hpstore.hp.co.uk/do/session/380863/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/entry.asp -http://www.shmoo.com/mail/ids/oct99/msg00288.html -http://bsd.sinica.edu.tw/ftp_pub/NetBSD/packages/1.3/hp300/?M=A -http://bsd.sinica.edu.tw/ftp_pub/NetBSD/packages/1.3/hp300/archivers/ -http://www.affiliate.hpstore.hp.co.uk/do/session/380868/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/REGISTRATION/entry.asp -http://www.insideneworleans.com/shared/health/adam/ency/imagepage/1562.000872.html -http://ring.omp.ad.jp/archives/NetBSD/packages/pkgsrc/devel/xxgdb/patches/patch-ac -http://genforum.genealogy.com/casey/messages/327.html -http://genforum.genealogy.com/casey/messages/164.html -http://genforum.genealogy.com/casey/messages/337.html -http://genforum.genealogy.com/casey/messages/73.html -http://genforum.genealogy.com/casey/messages/57.html -http://genforum.genealogy.com/casey/messages/50.html -http://genforum.genealogy.com/casey/messages/23.html -http://genforum.genealogy.com/casey/messages/116.html -http://www.msb.malmo.se/search*swe/aNorman,+Karin,+1947-/anorman+karin+1947/-5,-1,0,B/frameset&F=anorman+leslie&1,1 -http://forum.rai.it/aca-finestre/dispatch.cgi/FORUM/folderFrame/100001/0/rnumber/9096335 -http://www.mindspring.com/~arachnid/?S=D -http://www6.freeweb.ne.jp/business/n-bns/hre/ -http://news.swww.com.cn/wccdaily/review/200005/29/html/0908.htm -http://tucows.hom.net/croomnt_rating.html -http://www.trax.nilex.co.uk/trax.cgi/A1C/A2S/1AS/A4L/A4D/B1R/ -http://www.trax.nilex.co.uk/trax.cgi/A1C/A2S/1AS/A4L/A4D/A5L/ -http://www.5a8.com/book/kh/zg/zpj/h/heju/001.htm -http://www.5a8.com/book/kh/zg/zpj/h/heju/002.htm -http://www.luckyman.de/computer/hpaccess/java_cgi/java_applet/linien/applet_linien_nav1.htm -http://www.secure-me.net/information/kb/POP -http://in.egroups.com/message/BodybuildingContests/2804 -http://in.egroups.com/message/BodybuildingContests/2820 -http://in.egroups.com/message/BodybuildingContests/2822 -http://theconnection.vnunet.com/Analysis/Stfriend/70206 -http://www.yorosiku.net:8080/-_-http://www.nrcse.washington.edu/newsletter/newsletter.pdf -http://www.britishairways.nl/regional/barbados/docs/spec_world_offer.shtml -http://www.xmwb.sh.cn/xmwb/19981117/BIG5/13421^4111719.htm -http://www.z-plus.de/TEXTE/HOMEPAGE/HILFE/HILFE_SURFTIPS201099/text5.html -http://uzgamez.subportal.com/games/previews/0900/westwood/russian_general.html -http://bsd.sinica.edu.tw/ftp_pub/NetBSD/packages/1.3/sun3/?D=A -http://my.egroups.com/messages/dcfwriters/132?expand=1 -http://my.egroups.com/message/dcfwriters/147 -http://my.egroups.com/message/dcfwriters/149 -http://oss.sgi.com/cgi-bin/cvsweb.cgi/projects/failsafe/FailSafe/failsafe/scripts/?only_with_tag=MAIN -http://sound-dist.secured.co.uk/cgi-bin/psShop.cgi/add|8P007|972959615|Warm===and===Dry|user|0|1,0,0,1 -http://www.alsapresse.com/jdj/00/01/13/MA/photo_6.html -http://www.highwired.net/ESchoolDrive/Frameset/0,5592,13577-52,00.html -http://uk.sports.yahoo.com/000922/59/ak705.html -http://universal.eud.com/1999/02/26/26204DD.shtml -http://people.freebsd.org/~knu/cgi-bin/cvsweb.cgi/ports/audio/gkrellmvolume/pkg-descr?only_with_tag=MAIN -http://www3.skolverket.se/kursinfo/99_00/skolform/21/alt_nav/S_52S_10S_36VAV_SVSTEK_1715.HTML -http://www3.skolverket.se/kursinfo/99_00/skolform/21/alt_nav/S_52S_10S_36VAV_SVSTEK_1719.HTML -http://www.wsrn.com/apps/research/history.xpl?s=CMDCD&f=HISTORY -http://www.wsrn.com/apps/charts/?s=CMDCD&data=Z10 -http://pub3.ezboard.com/utherealcharron.showPublicProfile?language=EN -http://ring.shibaura-it.ac.jp/archives/graphics/gimp/gtk/binary/DEBIAN/stable/?S=A -http://209.52.189.2/discussion.cfm/autism/29762/198522 -http://www.affiliate.hpstore.hp.co.uk/do/session/380851/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/assistance/entry.asp -http://www01.sankei.co.jp/advertising/furusato/tokuhain/9810/1018sindou.html -http://kulichki-mac.rambler.ru/abiturient/ak.htm -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=3,0+9,1-20,0+9,0 -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=3,0+9,1-20,0+18,0 -http://ballesta.inrialpes.fr/Infos/Personnes/Christophe.Rippert/ressources/tutorial/security1.2/summary/glossary.html -http://www.affiliate.hpstore.hp.co.uk/do/session/380872/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.france.hp.com/main/respect/ -http://www11.cplaza.ne.jp/babyweb/bbs/bdnmp01/no24/99N.html -http://www.homeway.com.cn/lbi-html/news/zhxw/gatxw/20000922/165807.shtml -http://gd.cnread.net/cnread1/yqxs/d/dingqianrou/ssqj/009.htm -http://library.bangor.ac.uk/search/tBiol.+philos/tbiol+philos/-17,-1,0,B/frameset&F=tbioindicators+and+environmental+management&1,1 -http://dante.bdp.it/cgi-bin/poseidon_v2.0/reflect/poseidon/disc/peacelink-scuola/70630505/view/1 -http://www.indian-express.com/ie/daily/19980626/17750374.html -http://www.indian-express.com/ie/daily/19980626/17751044.html -http://www.indian-express.com/ie/daily/19980626/17751334.html -http://www.indian-express.com/ie/daily/19980626/17751494.html -http://polygraph.ircache.net:8181/services/define/http_-2www.disney.com/links.html -http://pub10.ezboard.com/fsavings4yousavings4you.subscribeUnregisteredToTopic?topicID=56.topic -http://www8.freeweb.ne.jp/shopping/arthome/arthome/menu.html -http://rainforest.parentsplace.com/dialog/get/medinfo/4/1.html?outline=3 -http://www.emerchandise.com/aboutus/b.TV%20SATNIGHTLIVE/s.afJ7iGE2 -http://ring.omp.ad.jp/archives/NetBSD/packages/pkgsrc/net/arpwatch/pkg/?S=A -http://ring.omp.ad.jp/archives/NetBSD/packages/pkgsrc/net/arpwatch/pkg/DESCR -http://210.178.135.1/netbbs/Bbs.cgi/nhic30872/qry/zka/B2-kBI-o/pno/0/qqo/004A/qqatt/^ -http://yp.gates96.com/8/48/0/54.html -http://yp.gates96.com/8/48/1/98.html -http://yp.gates96.com/8/48/2/23.html -http://yp.gates96.com/8/48/3/13.html -http://yp.gates96.com/8/48/3/14.html -http://yp.gates96.com/8/48/3/23.html -http://yp.gates96.com/8/48/3/84.html -http://yp.gates96.com/8/48/4/5.html -http://yp.gates96.com/8/48/4/72.html -http://yp.gates96.com/8/48/5/4.html -http://yp.gates96.com/8/48/5/49.html -http://yp.gates96.com/8/48/6/38.html -http://yp.gates96.com/8/48/6/89.html -http://yp.gates96.com/8/48/8/10.html -http://yp.gates96.com/8/48/8/41.html -http://yp.gates96.com/8/48/8/87.html -http://news.medscape.com/adis/CDI/2000/v19.n02/cdi1902.02.biel/cdi1902.02.biel-01.html -http://www.parsonstech.com/genealogy/trees/PKINGMAN/d2438.htm -http://www.parsonstech.com/genealogy/trees/PKINGMAN/d2502.htm -http://www.chaos.dk/sexriddle/j/c/b/o/ -http://www.outpersonals.com/cgi-bin/w3com/pws/out/FahI8ikSPIvk79ErK106-87Jy3U1_XgCksR4DWkUOldKaD_pciJBXOOmI2Sr4jXlDCT9Mkz59aBZhyyi3xxBeYROt0IpVObKZD4YcwBAhl9afrfb6y3nWI3SwdRE_Vp3d80RzmrDkPVZYQkJyvOgorzS -http://opac.lib.rpi.edu/search/dchemicals+dictionaries/-5,-1,0,E/frameset&dchemicals+catalogs&3,,0 -http://opac.lib.rpi.edu/search/dchemicals+dictionaries/-5,-1,0,E/frameset&dchemicals+catalogs+periodicals&1,1 -http://opac.lib.rpi.edu/search/dchemicals+dictionaries/-5,-1,0,E/frameset&dchemicals+dictionaries&3,,0 -http://opac.lib.rpi.edu/search/dchemicals+dictionaries/-5,-1,0,E/frameset&dchemicals+economic+aspects+united+states&1,,0 -http://www.jsonline.com/news/state/oct00/lambeau31103000a.asp -http://polygraph.ircache.net:8181/used/http_-2www.scubaring.com/http_-2www.alpinehotel.com/chinese/chine.htm -http://www.kaos.dk/sex-riddle/k/a/k/i/p/g/g/e/ -http://haikou.hainan.gov.cn/ghgl/ghsc/hkfg3020.html -http://variety.studiostore.com/main/VARIETY/s.Fz90iGDh -http://library.cuhk.edu.hk/search*chi/cPN595.C6I18+1993/cpn++595+c6+i18+1993/-5,1,1,E/frameset&F=cpn++595+c6+k6+1997&1,1, -http://library.cuhk.edu.hk/search*chi/cPN595.C6I18+1993/cpn++595+c6+i18+1993/-5,1,1,E/frameset&F=cpn++595+c6+l515&1,1, -http://link.fastpartner.com/do/session/600425/vsid/2870/tid/2870/cid/136966/mid/1060/rid/1926/chid/2870/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/learn.htm -http://www.nanyang.com.my/20001020/articles/15-10-2000k16.htm -http://202.99.23.245/rmrb/199912/11/newfiles/col_19991211001063_zhxw.html -http://help.sap.com/saphelp_45b/helpdata/en/a7/2872510a6c11d28a220000e829fbbd/frameset.htm -http://www.s10.sexshare.com/~pornking/hardcore/43.html -http://www.gbnf.com/genealogy/Lawler99/html/d0102/I1772.HTM -http://ring.edogawa-u.ac.jp/pub/linux/RedHat/aic/OLD/aic7xxx-5.0.x/boot_disks/5.0.11/SuSE/?D=A -http://www.t-online.de/sport/inhalte/adispi51.htm -http://ftp.lip6.fr/pub11/FreeBSD/development/FreeBSD-CVS/src/kerberos5/usr.sbin/k5stash/ -http://education.legend-net.com/xinwen/gaokao/zl5/zhsh/3/zhshyk.html -http://www.contractorresource.com/Wyoming/Cody/ -http://213.36.119.69/do/session/152998/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/FR/boutique/ -http://213.36.119.69/do/session/153000/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/FR/reserver/hotels.html -http://213.36.119.69/do/session/153000/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www3.travelprice.com/voyages/recherche.phtml -http://ftp.unina.it/pub/TeX/macros/latex/contrib/supported/combine/?D=A -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=237&discrim=178,2,11 -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=237&discrim=178,2,233 -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=237&discrim=178,2,5 -http://www12.freeweb.ne.jp/novel/urufu24/linkz/ug1.html -http://www12.freeweb.ne.jp/novel/urufu24/linkz/pv.html -http://computers.kharkov.ua/win/43/ -http://www.1001e.net/nk4/022.htm -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=4&discrim=93,164,176 -http://dic.empas.com/show.tsp/?q=revisable&f=B -http://yp.gates96.com/0/28/30/45.html -http://yp.gates96.com/0/28/30/46.html -http://yp.gates96.com/0/28/31/24.html -http://yp.gates96.com/0/28/32/64.html -http://yp.gates96.com/0/28/33/28.html -http://yp.gates96.com/0/28/33/85.html -http://yp.gates96.com/0/28/33/87.html -http://yp.gates96.com/0/28/33/96.html -http://yp.gates96.com/0/28/34/52.html -http://yp.gates96.com/0/28/35/7.html -http://yp.gates96.com/0/28/36/23.html -http://yp.gates96.com/0/28/36/52.html -http://yp.gates96.com/0/28/37/50.html -http://yp.gates96.com/0/28/38/85.html -http://yp.gates96.com/0/28/39/16.html -http://www.fan590.com/JamMoviesReviewsE/earth_king.html -http://www.sportbuecher.de/shop/3-88034-750-6.html -http://www.msb.malmo.se/search*swe/aWhitaker,+Galvin,+Utgivare/awhitaker+galvin/-5,-1,0,B/exact&F=awhitburn+joel&1,2 -http://ftp.sunet.se/pub/security/vendor/microsoft/winnt/frn/nt40/?M=A -http://www.intervoz.com.ar/2000/03/02/op_n04.htm -http://www.ntut.edu.tw/~s7370840/8-19.htm -http://www.back2roots.org/Music/Files/Wondergirl%20-%20You%26Me/ -http://www.private-immobilien-boerse.de/nordrhein-Westfalen/Muehlheim-ruhr/Verkauf/3d-service/IIM-Teil/Startseite/Gemeinsam/Inserieren/IIM-Teil/Startseite/frinfo.htm -http://web.singnet.com.sg/~spirit5/letters/oct2000/frankm1025-3.htm -http://web.singnet.com.sg/~spirit5/letters/oct2000/davidp1025.htm -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=decuplicavamo&l=it -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=decuplichiate&l=it -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=decuplichereste&l=it -http://members.tripod.com/~OZEMU/cgi-bin/ -http://ring.tains.tohoku.ac.jp/archives/pack/dos/hardware/midi/?D=A -http://kutschen.de/Schoner/info-e/info-e/collections/literature/ -http://www.jamba.de/KNet/_KNet-MJJ8j1-DGd-13dgc/showInfo-special1.de/node.0/cde7f1uou -http://www.jamba.de/KNet/_KNet-MJJ8j1-DGd-13dgy/browse.de/node.0/cenv0b09a -http://in.egroups.com/message/sfconsim-l/6415 -http://genforum.genealogy.com/cgi-genforum/forums/vt.cgi?4123 -http://www.linux.com/networking/network/sap/article/price/VA_Linux_Systems/ -http://www.linux.com/networking/network/sap/article/price/regulation/ -http://slacvx.slac.stanford.edu/sldmcwww/mc/MC74BB_98R16B_WIN_ALL.HTML -http://www.xmission.com/~dkenison/cgi/lwgate.cgi/KLR650/archives/v02.n1611/date/article-15.html -http://www.iwon.com/home/movies/movies_filmography_page/0,13178,Macon+McCalman,00.html -http://excite.de/spiele/katalog/26997 -http://www.trax.nilex.co.uk/trax.cgi/A1C/B1S/B2R/A2U/B3S/B1R/ -http://www.power2lead.com/Global/English.nsf/pgWWLocations!OpenPage&ExpandSection=2,6,27,9,26 -http://itcareers.careercast.com/texis/it/itjs/+owwBm1eP0-dzwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewDPwdGpdGwBodDa5dhBiwGna5O5BnManDtoDnnGa5nDodGa5BwhhaidGAanLpnGonDqnaqdMp1BnGamnVncdpaMFqhTfR20Dzme8twwwpBmer+D86e9qwww5rmeZpwwwBrmeZpwww/morelike.html -http://pub4.ezboard.com/fnationoferidinegeneral.showAddReplyScreenFromWeb?topicID=615.topic&index=2 -http://www.chaos.dk/sexriddle/m/i/s/x/ -http://kiasuplanet.subportal.com/sn/Games/Tetris_Clone_Games/5532.html -http://kiasuplanet.subportal.com/sn/Games/Tetris_Clone_Games/11418.html -http://kiasuplanet.subportal.com/sn/Games/Tetris_Clone_Games/676.html -http://www.rge.com/pub/networking/ldap/umich/max500/beta/?M=A -http://my.egroups.com/dir/Health/Fitness/Exercise_Equipment -http://my.egroups.com/messages/prevention -http://pub4.ezboard.com/factiveprodiscussioncommunityactivitiesquestions.showMessage?topicID=12.topic -http://www.look4cranes.com/catalog/AUCTIONRESULT/AGGREGATE+-+CONVEYOR+%2F+FEEDER+%2F+STACKER/POWERSCREEN/ -http://www.fogdog.com/cedroID/ssd3040183344300/cgi-bin/MyFogdog -http://www.fogdog.com/cedroID/ssd3040183344300/nav/products/featured_brands/3b/gloves_mittens/ -http://www.houses-apartment-listings.com/Washington/city_search_criteria.asp?state=WA&City=CONCONULLY -http://www.brunel.ac.uk/~ccusjpe/linux/howto/Consultants-HOWTO/c23417.html -http://www.brunel.ac.uk/~ccusjpe/linux/howto/Consultants-HOWTO/x12810.html -http://www.brunel.ac.uk/~ccusjpe/linux/howto/Consultants-HOWTO/x14250.html -http://www.brunel.ac.uk/~ccusjpe/linux/howto/Consultants-HOWTO/x14507.html -http://www.brunel.ac.uk/~ccusjpe/linux/howto/Consultants-HOWTO/x15988.html -http://www.brunel.ac.uk/~ccusjpe/linux/howto/Consultants-HOWTO/x17214.html -http://www.brunel.ac.uk/~ccusjpe/linux/howto/Consultants-HOWTO/x18550.html -http://www.brunel.ac.uk/~ccusjpe/linux/howto/Consultants-HOWTO/x19113.html -http://www.brunel.ac.uk/~ccusjpe/linux/howto/Consultants-HOWTO/x1949.html -http://www.brunel.ac.uk/~ccusjpe/linux/howto/Consultants-HOWTO/x21473.html -http://www.brunel.ac.uk/~ccusjpe/linux/howto/Consultants-HOWTO/x31101.html -http://www.brunel.ac.uk/~ccusjpe/linux/howto/Consultants-HOWTO/x3585.html -http://www.brunel.ac.uk/~ccusjpe/linux/howto/Consultants-HOWTO/x44035.html -http://www.brunel.ac.uk/~ccusjpe/linux/howto/Consultants-HOWTO/x4711.html -http://www.online.kokusai.co.jp/Home/V0043638/wrd/G100/ -http://ftp.lip6.fr/pub5/FreeBSD/branches/-current/ports/print/ghostscript5/ -http://ftp.lip6.fr/pub5/FreeBSD/branches/-current/ports/print/texinfo/ -http://ftpsearch.belnet.be/mirrors/ftp.isc.org/pub/usenet/control/ats/?N=D -http://garbo.uwasa.fi/pub/linux/distributions/SuSE/7.0/dosutils/exceed/USER/HOSTEX/SCHEME/?D=A -http://forum.rai.it/aca-finestre/dispatch.cgi/FORUM/showNextUnseen/fol/100001/922702 -http://link.fastpartner.com/do/session/600391/vsid/1314/tid/1314/cid/134340/mid/1060/rid/1180/chid/1314/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/local/redirect.php -http://www.jamba.de/KNet/_KNet-wEF8j1-bGd-13cma/showInfo-datenschutz.de/node.0/cenvptf1i -http://www.jamba.de/KNet/_KNet-wEF8j1-bGd-13cmd/browse.de/node.0/cenv0b09a -http://www-usa6.cricket.org/link_to_database/PLAYERS/RSA/T/THOMPSON_DS_03003252/ -http://sunsite.org.uk/public/public/packages/WWW/emacs-w3/?S=A -http://www.excelsior.com.mx/9811/981129/buh25.html -http://www.anixter.nl/SBJEVE/170699-2155-01.html -http://innopac.lib.tsinghua.edu.cn:2082/search*chi/aBrooks,+Jane+B./abrooks+jane+b/-5,-1,0,B/browse -http://tour.stanford.edu/cgi/options.prl/95.70/gMcto -http://www.cksd.edgate.com/emeraldheightses/elections/students/the_parties/ -http://novel.hichinese.net/comment/comment.php?page=2091&action=write -http://205.161.150.96/cgi-bin/c2k/additem.html&item=204578 -http://www.nhic.or.kr/netbbs/Bbs.cgi/nhic31282/qry/zka/B2-kB2-m/pno/0/qqo/004A/qqatt/^ -http://scripts.infoart.ru/magazine/znamia/n4-20/shpakov.htm -http://excite.de/bildung/katalog/19909 -http://911codes.com/games/platform/n64/sect/div/cont/list_cheat/spray/y/id/0000009557/gid/0000003573/_cheats/_walkthroughs/_codes/_pc/_n64/_psx/_gameboy/_playstation/ -http://ftp.jp.debian.org/debian/dists/stable/main/source/web/?M=A -http://www.fogdog.com/cedroID/ssd3040183335913/nav/products/featured_brands/3c/all/ -http://his.luky.org/ML/linux-users.3/msg08073.html -http://yomiuri-1422.excite.co.jp/entertainment/animated_cartoon_comic/each_work_title/ha_line/ha -http://yomiuri-1422.excite.co.jp/entertainment/animated_cartoon_comic/each_work_title/ha_line/hu_he/berserk -http://library.cwu.edu/search/dWorld+War,+1914-1918+--+Diplomatic+history/dworld+war+1914+1918+diplomatic+history/-5,-1,0,B/exact&F=dworld+war+1914+1918+diplomatic+history&1,49 -http://www.utdallas.edu/dept/sci_ed/Caribbean/images/Jennifer%20Jordan/Antigua%20Mangrove/?N=D -http://www.baustoffhandel.de/service/faqs/faq-tapezieren.htm -http://muc-zvs-web1.goethe.de/ms/bud/film/un_f2.htm -http://www.online.kokusai.co.jp/Map/V0043636/wrd/G1000/map/sitemap.html -http://win.www.citycat.ru/funny/fido/2000_05/25.html -http://nathanael.upi.jussieu.fr/tele6.nsf/autres+centres+de+formations!OpenPage&ExpandSection=9,1,7,13,15,6 -http://yp.gates96.com/11/79/50/1.html -http://yp.gates96.com/11/79/50/92.html -http://yp.gates96.com/11/79/52/64.html -http://yp.gates96.com/11/79/54/79.html -http://yp.gates96.com/11/79/54/81.html -http://yp.gates96.com/11/79/56/28.html -http://yp.gates96.com/11/79/56/30.html -http://yp.gates96.com/11/79/56/46.html -http://yp.gates96.com/11/79/56/83.html -http://yp.gates96.com/11/79/57/10.html -http://yp.gates96.com/11/79/57/33.html -http://yp.gates96.com/11/79/58/1.html -http://yp.gates96.com/11/79/58/48.html -http://yp.gates96.com/11/79/58/82.html -http://yp.gates96.com/11/79/59/62.html -http://l-infonet.phkk.fi/fi/TIETOPALVELUT/ELINKEINO-+JA+YRITYSTOIMINTA/Matkailu+-+maantiede/matkailu/linja-autoliikenne/joukkoliikenne/aikataulut/ -http://cn.egroups.com/message/romtrade/3823 -http://www.idgnet.com/idgns/1999/07/16/SmallFrenchBusinessesMoveSlowlyTo.shtml -http://www-d0.fnal.gov/d0dist/dist/releases/psim01.01.00/Exceptions/?M=A -http://www.4positiveimages.com/4positiveimages/781560892/Catalog -http://dellnet.excite.fr/yellow_pages/annuaire/823 -http://ftp.chg.ru/pub/math/grace/MIRRORS -http://ftp.chg.ru/pub/math/grace/aux/ -http://legalminds.lp.findlaw.com/list/lawlibref-l/mail8.html -http://carriage.de/Schoner/modelle/models/Info-d/Sammlungen/ -http://chunma.yeungnam.ac.kr/~j4390214/경기ìƒìй.htm -http://members.tripod.co.jp/stpp/?M=A -http://map.ipc.co.jp/asp/onmap/connect/f-525598/g-28/ -http://www.fortunecity.com/business/lerner/101/form.html -http://www.sportskorea.net/BBS/Bbs/db/L019/act/new/bnum/000060/zka/6/o/6/drc/f -http://ftp.jp.debian.org/debian/dists/Debian2.2r0/main/binary-all/hamradio/?M=A -http://admin.afiliando.com/do/session/189476/vsid/1507/tid/1507/cid/23455/mid/1025/rid/1168/chid/1205/parser/yes/imref/eqqLmwlGltt5tkpHrYjLXofLklkKZljLkju5lZa5l0/url/http://www.submarino.com.mx/toy/home.asp -http://www.gasex.com/gay.male.erotica/penis.gay.twink.men.html -http://ftpsearch.belnet.be/mirrors/ftp.isc.org/pub/usenet/control/ak/?S=A -http://gb.toget.com.tw/intro/desktop_wallpaper/desktop_wallpaper_idol/20000417_7747_dl.html -http://yp.gates96.com/13/50/50/27.html -http://yp.gates96.com/13/50/52/20.html -http://yp.gates96.com/13/50/52/31.html -http://yp.gates96.com/13/50/52/44.html -http://yp.gates96.com/13/50/53/33.html -http://yp.gates96.com/13/50/53/45.html -http://yp.gates96.com/13/50/53/72.html -http://yp.gates96.com/13/50/54/34.html -http://yp.gates96.com/13/50/54/62.html -http://yp.gates96.com/13/50/54/83.html -http://yp.gates96.com/13/50/54/84.html -http://yp.gates96.com/13/50/55/5.html -http://yp.gates96.com/13/50/55/61.html -http://yp.gates96.com/13/50/55/75.html -http://yp.gates96.com/13/50/56/0.html -http://yp.gates96.com/13/50/56/15.html -http://yp.gates96.com/13/50/56/21.html -http://yp.gates96.com/13/50/56/29.html -http://yp.gates96.com/13/50/57/2.html -http://yp.gates96.com/13/50/57/54.html -http://yp.gates96.com/13/50/58/9.html -http://yp.gates96.com/13/50/58/34.html -http://yp.gates96.com/13/50/59/64.html -http://yp.gates96.com/13/50/59/70.html -http://yp.gates96.com/13/50/59/75.html -http://yp.gates96.com/13/50/59/85.html -http://www.ilmessaggero.it/hermes/19990419/07_MARCHE/40/AGRI.htm -http://www.ilmessaggero.it/hermes/19990419/07_MARCHE/40/NERA.htm -http://amigos.com/cgi-bin/w3com/pws/ffe/IURImAxosglBgN4t3Iz538S9DOsFp6mHl6tpYJehgGibFrnWNcTM3WIsDckFomPqZ-JB8f_Qj8Aua4sE4AFvcFyidtj2iI6k1zPchuFbLwWMCo3hr8eXPNuxbHPQdRvo8J246667 -http://amigos.com/cgi-bin/w3com/pws/ffe/F3hIBiydr9mPRNSqk-dll3MTqIZCaRN3wRH0-H7o4qF0vlfPBXUV-Vhn028iva56e-GCSyYZKBQxuCJO8Y2JF25fVTkPHzFtrNMoOVhEp2n7Y11PhN9pvFNyqgssdZW8Eay0XJsP0vuD4oCbmJVx -http://home.digitalcity.com/boston/sportsguy/main.dci?page=curse2 -http://ftpsearch.belnet.be/mirror/ftp.funet.fi/pub/Linux/doc/logos/.cap/?S=A -http://ftpsearch.belnet.be/mirror/ftp.funet.fi/pub/Linux/doc/logos/.cap/?D=A -http://my.netian.com/~52tour/kyung1.html -http://aol.weather.com/weather/radar/single_site/us_ny_allegany.html -http://www-usa16.cricket.org/link_to_database/GROUNDS/RSA/CENTURION/ -http://polygraph.ircache.net:8181/prodev/career/http_-2www.getstats.com/http_-2www.shindex.com/in_dex/in_dex.html -http://polygraph.ircache.net:8181/prodev/career/http_-2www.getstats.com/http_-2www.microsoft.com/msoffice -http://www.5a8.com/book/wg/cp/p/puge/zhizhunv/005.htm -http://tukids.raha.com/crafts/preview/52044.html -http://tukids.raha.com/crafts/preview/52401.html -http://buc.co.kr/www.ecs.com.tw/ -http://wap.jamba.de/KNet/_KNet-EDS8j1-KHd-13gbq/showInfo-werbung.de/node.0/cde7f1uou -http://www.launch.com/music/songpage/1,4425,322514,00.html -http://www.emerchandise.com/browse/BUFFYTHEVAMP/CAP/b.TV%20BUFFYTHEVAMP/s.NGdTZGLC -http://www.emerchandise.com/browse/BUFFYTHEVAMP/STICKER/b.TV%20BUFFYTHEVAMP/s.NGdTZGLC -http://www.emerchandise.com/help_security/b.TV%20BUFFYTHEVAMP/s.NGdTZGLC -http://yp.gates96.com/14/70/50/9.html -http://yp.gates96.com/14/70/50/23.html -http://yp.gates96.com/14/70/50/24.html -http://yp.gates96.com/14/70/50/40.html -http://yp.gates96.com/14/70/50/47.html -http://yp.gates96.com/14/70/50/79.html -http://yp.gates96.com/14/70/50/89.html -http://yp.gates96.com/14/70/51/83.html -http://yp.gates96.com/14/70/52/98.html -http://yp.gates96.com/14/70/53/46.html -http://yp.gates96.com/14/70/54/4.html -http://yp.gates96.com/14/70/54/24.html -http://yp.gates96.com/14/70/54/97.html -http://yp.gates96.com/14/70/55/51.html -http://yp.gates96.com/14/70/57/51.html -http://yp.gates96.com/14/70/58/3.html -http://yp.gates96.com/14/70/58/84.html -http://yp.gates96.com/14/70/59/0.html -http://opac.lib.ntnu.edu.tw/search*chi/++ftlist/bp20046027/-5,-1,0,B/frameset&F=bp20046031&1,1 -http://www.free-phone.com/q/001p/ppc2/KtIYye9a8Pw.htm -http://www.1stemlm.com/q/001p/ppc2/7kwUxQYfGMk.htm -http://sports.excite.com/ten/grand_german -http://www.omniseek.com/dir/Arts+%26+Humanities/Fine+Arts/Ceramics/Organizations/Australia/ -http://ftp1.service.digital.com/patches/public/vms/axp/v7.1-2/dec-axpvms-vms712_usb-v0100--4.pcsi-dcx_axpexe -http://ftp1.service.digital.com/patches/public/vms/axp/v7.1-2/vms712_acrtl-v0100.README -http://ftp1.service.digital.com/patches/public/vms/axp/v7.1-2/vms712_acrtl-v0100.html -http://ftp1.service.digital.com/patches/public/vms/axp/v7.1-2/vms712_dqconfig-v0200.README -http://ftp1.service.digital.com/patches/public/vms/axp/v7.1-2/vms712_ds20e-v0100.html -http://ftp1.service.digital.com/patches/public/vms/axp/v7.1-2/vms712_shadowing-v0300.CVRLET_TXT -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=barrissait&l=fr -http://dk.egroups.com/message/M-1911/4394 -http://www.netsh.com.cn/wwwboardm/526/messages/2116.html -http://www.netsh.com.cn/wwwboardm/526/messages/2270.html -http://www.netsh.com.cn/wwwboardm/526/messages/773.html -http://www.netsh.com.cn/wwwboardm/526/messages/2058.html -http://www.netsh.com.cn/wwwboardm/526/messages/2329.html -http://www.netsh.com.cn/wwwboardm/526/messages/1813.html -http://linux.softhouse.com.cn/linux/knowledge/tech/HOWTO/Java-CGI-HOWTO-7.html -http://news.novgorod.ru/news/2000/9/22/2/12 -http://news.novgorod.ru/news/2000/9/24/2/12 -http://homepage1.nifty.com/sigenyan/nikki9.htm -http://perso.club-internet.fr/guige/ncpc78.htm -http://www.vr-homes.com/usa/California/Cities/Victorville/Travel/Maps_Images/ -http://www.incestpornstories.com/cum-sex-pics/underagecoed/spankingsweating/hardendurance.html -http://www.freeforums.com/forums/Hardball/000008-000007.asp -http://www.freeforums.com/forums/Hardball/000005-000001.asp -http://www.freeforums.com/forums/Hardball/000004-000001.asp -http://rex.skyline.net/html/Internet_Chat_Sites.html?315,computers,video,internet,computers -http://rex.skyline.net/html/Computers_-_Hardware.html?14,computers,video,internet,computers -http://194.128.65.4/pa/cm199899/cmhansrd/vo990216/text/90216w20.htm -http://pub14.ezboard.com/fyamguyskoflastblade.showMessage?topicID=3.topic -http://plant.reedexpo.ca/www.partnership.ca/?S=A -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=168&discrim=109,5,168 -http://www.aelita.net/products/~archive/Download_redirect/solutions/solutions/services/products/default.htm -http://www.jpc-music.com/7041801.htm -http://home.c2i.net/entreprenor/java/ra.html -http://gxschool.beelink.com.cn/mid_edu/midschool/geography3/t4cd7z/4d7z3.3_1.htm -http://ricoh.co.jp/SHOGI/emate/basic/mate3003a.html -http://www.diogenes.ch/4DACTION/web_rd_aut_frlist_az/ID=483385&chr=K -http://www.ebigchina.com/msg_post.phtml?cu=1003 -http://www.bemi-immobilien.de/allgemeine-ib/startseite/Gemeinsam/erreichenPartner/Gemeinsam/versicherungen/lebensversicherung/Gemeinsam/immolink/Gemeinsam/MarketingStrategie/Gemeinsam/Inserieren/onlineInserieren.htm -http://ftp.tku.edu.tw/OS/Linux/distributions/RedHat/rawhide/i386/doc/rhinst/stylesheet-images/?S=A -http://www.egroups.com/message/kicken/284 -http://www.guangmingdaily.com.cn/0_gm/1999/12/19991222/big5/gm^18278^2^GM2-2216.htm -http://brightnet.pda.tucows.com/www.psionsite.rcsed.ac.uk/ -http://www.symatrixinc.com/website/website.nsf/0/3e40df86fb357cd5882568720079613f!OpenDocument&ExpandSection=9,22,1,11 -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=durereste&l=it -http://click-to.tell-a-friend.boardhost.com/tell-a-friend-confirm.cgi?ylihilseen&msg=25 -http://www.gbgm-umc.org/EllisvilleMO/10-04-00.pdf -http://www.marketingtool.com/contribute/webfirm/b.435.r.2626.g.4134.html -http://www.chaos.dk/sexriddle/h/a/w/l/ -http://www.chaos.dk/sexriddle/h/a/w/t/ -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=3,0+9,5-0,3+( -http://www.guba.net/101/136/125E/index-4.phtml -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=3,0+9,5-0,3+21,0 -http://www.guba.net/101/136/125E/index-7.phtml -http://www.guba.net/101/136/125E/index-15.phtml -http://ftpsearch.belnet.be/ftp/mirror2/ftp.cert.dfn.de/pub/vendor/sun/security-alert/security-alert-108.txt -http://ftpsearch.belnet.be/ftp/mirror2/ftp.cert.dfn.de/pub/vendor/sun/security-alert/security-alert-170.txt -http://www.tente.de/us/produkte/rubriksuche/ad000000699.htm -http://www.angelfire.com/ky/kysweetpea/ -http://yp.gates96.com/7/69/60/1.html -http://www.amulation.com/md-l-archive/199908/frm00208.html -http://yp.gates96.com/7/69/60/4.html -http://yp.gates96.com/7/69/60/33.html -http://yp.gates96.com/7/69/60/49.html -http://yp.gates96.com/7/69/60/71.html -http://nanjingnews.jlonline.com/nanjingnews/njrb/20000226/04tiyu.htm -http://yp.gates96.com/7/69/61/44.html -http://yp.gates96.com/7/69/61/69.html -http://yp.gates96.com/7/69/61/82.html -http://yp.gates96.com/7/69/61/85.html -http://yp.gates96.com/7/69/62/4.html -http://yp.gates96.com/7/69/63/34.html -http://yp.gates96.com/7/69/63/48.html -http://yp.gates96.com/7/69/63/66.html -http://yp.gates96.com/7/69/64/22.html -http://www.bemi-immobilien.de/IIM-Teil/Startseite/Gemeinsam/MarketingStrategie/Gemeinsam/Inserieren/Startseite/Gemeinsam/versicherungen/unfall/Gemeinsam/3d-service/info.htm -http://yp.gates96.com/7/69/64/26.html -http://yp.gates96.com/7/69/65/89.html -http://yp.gates96.com/7/69/67/11.html -http://yp.gates96.com/7/69/67/28.html -http://yp.gates96.com/7/69/67/33.html -http://yp.gates96.com/7/69/67/70.html -http://yp.gates96.com/7/69/68/22.html -http://yp.gates96.com/7/69/68/72.html -http://yp.gates96.com/7/69/68/92.html -http://members.tripod.com/~katenleo/fading21.html -http://yp.gates96.com/7/69/69/6.html -http://members.tripod.com/~katenleo/fading26.html -http://yp.gates96.com/7/69/69/36.html -http://yp.gates96.com/7/69/69/91.html -http://yp.gates96.com/7/69/69/98.html -http://www.tribuneindia.com/98oct11/head1.htm -http://fi.egroups.com/message/internet-sig-announce/3 -http://info.verwaltung.uni-freiburg.de/doc/susehilf/pak/paket_inhalt_libxml.html -http://www.planetweb.com/cgi-bin/listmanager.pl/NETLINK-CUST/archives/1998Mar30-Apr05.archive/Date/article-23.html -http://www.maasvlakte-cam.nl/webcams/11/katowice__poland/2000/06/13/ -http://www.eveclub.com/cgi-bin/eveclub.front/972959521459/Home -http://totalsports.aol.com/stats/bbo/int/20000413/nor.at.lou.box.html -http://totalsports.aol.com/stats/bbo/int/20000413/ott.at.buf.game.html -http://fi.egroups.com/message/stccg-badlands/67 -http://www.fogdog.com/cedroID/ssd3040183315704/nav/stores/books_videos/ -http://xf-bbs.hb.cninfo.net/~socrates/sportold/images/football/_vti_cnf/ -http://cisc.tu-graz.ac.at/igi/lehre/semD_ss99/gruppe3/node10.html -http://in.egroups.com/message/sfconsim-l/8643 -http://ftp.cc.chuo-u.ac.jp/home/pub/lang/perl/CPAN/modules/by-authors/Karl_Glazebrook/ExtUtils-F77-1.13.readme -http://ftp.cc.chuo-u.ac.jp/home/pub/lang/perl/CPAN/modules/by-authors/Karl_Glazebrook/PGPLOT-2.17.readme -http://coe.ier.hit-u.ac.jp/BibEc/data/Papers/wopwobaiu2243.html -http://coe.ier.hit-u.ac.jp/BibEc/data/Papers/wopwobaiu2386.html -http://books.hyperlink.co.uk/bookinfo/Travel_Journal/0864427972 -http://dbc.copystar.com.tw/DelphiChat/200001/msg0650.htm -http://dbc.copystar.com.tw/DelphiChat/200001/msg0655.htm -http://dbc.copystar.com.tw/DelphiChat/200001/msg0666.htm -http://dbc.copystar.com.tw/DelphiChat/200001/msg0673.htm -http://dbc.copystar.com.tw/DelphiChat/200001/msg0681.htm -http://dbc.copystar.com.tw/DelphiChat/200001/msg0692.htm -http://www.expage.com/page/cavypigsponser -http://kernel2.adver.com.tw/Counter/log/kernel2.adver.com.tw/SaveCounter/2000-10-05/13/?S=A -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=210&discrim=214,253 -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=2&discrim=247,212,237 -http://wwwtios.cs.utwente.nl/archive/wilyfans/frm01740.html -http://z-06.land-sbg.gv.at/pressebuero/lpb/unserland/apr00/3.htm -http://z-06.land-sbg.gv.at/pressebuero/lpb/unserland/apr00/52.htm -http://gladstone.uoregon.edu/~sola/Stories/ -http://adetti.iscte.pt/RSI/HowTo/Java/jdk1.2.1/docs/guide/2d/api-jpeg/serialized-form.html -http://ocean.ntou.edu.tw/search*chi/aSloan,+Richard+P.,+jt.+ed./asloan+richard+p/-5,-1,0,E/frameset&F=asloan+irving+j&2,,0 -http://ttzcomputers.subportal.com/sn/Programming/C_and_C___Tools_and_Components/13286.html -http://ttzcomputers.subportal.com/sn/Programming/C_and_C___Tools_and_Components/1551.html -http://ftp.uni-stuttgart.de/pub/unix/tools/system/top/m/?N=D -http://no.egroups.com/message/romtrade/5216 -http://dk.egroups.com/message/Gunsmithing/80 -http://www.msb.malmo.se/search*swe/dMichelsen,+Hans/dmichelsen+hans/-5,-1,0,B/frameset&F=dmichels+robert&1,1 -http://solar.rtd.utk.edu/friends/news/omri/1998/05/980506I.html(opt,mozilla,pc,russian,koi8,default) -http://www.geocities.co.jp/HeartLand/6163/link8.htm -http://tucows.austria.com/sync95_size.html -http://tucows.austria.com/adnload/1082_30337.html -http://www.hotelboulevard.com/fr/paris/standard/html7752b1d358fd6459ebca66776e896614/sessionLang/ANG/prov/browse/cp/75015/resultatSearch.html -http://210.178.135.1/netbbs/Bbs.cgi/nhic30872/qry/zka/B2-kB2-o/pno/0/qqo/000A/qqatt/^ -http://210.178.135.1/netbbs/Bbs.cgi/nhic30872/new/pno/0/pno/0/qqo/000A -http://cometweb01.comet.co.uk/do!tid=20&rtid=2&vsid=700&session=132041&mid=1000&rid=1060&cid=37030&chid=1713&url=eqqLmwlGltt5tkZHljbLqkZHlkrHhlZHdfjKYfkLlkZ5ljjLboZLbplG5ubLZDXLZolLl3l5jbqLlci5XqVLkXsLkao4tloHbmlLoq5 -http://polygraph.ircache.net:8181/http_-2www.webtechs.com/html-val-svc/f-agents.html -http://www.linux.com/networking/network/development/communications/server/distro/ -http://www.linux.com/networking/network/development/communications/server/competition/ -http://www.linux.com/networking/network/development/communications/server/certification/ -http://www.linux.com/networking/network/development/communications/server/future/ -http://www.linux.com/networking/network/development/communications/server/Updates/ -http://people.freebsd.org/~knu/cgi-bin/cvsweb.cgi/ports/net/epic4/pkg/Attic/ -http://polygraph.ircache.net:8181/mo/mo_links/http_-2www.whowhere.com/tax_cuts.html -http://www.gov.ie/iveagh/angloirish/bloodysunday/summary4.htm -http://polygraph.ircache.net:8181/http_-2www.real-e-video.com/ftp_-2ftp.mpgn.com/Gaming/ADND/Worlds/BirthRight/MailingListArchive/Contents.htm -http://www.centc251.org/forums/aca-1/dispatch.cgi/isowg4/showNextUnseen/fol/100001/1323398 -http://www.centc251.org/forums/aca-1/dispatch.cgi/isowg4/folderFrame/100008/0/def/1323639 -http://user.alpha.co.kr/~selly/profile/main2.htm -http://polygraph.ircache.net:8181/company/http_-2www.aaainvestments.com/http_-2triad.cyberserv.com/http_-2207.90.134.3/miami/ -http://ring.htcn.ne.jp/pub/FreeBSD/FreeBSD-current/ports/archivers/zip/ -http://www.medoc-ias.u-psud.fr:81/synoptic/gif/950902/?S=A -http://in.egroups.com/message/GQRP/975 -http://idgnow.uol.com.br/idgnow/pcnews/2000/07/0046 -http://us.mandrakesoft.com/cgi-bin/cvsweb.cgi/kdebase/po/Attic/kdmconfig.pot?only_with_tag=beta1-0_2 -http://us.mandrakesoft.com/cgi-bin/cvsweb.cgi/kdebase/po/Attic/kwm.pot?only_with_tag=beta1-0_2 -http://lists.omnipotent.net/mysql/199912/msg02189.html -http://kyoto.cool.ne.jp/ryou_1125/lmax/list2.html -http://www.infodog.com/RESULTS/1998092302/1998092302800.HTM -http://www.infodog.com/RESULTS/1998092302/1998092302575.HTM -http://bedandbreakfast.com/bbc/p618230.asp -http://solaris.license.virginia.edu/os_product_patches/patches/5.5.1/103640-28/SUNWscpu/ -http://www.secinfo.com/d1Z36p.5n.htm -http://cn.egroups.com/messages/conscious_creation/2087 -http://www.brio.de/BRIO.catalog/39fdb4fb08541c02273fd472aa7806a2/UserTemplate/13 -http://www.chaos.dk/sexriddle/o/m/e/z/ -http://cgi.tbs.co.jp/cdtv/songdb/song1897-j.html -http://www.niwl.se/wais/new/12/12116.htm -http://bsdweb.pasta.cs.uit.no/bsdweb.cgi/~checkout~/pkgsrc/editors/vim-xaw/pkg/?sortby=log -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=boguerait&l=fr -http://www.medbulletin.com/scripts/medscape/jobsbystate.pl/diima00001/ND -http://ttz.soyou.edu.cn/tgyd/item/2000-05-31/3214.html -http://ttz.soyou.edu.cn/tgyd/item/2000-05-25/2973.html -http://ttz.soyou.edu.cn/tgyd/item/2000-05-23/2825.html -http://javatest.a-net.nl/servlet/pedit.Main/http://salon.com/tech/feature/2000/02/25/chatscan/ -http://javatest.a-net.nl/servlet/pedit.Main/http://www.wired.com/news/news/technology/story/20734.html -http://www.jps.net/fehlberg/diem9.html -http://chellobe.linux.tucows.com/x11html/adnload/9798_3876.html -http://chellobe.linux.tucows.com/x11html/preview/58190.html -http://internet.exit.de/akpolitik/Extern.htm -http://www.launch.com/music/albumpage/pvn_content/0,5258,163242_track,00.html -http://merumo.ne.jp/backno/i/00005163/20001001060103_024859.html -http://ftpsearch.belnet.be/mirrors/ftp.isc.org/pub/usenet/control/bc/?N=D -http://www-lehre.inf.uos.de/manuals/jdk1.2/docs/api/javax/swing/text/html/parser/class-use/Element.html -http://ftp.tku.edu.tw/OS/FreeBSD/ports/biology/deft/distinfo -http://javatest.a-net.nl/servlet/pedit.Main/http://www.cavejunction.com/phones/gower1.html -http://javatest.a-net.nl/servlet/pedit.Main/http://www.cavejunction.com/phones/contel1.html -http://www.allkorea.co.jp/cgi-bin/allkorea.front/972959966349/Catalog/1000002 -http://yp.gates96.com/5/82/41/1.html -http://yp.gates96.com/5/82/41/52.html -http://yp.gates96.com/5/82/41/59.html -http://yp.gates96.com/5/82/42/40.html -http://yp.gates96.com/5/82/42/73.html -http://yp.gates96.com/5/82/43/4.html -http://yp.gates96.com/5/82/43/20.html -http://yp.gates96.com/5/82/44/60.html -http://yp.gates96.com/5/82/44/95.html -http://yp.gates96.com/5/82/45/36.html -http://yp.gates96.com/5/82/45/43.html -http://yp.gates96.com/5/82/45/90.html -http://yp.gates96.com/5/82/46/37.html -http://yp.gates96.com/5/82/46/83.html -http://yp.gates96.com/5/82/47/22.html -http://yp.gates96.com/5/82/47/53.html -http://yp.gates96.com/5/82/48/8.html -http://yp.gates96.com/5/82/48/23.html -http://yp.gates96.com/5/82/48/41.html -http://yp.gates96.com/5/82/48/76.html -http://yp.gates96.com/5/82/49/5.html -http://yp.gates96.com/5/82/49/22.html -http://yp.gates96.com/5/82/49/37.html -http://yp.gates96.com/5/82/49/39.html -http://yp.gates96.com/5/82/49/65.html -http://yp.gates96.com/5/82/49/90.html -http://www.mirror.kiev.ua:8084/paper/1998/35/1251/power.htm -http://www.science.uva.nl/pub/NetBSD/NetBSD-current/pkgsrc/textproc/html/Makefile -http://www.fiss.at/1Root/Kontinent/6/Staat/7/Bundesland/16/Ort/708/Infrastruktur/7435/Homepage/homepage...1.html -http://linux.tnc.edu.tw/CPAN/authors/id/C/CH/CHOGAN/Apache-SetWWWTheme-1.02.readme -http://linux.tnc.edu.tw/CPAN/authors/id/C/CH/CHOGAN/Apache-SetWWWTheme-1.04.readme -http://linux.tnc.edu.tw/CPAN/authors/id/C/CH/CHOGAN/Apache-SetWWWTheme-1.05.readme -http://wufs.wustl.edu/vlander/vl_0002/browse/html/B0XX/22b090b4.htm -http://www.dnet.org/My_Locality/View_Statement.dnet/OH/43230-1863&SubjectItemID=6406&IssueID=47541&ElectionActivityID=4443&SubjectHolder=3462&type=Office&debate=yes -http://members.tripod.co.jp/suguruE/_private/ -http://members.tripod.lycos.nl/Kreeklaan/id19_cf.htm -http://forums.multimania.fr/general/login/login.phtml?_login=%2Flire%2Fjeuxvideospro%2Findex.phtml%3Fcollapse%3D1 -http://excite.de.netscape.com/jobs/katalog/30434 -http://excite.de.netscape.com/jobs/katalog/27370 -http://excite.de.netscape.com/jobs/katalog/127 -http://yp.gates96.com/2/54/20/79.html -http://yp.gates96.com/2/54/21/27.html -http://yp.gates96.com/2/54/22/14.html -http://yp.gates96.com/2/54/22/48.html -http://yp.gates96.com/2/54/22/78.html -http://yp.gates96.com/2/54/23/20.html -http://yp.gates96.com/2/54/23/62.html -http://yp.gates96.com/2/54/23/69.html -http://yp.gates96.com/2/54/24/1.html -http://yp.gates96.com/2/54/24/61.html -http://yp.gates96.com/2/54/24/95.html -http://yp.gates96.com/2/54/25/2.html -http://yp.gates96.com/2/54/25/16.html -http://yp.gates96.com/2/54/25/53.html -http://yp.gates96.com/2/54/25/67.html -http://yp.gates96.com/2/54/25/94.html -http://yp.gates96.com/2/54/26/3.html -http://yp.gates96.com/2/54/26/30.html -http://yp.gates96.com/2/54/26/65.html -http://yp.gates96.com/2/54/27/31.html -http://yp.gates96.com/2/54/27/41.html -http://yp.gates96.com/2/54/27/53.html -http://yp.gates96.com/2/54/27/71.html -http://yp.gates96.com/2/54/27/79.html -http://yp.gates96.com/2/54/27/80.html -http://yp.gates96.com/2/54/28/13.html -http://yp.gates96.com/2/54/28/14.html -http://yp.gates96.com/2/54/28/24.html -http://yp.gates96.com/2/54/28/34.html -http://yp.gates96.com/2/54/28/96.html -http://yp.gates96.com/2/54/29/49.html -http://ftp.sunet.se/pub/NT/mirror-microsoft/KB/Q134/3/40.TXT -http://members.tripod.com/joellogan/_cranedisc/000001d9.htm -http://members.tripod.com/joellogan/_cranedisc/000001cd.htm -http://www.ualberta.ca/CNS/RESEARCH/Software/SAS/vms/z-inf-zd.htm -http://www1.galaxy.com/galaxy/Leisure-and-Recreation/Games/Computer-Games/Titles/Virtual-Reality/Golf.html -http://www1.galaxy.com/galaxy/Leisure-and-Recreation/Games/Computer-Games/Titles/Virtual-Reality/Red-Planet.html -http://www.uni-duesseldorf.de/ftp/ftp/software/opt/zlib-1.1.2/?N=D -http://acbanks.know-where.com/acbanks/cgi/selection?place=Cavecreek&state=AZ -http://yp.gates96.com/10/26/70/49.html -http://yp.gates96.com/10/26/70/83.html -http://yp.gates96.com/10/26/72/40.html -http://yp.gates96.com/10/26/74/89.html -http://yp.gates96.com/10/26/75/15.html -http://yp.gates96.com/10/26/75/19.html -http://yp.gates96.com/10/26/76/87.html -http://yp.gates96.com/10/26/78/18.html -http://yp.gates96.com/10/26/78/76.html -http://yp.gates96.com/10/26/78/78.html -http://yp.gates96.com/10/26/78/81.html -http://cpan.nitco.com/modules/by-module/Devel/ADESC/Pod-DocBook-0.03.readme -http://www2.el-mundo.es/nuevaeconomia/2000/NE047/NE047-03b.html -http://www.familyeducation.com/whatworks/inappr_material/entry/1,2549,1-10119-1948-3469,00.html -http://ftp.nodomainname.net/pub/linux/daemons/raid/beta/ -http://192.80.57.161/corp/press/vannet.html -http://digilander.iol.it/mirkodeli/Stagioni/CI6_index.html -http://www.world-of-webs.de/magdeburg-in-bildern/_inhalt/_statnif/rechts/035.htm -http://ftpsearch.belnet.be/mirrors/src.doc.ic.ac.uk/usenet/usenet-by-hierarchy/rec/travel/?D=A -http://mirrortucows.technet.it/winme/netmiscme_rating.html -http://my.egroups.com/message/imperiumlarp/3148 -http://ep.com/js/about/c7857/b0/34551.html -http://webcrawler-sports.excite.com/ncaab/matchup/pafmax/ -http://www2.dbusiness.com/Quotes/1,1125,MSP_CORE,00.html?Ticker=CORE -http://tucows.wlink.com.np/regist95_size.html -http://www.babyheirlooms.com/catalog/htmlos.cat/041162.1.5960744054 -http://www.v2music.com/Scripts/WebObjects-ISAPI.dll/V2_New_Publisher.woa/71113000008423000000947720000021551/Labels.wo/168310000011551/1.0.1/3/Webobjects1 -http://www.v2music.com/Scripts/WebObjects-ISAPI.dll/V2_New_Publisher.woa/71113000008423000000947720000021551/Labels.wo/168310000011551/1.1.3.0.0/3/Webobjects1 -http://www.adcentral.com/cgi-bin/w3com/pws/adsites/vNhIXgVh_sji0rjcKc_GbuSlgBaEnCmKXU4ARmeefaqktCE3zwLsoXKDK_dlzoBzk2Ygr2cAuqN51PKOA0JxjzLEpPe-kic9TtvUJMbXG9Dlw8SggmHugQpwzjo-NiuofbUz4obq -http://ring.omp.ad.jp/archives/NetBSD/NetBSD-current/src/distrib/i386/floppies/ramdisk-big/Makefile -http://unofficial.capital.edu/students/alittle/ -http://213.36.119.69/do/session/153005/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/FR/reserver/promotions/promo9.html -http://213.36.119.69/do/session/153005/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/GB_EN/ -http://www.riello-hamburg.de/mSerieRSBLU_130_465kw.htm -http://tucows.knoware.nl/winnt/filesplitnt_license.html -http://www.kaos.dk/sex-riddle/k/a/k/i/n/h/b/b/ -http://www.kaos.dk/sex-riddle/k/a/k/i/n/h/b/c/ -http://caller-times.com/1999/july/13/today/national/3143.html -http://news.fm365.com/jiaoyu/20000804/113896.htm -http://variety.studiostore.com/browse/ILOVELUCY/CAP/b.FAVORITES%20NOSTALGI%20CLASTV%20ILOVELUCY/s.qyPsT2fz -http://www.ferien-immobilien.de/bayern/ingolstadt/Verkauf/Gemeinsam/Immolink/3d-service/Private-IB/Startseite/Gemeinsam/vertriebspartner.htm -http://jefferson.village.virginia.edu/wax/japanese/0front/cd/1/1a2a9a2.html -http://space.tin.it/scuola/ermenegh/thewall/il2.htm -http://www.maasvlakte-cam.nl/webcams/17/kremlin__moscou__russia/2000/02/29/?D=A -http://pub17.ezboard.com/fecilordsoflightgeneral.showMessage?topicID=211.topic -http://pub17.ezboard.com/fecilordsoflightgeneral.showMessage?topicID=214.topic -http://pub17.ezboard.com/fecilordsoflightgeneral.showMessage?topicID=210.topic -http://www.kaos.dk/sexriddle/x/u/e/s/p/ -http://www.kaos.dk/sexriddle/x/u/e/s/q/ -http://amc.hollywood.com/maltin/k/kellysheroes-1970.htm -http://amc.hollywood.com/maltin/k/kidsarealrightthe-1979.htm -http://amc.hollywood.com/maltin/k/killingofsistergeorgethe-1968.htm -http://amc.hollywood.com/maltin/k/kingandcountry-1964.htm -http://amc.hollywood.com/maltin/k/kinglear-1987.htm -http://amc.hollywood.com/maltin/k/kingofthezombies-1941.htm -http://amc.hollywood.com/maltin/k/kingqueenknave-1972.htm -http://amc.hollywood.com/maltin/k/kissthe-1988.htm -http://www.egroups.com/login.cgi?login_target=%2Fgroup%2Ft-ida -http://polygraph.ircache.net:8181/faculty/http_-2www.stopwaste.org/freecontent.html -http://kutschen.de/Schoner/literature/Literatur/models/collections/ -http://www.incestpornstories.com/cum-sex-pics/anal-sexone-night-stand/big-bonedpleasantly-plump/smallwomen/{hardcorelink} -http://www.nytimes.com/library/financial/102897market-turmoil.html -http://polygraph.ircache.net:8181/services/define/http_-2www.microsoft.com/ie/http_-2www.ci.alameda.ca.us/main_left.html -http://polygraph.ircache.net:8181/services/define/http_-2www.microsoft.com/ie/http_-2www.ci.alameda.ca.us/dream.htm -http://www.chiayi.gob.tw/ -http://www.maas.ccr.it/cgi-win/hiweb.exe/a17/d77/b77,c,4d,51,51,df1,df1,,4e,2b62,4d,4e,2b62,, -http://citeseer.nj.nec.com/cidcontext/6361 -http://citeseer.nj.nec.com/cidcontext/6456 -http://utenti.tripod.it/Psychozine/Grunge/Creed_MyOwnPrison.htm -http://tucows.multiweb.net/winme/adnload/138210_30315.html -http://tucows.multiweb.net/winme/adnload/138190_29551.html -http://tucows.multiweb.net/winme/adnload/138218_29576.html -http://tucows.multiweb.net/winme/preview/138219.html -http://playsky.home.chinaren.com/star_region/11.htm -http://tucows.phnet.fi/winme/adnload/137614_29054.html -http://www.fortunecity.com/millennium/blyton/118/www.bih.net.ba/~sda -http://www11.informatik.tu-muenchen.de/lehre/lectures/ws2000-01/hypermedia/extension/html-kurz/hm2.2.4.2-navigation.html -http://ads.puntopartenza.com/cgi-bin/redirect.cgi/31033737 -http://www.eud.com/1997/03/20/20324A.shtml -http://ftp.net.uni-c.dk/pub/linux/mandrake/i586/Mandrake/mdkinst/usr/share/locale/gl/?N=D -http://no.sport.yahoo.com/s/snowboard-1.html -http://www.egroups.com/login.cgi?login_target=%2Fmessages%2Fshamanism%2F1311 -http://yp.gates96.com/5/82/70/13.html -http://yp.gates96.com/5/82/70/74.html -http://yp.gates96.com/5/82/71/30.html -http://yp.gates96.com/5/82/71/44.html -http://yp.gates96.com/5/82/72/22.html -http://yp.gates96.com/5/82/72/72.html -http://yp.gates96.com/5/82/72/88.html -http://yp.gates96.com/5/82/73/60.html -http://yp.gates96.com/5/82/73/79.html -http://yp.gates96.com/5/82/74/21.html -http://yp.gates96.com/5/82/74/59.html -http://yp.gates96.com/5/82/74/62.html -http://yp.gates96.com/5/82/74/75.html -http://yp.gates96.com/5/82/74/78.html -http://yp.gates96.com/5/82/75/30.html -http://yp.gates96.com/5/82/75/32.html -http://yp.gates96.com/5/82/75/82.html -http://yp.gates96.com/5/82/76/16.html -http://yp.gates96.com/5/82/76/43.html -http://yp.gates96.com/5/82/76/72.html -http://yp.gates96.com/5/82/77/48.html -http://yp.gates96.com/5/82/77/99.html -http://yp.gates96.com/5/82/78/73.html -http://yp.gates96.com/5/82/79/28.html -http://yp.gates96.com/5/82/79/70.html -http://yp.gates96.com/5/82/79/83.html -http://polygraph.ircache.net:8181/http_-2www.microsoft.com/ie/http_-2www.petrophysics.com/http_-2www.uio.no/~thomas/lists/info.html -http://www.munster-express.ie/000623/sports1.htm -http://cisne.sim.ucm.es/search*spi/aThiollier,+François-Joël,+int./athiollier+francois+joel+int/-5,-1,0,B/marc&F=athion+soriano+molla+dolores&2,,2 -http://www.zjdaily.com.cn/gb/2000/10/05/zjrb0625/guoji/6.htm -http://commerce.was-inc.com/cgi-bin/abtwsam.dll/LbkWebCommerceStoreCategories-BBC70A38_9815_E7A26CDF19A4AB167DD4B69EFB5B17FC -http://commerce.was-inc.com/cgi-bin/abtwsam.dll/LbkWebCommerceUserProfile-BBC70A38_9815_E7A26CDF19A4AB167DD4B69EFB5B17FC -http://www.shopworks.com/tools/index.cfm/action/search/userid/0003875B-2E5B-19FE-AF65010C0A0A8CF2 -http://www.doofpot.nl/~lists/bugtraq/October-99/frm00087.html -http://shop.citde.net/b79923.htm -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=divinizzarono&l=it -http://pub8.ezboard.com/fwrestlecarwwf.showAddReplyScreenFromWeb?topicID=38.topic -http://amrr.com/agents/contact.html?Agents_id=4046 -http://www.intellicast.com/LocalWeather/World/UnitedStates/Southeast/NorthCarolina/CarolinaBeach/RAINcast/d1_12/bannerAd.shtml -http://www.ferien-immobilien.de/schleswig-holstein/nordfriesland/Verkauf/Gemeinsam/versicherungen/gebaeude/Allgemeine-IB/IIM-Teil/Startseite/Gemeinsam/Inserieren/inserieren.htm -http://www.ferien-immobilien.de/schleswig-holstein/nordfriesland/Verkauf/Gemeinsam/versicherungen/gebaeude/Allgemeine-IB/IIM-Teil/Startseite/Gemeinsam/feedback.html -http://de.excite.com/jobs/katalog/10349 -http://pub16.ezboard.com/frealitycheck95307youadoreus.showAddReplyScreenFromWeb?topicID=33.topic -http://www.maas.ccr.it/cgi-win/hiweb.exe/a17/d2424/b77,e,4d,51,51,df1,df1,,978,,51,978,815,,51,815, -http://dk.egroups.com/message/noholdsbarred/2138 -http://kr.news.yahoo.com/headlines/so/20001029/hankook/2000102919513187338.html -http://www.buybuddy.com/sleuth/27/1/11002/508910/ -http://yp.gates96.com/13/95/50/10.html -http://yp.gates96.com/13/95/50/47.html -http://yp.gates96.com/13/95/51/16.html -http://yp.gates96.com/13/95/51/17.html -http://yp.gates96.com/13/95/51/21.html -http://yp.gates96.com/13/95/51/76.html -http://yp.gates96.com/13/95/53/5.html -http://yp.gates96.com/13/95/54/17.html -http://yp.gates96.com/13/95/54/44.html -http://yp.gates96.com/13/95/54/67.html -http://yp.gates96.com/13/95/54/80.html -http://yp.gates96.com/13/95/55/67.html -http://yp.gates96.com/13/95/56/15.html -http://yp.gates96.com/13/95/56/91.html -http://yp.gates96.com/13/95/57/9.html -http://yp.gates96.com/13/95/57/12.html -http://yp.gates96.com/13/95/57/24.html -http://yp.gates96.com/13/95/57/30.html -http://yp.gates96.com/13/95/57/46.html -http://yp.gates96.com/13/95/58/38.html -http://yp.gates96.com/13/95/58/52.html -http://yp.gates96.com/13/95/58/80.html -http://yp.gates96.com/13/95/59/40.html -http://yp.gates96.com/13/95/59/78.html -http://ftp.net.uni-c.dk/pub/linux/mandrake/i586/Mandrake/mdkinst/usr/share/locale/gv/?S=A -http://home.swipnet.se/~w-10458/sksida.htm -http://www.irishnews.com/k_archive/260799/nnews14.html -http://dennou-q.geo.kyushu-u.ac.jp/library/Linux/debian-jp/dists/potato-jp/contrib/binary-all/admin/?M=A -http://ayasii.virtualspace.net/html/1104/11041141_syuuei_yosimi008.htm -http://ayasii.virtualspace.net/html/1104/11041104_nakamura_yuma_2_027.htm -http://kikakusvr3.city.yokohama.jp/yhspot/ysc/prelaunch.html -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=0,1-20,0-9,1-9,2 -http://209.52.189.2/discussion.cfm/disco_music/7738/79749 -http://www.du-et.net/cgi/mail.cgi?NickName=coota -http://ustlib.ust.hk/search*chi/a%7B214c7d%7D%7B213837%7D%7B213c44%7D%7B213779%7D%7B214267%7D%7B21586d%7D%7B21515b%7D%7B21517c%7D%7B213966%7D/a{214c7d}{213837}{213c44}{213779}{214267}{21586d}{21515b}{21517c}{213966}/7,-1,0,B/browse -http://user.alpha.co.kr/~backspin/CGI-BIN/upload/files/ -http://194.174.50.23/cgi-bin/FisRun/InsertExhibitorIntoNotebook/1/interpack99/e/1217 -http://www.paxcapital.com/news/datacenter/200010/27/20001027180508_01.shtml -http://www.paxcapital.com/news/datacenter/200010/27/20001027175828_07.shtml -http://www.paxcapital.com/news/datacenter/200010/27/20001027173309_53.shtml -http://www.paxcapital.com/news/datacenter/200010/27/20001027165004_52.shtml -http://genforum.genealogy.com/cgi-bin/print.cgi?lantz::325.html -http://mirror.cc.utsunomiya-u.ac.jp/mirror/FreeBSD/ports/alpha/packages-current/x11-toolkits/?D=A -http://hotop.on.net.cn/diguo/club/disp.asp?owner=A205&ID=914 -http://www.babyheirlooms.com/catalog/htmlos.cat/041137.1.3501106310 -http://debian.linux.org.tw/debian/dists/frozen/non-free/binary-m68k/mail/?N=D -http://cafe5.daum.net/Cafe-bin/Cafe.cgi/member?cafe=LOTTEcleaning -http://www-d0.fnal.gov/cgi-bin/cvsweb.cgi/root_gui/data/?sortby=date -http://www.concentric.net/~Psaros/DbzUncensored/editorial/edit06-07-98.html -http://www.jobvillage.com/channel/jobs/travel/travel_guide/b.4897.g.5093.html -http://www.jobvillage.com/channel/jobs/travel/travel_guide/b.4897.g.5070.html -http://www.cricket.org/link_to_database/ARCHIVE/1999/OTHERS+ICC/NL_LOCAL/EERSTEKL/VCC_ASIAN-SHAH_EERSTEKL_16MAY1999.html -http://health.phinfo.sc.cn/navigator/illness_treatment/diseases_conditions/bone_diseases/spinal_column_injury/default.htm -http://cn.egroups.com/message/dfwscan/1412 -http://www.babyheirlooms.com/catalog/htmlos.cat/001255.1.1999922108 -http://ibm1.cicrp.jussieu.fr/ibmc/classref/ref/UFullStopNumber_DSC.htm -http://pda.tucows.fi/palm/adnload/33651_21862.html -http://www.fogdog.com/cedroID/ssd3040183330232/nav/products/nhl/chicago_blackhawks/fan/gender/fashion_polo_shirts/ -http://www.fogdog.com/cedroID/ssd3040183330232/nav/products/nhl/chicago_blackhawks/fan/gender/nylon_jackets/ -http://www.5a8.com/book/wg/zpj/d/delaisai/mgbj/004.htm -http://www.5a8.com/book/wg/zpj/d/delaisai/mgbj/050.htm -http://jars.developer.com//classes/jresout.cgi?resource=1133 -http://dwp.bigplanet.com/billbritton/files/edit.nhtml -http://members.tripod.co.jp/snow4/?D=A -http://www.lanoticia.com.ni/cronologico/2000/julio/15sabado/capital/capital5.html -http://mayu.sourceforge.net/cgi-bin/nph-ml.cgi/000/http/www.geocrawler.com/archives/3/151/1996/4/0/870960/ -http://mayu.sourceforge.net/cgi-bin/nph-ml.cgi/000/http/www.geocrawler.com/archives/3/151/1996/4/0/870950/ -http://ftp.ccu.edu.tw/pub/packages/dns/bind/src/8.1.1/ -http://www.chez.com/photographies/photos/paysage/page8.htm -http://www.ayto-malaga.es/Organismos/Urbanismo/PGMOM/Hojas/calificacion/3/47/34734.htm -http://www.symatrixinc.com/website/website.nsf/0/3e40df86fb357cd5882568720079613f!OpenDocument&ExpandSection=3,24,5,18 -http://www.symatrixinc.com/website/website.nsf/0/3e40df86fb357cd5882568720079613f!OpenDocument&ExpandSection=9,24,5,18 -http://variety.studiostore.com/browse/STARWARSTRIL/PHOTO/b.MOVIES%20STARWARSSAGA%20STARWARSTRIL/s.5FhZToe4 -http://www.stud.ntnu.no/~kjonigse/pod/ -http://eastday.com/epublish/gb/paper10/20001025/class001000011/hwz225792.htm -http://eastday.com/epublish/gb/paper10/20001025/class001000011/hwz225253.htm -http://www.jamba.de/KNet/_KNet-KdS8j1-IHd-13g8y/browse.de/node.0/cergpnwyt -http://www.la-verdad.com/pg000828/suscr/primera.htm -http://www.centc251.org/forums/aca-1/dispatch.cgi/hsi/listUnseen/fol/100020/20,0/1338881 -http://ftp.du.se/disk4/FreeBSD/ports/ports/japanese/libicq/pkg-comment -http://www.geocities.com/SunsetStrip/Towers/2395/ -http://www.geocities.com/joanna_luo -http://www.geocities.com/eric_wang_tafe -http://www.geocities.com/shsugiharto -http://wynnsystems.com/79I_5ase/seek/modifyUser.html -http://www.uk.cricket.org/link_to_database/INTERACTIVE/REVIEWS/BOOKS/barry14.html -http://perso.wanadoo.fr/alain.falgas/poesie1.htm -http://www.linux.com/networking/network/windows_nt/support/tools/SAP/ -http://www.rdnet.nl/provstaten1999/491ps.html -http://www.thisislancashire.co.uk/lancashire/archive/1998/03/19/FEATURES3VQ.html -http://myhome.naver.com/myclass46 -http://www.bride.ru/htcgi/ladies/in-26-30/index3.html -http://www.internet-verzeichnis.de/branchen/schuhreparaturen/nordrhein-westfalen/ -http://dk.egroups.com/post/SonyMavica?act=reply&messageNum=3370 -http://www.sneezy.org/Databases/Composers/Instrumentation/008889.html -http://www.sneezy.org/Databases/Composers/Instrumentation/009161.html -http://fatema2.math.nat.tu-bs.de/doc/sdb/de/html/keylist.LARGEEBDA.html -http://ssb.no/kommuner/hoyre_side.cgi?region=1931 -http://www.egroups.com/subscribe/mentemalata -http://www.debian.org.cn/Bugs/db/67/67056-b.html -http://dk.egroups.com/message/ssrdistribution/775?source=1 -http://link.fastpartner.com/do/session/600429/vsid/2870/tid/2870/cid/136966/mid/1060/rid/1926/chid/2870/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/shopnett.php -http://ftp.uk.debian.org/debian/dists/stable/main/binary-arm/text/?D=A -http://www.bemi-immobilien.de/IIM-Teil/Startseite/Top-Darlehens-Konditionen/Gemeinsam/3d-service/Startseite/Gemeinsam/erreichenPartner/Top-Darlehens-Konditionen/anforderungsformular.htm -http://www.fujian-window.com/Fujian_w/news/mdrb/000816t/1_4.html -http://scholar.lib.vt.edu/VA-news/WDBJ-7/script_archives/98/0798/070498/?D=A -http://polygraph.ircache.net:8181/services/define/html/President.asp -http://old-maps.co.uk/10lancs191/HTML/nav_19034001g.htm -http://www.hanter21.co.kr/NetBBS/Bbs.dll/prdata/lst/qqa/f/qqo/000D/zka/B2-kB2-r -http://w3.webtourist.net/travel/europe/italy/milan/quarkallsuites.htm -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=9,5+0,0-9,6-0,1 -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=brillantant&l=fr -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=brillantais&l=fr -http://www.mathquest.com/~sarah/HTMLthreads/geopre.descriptions.html -http://www.retrobytes.org/classiccmp/9706/msg00827.html -http://www.retrobytes.org/classiccmp/9706/msg01408.html -http://www.rdnet.nl/provstaten1999/552ps.html -http://retailer.gocollect.com/do/session/1912828/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/checkout/shopping_cart.asp -http://retailer.gocollect.com/do/session/1912828/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/exclusives/limited_editions.asp -http://retailer.gocollect.com/do/session/1912828/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/company_info/privacy_policy.asp -http://de.news.yahoo.com/000322/36/nfqj.html -http://www.kl.gz.cn/~cco/FUNA022K.htm -http://www.launch.com/music/artistpage/pvn_content/0,5219,1013738_videos,00.html -http://www14.freeweb.ne.jp/play/kiryuus/keith-burn1-end.htm -http://variety.studiostore.com/help/b.MOVIES%20STARWARSSAGA%20STARWARSTRIL/s.BmesFhV7 -http://biblioteca.upv.es/bib/doc/doc_siglibros/1828105/26/25/////MLTPAID/Materia%20Lengua%20inglesa%20técnica:%20254/V -http://www.outpersonals.com/cgi-bin/w3com/pws/out/_AhIPkFr0_eq7P6TUMbkQGJgpHJOXqtNLZQ55qFmeZARJaJUKHP9RBX3tPWaLEWVLZ_-PAErnbukTTJzs-x0hew4G_r3S85M8fDFaJcIVi3EA4TxNjTbbGIaSLhr8VdNICuBwhPmgZEt662B -http://www.outpersonals.com/cgi-bin/w3com/pws/out/IxhI6dPotFAZDugwPbV2pjvsgvIvAP-oFtIZfMptEKMo48cUO8RmvG3Akuk2tktzM_RYBY3yIQE6nl7I2moLEV_nScO7wTfWpFfPR7LHZ3ntJxKS8-a_IukWT4q_o6mjhGw8SSwm -http://www.rge.com/pub/languages/perl/clpa/1995-11/171 -http://www.rge.com/pub/languages/perl/clpa/1995-11/186 -http://www.newmgm.com/cgi-bin/c2k/title_talent.html&id=146091&title_star=FOURFEAT -http://www.koreaweekly.co.kr/entertain/book/200009/en20000922185938E701133.htm -http://www.koreaweekly.co.kr/entertain/book/200008/en20000824183337E701112.htm -http://www.genome.wustl.edu:8021/pub/gsc10/nci/wl/wl72/?N=D -http://yp.gates96.com/13/50/70/33.html -http://yp.gates96.com/13/50/70/36.html -http://yp.gates96.com/13/50/70/53.html -http://yp.gates96.com/13/50/71/74.html -http://yp.gates96.com/13/50/72/13.html -http://yp.gates96.com/13/50/72/17.html -http://yp.gates96.com/13/50/72/83.html -http://yp.gates96.com/13/50/73/48.html -http://yp.gates96.com/13/50/73/79.html -http://yp.gates96.com/13/50/73/96.html -http://yp.gates96.com/13/50/74/14.html -http://yp.gates96.com/13/50/74/57.html -http://yp.gates96.com/13/50/75/13.html -http://yp.gates96.com/13/50/75/19.html -http://yp.gates96.com/13/50/75/30.html -http://yp.gates96.com/13/50/75/42.html -http://yp.gates96.com/13/50/75/53.html -http://yp.gates96.com/13/50/75/90.html -http://yp.gates96.com/13/50/77/45.html -http://yp.gates96.com/13/50/77/51.html -http://yp.gates96.com/13/50/77/79.html -http://yp.gates96.com/13/50/78/12.html -http://yp.gates96.com/13/50/78/47.html -http://yp.gates96.com/13/50/78/69.html -http://yp.gates96.com/13/50/78/96.html -http://www.tel.de/s/M/MSS.htm -http://linux.usu.edu/LDP/LDP/LG/issue23/shoham/node4.html -http://www.monaco.gouv.mc/dataweb/gouvmc.nsf/(NewsActu)/d28eaee29b3287d4c1256905004e1ef1!OpenDocument&ExpandSection=9,3,10.1,7,10.4,10.2,5,8,4 -http://fi.egroups.com/post/romtrade?act=reply&messageNum=5198 -http://www.outpersonals.com/cgi-bin/w3com/pws/out/erhIHCd-6X--WwWIQBR9tYYraJWo8ugur0GyAl8pg21sE-lotAURKodv9HAYnRuTT4ZM0aCKsA5ZVLlq8sgiFNqA4DyAY_GVTyPIEARrzArj8JrWabVCSpg03afQ_Xg3DaCQA17080y7T4EZ -http://oneplace.adbureau.net/accipiter/adclick/site=ONEPLACE/area=INDEX/POSITION=BLOCK_1/AAMSZ=120x90/ACC_RANDOM=619055616855 -http://cafe6.daum.net/Cafe-bin/Bbs.cgi/MyLoveNYpds/qry/zka/B2-kB23m/qqatt/^ -http://cafe6.daum.net/Cafe-bin/Bbs.cgi/MyLoveNYpds/qry/zka/B2-kB2-s/qqatt/^ -http://sas.uoregon.edu/sashtml/proc/z0292518.htm -http://www02.geocities.co.jp/PowderRoom-Rose/1346/flower02image.html -http://www02.geocities.co.jp/PowderRoom-Rose/1346/sozaiheart2.html -http://www.jamba.de/KNet/_KNet-sXN8j1-9Hd-13ej3/admLogin.de/node.0/cdn3r3qy3 -http://iccardreader.co.kr/ -http://online.linux.tucows.com/conhtml/ser_irc_size.html -http://www.fogdog.com/cedroID/ssd3040183339940/nav/products/winter_sports/1b/bibs/ -http://www.fogdog.com/cedroID/ssd3040183339940/nav/products/winter_sports/1c/jackets/ -http://www.fogdog.com/cedroID/ssd3040183339940/nav/products/winter_sports/1d/heavyweight_tops/ -http://www.affiliate.hpstore.hp.co.uk/do/session/380883/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/assistance/entry.asp -http://www.kaos.dk/sex-riddle/k/a/k/i/l/y/t/c/ -http://www.kaos.dk/sex-riddle/k/a/k/i/l/y/t/o/ -http://ftp1.se.debian.org/debian/dists/stable/main/disks-alpha/2.2.8-2000-03-08/jensen/ -http://213.36.119.69/do/session/153006/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/FR/contact/recrute.htm -http://www10.freeweb.ne.jp/photo/myukun2/cosplay/000130/0130_40.htm -http://l-infonet.phkk.fi/fi/TIETOPALVELUT/JULKINEN+HALLINTO/tiedonhaku/artikkelit/hakupalvelut/l%E4%E4ketiede/tietokannat/ -http://202.109.72.57/article/20000903/67099.htm -http://www.outpersonals.com/cgi-bin/w3com/pws/out/5xhIsrJ5LBhn_gBogN2-VgQ1DA6WvBlLMjSoxYeQAJ1ig69sK1i1DhQ5hA3iOw7y6Wb_HDA2rkG5aJy9DrUMZxD31cyUqEqg7LeZ3pssb70DsyPc1sGCTVIRFBz1Nb_1ikEcJ3ds -http://ftp.gwdg.de/pub/misc/standards/infomagic/nist/oiw/agreemnt/read_me.txt -http://linuxberg.arrakis.es/conhtml/adnload/8894_17109.html -http://ring.toyama-ix.net/archives/pc/winsock-l/WWW-Browsers/Plug-In/ppp16124.txt -http://opac.lib.ntnu.edu.tw/search*chi/++ftlist/bp20040288/-5,-1,0,B/frameset&F=bp20040286&1,1 -http://ftp.darenet.dk/tucows/winme/adnload/137475_28966.html -http://ftp.darenet.dk/tucows/winme/adnload/137525_29009.html -http://elib.zib.de/pub/UserHome/Mueller/Course/Tutorial/Postscript/US/?M=A -http://greenpeace.lu/Admin/usage/weekly/1999/01/03/ -http://greenpeace.lu/Admin/usage/weekly/1998/04/26/ -http://greenpeace.lu/Admin/usage/weekly/1998/08/16/ -http://greenpeace.lu/Admin/usage/weekly/1997/10/12/ -http://retailer.gocollect.com/do/session/1912819/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/clubhouse/index.asp -http://www.kusastro.kyoto-u.ac.jp/LCs/index/AURAU.html -http://www.linux.com/networking/network/windows_nt/support/microsoft/Red_Hat/ -http://www.linux.com/networking/network/windows_nt/support/microsoft/operating_system/ -http://www.linux.com/networking/network/windows_nt/support/microsoft/SAP/ -http://www.linux.com/networking/network/windows_nt/support/microsoft/Unix/ -http://www.linux.com/networking/network/windows_nt/support/microsoft/pop-3/ -http://www.cs.rit.edu/photo_album/smr3632.html -http://www.cpan.dk/CPAN/modules/by-authors/id/C/CH/CHRMASTO/?D=A -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/computers/lit/misc/unitest/lit/music/midi/ego.html -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/computers/lit/misc/unitest/lit/music/midi/lit/multiple.html -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/computers/lit/misc/unitest/lit/music/midi/misc/dissert.html -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/computers/lit/misc/unitest/lit/music/midi/misc/peanuts.html -http://www.eastsidejournal.com/sited/retr_story.pl/25409 -http://yp.gates96.com/8/46/50/23.html -http://yp.gates96.com/8/46/52/6.html -http://yp.gates96.com/8/46/52/10.html -http://yp.gates96.com/8/46/52/18.html -http://yp.gates96.com/8/46/52/25.html -http://yp.gates96.com/8/46/53/78.html -http://yp.gates96.com/8/46/53/95.html -http://yp.gates96.com/8/46/54/26.html -http://yp.gates96.com/8/46/54/41.html -http://yp.gates96.com/8/46/54/64.html -http://yp.gates96.com/8/46/54/76.html -http://yp.gates96.com/8/46/54/92.html -http://yp.gates96.com/8/46/55/62.html -http://yp.gates96.com/8/46/55/94.html -http://yp.gates96.com/8/46/55/98.html -http://yp.gates96.com/8/46/56/19.html -http://yp.gates96.com/8/46/56/42.html -http://yp.gates96.com/8/46/56/86.html -http://yp.gates96.com/8/46/58/53.html -http://yp.gates96.com/8/46/58/57.html -http://yp.gates96.com/8/46/59/41.html -http://yp.gates96.com/8/46/59/44.html -http://yp.gates96.com/8/46/59/84.html -http://yp.gates96.com/8/46/59/99.html -http://www.158.com.cn/news/2000/09/03/58946.htm -http://www.pobladores.com/territorios/juegos/Shanodin/pagina/2 -http://www.otemachi.ibm.co.jp/pc/vlp/ca20/32l9068/price.html -http://www.gutenberg2000.de/lessing/sinnged/sinna10.htm -http://www.gutenberg2000.de/lessing/sinnged/sinn138.htm -http://www.gutenberg2000.de/lessing/sinnged/sinnc27.htm -http://www.gutenberg2000.de/lessing/sinnged/sinnc06.htm -http://calcul.si.uji.es/Programes/SAS/stat/chap4/sect5.htm -http://calcul.si.uji.es/Programes/SAS/stat/chap4/sect6.htm -http://link.fastpartner.com/do/session/600436/vsid/3194/tid/3194/cid/137201/mid/1060/rid/2105/chid/3194/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/learn.htm -http://www.linux.com/networking/network/red_hat/performance/workstations/business/ -http://ftp.dei.uc.pt/pub/faqs/backrubs/faq/?D=A -http://www2.el-mundo.es/nuevaeconomia/2000/NE022/NE022-16b.html -http://ring.toyama-ix.net/pub/linux/linuxppc-jp/2.0/UsersGuide/?N=D -http://www.egroups.com/message/swchicks-rpg/763 -http://webraft.its.unimelb.edu.au/705195/students/caitlinb/pub/?N=D -http://cn.egroups.com/message/indexinvesting/17 -http://networkdesigner.subportal.com/sn/Programming/Setup_Utilities/11753.html -http://www.imagestation.com/member/?name=Mermaid34v&c=1 -http://crn.com/Components/TalkBack/tb-read.asp?ArticleId=8463 -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/lit/misc/lit/computers/music/linux/misc/thoughts/turingtest.html -http://www.egroups.com/message/house_caliburnus/1479 -http://pub14.ezboard.com/BBSForum.showForumSearch?boardName=bleemtest -http://spaceports.tucows.com/winme/adnload/136943_28461.html -http://www.cerent.com/warp/public/767/spcl/vaccess/req-lab.html -http://www.ualberta.ca/icons/icons/numbers/Big-orange-thin/ -http://www.gencat.es/cgi-bin/bc/drawer.cgi/LD/0004/A00027?98 -http://interhotel.com/romania/en/hoteles/49235.html -http://www.infoscape.com.cn:8171/nf/0001/19/nfzx1908.htm -http://www.hurriyetim.com/akdeniz/turk/00/05/25/akdhab/62akd.htm -http://www.hurriyetim.com/akdeniz/turk/00/05/25/akdhab/38akd.htm -http://dennou-t.ms.u-tokyo.ac.jp/arch/cc-env/Linux/debian-jp/dists/woody-jp/contrib/binary-ia64/misc/?M=A -http://www.angelfire.com/vt/Mystical2 -http://www.indonesiansources.com/HELP/COOKIES.HTM -http://members.nbci.com/cmeadows/gvi/45regt/45gvibat.html -http://members.nbci.com/cmeadows/gvi/45regt/45gvicob.html -http://landview.census.gov/hhes/www/housing/soma/char96/ch96tab5.html -http://www.legis.state.pa.us/WU01/LI/BI/TI/1985/0/MNPENNSYLVANIAdENERGYdASSISTANCEdANDdCONSERVATIONdACT.HTM -http://www.legis.state.pa.us/WU01/LI/BI/TI/1985/0/MNPENNSYLVANIAdSEWAGEdFACILITIESdACT.HTM -http://www.legis.state.pa.us/WU01/LI/BI/TI/1985/0/MNPODIATRYdPRACTICEdACT.HTM -http://www.legis.state.pa.us/WU01/LI/BI/TI/1985/0/MNPRESIDENT.HTM -http://www.legis.state.pa.us/WU01/LI/BI/TI/1985/0/MNPRIVATEdMORTGAGEdINSURANCEdACT.HTM -http://www.legis.state.pa.us/WU01/LI/BI/TI/1985/0/MNPROJECTd500.HTM -http://www.legis.state.pa.us/WU01/LI/BI/TI/1985/0/MNPUBLICdWORKSdCONTRACTdREGULATIONdLAW.HTM -http://oss.sgi.com/cgi-bin/cvsweb.cgi/inventor/apps/samples/4view/Attic/Imakefile?only_with_tag=MAIN -http://oss.sgi.com/cgi-bin/cvsweb.cgi/inventor/apps/samples/4view/Attic/Imakefile?only_with_tag=HEAD -http://www4.50megs.com/justiceinn/charpages/leaves/707.html -http://www4.50megs.com/justiceinn/charpages/leaves/859.html -http://www4.50megs.com/justiceinn/charpages/leaves/171.html -http://www4.50megs.com/justiceinn/charpages/leaves/114.html -http://megalink.tucows.com/win2k/adnload/38582_28844.html -http://members.tripod.lycos.nl/monthlysports/hello_and_welkom_at_the_new.htm -http://coe.ier.hit-u.ac.jp/BibEc/data/Papers/nbrnberwo4558.html -http://coe.ier.hit-u.ac.jp/BibEc/data/Papers/nbrnberwo4462.html -http://coe.ier.hit-u.ac.jp/BibEc/data/Papers/nbrnberwo4813.html -http://pub4.ezboard.com/factiveprodiscussioncommunityhottopicsresidentsandalcohol.showMessage?topicID=3.topic -http://207.138.41.133/subscribe/IndoVStudio -http://www.biuemountain.com/eng3/karen/EArejoice.html -http://polygraph.ircache.net:8181/wwwboard/capabilities/http_-2www.westnebr.net/http_-2www.excite.com/grservic.htm -http://pub7.ezboard.com/fturonneuemissionennebenwerteundsonstigewerte.showAddReplyScreenFromWeb?topicID=58.topic -http://dk.egroups.com/post/badbart-showdown?act=forward&messageNum=679 -http://www.kfi640.com/shared/mod_perl/looksmart/looksmart/eus1/eus62920/eus62921/eus64894/eus170276/eus163832/ -http://www.algonet.se/~d88628/engelsk/various.htm -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=220&discrim=220,215,11 -http://www.z-plus.de/TEXTE/INETCO/AUSG20000524/text7.html -http://www.gbnf.com/genealog2/varner/html/d0059/I11636.HTM -http://www.musiciansfriend.com/ex/ds/live/001030183152064208037007463633 -http://www.musiciansfriend.com/ex/ds/home/001030183152064208037007463633?dbase=info,order_info.html -http://www.musiciansfriend.com/ex/ds/guitar/amps/001030183152064208037007463633?dbase=info,contact.html -http://pix.egroups.com/message/ipe/1642?source=1 -http://213.36.119.69/do/session/153008/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://resa.travelprice.com/CallCenter/InitCommunicationAgence -http://213.36.119.69/do/session/153008/vsid/1113/tid/1113/cid/28507/mid/1020/rid/1041/chid/1103/parser/yes/imref/eqqLmwlGltt5tkqHoXsLbimLofZLbkZHljlK6IlK/url/http://www.travelprice.com/DE_DE/ -http://www.egroups.com/message/peninsulaserv/567 -http://www.scifi.com/bboard/browse.cgi/1/5/545/12425?pnum=3 -http://no.egroups.com/post/icc-info?act=reply&messageNum=759 -http://www.chaos.dk/sexriddle/s/e/x/e/c/s/l/ -http://www.chaos.dk/sexriddle/s/e/x/e/c/s/t/ -http://www.nissan.co.jp/RENAULT-DEALERS/PASSPORT/view.cgi/search/972959630-- -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=6,29,20,36,32 -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=7,29,20,36,32 -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=27,29,20,36,32 -http://dada.linuxberg.com/gnomehtml/adnload/31471_2540.html -http://augustasports.com/football99/college/box_50347.shtml -http://augustasports.com/football99/college/box_50365.shtml -http://augustasports.com/football99/college/box_50423.shtml -http://www.linux.com/networking/network/enterprise/e-commerce/management/open_source/ -http://usol.pdacentral.com/winnt/preview/1946.html -http://usol.pdacentral.com/winnt/preview/78287.html -http://usol.pdacentral.com/winnt/preview/1338.html -http://usol.pdacentral.com/winnt/preview/12860.html -http://usol.pdacentral.com/winnt/preview/6920.html -http://usol.pdacentral.com/winnt/preview/51381.html -http://ring.htcn.ne.jp/pub/lang/perl/CPAN/authors/id/W/WO/?N=D -http://grybrd.subportal.com/sn/Network_and_Internet/Text_Chat_Clients/index1.html -http://www.gurlpages.com/lacej/part13.html -http://ring.shibaura-it.ac.jp/archives/mac/info-mac/game/com/wolf/?D=A -http://cgi.cnnsi.com/baseball/mlb/nl/gamelog/2000/10/07/mets_giants/ -http://my.egroups.com/messages/not_honyaku/236 -http://members.tripod.com/agran_gassendi/Countdown.htm -http://www.tccomputers.com/cgi-bin/bp/1878637479/showcase/showcase.htm -http://207.138.41.133/message/AikensTrivia/264 -http://207.138.41.133/message/AikensTrivia/276 -http://www.shumway.org/thetree/ped13583.htm -http://link.fastpartner.com/do/session/600421/vsid/2870/tid/2870/cid/136966/mid/1060/rid/1926/chid/2870/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/dk/ -http://link.fastpartner.com/do/session/600421/vsid/2870/tid/2870/cid/136966/mid/1060/rid/1926/chid/2870/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/politiken.php -http://link.fastpartner.com/do/session/600421/vsid/2870/tid/2870/cid/136966/mid/1060/rid/1926/chid/2870/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/company/jobs.htm -http://in.egroups.com/message/canada/856 -http://in.egroups.com/message/canada/883 -http://debian.tod.net/OpenBSD/src/lib/libssl/README.OPENBSD -http://www.emerchandise.com/main/EMERCH/s.1M38gYrZ -http://www.emerchandise.com/browse/TOYSTORY2/FIGURINE/b.FAVORITES%20COMICS%20ANIMFEAT%20TOYSTORY2/s.1M38gYrZ -http://quotidiano.monrif.net/chan/cronaca_nazionale:410879.1:/1999/12/24 -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=baignes&l=fr -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=baignas&l=fr -http://www.egroups.com/message/swchicks-rpg/93 -http://usuarios.tripod.es/jlgolis/id142_l.htm -http://www9.freeweb.ne.jp/shopping/nossy/baby/200-59.html -http://www9.freeweb.ne.jp/shopping/nossy/baby/305-36.html -http://ftp.tku.edu.tw/OS/NetBSD/NetBSD-1.3.2/alpha/binary/kernel/?D=A -http://www-1.cisco.com/univercd/cc/td/doc/product/wanbu/82/access/fpmpmm12/fpmmappe.pdf -http://pub17.ezboard.com/fartofnorrathfavoritepaintings.threadControl?topicID=56.topic -http://itcareers.careercast.com/texis/it/itjs/+pwwBmew_D86eGrwwwqFqygdMpwDOeWXqqBcneWkjnwBneWkxqBOeWRlmmOtFqewyXwotoBwcaMwDwtnanmowcdt1naqconDBaGncwBodD5ropa5BGwBnton5amnVncdpaMwGAnBoDtanMwocaGn51MnaMFqryfHfREIDzmbwwwpBmFe-B-dehxwww5rmXmwwBrmeZpwww/morelike.html -http://www.thestateofcolorado.com/aoubicycling.html -http://www.freespeech.org/DISjak/disnews/maillist.html -http://www.freespeech.org/DISjak/sport/schwimm/bestlist.html -http://www.amigos.com/cgi-bin/w3com/pws/ffe/_MhIXE2wgPJZ1X047wqRwM-olUgaV3vI6fBPmDsoD0c26y7TrHjLUhhhTSIZ2PRmqLmBVyInWJLkLGkKScrdFyX1uyXCZhvaWFvbnSFioewAURJcXQC-hJE5KczVcMUiq3ncgKjQh7nynQEu662C -http://m.home.cern.ch/m/mrashid/www/cuisine/cuisin13.htm -http://m.home.cern.ch/m/mrashid/www/cuisine/cuisin28.htm -http://www.dayoo.com/channel/stock/news/cjzh/09/0921/06.htm -http://webcvs.kde.org/cgi-bin/cvsweb.cgi/KodeKnight/lib/Makefile.am?r1=1.3&sortby=rev -http://www.fogdog.com/cedroID/ssd3040183315779/nav/products/featured_brands/12p/all/ -http://www.fogdog.com/cedroID/ssd3040183315779/nav/stores/baseball/ -http://www.fogdog.com/cedroID/ssd3040183315779/nav/stores/squash/ -http://www9.hmv.co.uk:5555/do/session/1347832/vsid/199/tid/199/cid/1061396/mid/1020/rid/1052/chid/1029/parser/yes/imref/eqqLmwlGltt5tkeHjskKZlkKrhlK/url/http://www.hmv.co.uk/hmv/newmenu.html -http://www.arm.com/sitearchitek/support.ns4/html/cores_faq!OpenDocument&ExpandSection=9,36,8 -http://www.arm.com/sitearchitek/support.ns4/html/cores_faq!OpenDocument&ExpandSection=24,36,8 -http://www.hig.se/(append,countdown,set,sqloutput,sqltable)/~jackson/roxen/ -http://ring.jec.ad.jp/archives/linux/kernel.org/kernel/people/mingo/raid-patches/raid-2.2.17-A0 -http://www.wsrn.com/apps/links/?s=BKIRF -http://www.auto.ru/wwwboards/mercedes/0163/ -http://www.auto.ru/wwwboards/mercedes/0142/ -http://www.auto.ru/wwwboards/mercedes/0132/ -http://www.auto.ru/wwwboards/mercedes/0002/ -http://www.auto.ru/wwwboard/mercedes/0014/ -http://www.presa.spb.ru/newspapers/dp/arts/dp-178-art-12.html -http://pub8.ezboard.com/fnirlcomcenterracetalk.showMessage?topicID=8.topic -http://www.allhealth.com/pregnancy/labor/qa/0,3105,599,00.html -http://www3.newstimes.com/archive99/sep0499/lce.htm -http://jupiter.u-3mrs.fr/~msc41www/PSHTM/PS4330.HTM -http://www.gpul.org/ftp/os/linux/cd-images/other/suse/dosutils/pfdisktc/ -http://platsbanken.amv.se/kap/text/88/001025,010050,240907,10,0107051488.shtml -http://www.angel-bastel-zoo.de/detail/detail_811_3.htm -http://members.nbci.com/cmeadows/gvi/3battn/3bgvicob.html -http://www.chaos.dk/sexriddle/s/e/x/x/p/o/r/ -http://www.asiastockwatch.com/sg/Forum/ForumDetails/0,1819,561_1_2:15,00.html -http://mysanantonio.sportshuddle.com/sports/football/health/advisors/workouts/huff12.asp -http://mysanantonio.sportshuddle.com/sports/football/health/advisors/workouts/huff1.asp -http://ring.data-hotel.net/pub/linux/debian/debian-jp/dists/unstable/contrib/source/math/ -http://www.tel.de/s/I/IFG.htm -http://www.tel.de/s/I/IFHV.htm -http://chat.hr-online.de/fs/buecherbuecher/buch/kerr.html -http://mirror.cc.utsunomiya-u.ac.jp/mirror/FreeBSD/branches/2.2-stable/src/sys/dev/ -http://mirror.cc.utsunomiya-u.ac.jp/mirror/FreeBSD/branches/2.2-stable/src/sys/nfs/ -http://www.malaysia.net/lists/sangkancil/1998-12/msg01044.html -http://biblio.cesga.es:81/search*gag/aFerreiro,+Martín/aferreiro+martin/-5,1,1,E/frameset&F=aferreiro+manuel&4,,4 -http://www.ferien-immobilien.de/DominikanischeRep/verkauf/Exklusiv-IB/Startseite/Gemeinsam/MarketingStrategie/Exklusiv-IB/Startseite/Gemeinsam/erreichenPartner/email3d.htm -http://www.ferien-immobilien.de/DominikanischeRep/verkauf/Exklusiv-IB/Startseite/Gemeinsam/MarketingStrategie/Exklusiv-IB/Startseite/Gemeinsam/IIMMitglieder.htm -http://chunma.yeungnam.ac.kr/~home/home13/msgboard/msgboard.cgi?cmd=list&stat=start -http://link.fastpartner.com/do/session/600413/vsid/2870/tid/2870/cid/136966/mid/1060/rid/1926/chid/2870/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/local/redirect.php -http://www.eyeball.symantec.co.uk/region/se/sepress/20000418111220.htm -http://www.rezel.enst.fr/ftp/linux/distributions/debian/CD-1/dists/frozen/main/binary-all/news/?D=A -http://www.latimes.com/editions/orange/20001028/p000103070_ome0014.html -http://www.chaos.dk/sexriddle/j/c/u/t/ -http://cometweb01.comet.co.uk/do!session=132050&vsid=694&tid=20&cid=37044&mid=1000&rid=1060&chid=1711&url=eqqLmwlGltt5tkkHbqpLZXmLbkZHljlKaltLkilLXalKfkaLbukKeqjLi1 -http://perso.wanadoo.fr/jm.michaud/electronique_index.htm -http://dk.egroups.com/messages/Gunsmithing/1446?viscount=-30 -http://www-d0.fnal.gov/d0dist/dist/releases/psim01.02.00/pmcs_met/VERSION -http://mirror.cc.utsunomiya-u.ac.jp/mirror/CPAN/authors/id/P/PM/?N=D -http://www.movieguide.com/pressroom/events/amcinema96/award_amcinema965.html -http://www.sda.t-online.de/reise/index/aktrex201.htm -http://dic.empas.com/show.tsp/SMASHER -http://www.3w-posters.com/tomlinson.htm -http://www.3w-posters.com/tuttle.htm -http://www.xmission.com/(art,dots,ftp,geek,misc,music,caffiene,art,toys,dots,edge,misc,shopping,ftp,places,privacy,geek,cuseeme,apocalypse,people,stuffiuse,places,stuffiuse)/~bill/links.html -http://www.osiris.978.org/~brianr/mirrors/olga/main/g/gangi_mike/?N=D -http://www.best.com/~workpage/g/57/300g.htm -http://www.cyd.com.cn/zqb/19991109/GB/9677^Q212.htm -http://edu.news.chinaren.com/161/10112157.shtml -http://users.info.unicaen.fr/~jjousset/perso/html/entrainperso/page.html -http://www.wordtheque.com/owa-wt/wordtheque_dba.w.t?w=destituiscono&l=it -http://www.uk.multimap.com/p/browse.cgi?pc=B771AA&cat=loc -http://www.auxerre.culture.gouv.fr/culture/actualites/conferen/bonneuil-duffour.htm -http://www.auxerre.culture.gouv.fr/culture/actualites/communiq/mediaBonneuil-Duffour.htm -http://www.ancientsites.com/~Ftagn_Sithathor -http://biblioteca.upv.es/bib/doc/doc_fisbd/86/127697//C/1820009/0////25/N/MLTPAI -http://www.kfi640.com/shared/mod_perl/looksmart/looksmart/eus1/eus53930/eus169714/eus169722/eus542057/eus542410/ -http://www.kfi640.com/shared/mod_perl/looksmart/looksmart/eus1/eus53930/eus169714/eus169722/eus542057/eus542106/ -http://pub26.ezboard.com/fathanasiafrm1.showMessage?topicID=113.topic -http://www.sourceforge.net/softwaremap/trove_list.php?form_cat=186&discrim=186,226,251 -http://www.linux.com/networking/network/community/future/news/services/ -http://www.linux.com/networking/network/community/future/news/operating_system/ -http://www.linux.com/networking/network/community/future/news/?kw_offset=50 -http://www.linux.com/networking/network/development/unix/open_source/commercial/ -http://ring.shibaura-it.ac.jp/pub/misc/ham/funet/packet/00Index -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=3,0+20,0+17,0-( -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=3,0+20,0+17,0-9,1 -http://www.vorlesungen.uni-osnabrueck.de/informatik/c98/aufgaben/code/aufg50/ProcessInfo/ProcessInfo.bundle/Resources/?D=A -http://wap.jamba.de/KNet/_KNet-xOQ8j1-xHd-13fk7/showInfo-special1.de/node.0/cde7f1uou -http://nx5.salon.com/books/col/keil/2000/05/02/too_old/index2.html -http://pcmagazin.de/news/artikel/1999/04/29016-wf.htm -http://www.redrival.com/rgrascher/ -http://208.184.36.144/cwi/subscriptions/privacy_policy/0,1323,NAV47-68-85-98_STO52856,00.html -http://www.staroriental.net/nav/soeg_c/ihf,aol,n12,1,TVB香港å°å§2000.html -http://www.staroriental.net/nav/soeg_c/ihf,aol,n12,6,TVB香港å°å§2000.html -http://166.111.104.242/uscode/30/541b.head.html -http://stocks.tradingcharts.com/stocks/charts/fwrx/dchart.php?S=fwrx&T=d -http://genforum.genealogy.com/cgi-bin/print.cgi?plemmons::57.html -http://www.geocities.co.jp/Hollywood-Studio/3572/geodiary.html -http://www.luf.org/~jwills/LufWiki/view.cgi/Tech/ -http://www.doc.ic.ac.uk/lab/labsrc_area/firstyear/submissions/cs1/labs/Ex01/arr00/?M=A -http://citeseer.nj.nec.com/ps/332798 -http://citeseer.nj.nec.com/addcomment/332798 -http://citeseer.nj.nec.com/cidcontext/4075337 -http://ftp.te.fcu.edu.tw/cpatch/helputil/answerworks/?M=A -http://ftp.te.fcu.edu.tw/cpatch/helputil/answerworks/d2hpro4ethanks.htm -http://link.fastpartner.com/do/session/600423/vsid/2870/tid/2870/cid/136966/mid/1060/rid/1926/chid/2870/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/join/programmes/mondosoft.php -http://link.fastpartner.com/do/session/600423/vsid/2870/tid/2870/cid/136966/mid/1060/rid/1926/chid/2870/parser/yes/imref/eqqLmwlGltt5tkcHXpqLmXoLqkbLokZHljlK/url/http://www.fastpartner.com/company/ -http://library.cuhk.edu.hk/search*chi/dEnglish+language+--+Clauses./denglish+language+clauses/7,-1,0,B/browse -http://www04.u-page.so-net.ne.jp/yd5/yuma/top/home.html -http://www.smartshop.com/cgi-bin/main.cgi?c=1905&ssa=26 -http://www.smartshop.com/cgi-bin/main.cgi?c=1943&ssa=26 -http://se.egroups.com/dir/Business/Management/Project_and_Program_Management/Training?st=10 -http://www.hpl.online.sh.cn/WENXUE/tongsuo/wuxia/gulong/xueying/_vti_cnf/hs~001.htm -http://news.medscape.com/adis/PEON/public/archive/1999/toc-0221.html -http://news.medscape.com/adis/PEON/public/archive/1999/toc-0197.html -http://tucows.hongkong.com/winnt/adnload/4256_29575.html -http://www.etang.com/local/shenzhen/shopping/shop/0318mans02.htm -http://www.etang.com/local/shenzhen/shopping/shop/0319foll.htm -http://www.etang.com/local/shenzhen/shopping/shop/0319jialjs.htm -http://www.staffan.addr.com/cgi-bin/woda/icq.cgi/Edit?_id=2a5e -http://www.linux.com/networking/network/operating_system/kernel/distro/?printable=yes -http://www.linux.com/networking/network/operating_system/kernel/distro/commercial/ -http://www.linux.com/networking/network/operating_system/kernel/distro/white_dwarf/ -http://dir.dig.co.kr/parents/textbook/20301030101.html -http://www.affiliate.hpstore.hp.co.uk/do/session/380895/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/fr/CASHBACK/entry.asp -http://ccuftp.ccu.edu.tw/pub1/chinese/linux/clinux/c1/?N=D -http://cgi.cnnsi.com/basketball/college/women/boxscores/2000/03/07/cbp_rak -http://www.adcentral.com/cgi-bin/w3com/pws/adsites/5BRIztXQWHs_H_kyq8hmyrHpmCLb5RfQ09-DcKP1B6mZibAiJTLy1w3iiFS15WkFiCHMuMtjNK5FtHPDtZ7rxwckgoj0GaicnAZxhJLQ3zWaLoNUq8eTpG7wCxe3TWAb66jt -http://www.varsity.cam.ac.uk/varsity/live/2000/listings.nsf/44bbd1c2a6305036802567fb0081c76b!OpenView&Grid=1&Date=1999-04-06 -http://students.lsu.edu/students/main.nsf/Pages/CSISAJ1!OpenDocument&ExpandSection=15,21,5,4 -http://students.lsu.edu/students/main.nsf/Pages/CSISAJ1!OpenDocument&ExpandSection=18,21,5,4 -http://www.getplus.co.jp/category/catinet.homepagew2.asp -http://www.motorradversand.de/cgi-bin/antrieb/kettensatz_komplett_suzuki/RK82K872/beurteilung.htm -http://202.99.23.245/zdxw/13/20000328/200003281335.html -http://proxy.tiscover.com/1Root/Kontinent/6/Staat/7/Bundesland/22/Ort/120/Infrastruktur/299270/Homepage/homepage...1.html -http://www.jamba.de/KNet/_KNet-RcO8j1-cHd-13eq4/browse.de/node.0/cdel3j591 -http://www.jamba.de/KNet/_KNet-RcO8j1-cHd-13eqf/showInfo-wir.de/node.0/cde7f1uou -http://pub6.ezboard.com/fcrazyassmb47001generalshiznit.threadControl?topicID=685.topic -http://perso.infonie.fr/imagestld/photojyg5/images/alive5/?D=A -http://members.spree.com/sip1/take5planet/videos.htm -http://ae.boston.com/haiku/vote?haiku_id=4484 -http://adex3.flycast.com/server/socket/127.0.0.1:2800/click/OnlineCitiesSM/OnlineCitiesInteractiveCityGuides/bd129601192 -http://www.digitaldrucke.de/(aktuell,computer,marktplatz,shopping,verkehr)/suche/uebersicht.html -http://www.digitaldrucke.de/(aktuell,computer,hersteller,marktplatz,verkehr)/_fort/html/themen/computer/hard/herstell.htm -http://bbs.kcm.co.kr/NetBBS/Bbs.dll/kcmmission/lst/qqeq/1/zka/B2-kD2-l/qqo/004A -http://bbs.kcm.co.kr/NetBBS/Bbs.dll/kcmmission/rcm/zka/B2-kD2-l/qqo/004A/qqatt/^ -http://ftp.eq.uc.pt/software/lang/tcl/ftp.scriptics.com/nightly-cvs/tk/library/?S=A -http://www.infomedia.it/cgi-bin/lwgate/JAVA-IT/archives/java-it.log.9704/Subject/article-141.html -http://www.infomedia.it/cgi-bin/lwgate/JAVA-IT/archives/java-it.log.9704/Subject/article-165.html -http://www.infomedia.it/cgi-bin/lwgate/JAVA-IT/archives/java-it.log.9704/Subject/article-241.html -http://www.infomedia.it/cgi-bin/lwgate/JAVA-IT/archives/java-it.log.9704/Subject/article-239.html -http://www.infomedia.it/cgi-bin/lwgate/JAVA-IT/archives/java-it.log.9704/Subject/article-150.html -http://www.infomedia.it/cgi-bin/lwgate/JAVA-IT/archives/java-it.log.9704/Subject/article-44.html -http://www.infomedia.it/cgi-bin/lwgate/JAVA-IT/archives/java-it.log.9704/Subject/article-12.html -http://www.infomedia.it/cgi-bin/lwgate/JAVA-IT/archives/java-it.log.9704/Subject/article-4.html -http://www.infomedia.it/cgi-bin/lwgate/JAVA-IT/archives/java-it.log.9704/Subject/article-27.html -http://yp.gates96.com/5/88/50/47.html -http://yp.gates96.com/5/88/50/94.html -http://yp.gates96.com/5/88/51/20.html -http://yp.gates96.com/5/88/52/11.html -http://yp.gates96.com/5/88/52/26.html -http://yp.gates96.com/5/88/53/86.html -http://yp.gates96.com/5/88/53/99.html -http://yp.gates96.com/5/88/54/48.html -http://yp.gates96.com/5/88/55/29.html -http://yp.gates96.com/5/88/55/31.html -http://yp.gates96.com/5/88/55/41.html -http://yp.gates96.com/5/88/55/62.html -http://yp.gates96.com/5/88/55/77.html -http://yp.gates96.com/5/88/56/62.html -http://yp.gates96.com/5/88/56/93.html -http://yp.gates96.com/5/88/59/61.html -http://ceu.fi.udc.es:8000/mc/maillist/99-02/2090.918081010.176207534.html -http://ceu.fi.udc.es:8000/mc/maillist/99-02/1123.920140263.921690399.html -http://ceu.fi.udc.es:8000/mc/maillist/99-02/19089.918231855.610311830.html -http://ceu.fi.udc.es:8000/mc/maillist/99-02/16059.919279797.801472096.html -http://ceu.fi.udc.es:8000/mc/maillist/99-02/24001.919906575.275033199.html -http://ceu.fi.udc.es:8000/mc/maillist/99-02/14848.918256026.548154577.html -http://ceu.fi.udc.es:8000/mc/maillist/99-02/10783.918253985.660158806.html -http://ceu.fi.udc.es:8000/mc/maillist/99-02/27581.918670666.1055622954.html -http://www.activedayton.com/sportsticker/stnd/current/BBH.STAT.FSLKISLTRT.html -http://www.teenplatinum.com/barelylegal/japanesewomen/boots/petitesmall/explodingblowjob/eunuchbodyshots/homosexualass.html -http://books.hyperlink.co.uk/xt1/Methodology_for_the_Harmonization_of_European_Occupational_Accident_Statistics/9282641007 -http://www.jpc-music.com/2563637.htm -http://www.jpc-music.com/8168850.htm -http://www.expage.com/sugarshackstablesapryl -http://www.egroups.com/messages/svlug/31105 -http://www.chinawolf.com/~warson/japan/chichuan/bride/mldxn/009.htm -http://www.chinawolf.com/~warson/japan/chichuan/bride/mldxn/011.htm -http://yp.gates96.com/11/78/70/19.html -http://yp.gates96.com/11/78/70/95.html -http://yp.gates96.com/11/78/71/64.html -http://yp.gates96.com/11/78/71/65.html -http://yp.gates96.com/11/78/72/30.html -http://yp.gates96.com/11/78/73/35.html -http://yp.gates96.com/11/78/74/0.html -http://yp.gates96.com/11/78/75/58.html -http://yp.gates96.com/11/78/76/75.html -http://yp.gates96.com/11/78/77/36.html -http://yp.gates96.com/11/78/77/64.html -http://yp.gates96.com/11/78/78/20.html -http://yp.gates96.com/11/78/78/33.html -http://yp.gates96.com/11/78/78/70.html -http://yp.gates96.com/11/78/78/93.html -http://yp.gates96.com/11/78/79/3.html -http://yp.gates96.com/11/78/79/50.html -http://ben.aspads.net/ex/c/190/649604396 -http://www.lifl.fr/PRIVATE/Manuals/java/jdk1.2/docs/api/java/applet/class-use/AudioClip.html -http://dic.empas.com/show.tsp/?q=cea&f=B -http://beautifulthemes.subportal.com/sn/Utilities/Disk_Maintenance_and_Repair_Utilities/5294.html -http://ustlib.ust.hk/search*chi/anational+bureau+of+economic+research/anational+bureau+of+economic+research/-5,-1,0,E/frameset&F=anational+bureau+of+asian+and+soviet+research+u+s&1,,0 -http://www.canlii.org/ca/regl/dors99-120/art5.html -http://www.canlii.org/ca/regl/dors99-120/partie144284.html -http://www.incestpornstories.com/freshmanteen/eggbirth-canal/loverdrag-queen/birth-canalfull-term/stomachvagina.html -http://www.fashion-j.com/bs/013/013/19.html -http://www.fjtcm.edu.cn/Fujian_w/news/fjgsb/990311t/1-3.htm -http://www.kaos.dk/sex-riddle/k/a/k/i/s/z/r/d/ -http://www.kaos.dk/sex-riddle/k/a/k/i/s/z/r/f/ -http://www.tccomputers.com/cgi-bin/bp/41291345/products/specials/mbbundle.htm -http://www.tccomputers.com/cgi-bin/bp/41291345/services/insight.htm -http://www.tccomputers.com/cgi-bin/bp/41291345/products/batterybackups/batterybackups.htm -http://cartografia.comune.modena.it/Ril_Whip/menuogg/001-100/ME0068c.htm -http://library.bangor.ac.uk/search/cWS+5+V196a+2000/cws++++5+v196+a+2000/7,-1,0,B/frameset&F=cws+++21+e84+1989&5,,12 -http://mindit.netmind.com/proxy/http://www.exposure.aust.com/~promote1/auspalaeo/tectonix/tect1.htm -http://ftp.fi.debian.org/debian/dists/unstable/non-free/binary-i386/shells/?S=A -http://excite.de.netscape.com/unterhaltung/katalog/19344 -http://www.symatrixinc.com/website/website.nsf/0/3e40df86fb357cd5882568720079613f!OpenDocument&ExpandSection=25,20,21,29 -http://www.burstnet.com/ads/ad7826a-map.cgi/1708189811 -http://dic.empas.com/show.tsp/?s=b&q=CONSIDERABLE -http://www.kaos.dk/sex-riddle/k/a/k/i/p/g/t/c/ -http://www.kaos.dk/sex-riddle/k/a/k/i/p/g/t/h/ -http://www.kaos.dk/sex-riddle/k/a/k/i/p/g/t/n/ -http://www.kaos.dk/sex-riddle/k/a/k/i/p/g/t/x/ -http://www.cbe21.com.cn/xueke/dili/jiaoxuezs/ziliaojn/tupianhc/i0602.htm -http://babycenter.netscape.com/bbs/3788/thread530/message9.html -http://polygraph.ircache.net:8181/http_-2www.harborbay.com/home/webstuff/companyprofile.htm -http://dante.bdp.it/cgi-bin/poseidon_v2.0/reflect/poseidon/disc/bibl-uno/512098188/threadconfig -http://dante.bdp.it/cgi-bin/poseidon_v2.0/reflect/poseidon/disc/bibl-uno/512098188/newconfig -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=5,1,16,25,13 -http://www2.hgo.se/Kurskatalogen.nsf/a49e2126c83c4922412566f60052f831/f24cc45affc890eec12565d80055e0b9!OpenDocument&ExpandSection=28,1,16,25,13 -http://ftp.sunet.se/pub/lang/perl/CPAN/authors/id/R/RH/?D=A -http://www.geocities.co.jp/SilkRoad/1618/nixxki/010799.html -http://genforum.genealogy.com/cgi-genforum/forums/americanrev.cgi?4444 -http://in.egroups.com/message/djgppgames/358 -http://freehost.crazyhost.com/teengallery/apbh/panty.html -http://buffy.acmecity.com/xander/366/EDpt2.htm -http://www.tccomputers.com/cgi-bin/bp/505218695/promotional/deals.htm -http://www.tccomputers.com/cgi-bin/bp/505218695/products/cooling/cooling.htm -http://www.tccomputers.com/cgi-bin/bp/505218695/products/dvds/dvds.htm -http://www.tccomputers.com/cgi-bin/bp/505218695/products/mice/mice.htm -http://www.tccomputers.com/cgi-bin/bp/505218695/services/register.htm -http://www.foxsports.com/nba/scores/2000/000129_playbyplay_clewas.sml -http://pub1.ezboard.com/fcellofuncellistsbynightsemiprooramateur.showAddReplyScreenFromWeb?topicID=513.topic&index=9 -http://yp.gates96.com/0/22/30/81.html -http://yp.gates96.com/0/22/31/89.html -http://yp.gates96.com/0/22/32/1.html -http://yp.gates96.com/0/22/32/12.html -http://yp.gates96.com/0/22/32/48.html -http://yp.gates96.com/0/22/32/78.html -http://yp.gates96.com/0/22/34/48.html -http://yp.gates96.com/0/22/34/75.html -http://yp.gates96.com/0/22/34/85.html -http://yp.gates96.com/0/22/35/38.html -http://yp.gates96.com/0/22/35/73.html -http://yp.gates96.com/0/22/36/40.html -http://yp.gates96.com/0/22/36/92.html -http://yp.gates96.com/0/22/37/0.html -http://yp.gates96.com/0/22/37/61.html -http://yp.gates96.com/0/22/37/96.html -http://yp.gates96.com/0/22/39/13.html -http://yp.gates96.com/0/22/39/94.html -http://www.incestpornstories.com/underageflashing/plus-sizereal-size/beautiesasian/purpleanal-sex/maledomfantasy/high-schoolpretty/cherrybest-friends.html -http://variety.studiostore.com/browse/ELMOINGROU/TOY/s.2vzELAA2 -http://members.tripod.lycos.nl/BOGAERT/off2.htm -http://www.eveclub.com/cgi-bin/eveclub.front/972959555004/Catalog/2000019 -http://genforum.genealogy.com/cgi-genforum/forums/noel.cgi?662 -http://www.affiliate.hpstore.hp.co.uk/do/session/380888/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-expo.com/FR/REGISTRATION/entry.asp -http://yp.gates96.com/5/88/10/35.html -http://yp.gates96.com/5/88/10/44.html -http://yp.gates96.com/5/88/11/36.html -http://yp.gates96.com/5/88/13/1.html -http://yp.gates96.com/5/88/13/23.html -http://yp.gates96.com/5/88/13/77.html -http://yp.gates96.com/5/88/13/86.html -http://yp.gates96.com/5/88/14/47.html -http://yp.gates96.com/5/88/14/83.html -http://yp.gates96.com/5/88/15/11.html -http://yp.gates96.com/5/88/16/43.html -http://yp.gates96.com/5/88/16/86.html -http://yp.gates96.com/5/88/17/6.html -http://yp.gates96.com/5/88/17/12.html -http://yp.gates96.com/5/88/17/73.html -http://yp.gates96.com/5/88/18/1.html -http://yp.gates96.com/5/88/18/38.html -http://yp.gates96.com/5/88/18/47.html -http://yp.gates96.com/5/88/18/79.html -http://newnova.tucows.com/winme/adnload/138430_29763.html -http://yp.gates96.com/8/43/60/48.html -http://yp.gates96.com/8/43/60/55.html -http://yp.gates96.com/8/43/61/22.html -http://yp.gates96.com/8/43/62/40.html -http://yp.gates96.com/8/43/62/52.html -http://yp.gates96.com/8/43/62/94.html -http://yp.gates96.com/8/43/63/79.html -http://yp.gates96.com/8/43/64/73.html -http://yp.gates96.com/8/43/64/80.html -http://yp.gates96.com/8/43/66/26.html -http://yp.gates96.com/8/43/66/70.html -http://yp.gates96.com/8/43/67/16.html -http://yp.gates96.com/8/43/68/11.html -http://yp.gates96.com/8/43/69/74.html -http://www.fogdog.com/cedroID/ssd3040183354487/nav/products/winter_sports/1d/mid-weight_bottoms/ -http://www.fogdog.com/cedroID/ssd3040183354487/nav/products/winter_sports/1r/avalanche_safety/ -http://www.fogdog.com/cedroID/ssd3040183354487/boutique/marmot/ -http://www.affiliate.hpstore.hp.co.uk/do/session/380898/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.france.hp.com/Main/acheterhp/ -http://www.nd.edu/~dtl/cheg258/unix/unixhelp1.2/Pages/tasks_rm1.1.1.html -http://se.egroups.com/post/cyclesi?act=reply&messageNum=137 -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=22,0+18,0+22,0+9,4 -http://cidade.subportal.com/sn/Games/Action_Games/8120.html -http://wiem.onet.pl/wiem/0115d9-rp1.html -http://www.ferien-immobilien.de/detmold/Verkauf/Gemeinsam/Inserieren/Allgemeine-IB/Startseite/Gemeinsam/MarketingStrategie/Gemeinsam/erreichen.htm -http://retailer.gocollect.com/do/session/1912826/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/product_display/products/product_lines.asp -http://retailer.gocollect.com/do/session/1912826/vsid/2092/tid/2092/cid/569192/mid/1540/rid/1980/chid/2085/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLl0/url/http://www.gocollect.com/halloween/halloween.asp -http://www.iabusnet.org:90/forums/aca-1/dispatch.exe/survey/listUnseen/fol/100001/20,0/2542788 -http://www.dispatch.co.za/1998/06/25/easterncape/BISHO.HTM -http://pub24.ezboard.com/fsosatanfrm1.showMessage?topicID=48.topic -http://ftpsearch.belnet.be/ftp/packages/Linux-docs/howto/other-formats/INDEX -http://www.crosswinds.net/~mluotto/noframe/feedback/form2.htm -http://www.schoolweb.nl/studentensteden/Rotterdam/SVRGaudium/info.cfm -http://www.shopworks.com/index.cfm/action/directory/userid/0000BD9A-2F67-19FE-9038010B0A0ADCF2 -http://findmail.com/messages/masterhuen/802 -http://www.t-dialin.net/navkopf/service/websvkaa.htm -http://gallery2.simplenet.com/lobby/main/videocaps/ebaral/bigvalley/ebbva19.htm -http://gallery2.simplenet.com/lobby/main/videocaps/ebaral/bigvalley/ebbva31.htm -http://www.outpersonals.com/cgi-bin/w3com/pws/out/44hIVEhY5ZrKWoMKb0FtjCXhqcpntVLId5WTaJdeZmonn200jiiswYnK2vORJkjpm-x643ZCeLyy6kJnIAKa5rNx_42I13Ud9N03G9xPob7Hoci92HJhOlbEv4WsB85Au-cLXFlIHPd866jS -http://ftp.debian.org/debian/dists/Debian2.2r0/main/binary-all/editors/?D=A -http://ftp1.support.compaq.com/patches/public/Digital_UNIX/v3.2g/mailworks/2.0/?S=A -http://www.digitalhearth.com/Recipes/World_Cuisines/South_Asian/Indian/index5.html -http://ftp.gigabell.net/pub/Stormix/dists/rain/main/?M=A -http://www.stas.net/1/theparamanor/apartment.htm -http://www.netcom.com/~gfenzil/free.html -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/lit/misc/misc/thoughts/math/legendes/pages_new.html -http://www.eleves.ens.fr:8080/home/madore/index.shtml.fr/lit/misc/misc/thoughts/math/legendes/misc/orders_mag.html -http://dandini.cranfield.ac.uk/vl=-39658948/cl=171/nw=1/rpsv/catchword/routledg/13606719/contp1-1.htm -http://genforum.genealogy.com/cgi-genforum/forums/pugsley.cgi?81 -http://www.users.globalnet.co.uk/~mmayes/pages/cross.htm -http://dic.empas.com/show.tsp/?s=d&q=%C4%A7%BD%C7 -http://www.jamba.de/KNet/_KNet-rHP8j1-lHd-13f16/browse.de/node.0/cde7f1uou -http://library.bangor.ac.uk/search/aHolmgren,+Nils+Fritiof,+1877-1954/aholmgren+nils+fritiof+1877+1954/7,1,1,B/marc&F=aholmlund+chris&1,1, -http://www.spiral.at/Katalog/Artikel/0181030/ -http://www.spiral.at/Katalog/Artikel/0181242/ -http://www.generation-formation.fr/navig.htm---o21zAo06L2o0Ol9A074fo6VJGezMkEeIgI8eOkn2ApvFFo6Td4ezyr6feZJPdspt6dsSAtdsNhJdspt6dsrvrdjlhkfbz.htm -http://www.nextmedia.com.hk/netgirl/sport/images/chelsea/ch-30.htm -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=9,5-9,0-15,0-17,0 -http://www.realize.com/i82.htm,qt=35665aa9=645a273f-1a-31fa805-1-0-0-0-- -http://www.eud.com/1998/06/21/21121AA.shtml -http://www.eud.com/1998/06/21/21414AA.shtml -http://www.eud.com/1998/06/21/21434AA.shtml -http://chemtech.chinamarket.com.cn/E/Showdetail_company/5569.html -http://chemtech.chinamarket.com.cn/E/Showdetail_company/1095.html -http://www.ferien-immobilien.de/baden-wuertemberg/konstanz/Verkauf/Private-IB/Allgemeine-IB/Startseite/Gemeinsam/Immolink/Gemeinsam/MarketingStrategie/inhalt.htm -http://www.ferien-immobilien.de/baden-wuertemberg/konstanz/Verkauf/Private-IB/Allgemeine-IB/Startseite/Gemeinsam/Immolink/Gemeinsam/versicherungen/gebaeude/deckungsumfang.htm -http://retailer.gocollect.com/do/session/1912886/vsid/2312/tid/2312/cid/573127/mid/1020/rid/2147/chid/2210/parser/yes/imtarget/ImMainFrame/imref/eqqLmwlGltt5tkdHlZlLiibLZqkKZljLlZe5ofpLqjXLpl4/url/http://www.gocollect.com/company_info/terms_and_conditions.asp -http://eagle.synet.edu.cn/mirror/www.tuc.org.uk/ -http://eagle.synet.edu.cn/mirror/dcarolco.lanminds.com/home/ -http://www.chez.com/carabanon/Pagecabanon.htm -http://poetry.lezlisoft.com/kikelet/spiritualitas/lelekszinpad.shtml -http://lateline.muzi.net/ll/fanti/81373.shtml -http://www.egroups.com/message/vacuum/1140 -http://www.egroups.com/message/vacuum/1153 -http://www.egroups.com/message/vacuum/1157 -http://no.egroups.com/message/-1friendsliste/401 -http://no.egroups.com/message/-1friendsliste/411 -http://pike-community.org/(base=/forums/show.html,explode=146,forum=7,t=972959520359311)/forums/show.html -http://pike-community.org/(base=/forums/show.html,explode=512,forum=7,t=972959520359311)/forums/show.html -http://pike-community.org/(base=/forums/show.html,forum=7,show=413,t=972959520359311)/forums/show.html -http://pike-community.org/(base=/forums/show.html,forum=7,show=423,t=972959520359311)/forums/show.html -http://pike-community.org/(base=/forums/show.html,forum=7,show=761,t=972959520359311)/forums/show.html -http://pike-community.org/(base=/forums/show.html,forum=7,show=777,t=972959520359311)/forums/show.html -http://pike-community.org/(base=/forums/show.html,forum=7,show=831,t=972959520359311)/forums/show.html -http://astro1.cnu.ac.kr/NetBBS/Bbs.dll/bulletin/qry/zka/B2-kC2Jo/qqa/r -http://www.gbnf.com/genealog2/brothers/html/d0049/I1011.HTM -http://www.intellicast.com/Golf/World/UnitedStates/Midwest/Ohio/Zanesville/CurrentWinds/ -http://www.nada.kth.se/systemgruppen/docs/javadoc/jdk-1.3/docs/api/javax/swing/text/class-use/TabSet.html -http://www.my-cat.de/hunde/zucht/file24.htm -http://194.128.65.4/pa/cm199899/cmwib/wb981128/edms.htm -http://www.gutenberg2000.de/sagen/austria/tirol/adasbub.htm -http://www1.onelist.com/message/osaki/22 -http://www.highwired.net/ESchoolDrive/JumpPage/1,5565,25179-46,00.html -http://pcmagazin.de/download/library/deADW-wc.htm -http://www.affiliate.hpstore.hp.co.uk/do/session/380873/vsid/1148/tid/1148/cid/74115/mid/1001/rid/1003/chid/1050/parser/yes/imref/eqqLmwlGltt5tkeHmjbHumlLkZl5jlcHol4/url/http://www.hp-creativeworld.com/creativeworld.asp?lang=f -http://cscns.csc.gifu.gifu.jp/pushcorn-kit/tanigumi/paged/0300214020000147.html -http://cscns.csc.gifu.gifu.jp/pushcorn-kit/tanigumi/paged/0300214020002363.html -http://cscns.csc.gifu.gifu.jp/pushcorn-kit/tanigumi/paged/0300214020001617.html -http://cpan.nitco.com/modules/by-module/String/MLEHMANN/?N=D -http://www.rge.com/pub/tex/language/ethiopia/ethtex/lqh_fonts/ -http://130.158.208.53/WWW/PDB2/PCD4711/htmls/41.html -http://www.thisislancashire.co.uk/lancashire/archive/1997/05/15/LEIGH0VQ.html -http://www.thisislancashire.co.uk/lancashire/archive/1997/05/15/LEIGH10VQ.html -http://southwind.tukids.tucows.com/mac/parents/adnload/72310_26093.html -http://ftp1.support.compaq.com/public/vms/vax/v7.2/dsnlink/2.2/dsnlinke022.a-dcx_vaxexe -http://wynnsystems.com/i.I_5aGd/search/listCompanies.html -http://www.pobladores.com/territorios/juegos/Zhief_Fantasy_World/info -http://www.pobladores.com/territorios/juegos/Zhief_Fantasy_World/pagina/9 -http://www.aebius.com/rpm2html/contrib/libc5/i386/usr_sbin_Tree.html -http://info.rutgers.edu/cgi-bin/RUInfo/TallyStats/name=WebRequest&exec=buildlimit&limit=9,0-22,0-0,0-9,4 -http://polygraph.ircache.net:8181/services/define/http_-2www.fastcounter.com/noframes/specials.htm -http://polygraph.ircache.net:8181/services/define/http_-2www.fastcounter.com/noframes/sitebuilder.htm -http://www.jamba.nl/KNet/_KNet-7YT8j1-nD4-pxan/browse.nl/node.0/cdmvcam7k -http://www.outdoorwire.com/content/lists/jeepoffroad/200010/msg00234.html?{LoadingFrameset} -http://www-uk8.cricket.org/link_to_database/ARCHIVE/2000-01/ENG_IN_PAK/ENG_IN_PAK_OCT-DEC2000_ENG-SQUAD.html -http://www-uk8.cricket.org/link_to_database/ARCHIVE/CRICKET_NEWS/2000/OCT/057670_CI_25OCT2000.html -http://www.chaos.dk/sexriddle/c/c/e/k/ -http://ben.aspads.net/ex/c/190/608504034 -http://forum.rai.it/aca-finestre/dispatch.cgi/FORUM/folderFrame/100001/0/alpha/2040958 -http://www.teacherformation.org/html/od/facilitators.cfm/task1,help/discussion_id,2/xid,5237/yid,3113916 -http://www.mirror.edu.cn/res/www.isoc.org/inet98/proceedings/7d/ -http://www.sumthin.nu/archives/bugtraq/Nov_1998/msg00058.html -http://proxy.tiscover.com/1Root/Kontinent/6/Staat/7/Bundesland/20/Regionen/regionen_az...2.html -http://www.streetprices.com/products/sortdetailbylowprice/SP142252.html -http://www.streetprices.com/products/sortdetailby1day/SP142252.html -http://pp3.shef.ac.uk:4040/form/path=1,+%3A%22countryName%3DGB%40organizationName%3DUniversity+of+Sheffield%40organizationalUnitName%3DFinance%40commonName%3DS+Green%22 -http://travelocity-dest.excite.com/DestGuides/0,1840,TRAVELOCITY|2662|3|1|239114,00.html -http://www.maastrek.de/maas/4a73999ddfd2d79be20a/1/0/5 -http://aol.weather.com/weather/cities/us_pa_fairview.html -http://aol.weather.com/weather/cities/us_pa_fort_loudon.html -http://javatest.a-net.nl/servlet/pedit.Main/http://www.tigerden.com/junkmail/compladdr.html -http://ftp.dti.ad.jp/pub/windows/forest/file/backup/press1/?M=A -http://www.contest.edu.tw/85/endshow/5/baseball/news/97feb/0225t_1c.html -http://www.contest.edu.tw/85/endshow/5/baseball/news/97feb/0225c_3c.html -http://www.contest.edu.tw/85/endshow/5/baseball/news/97feb/0217c_2c.html -http://www.contest.edu.tw/85/endshow/5/baseball/news/97feb/0216c_play.html -http://www.contest.edu.tw/85/endshow/5/baseball/news/97feb/0214co_1c.html -http://preview.egroups.com/messages/decoratingplusnews/6 -http://astro1.chungnam.ac.kr/NetBBS/Bbs.dll/bulletin/rcm/zka/B2-kC23n/qqatt/^ \ No newline at end of file diff --git a/src/soci/.circleci/config.yml b/src/soci/.circleci/config.yml deleted file mode 100644 index 6293bf98d5..0000000000 --- a/src/soci/.circleci/config.yml +++ /dev/null @@ -1,59 +0,0 @@ -version: 2 -jobs: - lint: - docker: - - image: circleci/ruby:2.4.1-node - steps: - - checkout - - run: - name: install markdownlint - command: | - sudo npm install -g markdownlint-cli - markdownlint --version - - run: - name: lint README.md - command: markdownlint --config .markdownlint.json README.md - - run: - name: lint docs/ - command: markdownlint --config .markdownlint.json docs/ - build-deploy: - docker: - - image: circleci/python:2.7 - steps: - - checkout - - run: - name: install mkdocs - command: sudo pip install mkdocs - - run: - name: generate docs - command: mkdocs build --clean - - run: - name: install lftp - command: | - sudo apt-get update -q - sudo apt-get install -y lftp - - run: - name: deploy docs - command: lftp sftp://${DEPLOY_DOCS_USER}:${DEPLOY_DOCS_PASS}@${DEPLOY_DOCS_HOST} -e "set ftp:ssl-force true; set ftp:ssl-protect-data true; set ssl:verify-certificate no; set sftp:auto-confirm yes; mirror -v -R ./site ${DEPLOY_DOCS_BASE}/doc/${CIRCLE_BRANCH}; quit" - -workflows: - version: 2 - docs-workflow: - jobs: - - lint: - filters: - branches: - only: - - master - - /release*/ - - build-deploy: - requires: - - lint - filters: - branches: - only: - - master - - /release*/ -notify: - webhooks: - - url: https://webhooks.gitter.im/e/9ff4be3a6f08f55106e2 diff --git a/src/soci/.editorconfig b/src/soci/.editorconfig deleted file mode 100644 index 3db57fb750..0000000000 --- a/src/soci/.editorconfig +++ /dev/null @@ -1,32 +0,0 @@ -# This is the EditorConfig (http://editorconfig.org/) coding style file for SOCI. -root = true - -[*] -end_of_line = lf -insert_final_newline = true -charset = utf-8 -indent_style = space -indent_size = 4 -trim_trailing_whitespace = true - -# CMake configuration files -[{CMakeLists.txt,*.cmake}] -indent_size = 2 -indent_style = space -trim_trailing_whitespace = true -insert_final_newline = true - -# CI configuration files -[{.travis.yml,appveyor.yml,Vagrantfile}] -indent_size = 2 -indent_style = space -trim_trailing_whitespace = true -insert_final_newline = true - -# Windows shell scripts -[*.{cmd,bat,ps1}] -end_of_line = crlf -indent_size = 4 -indent_style = space -insert_final_newline = false -trim_trailing_whitespace = true diff --git a/src/soci/.gitattributes b/src/soci/.gitattributes deleted file mode 100644 index 638b14ee1a..0000000000 --- a/src/soci/.gitattributes +++ /dev/null @@ -1,30 +0,0 @@ -# Auto detect text files and perform LF normalization -* text=auto - -*.bash eol=lf -*.env eol=lf -*.sh eol=lf -*.cmd eol=crlf -*.bat eol=crlf -*.BAT eol=crlf -*.CMD eol=crlf - -# Custom for Visual Studio -*.cs diff=csharp -*.sln merge=union -*.csproj merge=union -*.vbproj merge=union -*.fsproj merge=union -*.dbproj merge=union - -# Standard to msysgit -*.doc diff=astextplain -*.DOC diff=astextplain -*.docx diff=astextplain -*.DOCX diff=astextplain -*.dot diff=astextplain -*.DOT diff=astextplain -*.pdf diff=astextplain -*.PDF diff=astextplain -*.rtf diff=astextplain -*.RTF diff=astextplain diff --git a/src/soci/.gitignore b/src/soci/.gitignore deleted file mode 100644 index 0452661566..0000000000 --- a/src/soci/.gitignore +++ /dev/null @@ -1,44 +0,0 @@ -# General -*.swp -*.kate-swp -tags -tmp - -# Build directories -/*build* -/*site* - -# Files generated by CMake -Makefile -src/core/soci_backends_config.h -tests/odbc/test-access.dsn -tests/odbc/test-mysql.dsn - -# ... and the rest of CMake spam -CMakeFiles/ -CMakeCache.txt -CTestTestfile.cmake -cmake_install.cmake - -# Visual Studio / Visual Studio Code -*.opensdf -*.sdf -*.suo -/*.vs* - -# KDevelop -*.kate-swp -*.kdev4 - -# Qt Creator -*.config -*.creator* -*.files -*.includes -CMakeLists.txt.user - -# Eclipse -/.project - -# Vagrant -/.vagrant/ diff --git a/src/soci/.markdownlint.json b/src/soci/.markdownlint.json deleted file mode 100644 index 7d75b410c9..0000000000 --- a/src/soci/.markdownlint.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "default": true, - "MD013": false, - "MD026": false, - "MD024": false, - "MD029": {"style": "ordered"} -} diff --git a/src/soci/.travis.yml b/src/soci/.travis.yml deleted file mode 100644 index cff9f9a18d..0000000000 --- a/src/soci/.travis.yml +++ /dev/null @@ -1,60 +0,0 @@ -# .travis.yml -# Configure Travis CI service to build SOCI library, http://github.com/SOCI -# -# Copyright (c) 2013 Mateusz Loskot -# -# TODO: Switch to Trusty https://github.com/SOCI/soci/issues/574 -dist: precise -language: cpp - -sudo: required - -compiler: - - g++ - #- clang - -services: - - mysql - - postgresql - -env: - global: - - secure: "I7/28jg7R24y64426d5XsfILrd/VW0BdwFbNpEgBfW1qNk9GpkNGTvp/ET6hKwBVrW5jmN9QdEviGcPpQRIAlMj6g9GvZeAUxM+VZTcXD2u30REUPPxNTJMRVHPfL9DA7EMFCST8SjBCgMdTHFwqLV4vSQEF4NTXbntley/IPfM=" - matrix: - - SOCI_TRAVIS_BACKEND=db2 - - SOCI_TRAVIS_BACKEND=empty - - SOCI_TRAVIS_BACKEND=firebird - - SOCI_TRAVIS_BACKEND=mysql - - SOCI_TRAVIS_BACKEND=odbc - - SOCI_TRAVIS_BACKEND=postgresql - - SOCI_TRAVIS_BACKEND=sqlite3 - - SOCI_TRAVIS_BACKEND=valgrind - - SOCI_TRAVIS_BACKEND=oracle WITH_BOOST=OFF - -addons: - apt: - sources: - - ubuntu-toolchain-r-test - - kalakris-cmake - packages: - - cmake - coverity_scan: - project: - name: "SOCI/soci" - notification_email: soci-devel@lists.sourceforge.net - build_command_prepend: "mkdir build.cov; cd build.cov; cmake .." - build_command: "make -j 4" - branch_pattern: coverity_scan - -before_install: ./scripts/travis/before_install.sh -before_script: ./scripts/travis/before_script.sh -script: ./scripts/travis/script.sh - -notifications: - webhooks: - urls: - - https://webhooks.gitter.im/e/000781732a3b1637ef82 - on_start: always - irc: - channels: - - "irc.freenode.org#soci" diff --git a/src/soci/AUTHORS b/src/soci/AUTHORS deleted file mode 100644 index 0b4d5487a8..0000000000 --- a/src/soci/AUTHORS +++ /dev/null @@ -1,78 +0,0 @@ -=== SOCI Team === - -Alex Ott -David Courtney -Denis Arnaud -Denis Chapligin -Julian Taylor -Maciej Sobczak -Mateusz Åoskot -PaweÅ‚ Aleksander FedoryÅ„ski -RafaÅ‚ Bobrowski -Sergei Nikulov -Steve Hutton -Vadim Zeitlin -Viacheslav Naydenov - -=== SOCI Contributors === - -We would like to thank you for your contributions -- they allowed us to improve the quality of the SOCI library: - -Adesmier -Alex Volanis -Andrey Belobrov -Andrey Utkin -Andriy Gapon -Artyom Beilis -Artyom Tonkikh -avg-I -b-s-a -Brian R. Toonen -Cengizhan PaÅŸaoÄŸlu -Chris Weed -Cory Bennett -creste -Daniel Lidström -Eli Green -Faik Uygur -Fedor Trushkin -Frank Bielig -Frederic Chateau -Gevorg Voskanyan -Henning Basold -Howard Butler -Ilia Barahovski -Jakub Stachowski -jamercee -Joerg Sonnenberger -Krzysztof BieleÅ„ -Mario Valesco -Martin Muenstermann -Mathias Hasselmann -Matt Arsenault -Matthieu Kermagoret -Michael Davidsaver -Mika Fischer -pacocamberos -Paul Bondo -Petr Vanek -Philip Pemberton -Rainer Bauer -Ricardo Andrade -ryandesign -Robert Massaioli -Roger Orr -Sergey Belyashov -Shridhar Daithankar -Sören Meyer-Eppler -soyersoyer -Stefan Chrobot -Tomasz Olszewski -Vaclav Slavik -xol - -There are a lot of people that help to drive SOCI project forward, -if we have forgot to mention someone in here, -if you would like to be listed by name instead of GitHub username, -send us an email! diff --git a/src/soci/CHANGELOG.md b/src/soci/CHANGELOG.md deleted file mode 100644 index 054f0ce987..0000000000 --- a/src/soci/CHANGELOG.md +++ /dev/null @@ -1,456 +0,0 @@ -# Change Log - -## [Unreleased](https://github.com/SOCI/soci/tree/HEAD) - -[Full Changelog](https://github.com/SOCI/soci/compare/3.2.3...HEAD) - -**Closed issues:** - -- Exception while selecting null values with indicators [\#581](https://github.com/SOCI/soci/issues/581) -- Null value fetched and no indicator defined [\#580](https://github.com/SOCI/soci/issues/580) -- sequence support MySQL and PostgreSQL [\#569](https://github.com/SOCI/soci/issues/569) -- Implement session::get\_table\_names\(\) for sqlite3 [\#563](https://github.com/SOCI/soci/issues/563) -- Make Oracle work again on Travis CI [\#554](https://github.com/SOCI/soci/issues/554) -- Split AppVeyor jobs per backend [\#550](https://github.com/SOCI/soci/issues/550) -- how to build soci with postgresql? [\#543](https://github.com/SOCI/soci/issues/543) -- How can I install SOCI on HP UX? [\#538](https://github.com/SOCI/soci/issues/538) -- Error C2065 'x\_type': undeclared identifier [\#531](https://github.com/SOCI/soci/issues/531) -- Unable to catch sqlite3\_soci\_error, program aborts [\#529](https://github.com/SOCI/soci/issues/529) -- unresolved external symbol sqlite3\_soci\_error::result when linking soci\_sqlite3\_test.exe on VS2015 U3 [\#528](https://github.com/SOCI/soci/issues/528) -- How to use rowset with Core interface [\#527](https://github.com/SOCI/soci/issues/527) -- can std::string of soci hold the right utf8 data? [\#525](https://github.com/SOCI/soci/issues/525) -- \[Q\] Store query in unsorted\_map [\#522](https://github.com/SOCI/soci/issues/522) -- use vector for `in` [\#520](https://github.com/SOCI/soci/issues/520) -- Deadlock found when trying to get lock; try restarting transaction [\#518](https://github.com/SOCI/soci/issues/518) -- Link issue with master [\#513](https://github.com/SOCI/soci/issues/513) -- Uninitialised type in oracle\_statement\_backend::describe\_column [\#511](https://github.com/SOCI/soci/issues/511) -- unfortunate placement of soci headers with common names [\#505](https://github.com/SOCI/soci/issues/505) -- SOCI\_STATIC and plugins [\#497](https://github.com/SOCI/soci/issues/497) -- Illegal memory access on Windows [\#488](https://github.com/SOCI/soci/issues/488) -- into/use\_container\ is causing troubles [\#485](https://github.com/SOCI/soci/issues/485) -- Provide CMake package configuration file [\#481](https://github.com/SOCI/soci/issues/481) -- delete already deleted pimpl if connection\_pool is assigned [\#478](https://github.com/SOCI/soci/issues/478) -- Is there any roadmap to support vertica ? [\#477](https://github.com/SOCI/soci/issues/477) -- Handle OCI\_SUCCESS\_WITH\_INFO [\#473](https://github.com/SOCI/soci/issues/473) -- Coverity not fully configured [\#472](https://github.com/SOCI/soci/issues/472) -- soci 3.2.3 build on windows is not complete [\#468](https://github.com/SOCI/soci/issues/468) -- Char \* not supported in use/into. Documentation states otherwise. [\#466](https://github.com/SOCI/soci/issues/466) -- VS2015 Exceptions =\> abort\(\) [\#465](https://github.com/SOCI/soci/issues/465) -- Error classification [\#464](https://github.com/SOCI/soci/issues/464) -- Oracle wallet authentication [\#463](https://github.com/SOCI/soci/issues/463) -- get the result in a c++ code of stored procedure after a call [\#460](https://github.com/SOCI/soci/issues/460) -- NLS supports for connection params in Oracle [\#458](https://github.com/SOCI/soci/issues/458) -- AppVeyor can not find sh.exe? [\#447](https://github.com/SOCI/soci/issues/447) -- async query call [\#445](https://github.com/SOCI/soci/issues/445) -- Does this library to work with firebird events? [\#442](https://github.com/SOCI/soci/issues/442) -- SOCI doesn't define SOCI\_HAVE\_CXX\_C11 for VS2015 [\#441](https://github.com/SOCI/soci/issues/441) -- ...is not a member of 'sqlite\_api' [\#440](https://github.com/SOCI/soci/issues/440) -- Compile errors [\#439](https://github.com/SOCI/soci/issues/439) -- C++11 \#define should be in soci-config.hpp defined [\#437](https://github.com/SOCI/soci/issues/437) -- Fix discrepency between SOCI\_USE\_BOOST and HAVE\_BOOST [\#433](https://github.com/SOCI/soci/issues/433) -- Add Vagrant configuration for easy development [\#432](https://github.com/SOCI/soci/issues/432) -- DB2 statement execute error handling is ambiguous [\#431](https://github.com/SOCI/soci/issues/431) -- Issue using boost::tuple integration after upgrading from soci 3.2.2 to 3.2.3 [\#429](https://github.com/SOCI/soci/issues/429) -- conversion\_use\_type misses members initialization [\#412](https://github.com/SOCI/soci/issues/412) -- AppVeyor: ODBC tests are failed [\#407](https://github.com/SOCI/soci/issues/407) -- Can't run SOCI tests under Windows using ODBC data source [\#396](https://github.com/SOCI/soci/issues/396) -- Problems building SOCI under windows [\#384](https://github.com/SOCI/soci/issues/384) -- std::strings in nvarchar\(max\) is still a problem [\#383](https://github.com/SOCI/soci/issues/383) -- Build VS2015 Win10 Errors [\#379](https://github.com/SOCI/soci/issues/379) -- soci-3.2.3/backends/mysql/session.cpp:202: bad if test ? [\#377](https://github.com/SOCI/soci/issues/377) -- Clang warnings preventing compilation [\#374](https://github.com/SOCI/soci/issues/374) -- Boost 1.58.0 fails static assertion when streaming optional w/o optional\_io header [\#370](https://github.com/SOCI/soci/issues/370) -- Building of very first file fails with mingw [\#369](https://github.com/SOCI/soci/issues/369) -- How to pass dynamic multiple variables to query [\#354](https://github.com/SOCI/soci/issues/354) -- Rename SOCI headers [\#342](https://github.com/SOCI/soci/issues/342) -- OSX: struct session conflicting with unqualified soci::session [\#340](https://github.com/SOCI/soci/issues/340) -- Remove old build .tcl scripts [\#339](https://github.com/SOCI/soci/issues/339) -- Building errors with mingw, linking and undef. reference [\#338](https://github.com/SOCI/soci/issues/338) -- Missing static ODBC object file in installation script [\#337](https://github.com/SOCI/soci/issues/337) -- Mac OS: master branch fails to build on Yosemite [\#334](https://github.com/SOCI/soci/issues/334) -- Port: Allow SOCI\_LIBDIR to be set on the command line for easier packaging. \#195 [\#311](https://github.com/SOCI/soci/issues/311) -- Port: Add WITH\_CXX11 configuration flag \(currently for gcc and clang\) \#203 [\#310](https://github.com/SOCI/soci/issues/310) -- Incorrect time zone in struct tm returned from SOCI [\#308](https://github.com/SOCI/soci/issues/308) -- Drop GitFlow branching model [\#305](https://github.com/SOCI/soci/issues/305) -- Merge master 3.2.3 into develop [\#303](https://github.com/SOCI/soci/issues/303) -- Get rid of asserts in the code [\#300](https://github.com/SOCI/soci/issues/300) -- Set up a test database for Oracle Travis CI build. [\#290](https://github.com/SOCI/soci/issues/290) -- Big std::strings in nvarchar\(max\)s via ODBC fails with HY104 [\#287](https://github.com/SOCI/soci/issues/287) -- BUG problem on the second iteration in a rowset [\#280](https://github.com/SOCI/soci/issues/280) -- ODBC stored procedure [\#275](https://github.com/SOCI/soci/issues/275) -- Build and compile soci odbc failed [\#274](https://github.com/SOCI/soci/issues/274) -- Add MinGW build to Travis CI [\#247](https://github.com/SOCI/soci/issues/247) -- Fix warnings in MySQL backend compilation [\#244](https://github.com/SOCI/soci/issues/244) -- \[fix\] Remove -ansi when building on FreeBSD 10 [\#236](https://github.com/SOCI/soci/issues/236) -- Clean up terse or misspelled exception messages in ODBC backend [\#231](https://github.com/SOCI/soci/issues/231) -- odbc\_soci\_error should append sqlstate\_, sqlcode\_ and message\_ to the string used to initialize soci\_error [\#228](https://github.com/SOCI/soci/issues/228) -- Install Oracle on Travis CI server [\#224](https://github.com/SOCI/soci/issues/224) -- ODBC string bulk insertions are adding an escape char at the end of each string [\#202](https://github.com/SOCI/soci/issues/202) -- soci test projects for MSVC using cmake end up with wrong include path and linker error [\#177](https://github.com/SOCI/soci/issues/177) -- \#include "soci-backend.h" in sqlite3/soci-sqlite3.h [\#169](https://github.com/SOCI/soci/issues/169) -- double free [\#142](https://github.com/SOCI/soci/issues/142) -- Allow unknown toolsets in SociConfig.cmake [\#104](https://github.com/SOCI/soci/issues/104) -- Includes are wrong with make-install on Linux Mint [\#101](https://github.com/SOCI/soci/issues/101) -- Throw if truncation happens but no indicators was provided [\#51](https://github.com/SOCI/soci/issues/51) -- MySQL IEEE floating point representation [\#22](https://github.com/SOCI/soci/issues/22) - -**Merged pull requests:** - -- Repair VC8 compile of test applications [\#593](https://github.com/SOCI/soci/pull/593) ([hrabe](https://github.com/hrabe)) -- Replace C alternative boolean operator representations with primary [\#592](https://github.com/SOCI/soci/pull/592) ([mloskot](https://github.com/mloskot)) -- \[cmake\] Update FindPostgreSQL.cmake from CMake 3.9 [\#590](https://github.com/SOCI/soci/pull/590) ([mloskot](https://github.com/mloskot)) -- \[AppVeyor\] Add build job with Visual Studio 2017 [\#588](https://github.com/SOCI/soci/pull/588) ([mloskot](https://github.com/mloskot)) -- More XML/CLOB-related changes, including ODBC "support" [\#586](https://github.com/SOCI/soci/pull/586) ([vadz](https://github.com/vadz)) -- Enable Oracle builds for pull requests [\#585](https://github.com/SOCI/soci/pull/585) ([mloskot](https://github.com/mloskot)) -- Fix bug with null strings in bulk selections in ODBC and DB2 [\#583](https://github.com/SOCI/soci/pull/583) ([vadz](https://github.com/vadz)) -- Oracle fix empty string as null handling in the test [\#582](https://github.com/SOCI/soci/pull/582) ([vadz](https://github.com/vadz)) -- Restore Oracle build job on Travis CI [\#579](https://github.com/SOCI/soci/pull/579) ([mloskot](https://github.com/mloskot)) -- Add CLOB and XML support to Firebird backend [\#578](https://github.com/SOCI/soci/pull/578) ([vadz](https://github.com/vadz)) -- Move directory /bin to /scripts [\#577](https://github.com/SOCI/soci/pull/577) ([mloskot](https://github.com/mloskot)) -- Add support for EditorConfig [\#576](https://github.com/SOCI/soci/pull/576) ([alexott](https://github.com/alexott)) -- fix some of warnings from fresh Coverity report [\#572](https://github.com/SOCI/soci/pull/572) ([alexott](https://github.com/alexott)) -- Sanitizer fix & cmake support for build in superprojects [\#570](https://github.com/SOCI/soci/pull/570) ([mcencora](https://github.com/mcencora)) -- Update structure of SOCI 4.0.0 documentation [\#566](https://github.com/SOCI/soci/pull/566) ([mloskot](https://github.com/mloskot)) -- Some fix for SQLite3 backend [\#564](https://github.com/SOCI/soci/pull/564) ([Arenoros](https://github.com/Arenoros)) -- Fix handling of strings in ODBC backend bulk operations [\#561](https://github.com/SOCI/soci/pull/561) ([vadz](https://github.com/vadz)) -- Refactor code for parsing date/time to avoid duplication [\#559](https://github.com/SOCI/soci/pull/559) ([vadz](https://github.com/vadz)) -- Lazy initialization of the temporary LOB objects for Oracle. [\#557](https://github.com/SOCI/soci/pull/557) ([msobczak](https://github.com/msobczak)) -- Fix check for clang in CMake configuration [\#556](https://github.com/SOCI/soci/pull/556) ([vadz](https://github.com/vadz)) -- Work around MySQL ODBC driver bug [\#555](https://github.com/SOCI/soci/pull/555) ([vadz](https://github.com/vadz)) -- Consistently check for connection in the session object methods [\#548](https://github.com/SOCI/soci/pull/548) ([vadz](https://github.com/vadz)) -- Use defaults for unsupported types in ODBC backend [\#545](https://github.com/SOCI/soci/pull/545) ([snikulov](https://github.com/snikulov)) -- moved to latest Catch UT Framework [\#544](https://github.com/SOCI/soci/pull/544) ([snikulov](https://github.com/snikulov)) -- disable autosetting of SOCI\_CXX\_C11 to OFF [\#541](https://github.com/SOCI/soci/pull/541) ([ckaminski](https://github.com/ckaminski)) -- Pull request for issues 511 and 473 [\#536](https://github.com/SOCI/soci/pull/536) ([ddowling](https://github.com/ddowling)) -- Fixing uninitialized gotData\_ [\#535](https://github.com/SOCI/soci/pull/535) ([csteifel](https://github.com/csteifel)) -- Corrections in README.md [\#534](https://github.com/SOCI/soci/pull/534) ([mutcher](https://github.com/mutcher)) -- Firebird blob bug [\#524](https://github.com/SOCI/soci/pull/524) ([ravselj](https://github.com/ravselj)) -- Add JSON support to the MySQL backend [\#517](https://github.com/SOCI/soci/pull/517) ([ayllon](https://github.com/ayllon)) -- Add missing declspec to properly export exception classes [\#510](https://github.com/SOCI/soci/pull/510) ([mloskot](https://github.com/mloskot)) -- Added bigstring \(XML and CLOB\) support. [\#509](https://github.com/SOCI/soci/pull/509) ([msobczak](https://github.com/msobczak)) -- Added uniform offset for BLOB read/write operations. [\#508](https://github.com/SOCI/soci/pull/508) ([msobczak](https://github.com/msobczak)) -- export cmake package [\#503](https://github.com/SOCI/soci/pull/503) ([wisk](https://github.com/wisk)) -- Fix travis-ci build [\#494](https://github.com/SOCI/soci/pull/494) ([snikulov](https://github.com/snikulov)) -- Fixed \#468 [\#493](https://github.com/SOCI/soci/pull/493) ([snikulov](https://github.com/snikulov)) -- Fixed driver name and passwd for PostgreSQL ODBC driver on AppVeyor [\#492](https://github.com/SOCI/soci/pull/492) ([snikulov](https://github.com/snikulov)) -- Fixed MinGW build with proper URL on AppVeyor [\#491](https://github.com/SOCI/soci/pull/491) ([snikulov](https://github.com/snikulov)) -- MSSQL ODBC // fixed \#383 - long lines insert/select [\#489](https://github.com/SOCI/soci/pull/489) ([snikulov](https://github.com/snikulov)) -- Bulk iterators [\#487](https://github.com/SOCI/soci/pull/487) ([msobczak](https://github.com/msobczak)) -- Added failover callback for Oracle and PostgreSQL. [\#486](https://github.com/SOCI/soci/pull/486) ([msobczak](https://github.com/msobczak)) -- Added support for portable DDL statements. [\#484](https://github.com/SOCI/soci/pull/484) ([msobczak](https://github.com/msobczak)) -- Added singlerows mode for PostgreSQL. [\#482](https://github.com/SOCI/soci/pull/482) ([msobczak](https://github.com/msobczak)) -- Portable metadata queries. [\#480](https://github.com/SOCI/soci/pull/480) ([msobczak](https://github.com/msobczak)) -- fixed \#478 [\#479](https://github.com/SOCI/soci/pull/479) ([snikulov](https://github.com/snikulov)) -- coverity // Fixed uninited local std::tm structs [\#475](https://github.com/SOCI/soci/pull/475) ([snikulov](https://github.com/snikulov)) -- Adding example of a oracle connection to a remote server without need of tnsnames.ora [\#474](https://github.com/SOCI/soci/pull/474) ([wdavilaneto](https://github.com/wdavilaneto)) -- Travis-CI: allowed failure for DB2 backend [\#471](https://github.com/SOCI/soci/pull/471) ([snikulov](https://github.com/snikulov)) -- Appveyour now using MySQL 5.7 [\#470](https://github.com/SOCI/soci/pull/470) ([snikulov](https://github.com/snikulov)) -- Documentation. exchange.md cleaned from typos [\#459](https://github.com/SOCI/soci/pull/459) ([shelomentsevd](https://github.com/shelomentsevd)) -- compilation fix for msvc2012 [\#455](https://github.com/SOCI/soci/pull/455) ([snikulov](https://github.com/snikulov)) -- added Address Sanitizer to expose memory errors [\#454](https://github.com/SOCI/soci/pull/454) ([snikulov](https://github.com/snikulov)) -- updated catch.hpp version to 1.3.3 [\#453](https://github.com/SOCI/soci/pull/453) ([snikulov](https://github.com/snikulov)) -- Define cxx\_details::auto\_ptr\<\> to get rid of preprocessor checks [\#452](https://github.com/SOCI/soci/pull/452) ([vadz](https://github.com/vadz)) -- Include soci/soci-platform.h instead of soci-config.h [\#451](https://github.com/SOCI/soci/pull/451) ([vadz](https://github.com/vadz)) -- Avoid recursive inclusion between soci-{config,platform}.h [\#450](https://github.com/SOCI/soci/pull/450) ([vadz](https://github.com/vadz)) -- fixed \#447 [\#449](https://github.com/SOCI/soci/pull/449) ([snikulov](https://github.com/snikulov)) -- Handle MSVS 2015 \(and 2013, to some extent\) as C++11 compiler [\#448](https://github.com/SOCI/soci/pull/448) ([vadz](https://github.com/vadz)) -- CMake read version from version.h [\#446](https://github.com/SOCI/soci/pull/446) ([ArnaudD-FR](https://github.com/ArnaudD-FR)) -- postgres library built as static would not install unless also buildi… [\#443](https://github.com/SOCI/soci/pull/443) ([julien-lecomte](https://github.com/julien-lecomte)) -- DB2: Switch session from SQLConnect ot SQLDriverConnect [\#438](https://github.com/SOCI/soci/pull/438) ([mloskot](https://github.com/mloskot)) -- CMake generates soci/version.h [\#436](https://github.com/SOCI/soci/pull/436) ([ArnaudD-FR](https://github.com/ArnaudD-FR)) -- Specify definitions in soci-config.h [\#435](https://github.com/SOCI/soci/pull/435) ([ArnaudD-FR](https://github.com/ArnaudD-FR)) -- Add Vagrant configuration [\#434](https://github.com/SOCI/soci/pull/434) ([mloskot](https://github.com/mloskot)) -- \[SQLITE3\] Add reset API to reset sqlite3 statement [\#430](https://github.com/SOCI/soci/pull/430) ([ArnaudD-FR](https://github.com/ArnaudD-FR)) -- reset count of affected rows \(sqlite3\) [\#428](https://github.com/SOCI/soci/pull/428) ([MonsieurNicolas](https://github.com/MonsieurNicolas)) -- Fixed Coverity issues for SQLite3: 12644, 12645, 12646 [\#427](https://github.com/SOCI/soci/pull/427) ([snikulov](https://github.com/snikulov)) -- Enabled mysql/postgresql odbc tests - fixed \#407 [\#426](https://github.com/SOCI/soci/pull/426) ([snikulov](https://github.com/snikulov)) -- moved SOCI\_CXX\_C11 define to common section [\#425](https://github.com/SOCI/soci/pull/425) ([snikulov](https://github.com/snikulov)) -- Clang: fixed \#374 [\#422](https://github.com/SOCI/soci/pull/422) ([snikulov](https://github.com/snikulov)) -- add ignore of cmake generated dsn file for access [\#421](https://github.com/SOCI/soci/pull/421) ([jeking3](https://github.com/jeking3)) -- add a unit test for the postgresql uuid data type [\#420](https://github.com/SOCI/soci/pull/420) ([jeking3](https://github.com/jeking3)) -- Travis-CI: added valgrind check [\#419](https://github.com/SOCI/soci/pull/419) ([snikulov](https://github.com/snikulov)) -- fixed get\_affected\_rows\(\) to pass test thats broken since \#414 [\#418](https://github.com/SOCI/soci/pull/418) ([hw-dwalter](https://github.com/hw-dwalter)) -- coverity: updated .travis.yml [\#417](https://github.com/SOCI/soci/pull/417) ([snikulov](https://github.com/snikulov)) -- Travis-CI: try add Coverity tool [\#416](https://github.com/SOCI/soci/pull/416) ([snikulov](https://github.com/snikulov)) -- AppVeyor: enable MSSQL ODBC connection [\#415](https://github.com/SOCI/soci/pull/415) ([snikulov](https://github.com/snikulov)) -- added test to demonstrate bug \#221 [\#414](https://github.com/SOCI/soci/pull/414) ([hw-dwalter](https://github.com/hw-dwalter)) -- Appveyor: added build for MySQL backend [\#410](https://github.com/SOCI/soci/pull/410) ([snikulov](https://github.com/snikulov)) -- Appveyor: added PosgreSQL 9.4 backend [\#409](https://github.com/SOCI/soci/pull/409) ([snikulov](https://github.com/snikulov)) -- Appveyor: Added SQLite to build [\#408](https://github.com/SOCI/soci/pull/408) ([snikulov](https://github.com/snikulov)) -- appvr: added db services to build workers [\#406](https://github.com/SOCI/soci/pull/406) ([snikulov](https://github.com/snikulov)) -- ODBC: test updates [\#405](https://github.com/SOCI/soci/pull/405) ([snikulov](https://github.com/snikulov)) -- fixed typo [\#403](https://github.com/SOCI/soci/pull/403) ([DraconPern](https://github.com/DraconPern)) -- Name struct to avoid clang error/warning \(issue \#374\) [\#402](https://github.com/SOCI/soci/pull/402) ([ArnaudD-FR](https://github.com/ArnaudD-FR)) -- Appveyor: added Boost libraries to build [\#401](https://github.com/SOCI/soci/pull/401) ([snikulov](https://github.com/snikulov)) -- fix for \#370 [\#400](https://github.com/SOCI/soci/pull/400) ([snikulov](https://github.com/snikulov)) -- Update README.md [\#399](https://github.com/SOCI/soci/pull/399) ([snikulov](https://github.com/snikulov)) -- mingw: not use ms extension for MinGW G++ compilation [\#398](https://github.com/SOCI/soci/pull/398) ([snikulov](https://github.com/snikulov)) -- cmake: generate verbose build [\#397](https://github.com/SOCI/soci/pull/397) ([snikulov](https://github.com/snikulov)) -- connection-pool: moved common part out of \#ifdef [\#395](https://github.com/SOCI/soci/pull/395) ([snikulov](https://github.com/snikulov)) -- Restore using -pedantic but use -Wno-pedantic-ms-format too [\#392](https://github.com/SOCI/soci/pull/392) ([vadz](https://github.com/vadz)) -- initial integration with AppVeyor-CI [\#391](https://github.com/SOCI/soci/pull/391) ([snikulov](https://github.com/snikulov)) -- boost: disable autolink, because soci controls required libs itself [\#389](https://github.com/SOCI/soci/pull/389) ([snikulov](https://github.com/snikulov)) -- cmake: updated FindODBC.cmake to search right sqlext.h on Windows [\#387](https://github.com/SOCI/soci/pull/387) ([snikulov](https://github.com/snikulov)) -- sqlite3\_close moved after sqlite3\_errmsg is called. [\#381](https://github.com/SOCI/soci/pull/381) ([ravselj](https://github.com/ravselj)) -- Build system: Replacing CMAKE\_SOURCE\_DIR with CMAKE\_CURRENT\_SOURCE\_DIR [\#380](https://github.com/SOCI/soci/pull/380) ([dgrafe](https://github.com/dgrafe)) -- Memory leak fix in sqlite3 backend [\#378](https://github.com/SOCI/soci/pull/378) ([ravselj](https://github.com/ravselj)) -- CMake debug postfix [\#376](https://github.com/SOCI/soci/pull/376) ([ravselj](https://github.com/ravselj)) -- Sqlite backend fetch bug [\#375](https://github.com/SOCI/soci/pull/375) ([ravselj](https://github.com/ravselj)) -- Fixed ambiguous 'session' reference [\#373](https://github.com/SOCI/soci/pull/373) ([musopr](https://github.com/musopr)) -- Include SOCI\_CXX\_VERSION\_FLAGS when compiling with Clang [\#372](https://github.com/SOCI/soci/pull/372) ([musopr](https://github.com/musopr)) -- CMake changes [\#368](https://github.com/SOCI/soci/pull/368) ([ravselj](https://github.com/ravselj)) -- MSVC warnings in SQLite backend [\#365](https://github.com/SOCI/soci/pull/365) ([ravselj](https://github.com/ravselj)) -- Fix connection-parameters options bug [\#364](https://github.com/SOCI/soci/pull/364) ([ravselj](https://github.com/ravselj)) -- Allow setting ORACLE\_HOME directly in CMake GUI [\#363](https://github.com/SOCI/soci/pull/363) ([ravselj](https://github.com/ravselj)) -- Sqlite3 optimization \[\#2\] [\#362](https://github.com/SOCI/soci/pull/362) ([ArnaudD-FR](https://github.com/ArnaudD-FR)) -- Add dt\_blob [\#361](https://github.com/SOCI/soci/pull/361) ([ArnaudD-FR](https://github.com/ArnaudD-FR)) -- Split Statement::clean\_up into bind\_clean\_up and clean\_up [\#358](https://github.com/SOCI/soci/pull/358) ([ArnaudD-FR](https://github.com/ArnaudD-FR)) -- Improve ODBC error messages. [\#357](https://github.com/SOCI/soci/pull/357) ([vadz](https://github.com/vadz)) -- Set CMake variable SOCI\_CORE\_TARGET at PARENT\_SCOPE [\#352](https://github.com/SOCI/soci/pull/352) ([ravselj](https://github.com/ravselj)) -- Updated classic Makefile for PostgreSQL backend. [\#348](https://github.com/SOCI/soci/pull/348) ([msobczak](https://github.com/msobczak)) -- Make it easier to override SOCI\_LIBDIR. [\#347](https://github.com/SOCI/soci/pull/347) ([jsonn](https://github.com/jsonn)) -- Updated classic Makefiles for Oracle Express 11.2. [\#346](https://github.com/SOCI/soci/pull/346) ([msobczak](https://github.com/msobczak)) -- Markdown Documentation [\#344](https://github.com/SOCI/soci/pull/344) ([OniDaito](https://github.com/OniDaito)) -- Minor C++11 Pragma bugfix and Inlining C++11 test pragmas [\#343](https://github.com/SOCI/soci/pull/343) ([OniDaito](https://github.com/OniDaito)) -- Fully qualify uses of session class with namespace soci::session [\#341](https://github.com/SOCI/soci/pull/341) ([mloskot](https://github.com/mloskot)) -- Added the C++11 changes back in. Replaces \#327 [\#336](https://github.com/SOCI/soci/pull/336) ([OniDaito](https://github.com/OniDaito)) -- Add -Wl,-flat\_namespace -Wl,-undefined -Wl,suppress to LINK\_FLAGS on Apple/OSX [\#335](https://github.com/SOCI/soci/pull/335) ([mloskot](https://github.com/mloskot)) -- Restore Oracle setup on Travis CI server [\#326](https://github.com/SOCI/soci/pull/326) ([mloskot](https://github.com/mloskot)) -- Use parameter names from query in the error messages. [\#318](https://github.com/SOCI/soci/pull/318) ([vadz](https://github.com/vadz)) -- Small cleanup remaining from the attempt to fix timezone handling [\#316](https://github.com/SOCI/soci/pull/316) ([vadz](https://github.com/vadz)) -- Updated FindMySQL.cmake to work under 64-bit windows. [\#314](https://github.com/SOCI/soci/pull/314) ([piotaixr](https://github.com/piotaixr)) -- Don't add DB2\_INCLUDE\_DIR to global include directories. [\#313](https://github.com/SOCI/soci/pull/313) ([vadz](https://github.com/vadz)) -- Add postgression service to Travis CI setup [\#306](https://github.com/SOCI/soci/pull/306) ([mloskot](https://github.com/mloskot)) -- Merging master \(SOCI 3.2.3\) into develop [\#304](https://github.com/SOCI/soci/pull/304) ([mloskot](https://github.com/mloskot)) - -## [3.2.3](https://github.com/SOCI/soci/tree/3.2.3) (2015-04-08) -[Full Changelog](https://github.com/SOCI/soci/compare/3.2.2...3.2.3) - -**Closed issues:** - -- I want adaptable dumper. [\#299](https://github.com/SOCI/soci/issues/299) -- ODBC Connection parameter SQL\_DRIVER\_NOPROMPT throws std::logic\_error [\#273](https://github.com/SOCI/soci/issues/273) -- Problems with UTF-8 encoding while using std::strings in soci::use [\#269](https://github.com/SOCI/soci/issues/269) -- Build failure on Visual C++ 2013 due to strtoll\(\) and strtoull\(\) functions [\#262](https://github.com/SOCI/soci/issues/262) -- soci odbi-backend spelling error Commiting -\> Committing [\#260](https://github.com/SOCI/soci/issues/260) -- Assignment operator := needs to be treated specially when parsing the MySQL query [\#259](https://github.com/SOCI/soci/issues/259) -- ORA-00932: inconsistent datatypes: expected NUMBER got TIMESTAMP [\#252](https://github.com/SOCI/soci/issues/252) -- Oracle Connection to Cluster via TNS description [\#250](https://github.com/SOCI/soci/issues/250) -- can't generate vc7.1 project [\#227](https://github.com/SOCI/soci/issues/227) -- Memory leak after using open/creating soci::session with std::string [\#222](https://github.com/SOCI/soci/issues/222) -- Uncaughtable exception [\#219](https://github.com/SOCI/soci/issues/219) -- SOCI\_LIBDIR ends up being hard-coded to 'lib64' [\#212](https://github.com/SOCI/soci/issues/212) -- Add SOCI to Upstream Tracker [\#210](https://github.com/SOCI/soci/issues/210) -- Set CMake 2.8.8 as minimum required [\#200](https://github.com/SOCI/soci/issues/200) -- CMake 2.8.7 cannot set include\_directories per target [\#199](https://github.com/SOCI/soci/issues/199) -- Set up postgression service for Travis CI [\#167](https://github.com/SOCI/soci/issues/167) -- Implement new source tree layout [\#125](https://github.com/SOCI/soci/issues/125) -- Buried headers and includes cleanup [\#25](https://github.com/SOCI/soci/issues/25) -- Deadlock in non-windows implementation of soci::connection\_pool::try\_lease [\#284](https://github.com/SOCI/soci/issues/284) -- Patch for Visual Studio 2013 \(VC12\) [\#272](https://github.com/SOCI/soci/issues/272) -- Patch for using Oracle Instantclient v. 12 [\#271](https://github.com/SOCI/soci/issues/271) -- Avoid exception from destructor while stack unwinding [\#256](https://github.com/SOCI/soci/issues/256) -- git flow hotfix finish 3.2.3 [\#235](https://github.com/SOCI/soci/issues/235) -- git flow hotfix start 3.2.3 [\#234](https://github.com/SOCI/soci/issues/234) -- Compiling SOCI on Visual Studio 2013 Express [\#233](https://github.com/SOCI/soci/issues/233) -- Add git-flow support branch for 3.2 releases [\#206](https://github.com/SOCI/soci/issues/206) -- Clarify bulk examples [\#204](https://github.com/SOCI/soci/issues/204) - -**Merged pull requests:** - -- Provide error context in the exceptions. [\#302](https://github.com/SOCI/soci/pull/302) ([vadz](https://github.com/vadz)) -- Add helper exchange\_type\_cast\<\>\(\) template function. [\#301](https://github.com/SOCI/soci/pull/301) ([vadz](https://github.com/vadz)) -- Use a base-class member instead of shadowing it. [\#297](https://github.com/SOCI/soci/pull/297) ([nbougalis](https://github.com/nbougalis)) -- Fix for the issue \#169: cleaner way to include headers. [\#294](https://github.com/SOCI/soci/pull/294) ([denisarnaud](https://github.com/denisarnaud)) -- Don't start implicit transaction too eagerly in Firebird backend. [\#292](https://github.com/SOCI/soci/pull/292) ([vadz](https://github.com/vadz)) -- Fix PostgreSQL unit test to pass with PostgreSQL \< 9.0. [\#242](https://github.com/SOCI/soci/pull/242) ([vadz](https://github.com/vadz)) -- Include all public headers using "soci/" prefix inside SOCI itself. [\#239](https://github.com/SOCI/soci/pull/239) ([vadz](https://github.com/vadz)) -- Add helper cstring\_to\_double\(\) and use it in PostgreSQL backend. [\#238](https://github.com/SOCI/soci/pull/238) ([vadz](https://github.com/vadz)) -- Fix compilation of ODBC-specific SOCI header with new include paths. [\#237](https://github.com/SOCI/soci/pull/237) ([vadz](https://github.com/vadz)) -- Add get\_last\_insert\_id for sqlite3 and mysql backends [\#216](https://github.com/SOCI/soci/pull/216) ([dgrambow](https://github.com/dgrambow)) -- Fix in soci::oracle to allow spaces in the params [\#213](https://github.com/SOCI/soci/pull/213) ([ayllon](https://github.com/ayllon)) -- Adding cmake SOCI\_SHARED option and lowercasing windows.h [\#286](https://github.com/SOCI/soci/pull/286) ([bingmann](https://github.com/bingmann)) -- fixed deadlock in soci::connection\_pool::try\_lease [\#285](https://github.com/SOCI/soci/pull/285) ([javerskulpa](https://github.com/javerskulpa)) -- Add missing include for std::max [\#278](https://github.com/SOCI/soci/pull/278) ([mika-fischer](https://github.com/mika-fischer)) -- Two enhancements for SOCI 3.2.3 hotfix, PostgreSQL UUID column support and SQLITE3 error code in exception [\#263](https://github.com/SOCI/soci/pull/263) ([Alex-Vol](https://github.com/Alex-Vol)) -- Spelling fix Comiting -\> Comitting \(Fixes \#260\) [\#261](https://github.com/SOCI/soci/pull/261) ([coldtobi](https://github.com/coldtobi)) -- vs2013 got strtoll/strtoull [\#217](https://github.com/SOCI/soci/pull/217) ([fly2xj](https://github.com/fly2xj)) - -## [3.2.2](https://github.com/SOCI/soci/tree/3.2.2) (2013-09-10) -[Full Changelog](https://github.com/SOCI/soci/compare/3.2.1...3.2.2) - -**Closed issues:** - -- sqlite3 backend abstract on build [\#139](https://github.com/SOCI/soci/issues/139) -- sqlite3: sqlite3\_prepare will return SQLITE\_SCHEMA, please use sqlite3\_prepare\_v2 [\#188](https://github.com/SOCI/soci/issues/188) -- CMake option SQLITE3\_LIBRARIES not handled correctly [\#182](https://github.com/SOCI/soci/issues/182) -- noexcept on once\_temp\_type [\#181](https://github.com/SOCI/soci/issues/181) -- git flow hotfix finish 3.2.2 [\#180](https://github.com/SOCI/soci/issues/180) -- Wrong GCC\_VERSION for commandline-overriden GCC [\#178](https://github.com/SOCI/soci/issues/178) -- Separate Travis CI builds per backend [\#171](https://github.com/SOCI/soci/issues/171) -- MSVC build of ODBC with UNICODE enabled fails on error handling [\#163](https://github.com/SOCI/soci/issues/163) -- git flow hotfix start 3.2.2 [\#159](https://github.com/SOCI/soci/issues/159) -- Calling undefine\_and\_bind and then define\_and\_bind causes a leak. [\#154](https://github.com/SOCI/soci/issues/154) -- Uninitialized soci::indicator values in type conversion specialisations [\#152](https://github.com/SOCI/soci/issues/152) -- Incorrect sscanf format strings on windows [\#149](https://github.com/SOCI/soci/issues/149) -- db2\_standard\_use\_type\_backend don't detect correctly size changes in string parameters [\#141](https://github.com/SOCI/soci/issues/141) -- db2\_standard\_use\_type\_backend doesn't detect correctly size changes in parameters [\#140](https://github.com/SOCI/soci/issues/140) -- Problem doing a cast because of the colon parsing [\#121](https://github.com/SOCI/soci/issues/121) -- Documentation for specializing type\_conversion\<\> doesn't fully explain indicators [\#102](https://github.com/SOCI/soci/issues/102) -- get\_affected\_rows\(\) returns -1 for bulk operations [\#83](https://github.com/SOCI/soci/issues/83) -- Undefined behaviour when use unitialized indicator [\#28](https://github.com/SOCI/soci/issues/28) - -**Merged pull requests:** - -- Handle SQLITE3\_LIBRARIES by find\_package\_handle\_standard\_args [\#193](https://github.com/SOCI/soci/pull/193) ([mloskot](https://github.com/mloskot)) -- Specify once\_temp\_type dtor with noexcept\(false\) [\#192](https://github.com/SOCI/soci/pull/192) ([mloskot](https://github.com/mloskot)) -- Replace sqlite3\_prepare with sqlite3\_prepare\_v2 [\#191](https://github.com/SOCI/soci/pull/191) ([mloskot](https://github.com/mloskot)) -- fixed wrong size parameter in final memcpy\(\) [\#185](https://github.com/SOCI/soci/pull/185) ([ghost](https://github.com/ghost)) -- In Unix System cmake could not find ORACLE\_NNZ\_LIBRARY for Oracle 12g.li... [\#183](https://github.com/SOCI/soci/pull/183) ([cngzhnp](https://github.com/cngzhnp)) -- Travis matrix builds [\#174](https://github.com/SOCI/soci/pull/174) ([mloskot](https://github.com/mloskot)) -- Explicitly include stdarg.h pulled in by namespace-protected sqlite.h. [\#172](https://github.com/SOCI/soci/pull/172) ([jsonn](https://github.com/jsonn)) -- A more compatible test for issue \#154, make firebird run it. [\#165](https://github.com/SOCI/soci/pull/165) ([ricardofandrade](https://github.com/ricardofandrade)) -- ODBC: Reviewed the local use of the rows\_processed [\#161](https://github.com/SOCI/soci/pull/161) ([ricardofandrade](https://github.com/ricardofandrade)) -- Fixes the compilation of the firebird tests with the backend as a DLL. [\#147](https://github.com/SOCI/soci/pull/147) ([ricardofandrade](https://github.com/ricardofandrade)) -- Handle PostgreSQL's UNKNOWNOID type as a string into row [\#135](https://github.com/SOCI/soci/pull/135) ([ricardofandrade](https://github.com/ricardofandrade)) -- Don't allow exceptions escape from postgresql\_statement\_backend dtor. [\#134](https://github.com/SOCI/soci/pull/134) ([vadz](https://github.com/vadz)) -- Implement session::get\_next\_sequence\_value\(\) for PostgreSQL backend. [\#133](https://github.com/SOCI/soci/pull/133) ([vadz](https://github.com/vadz)) -- Fix harmless warning about signed/unsigned comparison. [\#132](https://github.com/SOCI/soci/pull/132) ([vadz](https://github.com/vadz)) -- Some trivial optimizations in ODBC statement preparation code. [\#111](https://github.com/SOCI/soci/pull/111) ([vadz](https://github.com/vadz)) - -## [3.2.1](https://github.com/SOCI/soci/tree/3.2.1) (2013-04-12) -[Full Changelog](https://github.com/SOCI/soci/compare/3.2.0...3.2.1) - -**Closed issues:** - -- MySQL Backend issues on Mac OS X [\#130](https://github.com/SOCI/soci/issues/130) -- git flow hotfix finish 3.2.1 [\#131](https://github.com/SOCI/soci/issues/131) -- Incorrect usage of numeric\_limits trait in Oracle backed [\#126](https://github.com/SOCI/soci/issues/126) -- SOCI 3.2.0 does not build on Windows [\#123](https://github.com/SOCI/soci/issues/123) -- Clean up names and use of SOCI\_POSTGRESQL\_NOPARAMS [\#120](https://github.com/SOCI/soci/issues/120) -- Prepared insert statement with data exchange and custom type does not work [\#117](https://github.com/SOCI/soci/issues/117) -- deallocate\_prepared\_statement called for non-existing statement [\#116](https://github.com/SOCI/soci/issues/116) -- Query transformation not working with sessions from pool [\#113](https://github.com/SOCI/soci/issues/113) -- Add common tests to DB2 [\#94](https://github.com/SOCI/soci/issues/94) - -**Merged pull requests:** - -- DB2 backend patches [\#97](https://github.com/SOCI/soci/pull/97) ([toonen](https://github.com/toonen)) - -## [3.2.0](https://github.com/SOCI/soci/tree/3.2.0) (2013-03-26) -[Full Changelog](https://github.com/SOCI/soci/compare/3.1.0...3.2.0) - -**Closed issues:** - -- Run time error: what\(\): Malformed connection string. [\#20](https://github.com/SOCI/soci/issues/20) -- Unexpected behavior when making multiple calls to rowset's begin\(\) and end\(\) [\#17](https://github.com/SOCI/soci/issues/17) -- git flow finish release 3.2.0 [\#109](https://github.com/SOCI/soci/issues/109) -- Run common tests against DB2 [\#106](https://github.com/SOCI/soci/issues/106) -- Re-enable g++ testing on travis-ci [\#96](https://github.com/SOCI/soci/issues/96) -- Update CHANGES for 3.2.0 [\#93](https://github.com/SOCI/soci/issues/93) -- Add testing against clang on travis-ci [\#92](https://github.com/SOCI/soci/issues/92) -- Mark Makefile.basic as deprecated [\#91](https://github.com/SOCI/soci/issues/91) -- Build failure with Oracle Instant Client 11.2.0.3.0 [\#89](https://github.com/SOCI/soci/issues/89) -- SOCI\_COMPILER\_NAME not determined for VS2012 [\#87](https://github.com/SOCI/soci/issues/87) -- postgresql backend leaks a PGResult\* when an exception is thrown [\#86](https://github.com/SOCI/soci/issues/86) -- Update documentation for 3.2.0 release [\#85](https://github.com/SOCI/soci/issues/85) -- Binding procedure IN/OUT parameter has no out effect [\#81](https://github.com/SOCI/soci/issues/81) -- Add CMake option SOCI\_STATIC [\#80](https://github.com/SOCI/soci/issues/80) -- Patch with DB2 backend [\#70](https://github.com/SOCI/soci/issues/70) -- Allocated statement backend memory leaks on exception [\#67](https://github.com/SOCI/soci/issues/67) -- Add query transformation callback feature [\#66](https://github.com/SOCI/soci/issues/66) -- Add Firebird support to Travis-CI configuration [\#64](https://github.com/SOCI/soci/issues/64) -- Add missing ODBC tests to CMake configuration [\#62](https://github.com/SOCI/soci/issues/62) -- Add CMake configuration for Firebird [\#57](https://github.com/SOCI/soci/issues/57) -- Add ODBC support to Travis-CI configuration [\#49](https://github.com/SOCI/soci/issues/49) -- Incorrect assertion in postgresql::get\_error\_details [\#48](https://github.com/SOCI/soci/issues/48) -- Update code examples [\#47](https://github.com/SOCI/soci/issues/47) -- Placeholder at the last position of statement causing crash [\#44](https://github.com/SOCI/soci/issues/44) -- warning: comparing floating point with == or != is unsafe [\#42](https://github.com/SOCI/soci/issues/42) -- Bump SOCI version in master to 3.2.0 [\#39](https://github.com/SOCI/soci/issues/39) -- FindODBC.cmake deviates from soci\_backend\(\) conventions [\#32](https://github.com/SOCI/soci/issues/32) -- Building with Visual Studio 2010: identifier strtoull not found [\#27](https://github.com/SOCI/soci/issues/27) -- CMake ignores -DWITH\_\ option [\#23](https://github.com/SOCI/soci/issues/23) -- make install - Fedora 17 [\#21](https://github.com/SOCI/soci/issues/21) -- Server-side memory leak in PostgreSQL [\#19](https://github.com/SOCI/soci/issues/19) -- Apply Git workflow: GitFlow [\#18](https://github.com/SOCI/soci/issues/18) -- FindMySQL.cmake update for custom mysqlclient location [\#16](https://github.com/SOCI/soci/issues/16) -- Premature deallocation of prepared statement [\#13](https://github.com/SOCI/soci/issues/13) - -**Merged pull requests:** - -- Fix int and long mismatch for vector in ODBC [\#103](https://github.com/SOCI/soci/pull/103) ([mloskot](https://github.com/mloskot)) -- Fix OUT direction of IN/OUT procedure parameter [\#88](https://github.com/SOCI/soci/pull/88) ([mloskot](https://github.com/mloskot)) -- Implementation of query transformation callback feature [\#82](https://github.com/SOCI/soci/pull/82) ([mloskot](https://github.com/mloskot)) -- Fix Firebird tests: test\_get\_affected\_rows\(\) [\#74](https://github.com/SOCI/soci/pull/74) ([vnaydionov](https://github.com/vnaydionov)) -- Fix connection parsing in SOCI Firebird backend to handle spaces in values. [\#73](https://github.com/SOCI/soci/pull/73) ([vadz](https://github.com/vadz)) -- Firebird backend specific: add option to fetch decimals as strings [\#71](https://github.com/SOCI/soci/pull/71) ([vnaydionov](https://github.com/vnaydionov)) -- Improve fixes in pull \#5 [\#69](https://github.com/SOCI/soci/pull/69) ([mloskot](https://github.com/mloskot)) -- Fix memory leak of statement backend \(issue \#67\) [\#68](https://github.com/SOCI/soci/pull/68) ([mloskot](https://github.com/mloskot)) -- Improve input parameter binding in Firebird backend. [\#65](https://github.com/SOCI/soci/pull/65) ([vnaydionov](https://github.com/vnaydionov)) -- Add missing ODBC tests to CMake configuration \(issue \#62\) [\#63](https://github.com/SOCI/soci/pull/63) ([mloskot](https://github.com/mloskot)) -- Add PostgreSQL test for bytea to pull request \#46 [\#61](https://github.com/SOCI/soci/pull/61) ([mloskot](https://github.com/mloskot)) -- Added CMake scripts for Firebird backend and fixed it to pass all the tests [\#60](https://github.com/SOCI/soci/pull/60) ([vnaydionov](https://github.com/vnaydionov)) -- Fix to build the Firebird backend [\#56](https://github.com/SOCI/soci/pull/56) ([vnaydionov](https://github.com/vnaydionov)) -- Properly compute LIBDIR on \(modern\) Debian [\#55](https://github.com/SOCI/soci/pull/55) ([hasselmm](https://github.com/hasselmm)) -- Support reading bytea data in PostgreSQL backend as another string type [\#46](https://github.com/SOCI/soci/pull/46) ([hobu](https://github.com/hobu)) -- Patch received from Daniel Beaudoin \(Optel Vision\) on 23/07/2012\) [\#45](https://github.com/SOCI/soci/pull/45) ([mloskot](https://github.com/mloskot)) -- For Visual C++, defined std::strtoll in terms of \_strtoi64\(\) [\#43](https://github.com/SOCI/soci/pull/43) ([mloskot](https://github.com/mloskot)) -- Bumped version number to 3.2.0 [\#40](https://github.com/SOCI/soci/pull/40) ([mloskot](https://github.com/mloskot)) -- handle WITH\_{dependency} switch to turn on/off deps [\#38](https://github.com/SOCI/soci/pull/38) ([snikulov](https://github.com/snikulov)) -- qualify strtoull/strtoll with std namespace [\#37](https://github.com/SOCI/soci/pull/37) ([avg-I](https://github.com/avg-I)) -- FindSoci.cmake: fix couple of minor issues [\#36](https://github.com/SOCI/soci/pull/36) ([avg-I](https://github.com/avg-I)) -- FindODBC.cmake: rename ODBC\_INCLUDE\_DIRECTORIES to ODBC\_INCLUDE\_DIR [\#35](https://github.com/SOCI/soci/pull/35) ([avg-I](https://github.com/avg-I)) -- README update and minimal CMake version update [\#34](https://github.com/SOCI/soci/pull/34) ([mloskot](https://github.com/mloskot)) -- backends/oracle: support working in multithreaded programs [\#31](https://github.com/SOCI/soci/pull/31) ([avg-I](https://github.com/avg-I)) -- Set INSTALL\_NAME\_DIR as used on OS X [\#30](https://github.com/SOCI/soci/pull/30) ([arsenm](https://github.com/arsenm)) -- cmake: FindSQLite3 - add handling of SQLITE\_ROOT\_DIR [\#29](https://github.com/SOCI/soci/pull/29) ([snikulov](https://github.com/snikulov)) -- Fix proposal for issue SOCI/soci\#13 [\#14](https://github.com/SOCI/soci/pull/14) ([mloskot](https://github.com/mloskot)) -- This makes possible to disable empty backend build [\#11](https://github.com/SOCI/soci/pull/11) ([krieger-od](https://github.com/krieger-od)) -- OSX clang std::getline bug [\#10](https://github.com/SOCI/soci/pull/10) ([hobu](https://github.com/hobu)) -- cmake: updated backends build [\#8](https://github.com/SOCI/soci/pull/8) ([snikulov](https://github.com/snikulov)) -- SQLite database path may contain spaces if enclosed in quotes. [\#6](https://github.com/SOCI/soci/pull/6) ([belobrov-andrey](https://github.com/belobrov-andrey)) -- Backend is not set properly with connection pool [\#5](https://github.com/SOCI/soci/pull/5) ([ghost](https://github.com/ghost)) -- Fixed a compile error in FreeBSD 8.2, using the lates GCC version 4.2.1 [\#2](https://github.com/SOCI/soci/pull/2) ([jamercee](https://github.com/jamercee)) -- Implement get\_affected\_rows for SQLite3 backend [\#1](https://github.com/SOCI/soci/pull/1) ([mika-fischer](https://github.com/mika-fischer)) - -## [3.1.0](https://github.com/SOCI/soci/tree/3.1.0) (2011-10-20) -[Full Changelog](https://github.com/SOCI/soci/compare/v3.1.0...3.1.0) - -## [v3.1.0](https://github.com/SOCI/soci/tree/v3.1.0) (2011-10-20) -[Full Changelog](https://github.com/SOCI/soci/compare/soci-3.1.0.zip...v3.1.0) - -## [soci-3.1.0.zip](https://github.com/SOCI/soci/tree/soci-3.1.0.zip) (2011-10-08) -[Full Changelog](https://github.com/SOCI/soci/compare/v3.0.0...soci-3.1.0.zip) - -## [v3.0.0](https://github.com/SOCI/soci/tree/v3.0.0) (2008-07-09) -[Full Changelog](https://github.com/SOCI/soci/compare/soci-3.0.0.zip...v3.0.0) - -## [soci-3.0.0.zip](https://github.com/SOCI/soci/tree/soci-3.0.0.zip) (2008-07-08) -[Full Changelog](https://github.com/SOCI/soci/compare/soci-2.2.0.zip...soci-3.0.0.zip) - -## [soci-2.2.0.zip](https://github.com/SOCI/soci/tree/soci-2.2.0.zip) (2006-12-02) -[Full Changelog](https://github.com/SOCI/soci/compare/soci-2.1.0.zip...soci-2.2.0.zip) - -## [soci-2.1.0.zip](https://github.com/SOCI/soci/tree/soci-2.1.0.zip) (2006-05-12) -[Full Changelog](https://github.com/SOCI/soci/compare/soci-2.0.1.zip...soci-2.1.0.zip) - -## [soci-2.0.1.zip](https://github.com/SOCI/soci/tree/soci-2.0.1.zip) (2006-02-15) -[Full Changelog](https://github.com/SOCI/soci/compare/soci-2.0.0.zip...soci-2.0.1.zip) - -## [soci-2.0.0.zip](https://github.com/SOCI/soci/tree/soci-2.0.0.zip) (2006-01-15) -[Full Changelog](https://github.com/SOCI/soci/compare/soci-1.2.1.zip...soci-2.0.0.zip) - -## [soci-1.2.1.zip](https://github.com/SOCI/soci/tree/soci-1.2.1.zip) (2005-10-13) -[Full Changelog](https://github.com/SOCI/soci/compare/soci-1.2.0.zip...soci-1.2.1.zip) - -## [soci-1.2.0.zip](https://github.com/SOCI/soci/tree/soci-1.2.0.zip) (2005-10-02) -[Full Changelog](https://github.com/SOCI/soci/compare/soci-1.1.0.zip...soci-1.2.0.zip) - -## [soci-1.1.0.zip](https://github.com/SOCI/soci/tree/soci-1.1.0.zip) (2005-02-27) -[Full Changelog](https://github.com/SOCI/soci/compare/soci-1.0.1.zip...soci-1.1.0.zip) - -## [soci-1.0.1.zip](https://github.com/SOCI/soci/tree/soci-1.0.1.zip) (2004-10-16) - - -\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)* \ No newline at end of file diff --git a/src/soci/CHANGES b/src/soci/CHANGES deleted file mode 100644 index 6e664b99b3..0000000000 --- a/src/soci/CHANGES +++ /dev/null @@ -1,384 +0,0 @@ -This file contains the history of changes in the SOCI library. - ---- -Version 4.0.0 differs from 3.2.x in the following ways: - -- Provide context of the failure in soci_error::what() which now returns a - longer and more useful message. Use the new get_error_message() method to get - just the brief error message which used to be returned by what(). -- Add helpers for generating portable DDL and DML statements. - -- Firebird --- Add SOCI_FIREBIRD_EMBEDDED option to allow building with embedded library. --- Throw an exception instead of truncating too long VARCHAR columns values. - -- ODBC/MS SQL --- Fix inserting strings of length greater than 8000 bytes into database. - -- Oracle --- Use SQLT_BDOUBLE for floating point values instead of SQLT_FLT. - ---- -Version 3.2.3 differs from 3.2.2 in the following ways: - -- Improved Boost Tuple & Fusion integration by using boost::fusion::foreach - to reference each member of a sequence. Breaks compatibility with Boost 1.35 (2008). -- Fixed linker error when building 64-bit target with Visual Studio. -- Fixed several issues with building using Cygwin and MinGW. -- Clarified documentation and examples on bulk operations. - -- MySQL --- Fixed building against MySQL 3.23. - -- ODBC -- Improve readability of ODBC error messages. -- Fixed CMake configuration of ODBC backend for Visual Studio 64-bit targets. - -- Oracle --- We've had to disable Oracle target in the Travis CI configuration until we - figure out how to setup Oracle on Travis CI directly. - Therefore, this release hasn't been extensively tested against Oracle. - -- PostgreSQL --- Added support for UUID column type (tests and docs updated). - -- SQLite3 --- Added sqlite3_soci_error exception as subclass of soci_error to provide useful - exposure of specific SQLite3 error codes (tests and docs updated). - ---- -Version 3.2.2 differs from 3.2.1 in the following ways: - -- Fixed once_temp_type destructor with noexcept(false) specifier for C++11 -- Fix uninitialized indicators in conversion_into_type and conversion_use_type specialisations -- Fixed placeholder matching for PostgreSQL-style casts with ORM -- Fixed memory leaking in use binding in case of bind/unbind sequence -- Fixed sscanf formatter for MinGW/MSVC in backends -- Fixed partial placeholder name matching for ORM cases -- Added test for use of indicators with rowset -- Added test for get_affected_rows after bulk operations - -- DB2 --- Enable build and testing on Travis CI --- Fixed use type size calculation during bind/pre_use - -- Firebird --- Enable memory cleanup to avoid leaks after binding --- Added missing C++ library headers --- Added get_affected_rows() support for bulk operations --- Fixed compilation with VS2008 --- Fixed building tests with the backend built as DLL. - -- MySQL --- Added get_affected_rows() support for bulk operations - -- ODBC --- Always call ASCII version of ODBC function SQLGetDiagRec --- Fixed invalid condition test in assertions --- Added get_affected_rows() support for bulk operations --- Added support for (unsigned) long long vectors --- Changed mapping of SQL_BIGINT to dt_long_long in ODBC backend --- Added some trivial optimizations in statement preparation code - -- Oracle --- Fixed missing noData_ reported in particular case when OCIStmtExecute returns success --- Improved Oracle testing setup on Travis CI - -- PostgreSQL --- Added session::get_next_sequence_value() for PostgreSQL backend --- Added get_affected_rows() support for bulk operations --- Applied RAII and simplified error handling logic --- Fixed issue with exceptions escaping postgresql_statement_backend destructor - -- SQLite3 --- Replaced sqlite3_prepare with sqlite3_prepare_v2 --- Added missing header --- Fixed wrong size used in memcpy() during bulk processing --- Added get_affected_rows() support for bulk operations --- Added shared_cache=true propery to control SQLITE_OPEN_SHAREDCACHE flag - -- Documentation --- Corrected usage examples - -- Building --- Updated CMake for Oracle 12g --- Restructured and improved Travis CI setup to do single build per backend --- Fixed wrong GCC_VERSION used in CMake config for commandline-overriden GCC --- Allows CMake to find 32-bit DB2 on Windows x64 --- Removed redundant Oracle libclntsh library lookup --- Fixed SQLITE3_LIBRARIES handling by find_package_handle_standard_args - ---- -Version 3.2.1 differs from 3.2.0 in the following ways: - -- Fixed binding of Oracle type NUMBER(9,0) to C++ int, by Tomasz Olszewski -- Fixed Oracle client library detection on Windows, by Tomasz Olszewski -- Fixed PostgreSQL issue with deallocate_prepared_statement called for non-existing statement -- Fixed prepared insert statements with custom data types support, by Tomasz Olszewski -- Fixed recent improvements in x:=y name binding, by Poul Bondo -- Fixed query transformation assignment in pooled sessions, by Stefan Chrobot -- Cleaned up SOCI_POSTGRESQL_NOPARAMS and related options in code and documentation -- Dropped patch (micro) version number from documentation URLs on the website - ---- -Version 3.2.0 differs from 3.1.0 in the following ways: - -- SOCI is now organization at GitHub --- Git repository moved to https://github.com/SOCI/soci --- Opened new bug tracker (SF.net tracker is read-only) --- Opened Wiki for FAQ and development articles --- Website, mailing lists and downloads remain on SourceForge.net --- Applied GitFlow branching model --- Added package maintenance repository https://github.com/SOCI/soci-pkg - -- Core --- Added connection_parameters to enable support for session options used by core, backends or low-level API. --- Added user-defined query transformation support based on function, functor and lambda --- Fixed missing connection check and backend setup ensured for session --- Fixed backend initialization when used with connection pool (Core) --- Fixed memory leaks on exception thrown during statement preparation stage - -- DB2 --- Added new backend for IBM DB2 - -- Firebird --- Fixed bug in repeated statement execution --- Fixed issues with input parameter binding --- Fixed connection string parsing to handle possible white-spaces --- Fixed issues with C++ type unsigned long --- Fixed reading negative values into C++ type double --- Added option to fetch numeric/decimal data into string of characters --- Added CMake configuration --- Updated tests --- Continued regular testing on Windows and Unix platforms - -- MySQL --- Replaced use of type=InnoDB with engine=InnoDB --- Improved CMake configuration - -- ODBC --- Added connection_parameters option ODBC_OPTION_DRIVER_COMPLETE --- Fixed issues in handling C++ types int and long on 64-bit architectures --- Added missing CMake configuration for tests --- Continued regular testing on Windows and Unix platforms - -- Oracle --- Implemented statement::get_affected_rows() operation --- Use OCI_THREADED and OCI_ENV_NO_MUTEX with OCIEnvCreate --- Added numerous fixes and improvements in tests --- Added option to fetch numeric/decimal data into string of characters --- Fixed issues in binding procedure IN/OUT parameters - -- PostgreSQL --- Add reading of BYTEA data into std::string (not fully-featured binary data support yet) --- Add JSON data type support available in PostgreSQL 9.2+ --- Fixed incorrect assertion in postgresql::get_error_details --- Fixed premature deallocation of prepared statements --- Fixed servers-side memory leak in prepared statements --- Fixed memory leak of PGresult on exception thrown --- Fixed isues in parsing complex PL/PSQL functions - -- SQLite3 --- Implemented statement::get_affected_rows() operation --- Fixed handling of database file path with spaces - -- Building, testing and installation --- Marked Makefile.basic as deprecated (maintainer wanted) --- Cleaned numerous compilation warnings reported by various compilers --- Improved compilation using latest version of clang --- Added numerous improvements in CMake configuration --- Added SOCI_STATIC option to enable/disable static libraries build --- Fixed issues with ignored -DWITH_ options --- Fixed FindMySQL.cmake to allow use of mysqlclient from custom location --- Added support of SQLITE_ROOT_DIR variable to FindSQLite3.cmake module --- Fixed and tested CMake configuration on OSX --- Fixed and tested CMake configuration on FreeBSD --- Fixed and tested CMake configuration to use with Ninja --- Fixed building using Visual Studio 2010 --- Added support for building using Visual Studio 2012 --- Set up SOCI continuous integration at travis-ci.org --- Added Debian packaging support to soci-pkg repository --- Added Fedora/CentOS/RedHat packaging support to soci-pkg repository - -- Documentation --- Review and update to catch up with current status quo --- Updated code examples --- Start maintenance and hosting of SOCI documentation per released version - ---- -Version 3.1.0 differs from 3.0.0 in the following ways: - -- Added Ada language binding - -- Migraded build system from GNU Autotools and Visual Studio projects to CMake - -- CMake build tested with Visual Studio, GCC and clang - -- Incorporated a compromise for naming versioned shared libraries - -- Enhanced and improved integration with Boost libraries: --- Boost.DateTime --- Boost.Fusion --- Boost.Optional --- Boost.Tuple - -- Bug fixes and improvements in core and backends: --- Added soci::values::get_properties accessor useful for composing soci::type_conversion --- Export advanced API of backend loader from DLL. --- Added static factory registration functions for backends --- Added get_affected_rows operation --- Fixed thread-safety of connection pool under Windows --- Fixed bug with droping const qualifiers when binding to std::vector --- Fixed bug in default initialization of an object of const backend_factory wihch requires user-provided default constructor (see C++03/C++0x) --- Fixes for 64-bit builds --- Removed redundant exchange_traits breaking ODR on LP64 --- Better ODBC support --- Type conversion support for unsigned integer types --- Bug ID:1971436 - incorrect rowset copy operations --- Bug ID:2010367 - memory leak (ODBC) --- Bug ID:2010409 - invalid memory allocaton in define by position (ODBC) --- Bug ID:2021243 - long long type support in Visual C++ --- Patch ID:2483066 - 64bit Linux and 64bit integer submitted --- Patch ID:2809809 - Fix build with GCC 4.4 --- Patch ID:2809810 - Fix SQLite3 build with GCC 4.3 --- Patch ID:2581206 - Windows unicode application --- Patch ID:3058275 - install target for cmake build submitted --- Patch ID:3069375 - use $(prefix)/lib64 on AMD64 platforms. --- Improved performance while accessing query results (MySQL) --- Bug fixes for PROCEDURE support (MySQL) --- Removed throw statements from mysql_rowid_backend and mysql_blob_backend destructors (MySQL) --- Verify that prepared statements survive session::reconnect() operatoin (MySQL) --- Improved support for time and date (MySQL, PostgreSQL) --- Fixed bug with strings of length exceeding 255 characters (ODBC) --- Improved interpretation of the connect string (Oracle) --- Added handling of unsigned long long (Oracle, SQLite3, PostgreSQL) --- Fixes in integral types support (PostgreSQL) --- Support for colon-casts (PostgreSQL) --- Added possibility for use BLOB (PostgreSQL) --- Added support for connection property "synchronous=on|off" (SQLite3) --- Improved BLOB data handling (SQLite3) --- Improved boolean type suppport (SQLite3) --- Session timeout support (SQLite3) --- Improved tests clean-up (SQLite3) --- Added missing typedef of sqlite3_destructor_type which has been defined in sqlite3.h but since 3.3.10 (see comment for reference to SQLite ticket) - -- Updated tests for various backends and SQL data types - -- Migrated from CVS to Git repository - -- Changed naming convensions and style across all the source code - -- Firebird backend removed from official release as not actively maintained. Available in the Git repository. - ---- -Version 3.0.0 differs from 2.2.0 in the following ways: - -- Exposed the session's locale object. - -- Moved the "no data" flag from indicators to statement. - -- Allowed const objects as "use" elements. - -- Added connection mode for Oracle. - -- Added RAII support for transactions. - -- Added the open/close/reconnect functionality. - -- Added support for long long as a fundamental data type. - -- Unified column names for dynamic rowset description, to overcome - differences between database servers. - -- Added the "simple" interface for interfacing from other languages. - -- Added thread-safe connection pool. - -- Added integrated support for Boost data types: gregorian_date, - fusion and tuple. - -- Added dynamic backend loading. - -- Changed the naming convention to comply with Boost recommendations. - ---- -Version 2.2.0 differs from 2.1.0 in the following ways: - -- Added true support for statement preparation with PostgreSQL. - -- Added support for the stream-like extraction from Row. - -- Added STL-compatible iterator interface for select statements. - -- Refactored the set of common tests to validate core library functionality - independently on the target database server. - -- Introduced new backends for MS SQL Server (via ODBC) and Firebird. - -- Provided complete build system for both Unix (autotools) and - Windows (solution and project files for MSVC++). - ---- -Version 2.1.0 differs from 2.0.1 in the following ways: - -- Added two additional backends: MySQL and SQLite3 - -- Restructured the source code layout so that the whole library was broken - into the "core" part and independent "backends", each in its own - directory together with appropriate tests. - -- Provided basic Makefiles for static and shared libraries on - Linux-compatible systems. - -- Added the general class and function reference to the documentation. - ---- -Version 2.0.1 differs from 2.0.0 in the following ways: - -- Corrected some typos in documentation. - -- Corrected handling of dynamic rowset description for those backends - which do not have dedicated description functionality. - -- A bug fix to correctly handle std::tm in the Oracle backend. - -- A bug fix to correctly handle object relational mapping when - Values::set() and Values::get() are called where T is a - TypeConversion-based type. - ---- -Version 2.0.0 differs from 1.2.1 in the following ways: - -- The whole library was internally re-architectured to allow operation - with many different backends. The top-level part of the library - (the syntax layer) provides essentially the same interface as in previous - versions of the library, but it can work with independent (and dynamically - selected) backends, possibly targeting different database engines. - As a prove of concept (and to encourage developments of new backends), - the PostgreSQL backend was provided in addition to the Oracle one. - During this re-architecturing, some minor bugs were fixed as well. - -- The old Boost-style license was changed to the new (v. 1.0) Boost license. - ---- -The version 1.2.1 differs from 1.2.0 in the following ways: - -- A bug was fixed that caused compile errors on MS VC++ compiler. - ---- -The version 1.2.0 differs from 1.1.0 in the following ways: - -- A memory leak when reading into Row objects was fixed. - -- Bulk (array) operations were introduced for high-performance - applications, where the number of network round-trips can be - significantly reduced by operating on whole arrays (vectors). - ---- -The version 1.1.0 differs from 1.0.1 in the following ways: - -- Explicit support for calling stored procedures was added. - -- Dynamic row recognition (type discovery) was added. - -- Support for user-defined data types was added. diff --git a/src/soci/CMakeLists.txt b/src/soci/CMakeLists.txt deleted file mode 100644 index 7798b45fe9..0000000000 --- a/src/soci/CMakeLists.txt +++ /dev/null @@ -1,207 +0,0 @@ -############################################################################### -# -# This file is part of CMake configuration for SOCI library -# -# Copyright (C) 2009-2013 Mateusz Loskot -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -# -############################################################################### -# General settings -############################################################################### -cmake_minimum_required(VERSION 2.8.10 FATAL_ERROR) - -project(SOCI) - -############################################################################### -# Build features and variants -############################################################################## - -option(SOCI_SHARED "Enable build of shared libraries" ON) -option(SOCI_STATIC "Enable build of static libraries" ON) -option(SOCI_TESTS "Enable build of collection of SOCI tests" ON) -option(SOCI_ASAN "Enable address sanitizer on GCC v4.8+/Clang v 3.1+" OFF) - - -############################################################################### -# SOCI CMake modules -############################################################################### - -# Path to additional CMake modules -set(CMAKE_MODULE_PATH ${SOCI_SOURCE_DIR}/cmake ${CMAKE_MODULE_PATH}) -set(CMAKE_MODULE_PATH ${SOCI_SOURCE_DIR}/cmake/modules ${CMAKE_MODULE_PATH}) - -include(SociUtilities) -include(SociConfig) - -colormsg(_HIBLUE_ "Configuring SOCI:") - -############################################################################### -# SOCI version information -############################################################################### -include(SociVersion) - -soci_version() - -############################################################################### -# Build features and variants -############################################################################## - -boost_report_value(SOCI_SHARED) -boost_report_value(SOCI_STATIC) -boost_report_value(SOCI_TESTS) -boost_report_value(SOCI_ASAN) - -# from SociConfig.cmake -boost_report_value(SOCI_CXX_C11) -boost_report_value(LIB_SUFFIX) - -# Put the libaries and binaries that get built into directories at the -# top of the build tree rather than in hard-to-find leaf -# directories. This simplifies manual testing and the use of the build -# tree rather than installed Boost libraries. -set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) -set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) -set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) - -############################################################################### -# Find SOCI dependencies -############################################################################### - -set(SOCI_CORE_TARGET) -set(SOCI_CORE_TARGET_STATIC) -set(SOCI_CORE_DEPS_LIBS) - -include(SociDependencies) - -get_property(SOCI_INCLUDE_DIRS DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} - PROPERTY INCLUDE_DIRECTORIES) - -if(Threads_FOUND) - list(APPEND SOCI_CORE_DEPS_LIBS ${CMAKE_THREAD_LIBS_INIT}) -else() - message(FATAL_ERROR "No thread library found") -endif() - -if(NOT MSVC) - set(DL_FIND_QUIETLY TRUE) - find_package(DL) - if(DL_FOUND) - list(APPEND SOCI_CORE_DEPS_LIBS ${DL_LIBRARY}) - set_directory_properties(PROPERTIES INCLUDE_DIRECTORIES ${DL_INCLUDE_DIR}) - add_definitions(-DHAVE_DL=1) - endif() -endif() - -if(Boost_FOUND) - get_property(SOCI_COMPILE_DEFINITIONS - DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} - PROPERTY COMPILE_DEFINITIONS) - - set(SOCI_HAVE_BOOST ON) - - list(APPEND SOCI_COMPILE_DEFINITIONS "BOOST_ALL_NO_LIB") - - if(Boost_DATE_TIME_FOUND) - list(APPEND SOCI_CORE_DEPS_LIBS ${Boost_DATE_TIME_LIBRARY}) - set(SOCI_HAVE_BOOST_DATE_TIME ON) - endif() - - list(APPEND SOCI_INCLUDE_DIRS ${Boost_INCLUDE_DIRS}) - list(APPEND SOCI_CORE_INCLUDE_DIRS ${Boost_INCLUDE_DIRS}) - - set_directory_properties(PROPERTY COMPILE_DEFINITIONS "${SOCI_COMPILE_DEFINITIONS}") - - set_property(DIRECTORY ${SOCI_SOURCE_DIR} - PROPERTY COMPILE_DEFINITIONS "${SOCI_COMPILE_DEFINITIONS}") -else() - set(SOCI_HAVE_BOOST OFF) - set(SOCI_HAVE_BOOST_DATE_TIME OFF) -endif() - -set(SOCI_HAVE_BOOST ${SOCI_HAVE_BOOST} CACHE INTERNAL "Boost library") -set(SOCI_HAVE_BOOST_DATE_TIME ${SOCI_HAVE_BOOST_DATE_TIME} CACHE INTERNAL "Boost date_time library") - -list(APPEND SOCI_INCLUDE_DIRS ${CMAKE_CURRENT_BINARY_DIR}) - -set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} - PROPERTY - INCLUDE_DIRECTORIES ${SOCI_INCLUDE_DIRS}) - -############################################################################### -# Installation -############################################################################### - -if(NOT DEFINED SOCI_LIBDIR) - if(APPLE OR CMAKE_SIZEOF_VOID_P EQUAL 4) - set(SOCI_LIBDIR "lib") - else() - set(SOCI_LIBDIR "lib64") - endif() -endif() - -set(BINDIR "bin" CACHE PATH "The directory to install binaries into.") -set(LIBDIR ${SOCI_LIBDIR} CACHE PATH "The directory to install libraries into.") -set(DATADIR "share" CACHE PATH "The directory to install data files into.") -set(INCLUDEDIR "include" CACHE PATH "The directory to install includes into.") - -############################################################################### -# Configuration files -############################################################################### -set(CONFIG_INCLUDE_DIR ${CMAKE_CURRENT_BINARY_DIR}/include) -install(DIRECTORY ${CONFIG_INCLUDE_DIR}/soci DESTINATION ${INCLUDEDIR}) -set(CONFIG_FILE_IN "include/soci/soci-config.h.in") -set(CONFIG_FILE_OUT "${CONFIG_INCLUDE_DIR}/soci/soci-config.h") - - - -############################################################################### -# Build configured components -############################################################################### -include(SociBackend) - -include_directories(${SOCI_SOURCE_DIR}/include ${CONFIG_INCLUDE_DIR}) -add_subdirectory(src) - -if(SOCI_TESTS) - ############################################################################### - # Enable tests - ############################################################################### - enable_testing() - - file(TO_NATIVE_PATH ${PROJECT_SOURCE_DIR} TEST_ACCESS_PATH) - configure_file(${PROJECT_SOURCE_DIR}/cmake/configs/test-access.cmake ${PROJECT_SOURCE_DIR}/tests/odbc/test-access.dsn @ONLY) - - set(MYSQL_DRIVER_NAME "MySQL") - if(WIN32) - set(MYSQL_DRIVER_NAME "MySQL ODBC 5.3 ANSI Driver") - endif() - configure_file(${PROJECT_SOURCE_DIR}/cmake/configs/test-mysql.cmake ${PROJECT_SOURCE_DIR}/tests/odbc/test-mysql.dsn @ONLY) - - # Define "make check" as alias for "make test" - add_custom_target(check COMMAND ctest) - add_subdirectory(tests) -endif() - -############################################################################### -# build config file -############################################################################### - -get_cmake_property(ALL_VARIABLES CACHE_VARIABLES) -set(CONFIGURED_VARIABLES) -foreach(v ${ALL_VARIABLES}) - if (v MATCHES "^SOCI_HAVE.*") - get_property(CACHE_HELPSTRING CACHE ${v} PROPERTY HELPSTRING) - set(CONFIGURED_VARIABLES "${CONFIGURED_VARIABLES}\n// ${CACHE_HELPSTRING}\n") - if (${${v}}) - set(CONFIGURED_VARIABLES "${CONFIGURED_VARIABLES}#define ${v}\n") - else() - set(CONFIGURED_VARIABLES "${CONFIGURED_VARIABLES}/* #undef ${v} */\n") - endif() - endif() -endforeach() -configure_file("${CONFIG_FILE_IN}" "${CONFIG_FILE_OUT}") - -message(STATUS "") - diff --git a/src/soci/LICENSE_1_0.txt b/src/soci/LICENSE_1_0.txt deleted file mode 100644 index 36b7cd93cd..0000000000 --- a/src/soci/LICENSE_1_0.txt +++ /dev/null @@ -1,23 +0,0 @@ -Boost Software License - Version 1.0 - August 17th, 2003 - -Permission is hereby granted, free of charge, to any person or organization -obtaining a copy of the software and accompanying documentation covered by -this license (the "Software") to use, reproduce, display, distribute, -execute, and transmit the Software, and to prepare derivative works of the -Software, and to permit third-parties to whom the Software is furnished to -do so, all subject to the following: - -The copyright notices in the Software and this entire statement, including -the above license grant, this restriction and the following disclaimer, -must be included in all copies of the Software, in whole or in part, and -all derivative works of the Software, unless such copies or derivative -works are solely in the form of machine-executable object code generated by -a source language processor. - -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, TITLE AND NON-INFRINGEMENT. IN NO EVENT -SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE -FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/src/soci/README.md b/src/soci/README.md deleted file mode 100644 index bea1d6bad1..0000000000 --- a/src/soci/README.md +++ /dev/null @@ -1,59 +0,0 @@ -# SOCI - The C++ Database Access Library - -[![GitHub release](https://img.shields.io/github/tag/SOCI/soci.svg)](https://github.com/SOCI/soci/releases/tag/3.2.3) -[![GitHub commits](https://img.shields.io/github/commits-since/SOCI/soci/3.2.3.svg)](https://github.com/SOCI/soci/tree/master) - -[![Website](https://img.shields.io/website-up-down-green-red/http/shields.io.svg?label=soci.sourceforge.net)](http://soci.sourceforge.net) -[![SourceForge](https://img.shields.io/sourceforge/dm/soci.svg)](https://sourceforge.net/projects/soci/files/) - -[![Gitter](https://img.shields.io/gitter/room/SOCI/soci.svg)](https://gitter.im/SOCI/soci) -[![Mailing Lists](https://img.shields.io/badge/mailing--lists-ok-yellowgreen.svg)](https://sourceforge.net/p/soci/mailman/) -[![StackExchange](https://img.shields.io/stackexchange/stackoverflow/t/soci.svg)](https://stackoverflow.com/questions/tagged/soci) - -## Build Status - -| Branches | Travis-CI | AppVeyor-CI | Coverity Scan | Documentation | -|-------------|-----------|-------------|----------------|---------------| -| master | [![Build Status](https://travis-ci.org/SOCI/soci.svg?branch=master)](https://travis-ci.org/SOCI/soci) | [![Build status](https://ci.appveyor.com/api/projects/status/dtp5mvbeyu9aqupr/branch/master?svg=true)](https://ci.appveyor.com/project/SOCI/soci/branch/master) | [![Coverage](https://scan.coverity.com/projects/6581/badge.svg)](https://scan.coverity.com/projects/soci-soci) | [![Docs Status](https://circleci.com/gh/SOCI/soci.svg?style=shield&circle-token=5d31c692ed5fcffa5c5fc6b7fe2257b34d78f3c9)](https://circleci.com/gh/SOCI/soci) | -| release/3.2 | [![Build Status](https://travis-ci.org/SOCI/soci.svg?branch=release%2F3.2)](https://travis-ci.org/SOCI/soci) | | | | - -## History - -Originally, SOCI was developed by [Maciej Sobczak](http://www.msobczak.com/) -at [CERN](http://www.cern.ch/) as abstraction layer for Oracle, -a **Simple Oracle Call Interface**. -Later, several database backends have been developed for SOCI, -thus the long name has lost its practicality. -Currently, if you like, SOCI may stand for **Simple Open (Database) Call Interface** -or something similar. - -> "CERN is also a user of the SOCI library, which serves as a database access -> layer in some of the control system components." - --- Maciej Sobczak at [Inspirel](http://www.inspirel.com/users.html) - -## License - -SOCI library is distributed under the terms of the [Boost Software License](http://www.boost.org/LICENSE_1_0.txt). - -## Requirements - -Core: - -* C++ compiler -* Boost C++ Libraries (optional, headers and Boost.DateTime) - -Backend specific client libraries for: - -* DB2 -* Firebird -* MySQL -* ODBC with specific database driver -* Oracle -* PostgreSQL -* SQLite 3 - -See documentation at [soci.sourceforge.net](http://soci.sourceforge.net) for details - -[BSL](http://www.boost.org/LICENSE_1_0.txt) © -[Maciej Sobczak](http://github.com/msobczak) and [contributors](https://github.com/SOCI/soci/graphs/contributors). diff --git a/src/soci/TODO b/src/soci/TODO deleted file mode 100644 index f19f03f16f..0000000000 --- a/src/soci/TODO +++ /dev/null @@ -1,110 +0,0 @@ -TODO - -This file contains a raw bunch of ideas for future releases. -Not all of these ideas will necessarily make sense - they are here to get them together. - ---- -Source of many concepts -http://lists.boost.org/Archives/boost/2006/12/113961.php - ---- -RAII for transactions. - ---- -Query construction utilities (kind of Ultimate++) - can be easily incorporated into SOCI by just making them streamable. - ---- -CLOB - ---- -Streaming interface for BLOB - ---- -Standard names for Session constructor. - ---- -wstring -Unicode support - ---- -Handle locales in Session (so that operator<< is immune to strange global locale in the user program). It might even make sense to expose imbue(), so that users set up whatever locale they want. -It might even make sense to expose the whole stream object. -Alternatively, the backend should decide on the locale, because the backend will know best how to format numbers, dates, etc. - ---- -sql << "select...", into(x, default(7)); - -Note: default is a reserved word. - ---- -Provide statement-wide flag for eNoData case (because actually it *is* statement-wide, not field-wide). With this, boost.optional would handle the eNull case and the indicators could be dropped. - ---- - -query backend for supported featureset at runtime ---- - -Rowset ---- - -Rowset, including Rowset - way to indicate nulls? -Additional pair based val/indicator interface? - ---- -Consolidate iteration methods? -most radical: do we still need Statement::fetch()? into()? -(Rowset can currently be used for any query, supports indicators, -defaults, and no need to check for eNodata) - ---- -ColumnProperties() more logically belongs to Rowset than to Row -However Row::ColumnProperties() still needed if we support into(Row) - ---- -sql.prepare by default when constructing Rowsets and Statements? -Rowset rs = (sql << "select n from t";) - ---- -row[i].get() instead of row.get(i) -row["col"].get() instead of row.get("col") - ---- -Make more member functions private - ---- -Values class should be reference counted - ---- -CSV backend - -Example: -Session s("csv:///etc/protocols"); -rowset rs = (s.prepare << "1:*"); -copy(rs.begin(), rs.end(), ...); - -where "1:*" is taken from the top of my head and would mean "first field -from all rows" - -- joins are tricky - ---- -DBF backend, similar to CSV - -Session s("dbf:///table.dbf"); -rowset rs = (s.prepare << "1:*") // first field from all rows -rowset rs = (s.prepare << "firstname:*") // 'firstname' field from all rows -rowset rs = (s.prepare << "firstname='John'") // rows where 'firstname' value is 'John' - -Sub-concepts: - -- joins are tricky - -- boolean operators (<,>,=,<=,=> and <>) and WHERE-like clause support as a query - -rowset rs = (s.prepare << "age > 28") // rows where field 'age' is less than 28 -rowset rs = (s.prepare << "age <> 28") // rows where field 'age' is less or more than 28 -rowset rs = (s.prepare << "firstname='John' AND age > 28") // multi-fields combined queries - -- very simple home-made SQL parser or SQL-like queries support (see OGR utils from http://www.gdal.org) - ---- diff --git a/src/soci/Vagrantfile b/src/soci/Vagrantfile deleted file mode 100644 index a10d7309e8..0000000000 --- a/src/soci/Vagrantfile +++ /dev/null @@ -1,56 +0,0 @@ -# -*- mode: ruby -*- -# vi: set ft=ruby : - -# Vagrant virtual development environments for SOCI - -Vagrant.configure(2) do |config| - config.vm.box = "bento/ubuntu-14.04" - config.vm.box_check_update = true - - # Main SOCI development box with build essentials, FOSS DBs - config.vm.define "soci", primary: true do |soci| - soci.vm.hostname = "vmsoci" - soci.vm.network "private_network", type: "dhcp" - soci.vm.provider :virtualbox do |vb| - vb.customize ["modifyvm", :id, "--memory", "1024"] - end - scripts = [ - "bootstrap.sh", - "devel.sh", - "db2cli.sh", - "firebird.sh", - "mysql.sh", - "postgresql.sh", - "build.sh" - ] - scripts.each { |script| - soci.vm.provision :shell, privileged: false, :path => "scripts/vagrant/" << script - } - end - - # Database box with IBM DB2 Express-C - config.vm.define "db2", autostart: false do |db2| - db2.vm.hostname = "vmdb2" - db2.vm.network "private_network", type: "dhcp" - # Access to DB2 instance from host - db2.vm.network :forwarded_port, host: 50000, guest: 50000 - db2.vm.provider :virtualbox do |vb| - vb.customize ["modifyvm", :id, "--memory", "1024"] - end - scripts = [ - "bootstrap.sh", - "db2.sh" - ] - scripts.each { |script| - db2.vm.provision :shell, privileged: false, :path => "scripts/vagrant/" << script - } - end - - # Database box with Oracle XE - # config.vm.define "oracle", autostart: false do |oracle| - # oracle.vm.provision "database", type: "shell" do |s| - # s.inline = "echo Installing Oracle'" - # end - # end - -end diff --git a/src/soci/appveyor.yml b/src/soci/appveyor.yml deleted file mode 100644 index 3d7917f875..0000000000 --- a/src/soci/appveyor.yml +++ /dev/null @@ -1,104 +0,0 @@ -version: 4.0.0.{build} - -configuration: Release - -environment: - MINGW_ARCHIVE: C:\projects\mingw\x86_64-4.8.3-release-posix-seh-rt_v3-rev2.7z - MINGW_URL: https://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win64/Personal%20Builds/mingw-builds/4.8.3/threads-posix/seh/x86_64-4.8.3-release-posix-seh-rt_v3-rev2.7z/download - matrix: - - G: "Visual Studio 15 2017 Win64" - BOOST_ROOT: C:\Libraries\boost_1_59_0 - POSTGRESQL_ROOT: C:\Program Files\PostgreSQL\9.6 - MYSQL_DIR: C:\Program Files\MySql\MySQL Server 5.7 - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 - - G: "Visual Studio 14 2015 Win64" - BOOST_ROOT: C:\Libraries\boost_1_59_0 - POSTGRESQL_ROOT: C:\Program Files\PostgreSQL\9.4 - MYSQL_DIR: C:\Program Files\MySql\MySQL Server 5.7 - - G: "Visual Studio 12 2013 Win64" - BOOST_ROOT: C:\Libraries\boost_1_58_0 - POSTGRESQL_ROOT: C:\Program Files\PostgreSQL\9.4 - MYSQL_DIR: C:\Program Files\MySql\MySQL Server 5.7 - - G: "Visual Studio 11 2012 Win64" - BOOST_ROOT: C:\Libraries\boost_1_58_0 - POSTGRESQL_ROOT: C:\Program Files\PostgreSQL\9.4 - MYSQL_DIR: C:\Program Files\MySql\MySQL Server 5.7 - - G: "MinGW Makefiles" - MINGW_ROOT: C:\projects\mingw\4.8.3\mingw64\bin - BOOST_ROOT: C:\Libraries\boost_1_59_0 - POSTGRESQL_ROOT: C:\Program Files\PostgreSQL\9.4 - MYSQL_DIR: C:\Program Files\MySql\MySQL Server 5.7 - -services: - - mssql2014 - - mysql - - postgresql - -cache: - - C:\projects\mingw - -install: - - ps: | - if ($env:G -eq "MinGW Makefiles") - { - if (!(Test-Path C:\projects\mingw)) - { - mkdir C:\projects\mingw - } - if (!(Test-Path $env:MINGW_ARCHIVE)) - { - (new-object net.webclient).DownloadFile("$env:MINGW_URL", "$env:MINGW_ARCHIVE") - 7z x -y -oC:\projects\mingw\4.8.3\ $env:MINGW_ARCHIVE > $null - } - } - Import-Module C:\projects\soci\scripts\windows\Get-ODBCList.ps1 - Get-ODBCList - - git clone https://github.com/snikulov/sqlite.cmake.build.git C:\projects\sqlite\src - -before_build: - # dirty little hack - remove sh from Git to make generator happy - - ps: | - if ($env:G -eq "MinGW Makefiles") - { - $shellPath = (Get-Command sh.exe).definition - if ($shellPath) - { - if (Test-Path $shellPath) - { - Remove-Item $shellPath - } - } - } - - cd C:\projects\sqlite\src - - mkdir build - - cd build - - set SQLITE_ROOT=C:\projects\sqlite\sqlite - - set PATH=%MINGW_ROOT%;%PATH%;%SQLITE_ROOT%\bin;%POSTGRESQL_ROOT%\bin;%MYSQL_DIR%\bin;%MYSQL_DIR%\lib - - echo %PATH% - - cmake --version - - set PGUSER=postgres - - set PGPASSWORD=Password12! - - createdb soci_test - - set MYSQL_PWD=Password12! - - set USER=root - - mysql -e "create database soci_test;" --user=root - - sqlcmd -U sa -P Password12! -S (local)\SQL2014 -i C:\projects\soci\scripts\windows\mssql_db_create.sql - - cmake .. -G"%G%" -DCMAKE_BUILD_TYPE=%CONFIGURATION% -DCMAKE_INSTALL_PREFIX=C:\projects\sqlite\sqlite - - cmake --build . --config %CONFIGURATION% --target install - -build_script: - - cd C:\projects\soci - - mkdir build - - cd build - - cmake .. -G"%G%" -DCMAKE_BUILD_TYPE=%CONFIGURATION% -DCMAKE_VERBOSE_MAKEFILE=ON - - cmake --build . --config %CONFIGURATION% --clean-first - -test_script: - - ctest -V --output-on-failure -R "soci_empty|soci_postgresql|soci_sqlite3|soci_odbc_test_mssql|soci_mysql|soci_odbc_test_mysql|soci_odbc_test_postgresql" - -notifications: - - provider: Webhook - url: https://webhooks.gitter.im/e/2038138a652d952f9372 - on_build_success: true - on_build_failure: true - on_build_status_changed: true diff --git a/src/soci/cmake/.gitignore b/src/soci/cmake/.gitignore deleted file mode 100644 index 61caff875d..0000000000 --- a/src/soci/cmake/.gitignore +++ /dev/null @@ -1,21 +0,0 @@ -*~ -*.kdev[0-9] -*.swp -aclocal.m4 -autom4te.cache -confdefs.h -config.guess -config.log -config.status -config.sub -configure -depcomp -install-sh -libtool -ltmain.sh -m4 -missing -Makefile -Makefile.in -tmp - diff --git a/src/soci/cmake/CMakeLists.txt b/src/soci/cmake/CMakeLists.txt deleted file mode 100644 index 317236e6a0..0000000000 --- a/src/soci/cmake/CMakeLists.txt +++ /dev/null @@ -1,13 +0,0 @@ -############################################################################### -# -# This file is part of CMake configuration for SOCI library -# -# Copyright (C) 2009 Mateusz Loskot -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -# -############################################################################### - -# install the cmake modules -file(GLOB SOCI_CMAKE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/*.cmake") diff --git a/src/soci/cmake/SociBackend.cmake b/src/soci/cmake/SociBackend.cmake deleted file mode 100644 index 442d81d2fc..0000000000 --- a/src/soci/cmake/SociBackend.cmake +++ /dev/null @@ -1,394 +0,0 @@ -################################################################################ -# SociBackend.cmake - part of CMake configuration of SOCI library -################################################################################ -# Copyright (C) 2010-2013 Mateusz Loskot -# -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -################################################################################ -# Macros in this module: -# -# soci_backend -# - defines project of a database backend for SOCI library -# -# soci_backend_test -# - defines test project of a database backend for SOCI library -################################################################################ - -macro(soci_backend_deps_found NAME DEPS SUCCESS) - #message(STATUS "DEPS=${DEPS}") - - # Determine required dependencies - set(DEPS_INCLUDE_DIRS) - set(DEPS_LIBRARIES) - set(DEPS_NOT_FOUND) - - # CMake 2.8+ syntax only: - #foreach(dep IN LISTS DEPS) - foreach(dep ${DEPS}) - soci_check_package_found(${dep} DEPEND_FOUND) - if(NOT DEPEND_FOUND) - list(APPEND DEPS_NOT_FOUND ${dep}) - else() - string(TOUPPER "${dep}" DEPU) - if( ${DEPU}_INCLUDE_DIR ) - list(APPEND DEPS_INCLUDE_DIRS ${${DEPU}_INCLUDE_DIR}) - endif() - if( ${DEPU}_INCLUDE_DIRS ) - list(APPEND DEPS_INCLUDE_DIRS ${${DEPU}_INCLUDE_DIRS}) - endif() - list(APPEND DEPS_LIBRARIES ${${DEPU}_LIBRARIES}) - endif() - endforeach() - - list(LENGTH DEPS_NOT_FOUND NOT_FOUND_COUNT) - - if (NOT_FOUND_COUNT GREATER 0) - set(${SUCCESS} False) - else() - set(${NAME}_DEPS_INCLUDE_DIRS ${DEPS_INCLUDE_DIRS}) - set(${NAME}_DEPS_LIBRARIES ${DEPS_LIBRARIES}) - set(${SUCCESS} True) - endif() - - #message(STATUS "soci_backend_deps_found: ${SUCCESS}=${${SUCCESS}}") -endmacro() - -# Defines project of a database backend for SOCI library -# -# soci_backend(backendname -# DEPENDS dependency1 dependency2 -# DESCRIPTION description -# AUTHORS author1 author2 -# MAINTAINERS maintainer1 maintainer2) -# -macro(soci_backend NAME) - parse_arguments(THIS_BACKEND - "DEPENDS;DESCRIPTION;AUTHORS;MAINTAINERS;" - "" - ${ARGN}) - - colormsg(HIGREEN "${NAME} - ${THIS_BACKEND_DESCRIPTION}") - - # Backend name variants utils - string(TOLOWER "${PROJECT_NAME}" PROJECTNAMEL) - string(TOLOWER "${NAME}" NAMEL) - string(TOUPPER "${NAME}" NAMEU) - - # Backend option available to user - set(THIS_BACKEND_OPTION SOCI_${NAMEU}) - option(${THIS_BACKEND_OPTION} - "Attempt to build ${PROJECT_NAME} backend for ${NAME}" ON) - - soci_backend_deps_found(${NAMEU} "${THIS_BACKEND_DEPENDS}" ${NAMEU}_DEPS_FOUND) - if(NOT ${NAMEU}_DEPS_FOUND) - - colormsg(_RED_ "WARNING: Some required dependencies of ${NAME} backend not found:") - - if(${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION} LESS 2.8) - foreach(dep ${DEPENDS_NOT_FOUND}) - colormsg(RED " ${dep}") - endforeach() - else() - foreach(dep IN LISTS DEPENDS_NOT_FOUND) - colormsg(RED " ${dep}") - endforeach() - endif() - - # TODO: Abort or warn compilation may fail? --mloskot - colormsg(RED "Skipping") - - set(${THIS_BACKEND_OPTION} OFF) - - else() - - if(${THIS_BACKEND_OPTION}) - - get_directory_property(THIS_INCLUDE_DIRS INCLUDE_DIRECTORIES) - get_directory_property(THIS_COMPILE_DEFS COMPILE_DEFINITIONS) - - # Backend-specific depedencies - set(THIS_BACKEND_DEPENDS_INCLUDE_DIRS ${${NAMEU}_DEPS_INCLUDE_DIRS}) - set(THIS_BACKEND_DEPENDS_LIBRARIES ${${NAMEU}_DEPS_LIBRARIES}) - set(THIS_BACKEND_DEPENDS_DEFS ${${NAMEU}_DEPS_DEFS}) - - # Collect include directories - list(APPEND THIS_INCLUDE_DIRS ${SOCI_SOURCE_DIR}/include/private) - list(APPEND THIS_INCLUDE_DIRS ${THIS_BACKEND_DEPENDS_INCLUDE_DIRS}) - # Collect compile definitions - list(APPEND THIS_COMPILE_DEFS ${THIS_BACKEND_DEPENDS_DEFS}) - - set_directory_properties(PROPERTIES - INCLUDE_DIRECTORIES "${THIS_INCLUDE_DIRS}" - COMPILE_DEFINITIONS "${THIS_COMPILE_DEFS}") - - # Backend target - set(THIS_BACKEND_VAR SOCI_${NAMEU}) - set(THIS_BACKEND_TARGET ${PROJECTNAMEL}_${NAMEL}) - set(THIS_BACKEND_TARGET_VAR ${THIS_BACKEND_VAR}_TARGET) - set(${THIS_BACKEND_TARGET_VAR} ${THIS_BACKEND_TARGET}) - - soci_target_output_name(${THIS_BACKEND_TARGET} ${THIS_BACKEND_VAR}_OUTPUT_NAME) - - set(THIS_BACKEND_OUTPUT_NAME ${${THIS_BACKEND_VAR}_OUTPUT_NAME}) - set(THIS_BACKEND_OUTPUT_NAME_VAR ${THIS_BACKEND_VAR}_OUTPUT_NAME) - - set(${THIS_BACKEND_VAR}_COMPILE_DEFINITIONS ${THIS_COMPILE_DEFS}) - set(THIS_BACKEND_COMPILE_DEFINITIONS_VAR ${THIS_BACKEND_VAR}_COMPILE_DEFINITIONS) - - set(${THIS_BACKEND_VAR}_INCLUDE_DIRECTORIES ${THIS_INCLUDE_DIRS}) - set(THIS_BACKEND_INCLUDE_DIRECTORIES_VAR ${THIS_BACKEND_VAR}_INCLUDE_DIRECTORIES) - - # Backend installable headers and sources - file(GLOB THIS_BACKEND_HEADERS ${SOCI_SOURCE_DIR}/include/soci/${NAMEL}/*.h) - file(GLOB THIS_BACKEND_SOURCES *.cpp) - set(THIS_BACKEND_HEADERS_VAR SOCI_${NAMEU}_HEADERS) - set(${THIS_BACKEND_HEADERS_VAR} ${THIS_BACKEND_HEADERS}) - # Group source files for IDE source explorers (e.g. Visual Studio) - source_group("Header Files" FILES ${THIS_BACKEND_HEADERS}) - source_group("Source Files" FILES ${THIS_BACKEND_SOURCES}) - source_group("CMake Files" FILES CMakeLists.txt) - - # TODO: Extract as macros: soci_shared_lib_target and soci_static_lib_target --mloskot - # Shared library target - if (SOCI_SHARED) - add_library(${THIS_BACKEND_TARGET} - SHARED - ${THIS_BACKEND_SOURCES} - ${THIS_BACKEND_HEADERS}) - - target_link_libraries(${THIS_BACKEND_TARGET} - ${SOCI_CORE_TARGET} - ${THIS_BACKEND_DEPENDS_LIBRARIES}) - - if(WIN32) - set_target_properties(${THIS_BACKEND_TARGET} - PROPERTIES - OUTPUT_NAME ${THIS_BACKEND_OUTPUT_NAME} - DEFINE_SYMBOL SOCI_DLL) - else() - set_target_properties(${THIS_BACKEND_TARGET} - PROPERTIES - SOVERSION ${${PROJECT_NAME}_SOVERSION} - INSTALL_NAME_DIR ${CMAKE_INSTALL_PREFIX}/lib) - - if(APPLE) - set_target_properties(${THIS_BACKEND_TARGET} - PROPERTIES - LINK_FLAGS "-Wl,-flat_namespace -Wl,-undefined -Wl,suppress") - endif() - endif() - - set_target_properties(${THIS_BACKEND_TARGET} - PROPERTIES - VERSION ${${PROJECT_NAME}_VERSION} - CLEAN_DIRECT_OUTPUT 1) - endif() - - # Static library target - if(SOCI_STATIC) - set(THIS_BACKEND_TARGET_STATIC ${THIS_BACKEND_TARGET}_static) - - add_library(${THIS_BACKEND_TARGET_STATIC} - STATIC - ${THIS_BACKEND_SOURCES} - ${THIS_BACKEND_HEADERS}) - - # Still need to link the libraries for tests to work - target_link_libraries (${THIS_BACKEND_TARGET_STATIC} - ${THIS_BACKEND_DEPENDS_LIBRARIES} - ) - - set_target_properties(${THIS_BACKEND_TARGET_STATIC} - PROPERTIES - OUTPUT_NAME ${THIS_BACKEND_OUTPUT_NAME} - PREFIX "lib" - CLEAN_DIRECT_OUTPUT 1) - endif() - - # Backend installation - install(FILES ${THIS_BACKEND_HEADERS} - DESTINATION - ${INCLUDEDIR}/${PROJECTNAMEL}/${NAMEL}) - - if (SOCI_SHARED) - install(TARGETS ${THIS_BACKEND_TARGET} - EXPORT SOCI - RUNTIME DESTINATION ${BINDIR} - LIBRARY DESTINATION ${LIBDIR} - ARCHIVE DESTINATION ${LIBDIR}) - endif() - - if (SOCI_STATIC) - install(TARGETS ${THIS_BACKEND_TARGET_STATIC} - EXPORT SOCI - RUNTIME DESTINATION ${BINDIR} - LIBRARY DESTINATION ${LIBDIR} - ARCHIVE DESTINATION ${LIBDIR} - ) - endif() - - install(EXPORT SOCI NAMESPACE SOCI:: DESTINATION cmake) - - else() - colormsg(HIRED "${NAME}" RED "backend disabled, since") - endif() - - endif() - - boost_report_value(${THIS_BACKEND_OPTION}) - - if(${THIS_BACKEND_OPTION}) - boost_report_value(${THIS_BACKEND_TARGET_VAR}) - boost_report_value(${THIS_BACKEND_OUTPUT_NAME_VAR}) - boost_report_value(${THIS_BACKEND_COMPILE_DEFINITIONS_VAR}) - boost_report_value(${THIS_BACKEND_INCLUDE_DIRECTORIES_VAR}) - endif() - - # LOG - #message("soci_backend:") - #message("NAME: ${NAME}") - #message("${THIS_BACKEND_OPTION} = ${SOCI_BACKEND_SQLITE3}") - #message("DEPENDS: ${THIS_BACKEND_DEPENDS}") - #message("DESCRIPTION: ${THIS_BACKEND_DESCRIPTION}") - #message("AUTHORS: ${THIS_BACKEND_AUTHORS}") - #message("MAINTAINERS: ${THIS_BACKEND_MAINTAINERS}") - #message("SOURCES: ${THIS_BACKEND_SOURCES}") - #message("DEPENDS_LIBRARIES: ${THIS_BACKEND_DEPENDS_LIBRARIES}") - #message("DEPENDS_INCLUDE_DIRS: ${THIS_BACKEND_DEPENDS_INCLUDE_DIRS}") -endmacro() - -# Generates .vcxproj.user for target of each test. -# -# soci_backend_test_create_vcxproj_user( -# PostgreSQLTest -# "host=localhost dbname=soci_test user=mloskot") -# -function(soci_backend_test_create_vcxproj_user TARGET_NAME TEST_CMD_ARGS) - if(MSVC) - set(SYSTEM_NAME $ENV{USERDOMAIN}) - set(USER_NAME $ENV{USERNAME}) - set(SOCI_TEST_CMD_ARGS ${TEST_CMD_ARGS}) - - if(MSVC_VERSION EQUAL 1600) - configure_file( - ${SOCI_SOURCE_DIR}/cmake/resources/vs2010-test-cmd-args.vcxproj.user.in - ${CMAKE_CURRENT_BINARY_DIR}/${TARGET_NAME}.vcxproj.user - @ONLY) - endif() - endif() -endfunction(soci_backend_test_create_vcxproj_user) - -# Defines test project of a database backend for SOCI library -# -# soci_backend_test(BACKEND mybackend SOURCE mytest1.cpp -# NAME mytest1 -# CONNSTR "my test connection" -# DEPENDS library1 library2) -# -macro(soci_backend_test) - parse_arguments(THIS_TEST - "BACKEND;SOURCE;CONNSTR;NAME;DEPENDS;" - "" - ${ARGN}) - - # Test backend name - string(TOUPPER "${THIS_TEST_BACKEND}" BACKENDU) - string(TOLOWER "${THIS_TEST_BACKEND}" BACKENDL) - - if(SOCI_TESTS AND SOCI_${BACKENDU} AND NOT SOCI_${BACKENDU}_DO_NOT_TEST) - - # Test name - if(THIS_TEST_NAME) - string(TOUPPER "${THIS_TEST_NAME}" NAMEU) - set(TEST_FULL_NAME SOCI_${BACKENDU}_TEST_${NAMEU}) - else() - set(TEST_FULL_NAME SOCI_${BACKENDU}_TEST) - endif() - string(TOLOWER "${TEST_FULL_NAME}" TEST_TARGET) - string(TOUPPER "${TEST_FULL_NAME}" NAMEU) - - soci_backend_deps_found(${NAMEU} "${THIS_TEST_DEPENDS}" ${NAMEU}_DEPS_FOUND) - if(${NAMEU}_DEPS_FOUND) - get_directory_property(THIS_INCLUDE_DIRS INCLUDE_DIRECTORIES) - get_directory_property(THIS_COMPILE_DEFS COMPILE_DEFINITIONS) - - set(THIS_TEST_DEPENDS_INCLUDE_DIRS ${${NAMEU}_DEPS_INCLUDE_DIRS}) - set(THIS_TEST_DEPENDS_LIBRARIES ${${NAMEU}_DEPS_LIBRARIES}) - set(THIS_TEST_DEPENDS_DEFS ${${NAMEU}_DEPS_DEFS}) - - list(APPEND THIS_INCLUDE_DIRS ${THIS_TEST_DEPENDS_INCLUDE_DIRS}) - list(APPEND THIS_COMPILE_DEFS ${THIS_TEST_DEPENDS_DEFS}) - - set_directory_properties(PROPERTIES - INCLUDE_DIRECTORIES "${THIS_INCLUDE_DIRS}" - COMPILE_DEFINITIONS "${THIS_COMPILE_DEFS}") - else() - colormsg(_RED_ "WARNING: Some dependencies of ${THIS_TEST_BACKEND} test not found") - endif() - - set(TEST_CONNSTR_VAR ${TEST_FULL_NAME}_CONNSTR) - set(${TEST_CONNSTR_VAR} "" - CACHE STRING "Connection string for ${BACKENDU} test") - - if(NOT ${TEST_CONNSTR_VAR} AND THIS_TEST_CONNSTR) - set(${TEST_CONNSTR_VAR} ${THIS_TEST_CONNSTR}) - if(${TEST_CONNSTR_VAR} MATCHES ".dsn") - set(_dsnpath "${CMAKE_CURRENT_SOURCE_DIR}/${${TEST_CONNSTR_VAR}}") - set(${TEST_CONNSTR_VAR} "FILEDSN=${_dsnpath}") - endif() - endif() - - boost_message_value(${TEST_CONNSTR_VAR}) - - if( SOCI_SHARED ) - # Shared libraries test - add_executable(${TEST_TARGET} ${THIS_TEST_SOURCE}) - - target_link_libraries(${TEST_TARGET} - ${SOCI_CORE_DEPS_LIBS} - ${THIS_TEST_DEPENDS_LIBRARIES} - soci_core - soci_${BACKENDL}) - - add_test(${TEST_TARGET} - ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${TEST_TARGET} - ${${TEST_CONNSTR_VAR}}) - - soci_backend_test_create_vcxproj_user(${TEST_TARGET} "\"${${TEST_CONNSTR_VAR}}\"") - - # Ask make check to try to build tests first before executing them - add_dependencies(check ${TEST_TARGET}) - endif(SOCI_SHARED) - - # Static libraries test - if(SOCI_STATIC) - set(TEST_TARGET_STATIC ${TEST_TARGET}_static) - - add_executable(${TEST_TARGET_STATIC} ${THIS_TEST_SOURCE}) - - target_link_libraries(${TEST_TARGET_STATIC} - ${SOCI_CORE_DEPS_LIBS} - ${THIS_TEST_DEPENDS_LIBRARIES} - soci_${BACKENDL}_static - soci_core_static) - - add_test(${TEST_TARGET_STATIC} - ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${TEST_TARGET_STATIC} - ${${TEST_CONNSTR_VAR}}) - - soci_backend_test_create_vcxproj_user(${TEST_TARGET_STATIC} "\"${${TEST_CONNSTR_VAR}}\"") - - # Ask make check to try to build tests first before executing them - add_dependencies(check ${TEST_TARGET_STATIC}) - endif(SOCI_STATIC) - - - - # Group source files for IDE source explorers (e.g. Visual Studio) - source_group("Source Files" FILES ${THIS_TEST_SOURCE}) - source_group("CMake Files" FILES CMakeLists.txt) - - endif() -endmacro() diff --git a/src/soci/cmake/SociConfig.cmake b/src/soci/cmake/SociConfig.cmake deleted file mode 100644 index 97d907e4e9..0000000000 --- a/src/soci/cmake/SociConfig.cmake +++ /dev/null @@ -1,106 +0,0 @@ -################################################################################ -# SociConfig.cmake - CMake build configuration of SOCI library -################################################################################ -# Copyright (C) 2010 Mateusz Loskot -# -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -################################################################################ - -include(CheckCXXSymbolExists) - -if(WIN32) - check_cxx_symbol_exists("_M_AMD64" "" SOCI_TARGET_ARCH_X64) - if(NOT RTC_ARCH_X64) - check_cxx_symbol_exists("_M_IX86" "" SOCI_TARGET_ARCH_X86) - endif(NOT RTC_ARCH_X64) - # add check for arm here - # see http://msdn.microsoft.com/en-us/library/b0084kay.aspx -else(WIN32) - check_cxx_symbol_exists("__i386__" "" SOCI_TARGET_ARCH_X86) - check_cxx_symbol_exists("__x86_64__" "" SOCI_TARGET_ARCH_X64) - check_cxx_symbol_exists("__arm__" "" SOCI_TARGET_ARCH_ARM) -endif(WIN32) - -if(NOT DEFINED LIB_SUFFIX) - if(SOCI_TARGET_ARCH_X64) - set(_lib_suffix "64") - else() - set(_lib_suffix "") - endif() - set(LIB_SUFFIX ${_lib_suffix} CACHE STRING "Specifies suffix for the lib directory") -endif() - -# -# C++11 Option -# - -if(NOT SOCI_CXX_C11) - set (SOCI_CXX_C11 OFF CACHE BOOL "Build to the C++11 standard") -endif() - -# -# Force compilation flags and set desired warnings level -# - -if (MSVC) - add_definitions(-D_CRT_SECURE_NO_DEPRECATE) - add_definitions(-D_CRT_SECURE_NO_WARNINGS) - add_definitions(-D_CRT_NONSTDC_NO_WARNING) - add_definitions(-D_SCL_SECURE_NO_WARNINGS) - - if(CMAKE_CXX_FLAGS MATCHES "/W[0-4]") - string(REGEX REPLACE "/W[0-4]" "/W4" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") - else() - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4 /we4266") - endif() - -else() - - set(SOCI_GCC_CLANG_COMMON_FLAGS - "-pedantic -Werror -Wno-error=parentheses -Wall -Wextra -Wpointer-arith -Wcast-align -Wcast-qual -Wfloat-equal -Woverloaded-virtual -Wredundant-decls -Wno-long-long") - - - if (SOCI_CXX_C11) - set(SOCI_CXX_VERSION_FLAGS "-std=c++11") - else() - set(SOCI_CXX_VERSION_FLAGS "-std=gnu++98") - endif() - - if("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang" OR "${CMAKE_CXX_COMPILER}" MATCHES "clang") - - if(NOT CMAKE_CXX_COMPILER_VERSION LESS 3.1 AND SOCI_ASAN) - set(SOCI_GCC_CLANG_COMMON_FLAGS "${SOCI_GCC_CLANG_COMMON_FLAGS} -fsanitize=address") - endif() - - # enforce C++11 for Clang - set(SOCI_CXX_C11 ON) - set(SOCI_CXX_VERSION_FLAGS "-std=c++11") - add_definitions(-DCATCH_CONFIG_CPP11_NO_IS_ENUM) - - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${SOCI_GCC_CLANG_COMMON_FLAGS} ${SOCI_CXX_VERSION_FLAGS}") - - elseif(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX) - - if(NOT CMAKE_CXX_COMPILER_VERSION LESS 4.8 AND SOCI_ASAN) - set(SOCI_GCC_CLANG_COMMON_FLAGS "${SOCI_GCC_CLANG_COMMON_FLAGS} -fsanitize=address") - endif() - - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${SOCI_GCC_CLANG_COMMON_FLAGS} ${SOCI_CXX_VERSION_FLAGS} ") - if (CMAKE_COMPILER_IS_GNUCXX) - if (CMAKE_SYSTEM_NAME MATCHES "FreeBSD") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") - else() - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-variadic-macros") - endif() - endif() - - else() - message(WARNING "Unknown toolset - using default flags to build SOCI") - endif() - -endif() - -# Set SOCI_HAVE_* variables for soci-config.h generator -set(SOCI_HAVE_CXX_C11 ${SOCI_CXX_C11} CACHE INTERNAL "Enables C++11 support") diff --git a/src/soci/cmake/SociDependencies.cmake b/src/soci/cmake/SociDependencies.cmake deleted file mode 100644 index c097add67f..0000000000 --- a/src/soci/cmake/SociDependencies.cmake +++ /dev/null @@ -1,84 +0,0 @@ -################################################################################ -# SociDependencies.cmake - part of CMake configuration of SOCI library -# -# Based on BoostExternals.cmake from CMake configuration for Boost -################################################################################ -# Copyright (C) 2010 Mateusz Loskot -# Copyright (C) 2009 Troy Straszheim -# -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -################################################################################ -# Macros in this module: -# -# soci_backend - defines a database backend for SOCI library -# -################################################################################ - -# -# List of SOCI dependncies -# -set(SOCI_CORE_DEPENDENCIES - Threads - Boost) - -set(SOCI_BACKENDS_DB_DEPENDENCIES - MySQL - ODBC - Oracle - PostgreSQL - SQLite3 - Firebird - DB2) - -set(SOCI_ALL_DEPENDENCIES - ${SOCI_CORE_DEPENDENCIES} - ${SOCI_BACKENDS_DB_DEPENDENCIES}) - -# -# Perform checks -# -colormsg(_HIBLUE_ "Looking for SOCI dependencies:") - -macro(boost_external_report NAME) - - set(VARNAME ${NAME}) - string(TOUPPER ${NAME} VARNAMEU) - - set(VARNAMES ${ARGV}) - list(REMOVE_AT VARNAMES 0) - - # Test both, given original name and uppercase version too - if(NOT ${VARNAME}_FOUND AND NOT ${VARNAMEU}_FOUND) - colormsg(_RED_ "WARNING: ${NAME} libraries not found, some features will be disabled.") - endif() - - foreach(variable ${VARNAMES}) - if(${VARNAMEU}_FOUND) - boost_report_value(${VARNAMEU}_${variable}) - elseif(${VARNAME}_FOUND) - boost_report_value(${VARNAME}_${variable}) - endif() - endforeach() -endmacro() - -# -# Some externals default to OFF -# -option(WITH_VALGRIND "Run tests under valgrind" OFF) - -# -# Detect available dependencies -# -foreach(external ${SOCI_ALL_DEPENDENCIES}) - string(TOUPPER "${external}" EXTERNAL) - option(WITH_${EXTERNAL} "Attempt to find and configure ${external}" ON) - if(WITH_${EXTERNAL}) - colormsg(HICYAN "${external}:") - include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/dependencies/${external}.cmake) - else() - set(${EXTERNAL}_FOUND FALSE CACHE BOOL "${external} found" FORCE) - colormsg(HIRED "${external}:" RED "disabled, since WITH_${EXTERNAL}=OFF") - endif() -endforeach() diff --git a/src/soci/cmake/SociUtilities.cmake b/src/soci/cmake/SociUtilities.cmake deleted file mode 100644 index 0e6711c92e..0000000000 --- a/src/soci/cmake/SociUtilities.cmake +++ /dev/null @@ -1,426 +0,0 @@ -################################################################################ -# SociUtilities.cmake - part of CMake configuration of SOCI library -# -# Based on BoostUtilities.cmake from CMake configuration for Boost -################################################################################ -# Copyright (C) 2007 Douglas Gregor -# Copyright (C) 2007 Troy Straszheim -# Copyright (C) 2010-2013 Mateusz Loskot -# -# Distributed under the Boost Software License, Version 1.0. -# See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt -################################################################################ -# Macros in this module: -# -# list_contains: Determine whether a string value is in a list. -# -# car: Return the first element in a list -# -# cdr: Return all but the first element in a list -# -# parse_arguments: Parse keyword arguments for use in other macros. -# -# soci_check_package_found: Test varname-FOUND for case-insensitive varname -# -################################################################################ - -# This utility macro determines whether a particular string value -# occurs within a list of strings: -# -# list_contains(result string_to_find arg1 arg2 arg3 ... argn) -# -# This macro sets the variable named by result equal to TRUE if -# string_to_find is found anywhere in the following arguments. -macro(list_contains var value) - set(${var}) - foreach (value2 ${ARGN}) - if (${value} STREQUAL ${value2}) - set(${var} TRUE) - endif (${value} STREQUAL ${value2}) - endforeach (value2) -endmacro(list_contains) - -# This utility macro extracts the first argument from the list of -# arguments given, and places it into the variable named var. -# -# car(var arg1 arg2 ...) -macro(car var) - set(${var} ${ARGV1}) -endmacro(car) - -# This utility macro extracts all of the arguments given except the -# first, and places them into the variable named var. -# -# car(var arg1 arg2 ...) -macro(cdr var junk) - set(${var} ${ARGN}) -endmacro(cdr) - -# The parse_arguments macro will take the arguments of another macro and -# define several variables. The first argument to parse_arguments is a -# prefix to put on all variables it creates. The second argument is a -# list of names, and the third argument is a list of options. Both of -# these lists should be quoted. The rest of parse_arguments are -# arguments from another macro to be parsed. -# -# parse_arguments(prefix arg_names options arg1 arg2...) -# -# For each item in options, parse_arguments will create a variable with -# that name, prefixed with prefix_. So, for example, if prefix is -# MY_MACRO and options is OPTION1;OPTION2, then parse_arguments will -# create the variables MY_MACRO_OPTION1 and MY_MACRO_OPTION2. These -# variables will be set to true if the option exists in the command line -# or false otherwise. -# -# For each item in arg_names, parse_arguments will create a variable -# with that name, prefixed with prefix_. Each variable will be filled -# with the arguments that occur after the given arg_name is encountered -# up to the next arg_name or the end of the arguments. All options are -# removed from these lists. parse_arguments also creates a -# prefix_DEFAULT_ARGS variable containing the list of all arguments up -# to the first arg_name encountered. -macro(parse_arguments prefix arg_names option_names) - set(DEFAULT_ARGS) - foreach(arg_name ${arg_names}) - set(${prefix}_${arg_name}) - endforeach(arg_name) - foreach(option ${option_names}) - set(${prefix}_${option} FALSE) - endforeach(option) - - set(current_arg_name DEFAULT_ARGS) - set(current_arg_list) - foreach(arg ${ARGN}) - list_contains(is_arg_name ${arg} ${arg_names}) - if (is_arg_name) - set(${prefix}_${current_arg_name} ${current_arg_list}) - set(current_arg_name ${arg}) - set(current_arg_list) - else (is_arg_name) - list_contains(is_option ${arg} ${option_names}) - if (is_option) - set(${prefix}_${arg} TRUE) - else (is_option) - set(current_arg_list ${current_arg_list} ${arg}) - endif (is_option) - endif (is_arg_name) - endforeach(arg) - set(${prefix}_${current_arg_name} ${current_arg_list}) -endmacro(parse_arguments) - -# Perform a reverse topological sort on the given LIST. -# -# topological_sort(my_list "MY_" "_EDGES") -# -# LIST is the name of a variable containing a list of elements to be -# sorted in reverse topological order. Each element in the list has a -# set of outgoing edges (for example, those other list elements that -# it depends on). In the resulting reverse topological ordering -# (written back into the variable named LIST), an element will come -# later in the list than any of the elements that can be reached by -# following its outgoing edges and the outgoing edges of any vertices -# they target, recursively. Thus, if the edges represent dependencies -# on build targets, for example, the reverse topological ordering is -# the order in which one would build those targets. -# -# For each element E in this list, the edges for E are contained in -# the variable named ${PREFIX}${E}${SUFFIX}, where E is the -# upper-cased version of the element in the list. If no such variable -# exists, then it is assumed that there are no edges. For example, if -# my_list contains a, b, and c, one could provide a dependency graph -# using the following variables: -# -# MY_A_EDGES b -# MY_B_EDGES -# MY_C_EDGES a b -# -# With the involcation of topological_sort shown above and these -# variables, the resulting reverse topological ordering will be b, a, -# c. -function(topological_sort LIST PREFIX SUFFIX) - # Clear the stack and output variable - set(VERTICES "${${LIST}}") - set(STACK) - set(${LIST}) - - # Loop over all of the vertices, starting the topological sort from - # each one. - foreach(VERTEX ${VERTICES}) - string(TOUPPER ${VERTEX} UPPER_VERTEX) - - # If we haven't already processed this vertex, start a depth-first - # search from where. - if (NOT FOUND_${UPPER_VERTEX}) - # Push this vertex onto the stack with all of its outgoing edges - string(REPLACE ";" " " NEW_ELEMENT - "${VERTEX};${${PREFIX}${UPPER_VERTEX}${SUFFIX}}") - list(APPEND STACK ${NEW_ELEMENT}) - - # We've now seen this vertex - set(FOUND_${UPPER_VERTEX} TRUE) - - # While the depth-first search stack is not empty - list(LENGTH STACK STACK_LENGTH) - while(STACK_LENGTH GREATER 0) - # Remove the vertex and its remaining out-edges from the top - # of the stack - list(GET STACK -1 OUT_EDGES) - list(REMOVE_AT STACK -1) - - # Get the source vertex and the list of out-edges - separate_arguments(OUT_EDGES) - list(GET OUT_EDGES 0 SOURCE) - list(REMOVE_AT OUT_EDGES 0) - - # While there are still out-edges remaining - list(LENGTH OUT_EDGES OUT_DEGREE) - while (OUT_DEGREE GREATER 0) - # Pull off the first outgoing edge - list(GET OUT_EDGES 0 TARGET) - list(REMOVE_AT OUT_EDGES 0) - - string(TOUPPER ${TARGET} UPPER_TARGET) - if (NOT FOUND_${UPPER_TARGET}) - # We have not seen the target before, so we will traverse - # its outgoing edges before coming back to our - # source. This is the key to the depth-first traversal. - - # We've now seen this vertex - set(FOUND_${UPPER_TARGET} TRUE) - - # Push the remaining edges for the current vertex onto the - # stack - string(REPLACE ";" " " NEW_ELEMENT - "${SOURCE};${OUT_EDGES}") - list(APPEND STACK ${NEW_ELEMENT}) - - # Setup the new source and outgoing edges - set(SOURCE ${TARGET}) - string(TOUPPER ${SOURCE} UPPER_SOURCE) - set(OUT_EDGES - ${${PREFIX}${UPPER_SOURCE}${SUFFIX}}) - endif(NOT FOUND_${UPPER_TARGET}) - - list(LENGTH OUT_EDGES OUT_DEGREE) - endwhile (OUT_DEGREE GREATER 0) - - # We have finished all of the outgoing edges for - # SOURCE; add it to the resulting list. - list(APPEND ${LIST} ${SOURCE}) - - # Check the length of the stack - list(LENGTH STACK STACK_LENGTH) - endwhile(STACK_LENGTH GREATER 0) - endif (NOT FOUND_${UPPER_VERTEX}) - endforeach(VERTEX) - - set(${LIST} ${${LIST}} PARENT_SCOPE) -endfunction(topological_sort) - -# Small little hack that tweaks a component name (as used for CPack) -# to make sure to avoid certain names that cause problems. Sets the -# variable named varname to the "sanitized" name. -# -# FIXME: This is a complete hack. We probably need to fix the CPack -# generators (NSIS in particular) to get rid of the need for this. -macro(fix_cpack_component_name varname name) - if (${name} STREQUAL "foreach") - set(${varname} "boost_foreach") - else() - set(${varname} ${name}) - endif() -endmacro() - - -# -# A big shout out to the cmake gurus @ compiz -# -function (colormsg) - string (ASCII 27 _escape) - set(WHITE "29") - set(GRAY "30") - set(RED "31") - set(GREEN "32") - set(YELLOW "33") - set(BLUE "34") - set(MAG "35") - set(CYAN "36") - - foreach (color WHITE GRAY RED GREEN YELLOW BLUE MAG CYAN) - set(HI${color} "1\;${${color}}") - set(LO${color} "2\;${${color}}") - set(_${color}_ "4\;${${color}}") - set(_HI${color}_ "1\;4\;${${color}}") - set(_LO${color}_ "2\;4\;${${color}}") - endforeach() - - set(str "") - set(coloron FALSE) - foreach(arg ${ARGV}) - if (NOT ${${arg}} STREQUAL "") - if (CMAKE_COLOR_MAKEFILE) - set(str "${str}${_escape}[${${arg}}m") - set(coloron TRUE) - endif() - else() - set(str "${str}${arg}") - if (coloron) - set(str "${str}${_escape}[0m") - set(coloron FALSE) - endif() - set(str "${str} ") - endif() - endforeach() - message(STATUS ${str}) -endfunction() - -# colormsg("Colors:" -# WHITE "white" GRAY "gray" GREEN "green" -# RED "red" YELLOW "yellow" BLUE "blue" MAG "mag" CYAN "cyan" -# _WHITE_ "white" _GRAY_ "gray" _GREEN_ "green" -# _RED_ "red" _YELLOW_ "yellow" _BLUE_ "blue" _MAG_ "mag" _CYAN_ "cyan" -# _HIWHITE_ "white" _HIGRAY_ "gray" _HIGREEN_ "green" -# _HIRED_ "red" _HIYELLOW_ "yellow" _HIBLUE_ "blue" _HIMAG_ "mag" _HICYAN_ "cyan" -# HIWHITE "white" HIGRAY "gray" HIGREEN "green" -# HIRED "red" HIYELLOW "yellow" HIBLUE "blue" HIMAG "mag" HICYAN "cyan" -# "right?") - -# -# pretty-prints the value of a variable so that the -# equals signs align -# -function(boost_report_value NAME) - string(LENGTH "${NAME}" varlen) - # LOG - #message(STATUS "boost_report_value: NAME=${NAME} (${varlen})") - #message(STATUS "boost_report_value: \${NAME}=${${NAME}}") - math(EXPR padding_len 40-${varlen}) - string(SUBSTRING " " - 0 ${padding_len} varpadding) - colormsg("${NAME}${varpadding} = ${${NAME}}") -endfunction() - -function(boost_message_value NAME) - string(LENGTH "${NAME}" varlen) - math(EXPR padding_len 40-${varlen}) - string(SUBSTRING " " - 0 ${padding_len} varpadding) - message(STATUS "${NAME}${varpadding} = ${${NAME}}") -endfunction() - -function(trace NAME) - if(BOOST_CMAKE_TRACE) - string(LENGTH "${NAME}" varlen) - math(EXPR padding_len 40-${varlen}) - string(SUBSTRING "........................................" - 0 ${padding_len} varpadding) - message("${NAME} ${varpadding} ${${NAME}}") - endif() -endfunction() - -# -# pretty-prints the value of a variable so that the -# equals signs align -# -function(boost_report_pretty PRETTYNAME VARNAME) - string(LENGTH "${PRETTYNAME}" varlen) - math(EXPR padding_len 30-${varlen}) - string(SUBSTRING " " - 0 ${padding_len} varpadding) - message(STATUS "${PRETTYNAME}${varpadding} = ${${VARNAME}}") -endfunction() - -# -# assert that ARG is actually a library target -# -macro(dependency_check ARG) - trace(ARG) - if (NOT "${ARG}" STREQUAL "") - get_target_property(deptype ${ARG} TYPE) - if(NOT deptype MATCHES ".*_LIBRARY$") - set(DEPENDENCY_OKAY FALSE) - list(APPEND DEPENDENCY_FAILURES ${ARG}) - endif() - endif() -endmacro() - -# -# Tests package-FOUND for varname in three cases as given, lowercase and -# uppercase. -# -macro(soci_check_package_found NAME SUCCESS) - - set(${SUCCESS} FALSE) - set(VARNAME ${NAME}) - set(VARNAME_SUCCESS ${${VARNAME}_FOUND}) - - # Test both, given original name and uppercase version too - if(VARNAME_SUCCESS) - set(${SUCCESS} TRUE) - else() - string(TOUPPER ${NAME} VARNAME) - set(VARNAME_SUCCESS ${${VARNAME}_FOUND}) - if(VARNAME_SUCCESS) - set(${SUCCESS} TRUE) - endif() - endif() - - #message(STATUS "soci_check_package_found: ${SUCCESS}=${${SUCCESS}}") -endmacro() - -# -# Pretty-print of given property of current directory. -# -function(soci_report_directory_property PROPNAME) - get_directory_property(${PROPNAME} ${PROPNAME}) - boost_report_value(${PROPNAME}) -endfunction() - -# -# Scans the current directory and returns a list of subdirectories. -# Author: Robert Fleming -# Source: http://www.cmake.org/pipermail/cmake/2008-February/020114.html -# -# Third parameter is 1 if you want relative paths returned. -# Usage: list_subdirectories(the_list_is_returned_here /path/to/project TRUE) -# -macro(list_subdirectories retval curdir return_relative) - file(GLOB sub-dir RELATIVE ${curdir} *) - set(list_of_dirs "") - foreach(dir ${sub-dir}) - if(IS_DIRECTORY ${curdir}/${dir}) - if (${return_relative}) - set(list_of_dirs ${list_of_dirs} ${dir}) - else() - set(list_of_dirs ${list_of_dirs} ${curdir}/${dir}) - endif() - endif() - endforeach() - set(${retval} ${list_of_dirs}) -endmacro() - -# -# Generates output name for given target depending on platform and version. -# For instance, on Windows, libraries get ABI version suffix soci_coreXY.{dll|lib}. -# -function(soci_target_output_name TARGET_NAME OUTPUT_NAME) - if(NOT DEFINED TARGET_NAME) - message(SEND_ERROR "Error, the variable TARGET_NAME is not defined!") - endif() - - if(NOT DEFINED ${PROJECT_NAME}_VERSION) - message(SEND_ERROR "Error, the variable ${${PROJECT_NAME}_VERSION} is not defined!") - endif() - - # On Windows, ABI version is specified using binary file name suffix. - # On Unix, suffix is empty and SOVERSION is used instead. - if (WIN32) - string(LENGTH "${${PROJECT_NAME}_ABI_VERSION}" abilen) - if(abilen GREATER 0) - set(SUFFIX "_${${PROJECT_NAME}_ABI_VERSION}") - endif() - endif() - - set(${OUTPUT_NAME} ${TARGET_NAME}${SUFFIX} PARENT_SCOPE) -endfunction() diff --git a/src/soci/cmake/SociVersion.cmake b/src/soci/cmake/SociVersion.cmake deleted file mode 100644 index 5c8b5d75a7..0000000000 --- a/src/soci/cmake/SociVersion.cmake +++ /dev/null @@ -1,62 +0,0 @@ -################################################################################ -# SociVersion.cmake - part of CMake configuration of SOCI library -################################################################################ -# Copyright (C) 2010 Mateusz Loskot -# -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -################################################################################ -# Macros in this module: -# -# soci_version - defines version information for SOCI library -# -################################################################################ - -# Defines version information for SOCI library -# -# soci_version(MAJOR major_version MINOR minor_version PATCH patch_level) -# -# MAJOR.MINOR version is used to set SOVERSION -# -macro(soci_version) - # get version from soci/version.h - file( - STRINGS - "${PROJECT_SOURCE_DIR}/include/soci/version.h" - _VERSION - REGEX - "#define SOCI_VERSION ([0-9]+)" - ) - string(REGEX MATCH "([0-9]+)" _VERSION "${_VERSION}") - - math(EXPR ${PROJECT_NAME}_VERSION_MAJOR "${_VERSION} / 100000") - math(EXPR ${PROJECT_NAME}_VERSION_MINOR "${_VERSION} / 100 % 1000") - math(EXPR ${PROJECT_NAME}_VERSION_PATCH "${_VERSION} % 100") - - # Set VERSION string - set(${PROJECT_NAME}_VERSION - "${${PROJECT_NAME}_VERSION_MAJOR}.${${PROJECT_NAME}_VERSION_MINOR}.${${PROJECT_NAME}_VERSION_PATCH}") - - # Set SOVERSION based on major and minor - set(${PROJECT_NAME}_SOVERSION - "${${PROJECT_NAME}_VERSION_MAJOR}.${${PROJECT_NAME}_VERSION_MINOR}") - - # Set ABI version string used to name binary output and, by SOCI loader, to find binaries. - # On Windows, ABI version is specified using binary file name suffix. - # On Unix, suffix ix empty and SOVERSION is used instead. - if (UNIX) - set(${PROJECT_NAME}_ABI_VERSION ${${PROJECT_NAME}_SOVERSION}) - elseif(WIN32) - set(${PROJECT_NAME}_ABI_VERSION - "${${PROJECT_NAME}_VERSION_MAJOR}_${${PROJECT_NAME}_VERSION_MINOR}") - else() - message(FATAL_ERROR "Ambiguous target platform with unknown ABI version scheme. Giving up.") - endif() - - boost_report_value(${PROJECT_NAME}_VERSION) - boost_report_value(${PROJECT_NAME}_ABI_VERSION) - - add_definitions(-DSOCI_ABI_VERSION="${${PROJECT_NAME}_ABI_VERSION}") - -endmacro() diff --git a/src/soci/cmake/configs/test-access.cmake b/src/soci/cmake/configs/test-access.cmake deleted file mode 100644 index abc44deb03..0000000000 --- a/src/soci/cmake/configs/test-access.cmake +++ /dev/null @@ -1,13 +0,0 @@ -[ODBC] -DRIVER=Microsoft Access Driver (*.mdb, *.accdb) -UID=admin -UserCommitSync=Yes -Threads=3 -SafeTransactions=0 -PageTimeout=5 -MaxScanRows=8 -MaxBufferSize=2048 -FIL=MS Access -DriverId=25 -DefaultDir=@TEST_ACCESS_PATH@\tests\odbc -DBQ=@TEST_ACCESS_PATH@\tests\odbc\soci_test.mdb diff --git a/src/soci/cmake/configs/test-mysql.cmake b/src/soci/cmake/configs/test-mysql.cmake deleted file mode 100644 index 48e54033d5..0000000000 --- a/src/soci/cmake/configs/test-mysql.cmake +++ /dev/null @@ -1,4 +0,0 @@ -[ODBC] -DRIVER=@MYSQL_DRIVER_NAME@ -DATABASE=soci_test -OPTION=0 diff --git a/src/soci/cmake/dependencies/Boost.cmake b/src/soci/cmake/dependencies/Boost.cmake deleted file mode 100644 index 366d32b748..0000000000 --- a/src/soci/cmake/dependencies/Boost.cmake +++ /dev/null @@ -1,13 +0,0 @@ -set(Boost_FIND_QUIETLY TRUE) - -set(Boost_USE_MULTITHREADED ON) -find_package(Boost 1.33.1 COMPONENTS date_time) - -if (NOT Boost_DATE_TIME_FOUND) - find_package(Boost 1.33.1) -endif() - -set(Boost_RELEASE_VERSION - "${Boost_MAJOR_VERSION}.${Boost_MINOR_VERSION}.${Boost_SUBMINOR_VERSION}") - -boost_external_report(Boost RELEASE_VERSION INCLUDE_DIR LIBRARIES) diff --git a/src/soci/cmake/dependencies/DB2.cmake b/src/soci/cmake/dependencies/DB2.cmake deleted file mode 100644 index 063f1a17d8..0000000000 --- a/src/soci/cmake/dependencies/DB2.cmake +++ /dev/null @@ -1,5 +0,0 @@ -set(DB2_FIND_QUIETLY TRUE) - -find_package(DB2) - -boost_external_report(DB2 INCLUDE_DIR LIBRARIES) diff --git a/src/soci/cmake/dependencies/Firebird.cmake b/src/soci/cmake/dependencies/Firebird.cmake deleted file mode 100644 index b072702b0a..0000000000 --- a/src/soci/cmake/dependencies/Firebird.cmake +++ /dev/null @@ -1,9 +0,0 @@ -option(SOCI_FIREBIRD_EMBEDDED "Use embedded library in Firebird backend" OFF) -boost_report_value(SOCI_FIREBIRD_EMBEDDED) - -set(Firebird_FIND_QUIETLY TRUE) - -find_package(Firebird) - -boost_external_report(Firebird INCLUDE_DIR LIBRARIES VERSION) - diff --git a/src/soci/cmake/dependencies/MySQL.cmake b/src/soci/cmake/dependencies/MySQL.cmake deleted file mode 100644 index 5599b08858..0000000000 --- a/src/soci/cmake/dependencies/MySQL.cmake +++ /dev/null @@ -1,5 +0,0 @@ -set(MySQL_FIND_QUIETLY TRUE) - -find_package(MySQL) - -boost_external_report(MySQL INCLUDE_DIR LIBRARIES) diff --git a/src/soci/cmake/dependencies/ODBC.cmake b/src/soci/cmake/dependencies/ODBC.cmake deleted file mode 100644 index 88b85a1c59..0000000000 --- a/src/soci/cmake/dependencies/ODBC.cmake +++ /dev/null @@ -1,5 +0,0 @@ -set(ODBC_FIND_QUIETLY TRUE) - -find_package(ODBC) - -boost_external_report(ODBC INCLUDE_DIR LIBRARIES) diff --git a/src/soci/cmake/dependencies/Oracle.cmake b/src/soci/cmake/dependencies/Oracle.cmake deleted file mode 100644 index c66452040e..0000000000 --- a/src/soci/cmake/dependencies/Oracle.cmake +++ /dev/null @@ -1,5 +0,0 @@ -set(ORACLE_FIND_QUIETLY TRUE) - -find_package(Oracle) - -boost_external_report(Oracle INCLUDE_DIR LIBRARIES) diff --git a/src/soci/cmake/dependencies/PostgreSQL.cmake b/src/soci/cmake/dependencies/PostgreSQL.cmake deleted file mode 100644 index c6f2154258..0000000000 --- a/src/soci/cmake/dependencies/PostgreSQL.cmake +++ /dev/null @@ -1,5 +0,0 @@ -set(PostgreSQL_FIND_QUIETLY TRUE) - -find_package(PostgreSQL) - -boost_external_report(PostgreSQL INCLUDE_DIRS LIBRARIES VERSION) diff --git a/src/soci/cmake/dependencies/SQLite3.cmake b/src/soci/cmake/dependencies/SQLite3.cmake deleted file mode 100644 index 0daa9a593a..0000000000 --- a/src/soci/cmake/dependencies/SQLite3.cmake +++ /dev/null @@ -1,5 +0,0 @@ -set(SQLITE3_FIND_QUIETLY TRUE) - -find_package(SQLite3) - -boost_external_report(SQLite3 INCLUDE_DIR LIBRARIES) diff --git a/src/soci/cmake/dependencies/Threads.cmake b/src/soci/cmake/dependencies/Threads.cmake deleted file mode 100644 index 6a5487554b..0000000000 --- a/src/soci/cmake/dependencies/Threads.cmake +++ /dev/null @@ -1,4 +0,0 @@ -set(Threads_FIND_QUIETLY TRUE) - -find_package(Threads) -boost_report_value(CMAKE_THREAD_LIBS_INIT) diff --git a/src/soci/cmake/modules/FindDB2.cmake b/src/soci/cmake/modules/FindDB2.cmake deleted file mode 100644 index b4c36a06fb..0000000000 --- a/src/soci/cmake/modules/FindDB2.cmake +++ /dev/null @@ -1,105 +0,0 @@ -############################################################################### -# CMake module to search for DB2 client library -# -# On success, the macro sets the following variables: -# DB2_FOUND = if the library found -# DB2_LIBRARY = full path to the library -# DB2_LIBRARIES = full path to the library -# DB2_INCLUDE_DIR = where to find the library headers -# -# Copyright (c) 2013 Denis Chapligin -# -# Redistribution and use is allowed according to the terms of the BSD license. -# For details see the accompanying COPYING-CMAKE-SCRIPTS file. -# -############################################################################### - -if(UNIX) - set(DB2_INSTALL_PATHS - /opt/ibm/db2/V10.1 - /opt/ibm/db2/V9.7 - /opt/ibm/db2/V9.5 - /opt/ibm/db2/V9.1 - /opt/ibm/clidriver - /opt/clidriver) - - if(CMAKE_SIZEOF_VOID_P EQUAL 4) - set(DB2_LIBDIRS "lib32" "lib") - else() - set(DB2_LIBDIRS "lib64" "lib") - endif() - - set(DB2_FIND_INCLUDE_PATHS) - set(DB2_FIND_LIB_PATHS) - foreach(db2_install_path ${DB2_INSTALL_PATHS}) - if (IS_DIRECTORY ${db2_install_path}/include) - set(DB2_FIND_INCLUDE_PATHS - ${DB2_FIND_INCLUDE_PATHS} - ${db2_install_path}/include) - endif() - foreach(db2_libdir ${DB2_LIBDIRS}) - if (IS_DIRECTORY ${db2_install_path}/${db2_libdir}) - set(DB2_FIND_LIB_PATHS - ${DB2_FIND_LIB_PATHS} - ${db2_install_path}/${db2_libdir}) - endif() - endforeach(db2_libdir) - endforeach(db2_install_path) -elseif(WIN32) - if (CMAKE_CL_64) # 64-bit build, DB2 64-bit installed - set(DB2_FIND_INCLUDE_PATHS $ENV{ProgramW6432}/IBM/SQLLIB/include) - set(DB2_FIND_LIB_PATHS $ENV{ProgramW6432}/IBM/SQLLIB/lib) - else() # 32-bit build, DB2 64-bit or DB2 32-bit installed - - if(EXISTS "$ENV{ProgramW6432}/IBM/SQLLIB/lib") - # On 64-bit Windows with DB2 64-bit installed: - # LIB environment points to {DB2}/IBM/SQLLIB/lib with64-bit db2api.lib, - # this flag prevents checking paths in LIB, so Win32 version can be detected - set(DB2_FIND_LIB_NO_LIB NO_SYSTEM_ENVIRONMENT_PATH) - - endif() - - set(DB2_FIND_INCLUDE_PATHS - $ENV{ProgramW6432}/IBM/SQLLIB/include - $ENV{ProgramFiles}/IBM/SQLLIB/include) - set(DB2_FIND_LIB_PATHS - $ENV{ProgramFiles}/IBM/SQLLIB/lib - $ENV{ProgramFiles}/IBM/SQLLIB/lib/win32 - $ENV{ProgramW6432}/IBM/SQLLIB/lib/win32) - endif() -endif() - -find_path(DB2_INCLUDE_DIR sqlcli1.h - $ENV{DB2_INCLUDE_DIR} - $ENV{DB2_DIR}/include - $ENV{DB2_HOME} - $ENV{IBM_DB_INCLUDE} - ${DB2_FIND_INCLUDE_PATHS}) - -find_library(DB2_LIBRARY - NAMES db2 db2api - PATHS - $ENV{DB2LIB} - $ENV{IBM_DB_LIB} - ${DB2_FIND_LIB_PATHS} - ${DB2_FIND_LIB_NO_LIB}) - -if(DB2_LIBRARY) - get_filename_component(DB2_LIBRARY_DIR ${DB2_LIBRARY} PATH) -endif() - -if(DB2_INCLUDE_DIR AND DB2_LIBRARY_DIR) - set(DB2_FOUND TRUE) -endif() - -set(DB2_LIBRARIES ${DB2_LIBRARY}) - -# Handle the QUIETLY and REQUIRED arguments and set DB2_FOUND to TRUE -# if all listed variables are TRUE -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(DB2 - DEFAULT_MSG - DB2_INCLUDE_DIR - DB2_LIBRARIES) - -mark_as_advanced(DB2_INCLUDE_DIR DB2_LIBRARIES) diff --git a/src/soci/cmake/modules/FindDL.cmake b/src/soci/cmake/modules/FindDL.cmake deleted file mode 100644 index 3f7f889f3a..0000000000 --- a/src/soci/cmake/modules/FindDL.cmake +++ /dev/null @@ -1,21 +0,0 @@ -if(DL_INCLUDE_DIR) - set(DL_FIND_QUIETLY TRUE) -endif() - -find_path(DL_INCLUDE_DIR dlfcn.h) -find_library(DL_LIBRARY NAMES dl) - -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(DL DEFAULT_MSG DL_LIBRARY DL_INCLUDE_DIR) - -if(NOT DL_FOUND) - # if dlopen can be found without linking in dl then, - # dlopen is part of libc, so don't need to link extra libs. - include(CheckFunctionExists) - check_function_exists(dlopen DL_FOUND) - set(DL_LIBRARY "") -endif() - -set(DL_LIBRARIES ${DL_LIBRARY}) - -mark_as_advanced(DL_LIBRARY DL_INCLUDE_DIR) diff --git a/src/soci/cmake/modules/FindFirebird.cmake b/src/soci/cmake/modules/FindFirebird.cmake deleted file mode 100644 index 0e9b6784bf..0000000000 --- a/src/soci/cmake/modules/FindFirebird.cmake +++ /dev/null @@ -1,38 +0,0 @@ -############################################################## -# Copyright (c) 2008 Daniel Pfeifer # -# # -# Distributed under the Boost Software License, Version 1.0. # -############################################################## - -# This module defines -# FIREBIRD_INCLUDE_DIR - where to find ibase.h -# FIREBIRD_LIBRARIES - the libraries to link against to use FIREBIRD -# FIREBIRD_FOUND - true if FIREBIRD was found - -find_path(FIREBIRD_INCLUDE_DIR ibase.h - /usr/include - $ENV{ProgramFiles}/Firebird/*/include -) - -if(SOCI_FIREBIRD_EMBEDDED) - set(FIREBIRD_LIB_NAMES fbembed) -else() - set(FIREBIRD_LIB_NAMES fbclient fbclient_ms) -endif() - -find_library(FIREBIRD_LIBRARIES - NAMES - ${FIREBIRD_LIB_NAMES} - PATHS - /usr/lib - $ENV{ProgramFiles}/Firebird/*/lib -) - -# fbembed ? - -include(FindPackageHandleStandardArgs) -FIND_PACKAGE_HANDLE_STANDARD_ARGS(Firebird - DEFAULT_MSG FIREBIRD_LIBRARIES FIREBIRD_INCLUDE_DIR) - -mark_as_advanced(FIREBIRD_INCLUDE_DIR FIREBIRD_LIBRARIES) - diff --git a/src/soci/cmake/modules/FindMySQL.cmake b/src/soci/cmake/modules/FindMySQL.cmake deleted file mode 100644 index 1233568932..0000000000 --- a/src/soci/cmake/modules/FindMySQL.cmake +++ /dev/null @@ -1,129 +0,0 @@ -# - Try to find MySQL / MySQL Embedded library -# Find the MySQL includes and client library -# This module defines -# MYSQL_INCLUDE_DIR, where to find mysql.h -# MYSQL_LIBRARIES, the libraries needed to use MySQL. -# MYSQL_LIB_DIR, path to the MYSQL_LIBRARIES -# MYSQL_EMBEDDED_LIBRARIES, the libraries needed to use MySQL Embedded. -# MYSQL_EMBEDDED_LIB_DIR, path to the MYSQL_EMBEDDED_LIBRARIES -# MYSQL_FOUND, If false, do not try to use MySQL. -# MYSQL_EMBEDDED_FOUND, If false, do not try to use MySQL Embedded. - -# Copyright (c) 2006-2008, JarosÅ‚aw Staniek -# -# Redistribution and use is allowed according to the terms of the BSD license. -# For details see the accompanying COPYING-CMAKE-SCRIPTS file. - -include(CheckCXXSourceCompiles) - -if(WIN32) - find_path(MYSQL_INCLUDE_DIR mysql.h - PATHS - $ENV{MYSQL_INCLUDE_DIR} - $ENV{MYSQL_DIR}/include - $ENV{ProgramFiles}/MySQL/*/include - $ENV{SystemDrive}/MySQL/*/include - $ENV{ProgramW6432}/MySQL/*/include - ) -else(WIN32) - find_path(MYSQL_INCLUDE_DIR mysql.h - PATHS - $ENV{MYSQL_INCLUDE_DIR} - $ENV{MYSQL_DIR}/include - /usr/local/mysql/include - /opt/mysql/mysql/include - PATH_SUFFIXES - mysql - ) -endif(WIN32) - -if(WIN32) - if (${CMAKE_BUILD_TYPE}) - string(TOLOWER ${CMAKE_BUILD_TYPE} CMAKE_BUILD_TYPE_TOLOWER) - endif() - - # path suffix for debug/release mode - # binary_dist: mysql binary distribution - # build_dist: custom build - if(CMAKE_BUILD_TYPE_TOLOWER MATCHES "debug") - set(binary_dist debug) - set(build_dist Debug) - else(CMAKE_BUILD_TYPE_TOLOWER MATCHES "debug") - ADD_DEFINITIONS(-DDBUG_OFF) - set(binary_dist opt) - set(build_dist Release) - endif(CMAKE_BUILD_TYPE_TOLOWER MATCHES "debug") - -# find_library(MYSQL_LIBRARIES NAMES mysqlclient - set(MYSQL_LIB_PATHS - $ENV{MYSQL_DIR}/lib/${binary_dist} - $ENV{MYSQL_DIR}/libmysql/${build_dist} - $ENV{MYSQL_DIR}/client/${build_dist} - $ENV{ProgramFiles}/MySQL/*/lib/${binary_dist} - $ENV{SystemDrive}/MySQL/*/lib/${binary_dist} - $ENV{MYSQL_DIR}/lib/opt - $ENV{MYSQL_DIR}/client/release - $ENV{ProgramFiles}/MySQL/*/lib/opt - $ENV{SystemDrive}/MySQL/*/lib/opt - $ENV{ProgramW6432}/MySQL/*/lib - ) - find_library(MYSQL_LIBRARIES NAMES libmysql - PATHS - ${MYSQL_LIB_PATHS} - ) -else(WIN32) -# find_library(MYSQL_LIBRARIES NAMES mysqlclient - set(MYSQL_LIB_PATHS - $ENV{MYSQL_DIR}/libmysql_r/.libs - $ENV{MYSQL_DIR}/lib - $ENV{MYSQL_DIR}/lib/mysql - /usr/local/mysql/lib - /opt/mysql/mysql/lib - $ENV{MYSQL_DIR}/libmysql_r/.libs - $ENV{MYSQL_DIR}/lib - $ENV{MYSQL_DIR}/lib/mysql - /usr/local/mysql/lib - /opt/mysql/mysql/lib - PATH_SUFFIXES - mysql - ) - find_library(MYSQL_LIBRARIES NAMES mysqlclient - PATHS - ${MYSQL_LIB_PATHS} - ) -endif(WIN32) - -find_library(MYSQL_EMBEDDED_LIBRARIES NAMES mysqld - PATHS - ${MYSQL_LIB_PATHS} -) - -if(MYSQL_LIBRARIES) - get_filename_component(MYSQL_LIB_DIR ${MYSQL_LIBRARIES} PATH) -endif(MYSQL_LIBRARIES) - -if(MYSQL_EMBEDDED_LIBRARIES) - get_filename_component(MYSQL_EMBEDDED_LIB_DIR ${MYSQL_EMBEDDED_LIBRARIES} PATH) -endif(MYSQL_EMBEDDED_LIBRARIES) - -set( CMAKE_REQUIRED_INCLUDES ${MYSQL_INCLUDE_DIR} ) -set( CMAKE_REQUIRED_LIBRARIES ${MYSQL_EMBEDDED_LIBRARIES} ) -check_cxx_source_compiles( "#include \nint main() { int i = MYSQL_OPT_USE_EMBEDDED_CONNECTION; }" HAVE_MYSQL_OPT_EMBEDDED_CONNECTION ) - -if(MYSQL_INCLUDE_DIR AND MYSQL_LIBRARIES) - set(MYSQL_FOUND TRUE) - message(STATUS "Found MySQL: ${MYSQL_INCLUDE_DIR}, ${MYSQL_LIBRARIES}") -else(MYSQL_INCLUDE_DIR AND MYSQL_LIBRARIES) - set(MYSQL_FOUND FALSE) - message(STATUS "MySQL not found.") -endif(MYSQL_INCLUDE_DIR AND MYSQL_LIBRARIES) - -if(MYSQL_INCLUDE_DIR AND MYSQL_EMBEDDED_LIBRARIES AND HAVE_MYSQL_OPT_EMBEDDED_CONNECTION) - set(MYSQL_EMBEDDED_FOUND TRUE) - message(STATUS "Found MySQL Embedded: ${MYSQL_INCLUDE_DIR}, ${MYSQL_EMBEDDED_LIBRARIES}") -else(MYSQL_INCLUDE_DIR AND MYSQL_EMBEDDED_LIBRARIES AND HAVE_MYSQL_OPT_EMBEDDED_CONNECTION) - set(MYSQL_EMBEDDED_FOUND FALSE) - message(STATUS "MySQL Embedded not found.") -endif(MYSQL_INCLUDE_DIR AND MYSQL_EMBEDDED_LIBRARIES AND HAVE_MYSQL_OPT_EMBEDDED_CONNECTION) - -mark_as_advanced(MYSQL_INCLUDE_DIR MYSQL_LIBRARIES MYSQL_EMBEDDED_LIBRARIES) diff --git a/src/soci/cmake/modules/FindODBC.cmake b/src/soci/cmake/modules/FindODBC.cmake deleted file mode 100644 index 6cee4088bd..0000000000 --- a/src/soci/cmake/modules/FindODBC.cmake +++ /dev/null @@ -1,69 +0,0 @@ -# -# Find the ODBC driver manager includes and library. -# -# ODBC is an open standard for connecting to different databases in a -# semi-vendor-independent fashion. First you install the ODBC driver -# manager. Then you need a driver for each separate database you want -# to connect to (unless a generic one works). VTK includes neither -# the driver manager nor the vendor-specific drivers: you have to find -# those yourself. -# -# This module defines -# ODBC_INCLUDE_DIR, where to find sql.h -# ODBC_LIBRARIES, the libraries to link against to use ODBC -# ODBC_FOUND. If false, you cannot build anything that requires MySQL. - -# also defined, but not for general use is -# ODBC_LIBRARY, where to find the ODBC driver manager library. - -set(ODBC_FOUND FALSE) -include(CheckIncludeFiles) -check_include_files("windows.h;sqlext.h" HAVE_SQLEXT_H) - -if(NOT HAVE_SQLEXT_H) - find_path(ODBC_INCLUDE_DIR sqlext.h - /usr/include - /usr/include/odbc - /usr/local/include - /usr/local/include/odbc - /usr/local/odbc/include - "C:/Program Files (x86)/Windows Kits/8.0/include/um" - "C:/Program Files (x86)/Microsoft SDKs/Windows/v7.0A/Include" - "C:/Program Files/ODBC/include" - "C:/Program Files/Microsoft SDKs/Windows/v7.0/include" - "C:/Program Files/Microsoft SDKs/Windows/v6.0a/include" - "C:/ODBC/include" - DOC "Specify the directory containing sql.h." - ) -endif() - -if(MSVC) - # msvc knows where to find sdk libs - set(ODBC_LIBRARY odbc32) -else() - find_library(ODBC_LIBRARY - NAMES iodbc odbc odbcinst odbc32 - PATHS - /usr/lib - /usr/lib/odbc - /usr/local/lib - /usr/local/lib/odbc - /usr/local/odbc/lib - "C:/Program Files (x86)/Windows Kits/8.0/Lib/win8/um/x86/" - "C:/Program Files (x86)/Microsoft SDKs/Windows/v7.0A/Lib" - "C:/Program Files/ODBC/lib" - "C:/ODBC/lib/debug" - DOC "Specify the ODBC driver manager library here." - ) -endif() - -if(ODBC_LIBRARY) - if(ODBC_INCLUDE_DIR OR HAVE_SQLEXT_H) - set( ODBC_FOUND 1 ) - endif() -endif() - -set(ODBC_LIBRARIES ${ODBC_LIBRARY}) - -mark_as_advanced(ODBC_FOUND ODBC_LIBRARY ODBC_EXTRA_LIBRARIES ODBC_INCLUDE_DIR) - diff --git a/src/soci/cmake/modules/FindOracle.cmake b/src/soci/cmake/modules/FindOracle.cmake deleted file mode 100644 index 97997c61d0..0000000000 --- a/src/soci/cmake/modules/FindOracle.cmake +++ /dev/null @@ -1,81 +0,0 @@ -############################################################################### -# -# CMake module to search for Oracle client library (OCI) -# -# On success, the macro sets the following variables: -# ORACLE_FOUND = if the library found -# ORACLE_LIBRARY = full path to the library -# ORACLE_LIBRARIES = full path to the library -# ORACLE_INCLUDE_DIR = where to find the library headers also defined, -# but not for general use are -# ORACLE_VERSION = version of library which was found, e.g. "1.2.5" -# -# Copyright (c) 2009-2013 Mateusz Loskot -# -# Developed with inspiration from Petr Vanek -# who wrote similar macro for TOra - http://torasql.com/ -# -# Module source: http://github.com/mloskot/workshop/tree/master/cmake/ -# -# Redistribution and use is allowed according to the terms of the BSD license. -# For details see the accompanying COPYING-CMAKE-SCRIPTS file. -# -############################################################################### - -# First check for CMAKE variable -if(NOT ORACLE_HOME) - # If ORACLE_HOME is not defined check for env var and if exists set from env var - if(EXISTS $ENV{ORACLE_HOME}) - set(ORACLE_HOME $ENV{ORACLE_HOME}) - endif() -endif() - -message(STATUS "ORACLE_HOME=${ORACLE_HOME}") - -find_path(ORACLE_INCLUDE_DIR - NAMES oci.h - PATHS - ${ORACLE_HOME}/rdbms/public - ${ORACLE_HOME}/include - ${ORACLE_HOME}/sdk/include # Oracle SDK - ${ORACLE_HOME}/OCI/include # Oracle XE on Windows - # instant client from rpm - /usr/include/oracle/*/client${LIB_SUFFIX}) - -set(ORACLE_OCI_NAMES clntsh libclntsh oci) # Dirty trick might help on OSX, see issues/89 -set(ORACLE_OCCI_NAMES libocci occi oraocci10 oraocci11 oraocci12) -set(ORACLE_NNZ_NAMES nnz10 libnnz10 nnz11 libnnz11 nnz12 libnnz12 ociw32) - -set(ORACLE_LIB_DIR - ${ORACLE_HOME} - ${ORACLE_HOME}/lib - ${ORACLE_HOME}/sdk/lib # Oracle SDK - ${ORACLE_HOME}/sdk/lib/msvc - ${ORACLE_HOME}/OCI/lib/msvc # Oracle XE on Windows - # Instant client from rpm - /usr/lib/oracle/*/client${LIB_SUFFIX}/lib) - -find_library(ORACLE_OCI_LIBRARY - NAMES ${ORACLE_OCI_NAMES} PATHS ${ORACLE_LIB_DIR}) -find_library(ORACLE_OCCI_LIBRARY - NAMES ${ORACLE_OCCI_NAMES} PATHS ${ORACLE_LIB_DIR}) -find_library(ORACLE_NNZ_LIBRARY - NAMES ${ORACLE_NNZ_NAMES} PATHS ${ORACLE_LIB_DIR}) - -set(ORACLE_LIBRARY - ${ORACLE_OCI_LIBRARY} - ${ORACLE_OCCI_LIBRARY} - ${ORACLE_NNZ_LIBRARY}) - -if(NOT WIN32) - set(ORACLE_LIBRARY ${ORACLE_LIBRARY} ${ORACLE_CLNTSH_LIBRARY}) -endif(NOT WIN32) - -set(ORACLE_LIBRARIES ${ORACLE_LIBRARY}) - -# Handle the QUIETLY and REQUIRED arguments and set ORACLE_FOUND to TRUE -# if all listed variables are TRUE -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(ORACLE DEFAULT_MSG ORACLE_LIBRARY ORACLE_INCLUDE_DIR) - -mark_as_advanced(ORACLE_INCLUDE_DIR ORACLE_LIBRARY) diff --git a/src/soci/cmake/modules/FindPostgreSQL.cmake b/src/soci/cmake/modules/FindPostgreSQL.cmake deleted file mode 100644 index 48937e2efa..0000000000 --- a/src/soci/cmake/modules/FindPostgreSQL.cmake +++ /dev/null @@ -1,176 +0,0 @@ -# Distributed under the OSI-approved BSD 3-Clause License. See accompanying -# file Copyright.txt or https://cmake.org/licensing for details. - -#.rst: -# FindPostgreSQL -# -------------- -# -# Find the PostgreSQL installation. -# -# This module defines -# -# :: -# -# POSTGRESQL_LIBRARIES - the PostgreSQL libraries needed for linking -# POSTGRESQL_INCLUDE_DIRS - the directories of the PostgreSQL headers -# POSTGRESQL_LIBRARY_DIRS - the link directories for PostgreSQL libraries -# POSTGRESQL_VERSION_STRING - the version of PostgreSQL found (since CMake 2.8.8) - -# ---------------------------------------------------------------------------- -# History: -# This module is derived from the module originally found in the VTK source tree. -# -# ---------------------------------------------------------------------------- -# Note: -# POSTGRESQL_ADDITIONAL_VERSIONS is a variable that can be used to set the -# version mumber of the implementation of PostgreSQL. -# In Windows the default installation of PostgreSQL uses that as part of the path. -# E.g C:\Program Files\PostgreSQL\8.4. -# Currently, the following version numbers are known to this module: -# "9.6" "9.5" "9.4" "9.3" "9.2" "9.1" "9.0" "8.4" "8.3" "8.2" "8.1" "8.0" -# -# To use this variable just do something like this: -# set(POSTGRESQL_ADDITIONAL_VERSIONS "9.2" "8.4.4") -# before calling find_package(PostgreSQL) in your CMakeLists.txt file. -# This will mean that the versions you set here will be found first in the order -# specified before the default ones are searched. -# -# ---------------------------------------------------------------------------- -# You may need to manually set: -# POSTGRESQL_INCLUDE_DIR - the path to where the PostgreSQL include files are. -# POSTGRESQL_LIBRARY_DIR - The path to where the PostgreSQL library files are. -# If FindPostgreSQL.cmake cannot find the include files or the library files. -# -# ---------------------------------------------------------------------------- -# The following variables are set if PostgreSQL is found: -# POSTGRESQL_FOUND - Set to true when PostgreSQL is found. -# POSTGRESQL_INCLUDE_DIRS - Include directories for PostgreSQL -# POSTGRESQL_LIBRARY_DIRS - Link directories for PostgreSQL libraries -# POSTGRESQL_LIBRARIES - The PostgreSQL libraries. -# -# ---------------------------------------------------------------------------- -# If you have installed PostgreSQL in a non-standard location. -# (Please note that in the following comments, it is assumed that -# points to the root directory of the include directory of PostgreSQL.) -# Then you have three options. -# 1) After CMake runs, set POSTGRESQL_INCLUDE_DIR to /include and -# POSTGRESQL_LIBRARY_DIR to wherever the library pq (or libpq in windows) is -# 2) Use CMAKE_INCLUDE_PATH to set a path to /PostgreSQL<-version>. This will allow find_path() -# to locate POSTGRESQL_INCLUDE_DIR by utilizing the PATH_SUFFIXES option. e.g. In your CMakeLists.txt file -# set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "/include") -# 3) Set an environment variable called ${POSTGRESQL_ROOT} that points to the root of where you have -# installed PostgreSQL, e.g. . -# -# ---------------------------------------------------------------------------- - -set(POSTGRESQL_INCLUDE_PATH_DESCRIPTION "top-level directory containing the PostgreSQL include directories. E.g /usr/local/include/PostgreSQL/8.4 or C:/Program Files/PostgreSQL/8.4/include") -set(POSTGRESQL_INCLUDE_DIR_MESSAGE "Set the POSTGRESQL_INCLUDE_DIR cmake cache entry to the ${POSTGRESQL_INCLUDE_PATH_DESCRIPTION}") -set(POSTGRESQL_LIBRARY_PATH_DESCRIPTION "top-level directory containing the PostgreSQL libraries.") -set(POSTGRESQL_LIBRARY_DIR_MESSAGE "Set the POSTGRESQL_LIBRARY_DIR cmake cache entry to the ${POSTGRESQL_LIBRARY_PATH_DESCRIPTION}") -set(POSTGRESQL_ROOT_DIR_MESSAGE "Set the POSTGRESQL_ROOT system variable to where PostgreSQL is found on the machine E.g C:/Program Files/PostgreSQL/8.4") - - -set(POSTGRESQL_KNOWN_VERSIONS ${POSTGRESQL_ADDITIONAL_VERSIONS} - "9.6" "9.5" "9.4" "9.3" "9.2" "9.1" "9.0" "8.4" "8.3" "8.2" "8.1" "8.0") - -# Define additional search paths for root directories. -set( POSTGRESQL_ROOT_DIRECTORIES - ENV POSTGRESQL_ROOT - ${POSTGRESQL_ROOT} -) -foreach(suffix ${POSTGRESQL_KNOWN_VERSIONS}) - if(WIN32) - list(APPEND POSTGRESQL_LIBRARY_ADDITIONAL_SEARCH_SUFFIXES - "PostgreSQL/${suffix}/lib") - list(APPEND POSTGRESQL_INCLUDE_ADDITIONAL_SEARCH_SUFFIXES - "PostgreSQL/${suffix}/include") - list(APPEND POSTGRESQL_TYPE_ADDITIONAL_SEARCH_SUFFIXES - "PostgreSQL/${suffix}/include/server") - endif() - if(UNIX) - list(APPEND POSTGRESQL_LIBRARY_ADDITIONAL_SEARCH_SUFFIXES - "pgsql-${suffix}/lib") - list(APPEND POSTGRESQL_INCLUDE_ADDITIONAL_SEARCH_SUFFIXES - "pgsql-${suffix}/include") - list(APPEND POSTGRESQL_TYPE_ADDITIONAL_SEARCH_SUFFIXES - "postgresql/${suffix}/server" - "pgsql-${suffix}/include/server") - endif() -endforeach() - -# -# Look for an installation. -# -find_path(POSTGRESQL_INCLUDE_DIR - NAMES libpq-fe.h - PATHS - # Look in other places. - ${POSTGRESQL_ROOT_DIRECTORIES} - PATH_SUFFIXES - pgsql - postgresql - include - ${POSTGRESQL_INCLUDE_ADDITIONAL_SEARCH_SUFFIXES} - # Help the user find it if we cannot. - DOC "The ${POSTGRESQL_INCLUDE_DIR_MESSAGE}" -) - -# The PostgreSQL library. -set (POSTGRESQL_LIBRARY_TO_FIND pq) -# Setting some more prefixes for the library -set (POSTGRESQL_LIB_PREFIX "") -if ( WIN32 ) - set (POSTGRESQL_LIB_PREFIX ${POSTGRESQL_LIB_PREFIX} "lib") - set (POSTGRESQL_LIBRARY_TO_FIND ${POSTGRESQL_LIB_PREFIX}${POSTGRESQL_LIBRARY_TO_FIND}) -endif() - -find_library(POSTGRESQL_LIBRARY - NAMES ${POSTGRESQL_LIBRARY_TO_FIND} - PATHS - ${POSTGRESQL_ROOT_DIRECTORIES} - PATH_SUFFIXES - lib - ${POSTGRESQL_LIBRARY_ADDITIONAL_SEARCH_SUFFIXES} - # Help the user find it if we cannot. - DOC "The ${POSTGRESQL_LIBRARY_DIR_MESSAGE}" -) -get_filename_component(POSTGRESQL_LIBRARY_DIR ${POSTGRESQL_LIBRARY} PATH) - -if (POSTGRESQL_INCLUDE_DIR) - # Some platforms include multiple pg_config.hs for multi-lib configurations - # This is a temporary workaround. A better solution would be to compile - # a dummy c file and extract the value of the symbol. - file(GLOB _PG_CONFIG_HEADERS "${POSTGRESQL_INCLUDE_DIR}/pg_config*.h") - foreach(_PG_CONFIG_HEADER ${_PG_CONFIG_HEADERS}) - if(EXISTS "${_PG_CONFIG_HEADER}") - file(STRINGS "${_PG_CONFIG_HEADER}" pgsql_version_str - REGEX "^#define[\t ]+PG_VERSION[\t ]+\".*\"") - if(pgsql_version_str) - string(REGEX REPLACE "^#define[\t ]+PG_VERSION[\t ]+\"([^\"]*)\".*" - "\\1" POSTGRESQL_VERSION_STRING "${pgsql_version_str}") - break() - endif() - endif() - endforeach() - unset(pgsql_version_str) -endif() - -# Did we find anything? -# -#include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake) -include(FindPackageHandleStandardArgs) -# -find_package_handle_standard_args(PostgreSQL - REQUIRED_VARS POSTGRESQL_LIBRARY POSTGRESQL_INCLUDE_DIR - VERSION_VAR POSTGRESQL_VERSION_STRING) -set(POSTGRESQL_FOUND ${POSTGRESQL_FOUND}) - -# Now try to get the include and library path. -if(POSTGRESQL_FOUND) - set(POSTGRESQL_INCLUDE_DIRS ${POSTGRESQL_INCLUDE_DIR}) - set(POSTGRESQL_LIBRARY_DIRS ${POSTGRESQL_LIBRARY_DIR}) - set(POSTGRESQL_LIBRARIES ${POSTGRESQL_LIBRARY}) - set(POSTGRESQL_VERSION ${POSTGRESQL_VERSION_STRING}) -endif() - -mark_as_advanced(POSTGRESQL_INCLUDE_DIR POSTGRESQL_LIBRARY) diff --git a/src/soci/cmake/modules/FindSQLite3.cmake b/src/soci/cmake/modules/FindSQLite3.cmake deleted file mode 100644 index 1359bc79ab..0000000000 --- a/src/soci/cmake/modules/FindSQLite3.cmake +++ /dev/null @@ -1,62 +0,0 @@ -############################################################################### -# CMake module to search for SQLite 3 library -# -# On success, the macro sets the following variables: -# SQLITE3_FOUND = if the library found -# SQLITE3_LIBRARY = full path to the library -# SQLITE3_LIBRARIES = full path to the library -# SSQLITE3_INCLUDE_DIR = where to find the library headers -# -# Copyright (c) 2009 Mateusz Loskot -# -# Redistribution and use is allowed according to the terms of the BSD license. -# For details see the accompanying COPYING-CMAKE-SCRIPTS file. -# -############################################################################### - -find_path(SQLITE3_INCLUDE_DIR - NAMES sqlite3.h - PATH_PREFIXES sqlite sqlite3 - PATHS - /usr/include - /usr/local/include - $ENV{LIB_DIR}/include - $ENV{LIB_DIR}/include/sqlite - $ENV{LIB_DIR}/include/sqlite3 - $ENV{ProgramFiles}/SQLite/*/include - $ENV{ProgramFiles}/SQLite3/*/include - $ENV{SystemDrive}/SQLite/*/include - $ENV{SystemDrive}/SQLite3/*/include - $ENV{SQLITE_ROOT}/include - ${SQLITE_ROOT_DIR}/include - $ENV{OSGEO4W_ROOT}/include) - -set(SQLITE3_NAMES sqlite3_i sqlite3) -find_library(SQLITE3_LIBRARY - NAMES ${SQLITE3_NAMES} - PATHS - /usr/lib - /usr/local/lib - $ENV{LIB_DIR}/lib - $ENV{ProgramFiles}/SQLite/*/lib - $ENV{ProgramFiles}/SQLite3/*/lib - $ENV{SystemDrive}/SQLite/*/lib - $ENV{SystemDrive}/SQLite3/*/lib - $ENV{SQLITE_ROOT}/lib - ${SQLITE_ROOT_DIR}/lib - $ENV{OSGEO4W_ROOT}/lib) - -set(SQLITE3_LIBRARIES - ${SQLITE3_LIBRARIES} - ${SQLITE3_LIBRARY}) - -#message(STATUS ${SQLITE3_LIBRARY}) -# Handle the QUIETLY and REQUIRED arguments and set SQLITE3_FOUND to TRUE -# if all listed variables are TRUE -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(SQLITE3 - DEFAULT_MSG - SQLITE3_LIBRARIES - SQLITE3_INCLUDE_DIR) - -mark_as_advanced(SQLITE3_LIBRARY SQLITE3_INCLUDE_DIR SQLITE3_LIBRARIES) diff --git a/src/soci/cmake/modules/FindSoci.cmake b/src/soci/cmake/modules/FindSoci.cmake deleted file mode 100644 index f49b874289..0000000000 --- a/src/soci/cmake/modules/FindSoci.cmake +++ /dev/null @@ -1,98 +0,0 @@ -############################################################################### -# CMake module to search for SOCI library -# -# WARNING: This module is experimental work in progress. -# -# This module defines: -# SOCI_INCLUDE_DIRS = include dirs to be used when using the soci library -# SOCI_LIBRARY = full path to the soci library -# SOCI_VERSION = the soci version found (not yet. soci does not provide that info.) -# SOCI_FOUND = true if soci was found -# -# This module respects: -# LIB_SUFFIX = (64|32|"") Specifies the suffix for the lib directory -# -# For each component you specify in find_package(), the following variables are set. -# -# SOCI_${COMPONENT}_PLUGIN = full path to the soci plugin -# SOCI_${COMPONENT}_FOUND -# -# Copyright (c) 2011 Michael Jansen -# -# Redistribution and use is allowed according to the terms of the BSD license. -# For details see the accompanying COPYING-CMAKE-SCRIPTS file. -# -############################################################################### -# -### Global Configuration Section -# -SET(_SOCI_ALL_PLUGINS mysql odbc postgresql sqlite3) -SET(_SOCI_REQUIRED_VARS SOCI_INCLUDE_DIR SOCI_LIBRARY) - -# -### FIRST STEP: Find the soci headers. -# -FIND_PATH( - SOCI_INCLUDE_DIR soci.h - PATH "/usr/local" - PATH_SUFFIXES "" "soci" - DOC "Soci (http://soci.sourceforge.net) include directory") -MARK_AS_ADVANCED(SOCI_INCLUDE_DIR) - -SET(SOCI_INCLUDE_DIRS ${SOCI_INCLUDE_DIR}) - -# -### SECOND STEP: Find the soci core library. Respect LIB_SUFFIX -# -FIND_LIBRARY( - SOCI_LIBRARY - NAMES soci_core - HINTS ${SOCI_INCLUDE_DIR}/.. - PATH_SUFFIXES lib${LIB_SUFFIX}) -MARK_AS_ADVANCED(SOCI_LIBRARY) - -GET_FILENAME_COMPONENT(SOCI_LIBRARY_DIR ${SOCI_LIBRARY} PATH) -MARK_AS_ADVANCED(SOCI_LIBRARY_DIR) - -# -### THIRD STEP: Find all installed plugins if the library was found -# -IF(SOCI_INCLUDE_DIR AND SOCI_LIBRARY) - - MESSAGE(STATUS "Soci found: Looking for plugins") - FOREACH(plugin IN LISTS _SOCI_ALL_PLUGINS) - - FIND_LIBRARY( - SOCI_${plugin}_PLUGIN - NAMES soci_${plugin} - HINTS ${SOCI_INCLUDE_DIR}/.. - PATH_SUFFIXES lib${LIB_SUFFIX}) - MARK_AS_ADVANCED(SOCI_${plugin}_PLUGIN) - - IF(SOCI_${plugin}_PLUGIN) - MESSAGE(STATUS " * Plugin ${plugin} found ${SOCI_${plugin}_PLUGIN}.") - SET(SOCI_${plugin}_FOUND True) - ELSE() - MESSAGE(STATUS " * Plugin ${plugin} not found.") - SET(SOCI_${plugin}_FOUND False) - ENDIF() - - ENDFOREACH() - - # - ### FOURTH CHECK: Check if the required components were all found - # - FOREACH(component ${Soci_FIND_COMPONENTS}) - IF(NOT SOCI_${component}_FOUND) - MESSAGE(SEND_ERROR "Required component ${component} not found.") - ENDIF() - ENDFOREACH() - -ENDIF() - -# -### ADHERE TO STANDARDS -# -include(FindPackageHandleStandardArgs) -FIND_PACKAGE_HANDLE_STANDARD_ARGS(Soci DEFAULT_MSG ${_SOCI_REQUIRED_VARS}) - diff --git a/src/soci/cmake/resources/vs2010-test-cmd-args.vcxproj.user.in b/src/soci/cmake/resources/vs2010-test-cmd-args.vcxproj.user.in deleted file mode 100644 index f41ec9b27b..0000000000 --- a/src/soci/cmake/resources/vs2010-test-cmd-args.vcxproj.user.in +++ /dev/null @@ -1,7 +0,0 @@ - - - - @SOCI_TEST_CMD_ARGS@ - WindowsLocalDebugger - - diff --git a/src/soci/docs/api/backend.md b/src/soci/docs/api/backend.md deleted file mode 100644 index 22fae9e70f..0000000000 --- a/src/soci/docs/api/backend.md +++ /dev/null @@ -1,313 +0,0 @@ -# Backends reference - -This part of the documentation is provided for those who want towrite (and contribute!) their -own backends. It is anyway recommendedthat authors of new backend see the code of some existing -backend forhints on how things are really done. - -The backend interface is a set of base classes that the actual backendsare supposed to specialize. -The main SOCI interface uses only theinterface and respecting the protocol (for example, -the order of function calls) described here. -Note that both the interface and theprotocol were initially designed with the Oracle database in -mind, which means that whereas it is quite natural with respect to the way Oracle API (OCI) works, -it might impose some implementation burden on otherbackends, where things are done differently -and therefore have to beadjusted, cached, converted, etc. - -The interface to the common SOCI interface is defined in the `core/soci-backend.h` header file. -This file is dissected below. - -All names are defined in either `soci` or `soci::details` namespace. - -```cpp -// data types, as seen by the user -enum data_type -{ - dt_string, dt_date, dt_double, dt_integer, dt_long_long, dt_unsigned_long_long -}; - -// the enum type for indicator variables -enum indicator { i_ok, i_null, i_truncated }; - -// data types, as used to describe exchange format -enum exchange_type -{ - x_char, - x_stdstring, - x_short, - x_integer, - x_long_long, - x_unsigned_long_long, - x_double, - x_stdtm, - x_statement, - x_rowid, - x_blob -}; - -struct cstring_descriptor -{ - cstring_descriptor(char * str, std::size_t bufSize) - : str_(str), bufSize_(bufSize) {} - - char * str_; - std::size_t bufSize_; -}; - -// actually in error.h: -class soci_error : public std::runtime_error -{ -public: - soci_error(std::string const & msg); -}; -``` - -The `data_type` enumeration type defines all types that form the core type support for SOCI. -The enum itself can be used by clients when dealing with dynamic rowset description. - -The `indicator` enumeration type defines all recognized *states* of data. -The `i_truncated` state is provided for the case where the string is retrieved from the database -into the char buffer that is not long enough to hold the whole value. - -The `exchange_type` enumeration type defines all possible types that can be used -with the `into` and `use` elements. - -The `cstring_descriptor` is a helper class that allows to store the address of `char` buffer -together with its size. -The objects of this class are passed to the backend when the `x_cstring` type is involved. - -The `soci_error` class is an exception type used for database-related (and also usage-related) errors. -The backends should throw exceptions of this or derived type only. - -```cpp -class standard_into_type_backend -{ -public: - standard_into_type_backend() {} - virtual ~standard_into_type_backend() {} - - virtual void define_by_pos(int& position, void* data, exchange_type type) = 0; - - virtual void pre_fetch() = 0; - virtual void post_fetch(bool gotData, bool calledFromFetch, indicator* ind) = 0; - - virtual void clean_up() = 0; -}; -``` - -The `standard_into_type_back_end` class implements the dynamic interactions with the simple -(non-bulk) `into` elements. -The objects of this class (or, rather, of the derived class implemented by the actual backend) -are created by the `statement` object when the `into` element is bound - in terms of lifetime -management, `statement` is the master of this class. - -* `define_by_pos` - Called when the `into` element is bound, once and before the statement is executed. The `data` pointer points to the variable used for `into` element (or to the `cstring_descriptor` object, which is artificially created when the plain `char` buffer is used for data exchange). The `position` parameter is a "column number", assigned by the library. The backend should increase this parameter, according to the number of fields actually taken (usually 1). -* `pre_fetch` - Called before each row is fetched. -* `post_fetch` - Called after each row is fetched. The `gotData` parameter is `true` if the fetch operation really retrievedsome data and `false` otherwise; `calledFromFetch` is `true` when the call is from the fetch operation and `false` if it is from the execute operation (this is also the case for simple, one-time queries). In particular, `(calledFromFetch && !gotData)` indicates that there is an end-of-rowset condition. `ind` points to the indicator provided by the user, or is `NULL`, if there is no indicator. -* `clean_up` - Called once when the statement is destroyed. - -The intended use of `pre_fetch` and `post_fetch` functions is to manage any internal buffer and/or data conversion foreach value retrieved from the database. -If the given server supportsbinary data transmission and the data format for the given type agreeswith what is used on the client machine, then these two functions neednot do anything; otherwise buffer management and data conversionsshould go there. - -```cpp -class vector_into_type_backend -{ -public: - vector_into_type_backend() {} - virtual ~vector_into_type_backend() {} - - virtual void define_by_pos(int& position, void* data, exchange_type type) = 0; - - virtual void pre_fetch() = 0; - virtual void post_fetch(bool gotData, indicator* ind) = 0; - - virtual void resize(std::size_t sz) = 0; - virtual std::size_t size() = 0; - - virtual void clean_up() = 0; -}; -``` - -The `vector_into_type_back_end` has similar structure and purpose as the previous one, but is used for vectors (bulk data retrieval). - -The `data` pointer points to the variable of type `std::vector;` (and *not* to its internal buffer), `resize` is supposed to really resize the user-provided vector and `size` is supposed to return the current size of this vector. -The important difference with regard to the previous class is that `ind` points (if not `NULL`) to the beginning of the *array* of indicators. -The backend should fill this array according to the actual state of the retrieved data. - -* `bind_by_pos` - Called for each `use` element, once and before the statement is executed - for those `use` elements that do not provide explicit names for parameter binding. The meaning of parameters is same as in previous classes. -* `bind_by_name` - Called for those `use` elements that provide the explicit name. -* `pre_use` - Called before the data is transmitted to the server (this means before the statement is executed, which can happen many times for the prepared statement). `ind` points to the indicator provided by the user (or is `NULL`). -* `post_use` - Called after statement execution. `gotData` and `ind` have the same meaning as in `standard_into_type_back_end::post_fetch`, and this can be used by those backends whose respective servers support two-way data exchange (like in/out parameters in stored procedures). - -The intended use for `pre_use` and `post_use` methods is to manage any internal buffers and/or data conversion. -They can be called many times with the same statement. - -```cpp -class vector_use_type_backend -{ -public: - virtual ~vector_use_type_backend() {} - - virtual void bind_by_pos(int& position, - void* data, exchange_type type) = 0; - virtual void bind_by_name(std::string const& name, - void* data, exchange_type type) = 0; - - virtual void pre_use(indicator const* ind) = 0; - - virtual std::size_t size() = 0; - - virtual void clean_up() = 0; -}; -``` - -Objects of this type (or rather of type derived from this one) are used to implement interactions with user-provided vector (bulk) `use` elements and are managed by the `statement` object. -The `data` pointer points to the whole vector object provided by the user (and *not* to its internal buffer); `ind` points to the beginning of the array of indicators (or is `NULL`). -The meaning of this interface is analogous to those presented above. - -```cpp -class statement_backend -{ -public: - statement_backend() {} - virtual ~statement_backend() {} - - virtual void alloc() = 0; - virtual void clean_up() = 0; - - virtual void prepare(std::string const& query, statement_type eType) = 0; - - enum exec_fetch_result - { - ef_success, - ef_no_data - }; - - virtual exec_fetch_result execute(int number) = 0; - virtual exec_fetch_result fetch(int number) = 0; - - virtual long long get_affected_rows() = 0; - virtual int get_number_of_rows() = 0; - - virtual std::string rewrite_for_procedure_call(std::string const& query) = 0; - - virtual int prepare_for_describe() = 0; - virtual void describe_column(int colNum, data_type& dtype, - std::string& column_name) = 0; - - virtual standard_into_type_backend* make_into_type_backend() = 0; - virtual standard_use_type_backend* make_use_type_backend() = 0; - virtual vector_into_type_backend* make_vector_into_type_backend() = 0; - virtual vector_use_type_backend* make_vector_use_type_backend() = 0; -}; -``` - -The `statement_backend` type implements the internals of the `statement` objects. -The objects of this class are created by the `session` object. - -* `alloc` - Called once to allocate everything that is needed for the statement to work correctly. -* `clean_up` - Supposed to clean up the resources, called once. -* `prepare` - Called once with the text of the SQL query. For servers that support explicit query preparation, this is the place to do it. -* `execute` - Called to execute the query; if number is zero, the intent is not to exchange data with the user-provided objects (`into` and `use` elements); positive values mean the number of rows to exchange (more than 1 is used only for bulk operations). -* `fetch` - Called to fetch next bunch of rows; number is positive and determines the requested number of rows (more than 1 is used only for bulk operations). -* `get_affected_rows` - Called to determine the actual number of rows affected by data modifying statement. -* `get_number_of_rows` - Called to determine the actual number of rows retrieved by the previous call to `execute` or `fetch`. -* `rewrite_for_procedure_call` - Used when the `procedure` is used instead of `statement`, to call the stored procedure. This function should rewrite the SQL query (if necessary) to the form that will allow to execute the given procedure. -* `prepare_for_describe` - Called once when the `into` element is used with the `row` type, which means that dynamic rowset description should be performed. It is supposed to do whatever is needed to later describe the column properties and should return the number of columns. -* `describe_column` - Called once for each column (column numbers - `colNum` - start from 1), should fill its parameters according to the column properties. -* `make_into_type_backend`, `make_use_type_backend`, `make_vector_into_type_backend`, `make_vector_use_type_backend` - Called once for each `into` or `use` element, to create the objects of appropriate classes (described above). - -**Notes:** - -1. Whether the query is executed using the simple one-time syntax or is prepared, the `alloc`, `prepare` and `execute` functions are always called, in this order. -2. All `into` and `use` elements are bound (their `define_by_pos` or `bind_by_pos`/`bind_by_name` functions are called) *between* statement preparation and execution. - -```cpp -class rowid_backend -{ -public: - virtual ~rowid_backend() {} -}; -``` - -The `rowid_backend` class is a hook for the backends to provide their own state for the row identifier. It has no functions, since the only portable interaction with the row identifier object is to use it with `into` and `use` elements. - -```cpp -class blob_backend -{ -public: - virtual ~blob_backend() {} - - virtual std::size_t get_len() = 0; - virtual std::size_t read(std::size_t offset, char * buf, - std::size_t toRead) = 0; - virtual std::size_t write(std::size_t offset, char const * buf, - std::size_t toWrite) = 0; - virtual std::size_t append(char const * buf, std::size_t toWrite) = 0; - virtual void trim(std::size_t newLen) = 0; -}; -``` - -The `blob_backend` interface provides the entry points for the `blob` methods. - -```cpp -class session_backend -{ -public: - virtual ~session_backend() {} - - virtual void begin() = 0; - virtual void commit() = 0; - virtual void rollback() = 0; - - virtual bool get_next_sequence_value(session&, std::string const&, long&); - virtual bool get_last_insert_id(session&, std::string const&, long&); - - virtual std::string get_backend_name() const = 0; - - virtual statement_backend * make_statement_backend() = 0; - virtual rowid_backend * make_rowid_backend() = 0; - virtual blob_backend * make_blob_backend() = 0; -}; -``` - -The object of the class derived from `session_backend` implements the internals of the `session` object. - -* `begin`, `commit`, `rollback` - Forward-called when the same functions of `session` are called by user. -* `get_next_sequence_value`, `get_last_insert_id` - Called to retrieve sequences or auto-generated values and every backend should define at least one of them to allow the code using auto-generated values to work. -* `make_statement_backend`, `make_rowid_backend`, `make_blob_backend` - Called to create respective implementations for the `statement`, `rowid` and `blob` classes. - -```cpp -struct backend_factory -{ - virtual ~backend_factory() {} - - virtual details::session_backend * make_session( - std::string const& connectString) const = 0; -}; -``` - -The `backend_factory` is a base class for backend-provided factory class that is able to create valid sessions. The `connectString` parameter passed to `make_session` is provided here by the `session` constructor and contains only the backend-related parameters, without the backend name (if the dynamic backend loading is used). - -The actual backend factory object is supposed to be provided by the backend implementation and declared in its header file. In addition to this, the `factory_ABC` function with the "C" calling convention and returning the pointer to concrete factory object should be provided, where `ABC` is the backend name. - -The following example is taken from `soci-postgresql.h`, which declares entities of the PostgreSQL backend: - -```cpp -struct postgresql_backend_factory : backend_factory -{ - virtual postgresql_session_backend* make_session( - std::string const& connectString) const; -}; -extern postgresql_backend_factory const postgresql; - -extern "C" -{ - -// for dynamic backend loading -backend_factory const * factory_postgresql(); - -} // extern "C" -``` - -With the above declarations, it is enough to pass the `postgresql` factory name to the constructor of the `session` object, which will use this factory to create concrete implementations for any other objects that are needed, with the help of appropriate `make_XYZ` functions. Alternatively, the `factory_postgresql` function will be called automatically by the backend loader if the backend name is provided at run-time instead. - -Note that the backend source code is placed in the `backends/*name*` directory (for example, `backends/oracle`) and the test driver is in `backends/*name*/test`. There is also `backends/empty` directory provided as a skeleton for development of new backends and their tests. It is recommended that all backends respect naming conventions by just appending their name to the base-class names. The backend name used for the global factory object should clearly identify the given database engine, like `oracle`, `postgresql`, `mysql`, and so on. diff --git a/src/soci/docs/api/client.md b/src/soci/docs/api/client.md deleted file mode 100644 index c21c96ec9c..0000000000 --- a/src/soci/docs/api/client.md +++ /dev/null @@ -1,753 +0,0 @@ -# API Reference - -The core client interface is a set of classes and free functions declared in the `soci.h` header file. -All names are dbeclared in the `soci` namespace. - -There are also additional names declared in the `soci::details` namespace, but they are not supposed to be directly used by the users of the library and are therefore not documented here. -When such types are used in the declarations that are part of the "public" interface, they are replaced by "IT", which means "internal type". -Types related to the backend interface are named here. - -## Commonly used types - -The following types are commonly used in the rest of the interface: - -```cpp -// data types, as seen by the user -enum data_type { dt_string, dt_date, dt_double, dt_integer, dt_long_long, dt_unsigned_long_long }; - -// the enum type for indicator variables -enum indicator { i_ok, i_null, i_truncated }; - -// the type used for reporting exceptions -class soci_error : public std::runtime_error { /* ... */ }; -``` - -The `data_type` type defines the basic SOCI data types. User provided data types need to be associated with one of these basic types. - -The `indicator` type defines the possible states of data. - -The `soci_error` type is used for error reporting. - -## class session - -The `session` class encapsulates the connection to the database. - -```cpp -class session -{ -public: - session(); - explicit session(connection_parameters const & parameters); - session(backend_factory const & factory, std::string const & connectString); - session(std::string const & backendName, std::string const & connectString); - explicit session(std::string const & connectString); - explicit session(connection_pool & pool); - - ~session(); - - void open(backend_factory const & factory, std::string const & connectString); - void open(std::string const & backendName, std::string const & connectString); - void open(std::string const & connectString); - void close(); - void reconnect(); - - void begin(); - void commit(); - void rollback(); - - *IT* once; - *IT* prepare; - - template *IT* operator<<(T const & t); - - bool got_data() const; - - bool get_next_sequence_value(std::string const & sequence, long & value); - bool get_last_insert_id(std::string const & table, long & value); - - std::ostringstream & get_query_stream(); - - void set_log_stream(std::ostream * s); - std::ostream * get_log_stream() const; - - std::string get_last_query() const; - - void uppercase_column_names(bool forceToUpper); - - std::string get_dummy_from_table() const; - std::string get_dummy_from_clause() const; - - details::session_backend * get_backend(); - - std::string get_backend_name() const; -}; -``` - -This class contains the following members: - -* Various constructors. The default one creates the session in the disconnected state. The others expect the backend factory object, or the backend name, or the URL-like composed connection string or the special parameters object containing both the backend and the connection string as well as possibly other connection options. The last constructor creates a session proxy associated with the session that is available in the given pool and releases it back to the pool when its lifetime ends. Example: - -```cpp -session sql(postgresql, "dbname=mydb"); -session sql("postgresql", "dbname=mydb"); -session sql("postgresql://dbname=mydb"); -``` - -* The constructors that take backend name as string load the shared library (if not yet loaded) with name computed as `libsoci_ABC.so` (or `libsoci_ABC.dll` on Windows) where `ABC` is the given backend name. -* `open`, `close` and `reconnect` functions for reusing the same session object many times; the `reconnect` function attempts to establish the connection with the same parameters as most recently used with constructor or `open`. The arguments for `open` are treated in the same way as for constructors. -* `begin`, `commit` and `rollback` functions for transaction control. -* `once` member, which is used for performing *instant* queries that do not need to be separately prepared. Example: - -```cpp -sql.once << "drop table persons"; -``` - -* `prepare` member, which is used for statement preparation - the result of the statement preparation must be provided to the constructor of the `statement` class. Example: - -```cpp -int i; -statement st = (sql.prepare << - "insert into numbers(value) values(:val)", use(i)); -``` - -`operator<<` that is a shortcut forwarder to the equivalent operator of the `once` member. Example: - -```cpp -sql << "drop table persons"; -``` - -* `got_data` returns true if the last executed query had non-empty result. -* `get_next_sequence_value` returns true if the next value of the sequence with the specified name was generated and returned in its second argument. Unless you can be sure that your program will use only databases that support sequences, consider using this method in conjunction with `get_last_insert_id()` as explained in ["Working with sequences"](beyond.html#sequences) section. -* `get_last_insert_id` returns true if it could retrieve the last value automatically generated by the database for an auto-incremented field. Notice that although this method takes the table name, for some databases, such as Microsoft SQL Server and SQLite, this value is actually global, so you should attempt to retrieve it immediately after performing an insertion. -* `get_query_stream` provides direct access to the stream object that is used to accumulate the query text and exists in particular to allow the user to imbue specific locale to this stream. -* `set_log_stream` and `get_log_stream` functions for setting and getting the current stream object used for basic query logging. By default, it is `NULL`, which means no logging The string value that is actually logged into the stream is one-line verbatim copy of the query string provided by the user, without including any data from the `use` elements. The query is logged exactly once, before the preparation step. -* `get_last_query` retrieves the text of the last used query. -* `uppercase_column_names` allows to force all column names to uppercase in dynamic row description; this function is particularly useful for portability, since various database servers report column names differently (some preserve case, some change it). -* `get_dummy_from_table` and `get_dummy_from_clause()`: helpers for writing portable DML statements, see [DML helpers](statement.html#dml) for more details. -* `get_backend` returns the internal pointer to the concrete backend implementation of the session. This is provided for advanced users that need access to the functionality that is not otherwise available. -* `get_backend_name` is a convenience forwarder to the same function of the backend object. - -See [Connections and simple queries](basics.html) for more examples. - -## class connection_parameters - -The `connection_parameters` class is a simple container for the backend pointer, connection string and any other connection options. It is used together with `session` constructor and `open()` method. - -```cpp -class connection_parameters -{ -public: - connection_parameters(); - connection_parameters(backend_factory const & factory, std::string const & connectString); - connection_parameters(std::string const & backendName, std::string const & connectString); - explicit connection_parameters(std::string const & fullConnectString); - - void set_option(const char * name, std::string const & value); - bool get_option(const char * name, std::string & value) const -}; -``` - -The methods of this class are: - -* Default constructor is rarely used as it creates an uninitialized object and the only way to initialize it later is to assign another, valid, connection_parameters object to this one. -* The other constructors correspond to the similar constructors of the `session` class and specify both the backend, either as a pointer to it or by name, and the connection string. -* `set_option` can be used to set the value of an option with the given name. Currently all option values are strings, so if you need to set a numeric option you need to convert it to a string first. If an option with the given name had been already set before, its old value is overwritten. - -## class connection_pool - -The `connection_pool` class encapsulates the thread-safe pool of connections and ensures that only one thread at a time has access to any connection that it manages. - -```cpp -class connection_pool -{ -public: - explicit connection_pool(std::size_t size); - ~connection_pool(); - - session & at(std::size_t pos); - - std::size_t lease(); - bool try_lease(std::size_t & pos, int timeout); - void give_back(std::size_t pos); -}; -``` - -The operations of the pool are: - -* Constructor that takes the intended size of the pool. After construction, the pool contains regular `session` objects in disconnected state. -* `at` function that provides direct access to any given entryin the pool. This function is *non-synchronized*. -* `lease` function waits until some entry is available (which means that it is not used) and returns the position of that entry in the pool, marking it as *locked*. -* `try_lease` acts like `lease`, but allows to set up a time-out (relative, in milliseconds) on waiting. Negative time-out value means no time-out. Returns `true` if the entry was obtained, in which case its position is written to the `pos` parametr, and `false` if no entry was available before the time-out. -* `give_back` should be called when the entry on the given position is no longer in use and can be passed to other requesting thread. - -## class transaction - -The class `transaction` can be used for associating the transaction with some code scope. It is a RAII wrapper for regular transaction operations that automatically rolls back in its destructor *if* the transaction was not explicitly committed before. - -```cpp -class transaction -{ -public: - explicit transaction(session & sql); - - ~transaction(); - - void commit(); - void rollback(); - -private: - // ... -}; -``` - -Note that objects of this class are not notified of other transaction related operations that might be executed by user code explicitly or hidden inside SQL queries. It is not recommended to mix different ways of managing transactions. - -## function into - -The function `into` is used for binding local output data (in other words, it defines where the results of the query are stored). - -```cpp -template -IT into(T & t); - -template -IT into(T & t, T1 p1); - -template -IT into(T & t, indicator & ind); - -template -IT into(T & t, indicator & ind, T1 p1); - -template -IT into(T & t, std::vector & ind); -``` - -Example: - -```cpp -int count; -sql << "select count(*) from person", into(count); -``` - -See [Binding local dat](exchange.html#bind_local) for more examples - -## function use - -The function `use` is used for binding local input data (in other words, it defines where the parameters of the query come from). - -```cpp -template -*IT* use(T & t); - -template -*IT* use(T & t, T1 p1); - -template -*IT* use(T & t, indicator & ind); - -template -*IT* use(T & t, indicator & ind, T1 p1); - -template -*IT* use(T & t, std::vector const & ind); - -template -*IT* use(T & t, std::vector const & ind, T1 p1); -``` - -Example: - -```cpp -int val = 7; -sql << "insert into numbers(val) values(:val)", use(val); -``` - -See [Binding local data](exchange.html#bind_local) for more examples. - -## class statement - -The `statement` class encapsulates the prepared statement. - -```cpp -class statement -{ -public: - statement(session & s); - statement(*IT* const & prep); - ~statement(); - - statement(statement const & other); - void operator=(statement const & other); - - void alloc(); - void bind(values & v); - void exchange(*IT* const & i); - void exchange(*IT* const & u); - void clean_up(); - void bind_clean_up(); - - void prepare(std::string const & query); - void define_and_bind(); - - bool execute(bool withDataExchange = false); - long long get_affected_rows(); - bool fetch(); - - bool got_data() const; - - void describe(); - void set_row(row * r); - void exchange_for_rowset(*IT* const & i); - - details::statement_backend * get_backend(); -}; -``` - -This class contains the following members: - -* Constructor accepting the `session` object. This can be used for later query preparation. Example: - -```cpp -statement stmt(sql); -``` - -* Constructor accepting the result of using `prepare` on the `session` object, see example provided above for the `session` class. -* Copy operations. -* `alloc` function, which allocates necessary internal resources. -* `bind` function, which is used to bind the `values` object - this is used in the object-relational mapping and normally called automatically. -* exchange functions for registering the binding of local data - they expect the result of calling the `into` or `use` functions and are normally invoked automatically. -* `clean_up` function for cleaning up resources, normally called automatically. -* `bind_clean_up` function for cleaning up any bound references. It allows to keep statement in cache and reuse it later with new references by calling `exchange` for each new bind variable. -* `prepare` function for preparing the statement for repeated execution. -* `define_and_bind` function for actually executing the registered bindings, normally called automatically. -* `execute` function for executing the statement. If its parameter is `false` then there is no data exchange with locally bound variables (this form should be used if later `fetch` of multiple rows is foreseen). Returns `true` if there was at least one row of data returned. -* `get_affected_rows` function returns the number of rows affected by the last statement. Returns `-1` if it's not implemented by the backend being used. -* `fetch` function for retrieving the next portion of the result. Returns `true` if there was new data. -* `got_data` return `true` if the most recent execution returned any rows. -* `describe` function for extracting the type information for the result (**Note:** no data is exchanged). This is normally called automatically and only when dynamic resultset binding is used. -* `set_row` function for associating the `statement` and `row` objects, normally called automatically. -* `exchange_for_rowset` as a special case for binding `rowset` objects. -* `get_backend` function that returns the internal pointer to the concrete backend implementation of the statement object. This is provided for advanced users that need access to the functionality that is not otherwise available. - -See [Statement preparation and repeated execution](statements.html#preparation) for example uses. - -Most of the functions from the `statement` class interface are called automatically, but can be also used explicitly. See [Interfaces](interfaces) for the description of various way to use this interface. - -## class procedure - -The `procedure` class encapsulates the call to the stored procedure and is aimed for higher portability of the client code. - -```cpp -class procedure -{ -public: - procedure(*IT* const & prep); - - bool execute(bool withDataExchange = false); - bool fetch(); - bool got_data() const; -}; -``` - -The constructor expects the result of using `prepare` on the `session` object. - -See [Stored procedures](statements.html#procedures) for examples. - -## class type_conversion - -The `type_conversion` class is a traits class that is supposed to be provided (specialized) by the user for defining conversions to and from one of the basic SOCI types. - -```cpp -template -struct type_conversion -{ - typedef T base_type; - - static void from_base(base_type const & in, indicator ind, T & out); - - static void to_base(T const & in, base_type & out, indicator & ind); -}; -``` - -Users are supposed to properly implement the `from_base` and `to_base` functions in their specializations of this template class. - -See [Extending SOCI to support custom (user-defined) C++ types](exchange.html#custom_types). - -## class row - -The `row` class encapsulates the data and type information retrieved for the single row when the dynamic rowset binding is used. - -```cpp -class row -{ -public: - row(); - ~row(); - - void uppercase_column_names(bool forceToUpper); - - std::size_t size() const; - - indicator get_indicator(std::size_t pos) const; - indicator get_indicator(std::string const & name) const; - - column_properties const & get_properties (std::size_t pos) const; - column_properties const & get_properties (std::string const & name) const; - - template - T get(std::size_t pos) const; - - template - T get(std::size_t pos, T const & nullValue) const; - - template - T get(std::string const & name) const; - - template - T get(std::string const & name, T const & nullValue) const; - - template - row const & operator>>(T & value) const; - - void skip(std::size_t num = 1) const; - - void reset_get_counter() const -}; -``` - -This class contains the following members: - -* Default constructor that allows to declare a `row` variable. -* `uppercase_column_names` - see the same function in the `session` class. -* `size` function that returns the number of columns in the row. -* `get_indicator` function that returns the indicator value for the given column (column is specified by position - starting from 0 - or by name). -* `get_properties` function that returns the properties of the column given by position (starting from 0) or by name. -* `get` functions that return the value of the column given by position or name. If the column contains null, then these functions either return the provided "default" `nullValue` or throw an exception. -* `operator>>` for convenience stream-like extraction interface. Subsequent calls to this function are equivalent to calling `get` with increasing position parameter, starting from the beginning. -* `skip` and `reset_get_counter` allow to change the order of data extraction for the above operator. - -See [Dynamic resultset binding](exchange.html#dynamic) for examples. - -## class column_properties - -The `column_properties` class provides the type and name information about the particular column in a rowset. - -```cpp -class column_properties -{ -public: - std::string get_name() const; - data_type get_data_type() const; -}; -``` - -This class contains the following members: - -* `get_name` function that returns the name of the column. -* `get_data_type` that returns the type of the column. - -See [Dynamic resultset binding](exchange.html#dynamic) for examples. - -## class values - -The `values` class encapsulates the data and type information and is used for object-relational mapping. - -```cpp -class values -{ -public: - values(); - - void uppercase_column_names(bool forceToUpper); - - indicator get_indicator(std::size_t pos) const; - indicator get_indicator(std::string const & name) const; - - template - T get(std::size_t pos) const; - - template - T get(std::size_t pos, T const & nullValue) const; - - template - T get(std::string const & name) const; - - template - T get(std::string const & name, T const & nullValue) const; - - template - values const & operator>>(T & value) const; - - void skip(std::size_t num = 1) const; - void reset_get_counter() const; - - template - void set(std::string const & name, T const & value, indicator indic = i_ok); - - template - void set(const T & value, indicator indic = i_ok); - - template - values & operator<<(T const & value); -}; -``` - -This class contains the same members as the `row` class (with the same meaning) plus: - -* `set` function for storing values in named columns or in subsequent positions. -* `operator<<` for convenience. - -See [Object-relational mapping](exchange.html#object_relational) for examples. - -## class blob - -The `blob` class encapsulates the "large object" functionality. - -```cpp -class blob -{ -public: - explicit blob(session & s); - ~blob(); - - std::size_t getLen(); - std::size_t read(std::size_t offset, char * buf, std::size_t toRead); - std::size_t write(std::size_t offset, char const * buf, std::size_t toWrite); - std::size_t append(char const * buf, std::size_t toWrite); - void trim(std::size_t newLen); - - details::blob_backend * get_backend(); -}; -``` - -This class contains the following members: - -* Constructor associating the `blob` object with the `session` object. -* `get_len` function that returns the size of the BLOB object. -* `read` function that reads the BLOB data into provided buffer. -* `write` function that writes the BLOB data from provided buffer. -* `append` function that appends to the existing BLOB data. -* `trim` function that truncates the existing data to the new length. -* `get_backend` function that returns the internal pointer to the concrete backend implementation of the BLOB object. This is provided for advanced users that need access to the functionality that is not otherwise available. - -See [Large objects (BLOBs)](exchange.html#blob) for more discussion. - -## class rowid - -The `rowid` class encapsulates the "row identifier" object. - -```cpp -class rowid -{ -public: - explicit rowid(Session & s); - ~rowid(); - - details::rowid_backend * get_backend(); -}; -``` - -This class contains the following members: - -* Constructor associating the `rowid` object with the `session` object. -* `get_backend` function that returns the internal pointer to the concrete backend implementation of the `rowid` object. - -## class backend_factory - -The `backend_factory` class provides the abstract interface for concrete backend factories. - -```cpp -struct backend_factory -{ - virtual details::session_backend * make_session( - std::string const & connectString) const = 0; -}; -``` - -The only member of this class is the `make_session` function that is supposed to create concrete backend implementation of the session object. - -Objects of this type are declared by each backend and should be provided to the constructor of the `session` class. In simple programs users do not need to use this class directly, but the example use is: - -```cpp -backend_factory & factory = postgresql; -std::string connectionParameters = "dbname=mydb"; - -session sql(factory, parameters); -``` - -## Simple Client Interface - -The simple client interface is provided with other languages in mind, to allow easy integration of the SOCI library with script interpreters and those languages that have the ability to link directly with object files using the "C" calling convention. - -The functionality of this interface is limited and in particular the dynamic rowset description and type conversions are not supported in this release. On the other hand, the important feature of this interface is that it does not require passing pointers to data managed by the user, because all data is handled at the SOCI side. This should make it easier to integrate SOCI with languages that have constrained ability to understand the C type system. - -Users of this interface need to explicitly `#include `. - -```c -typedef void * session_handle; -session_handle soci_create_session(char const * connectionString); -void soci_destroy_session(session_handle s); - -void soci_begin(session_handle s); -void soci_commit(session_handle s); -void soci_rollback(session_handle s); - -int soci_session_state(session_handle s); -char const * soci_session_error_message(session_handle s); -``` - -The functions above provide the *session* abstraction with the help of opaque handle. The `soci_session_state` function returns `1` if there was no error during the most recently executed function and `0` otherwise, in which case the `soci_session_error_message` can be used to obtain a human-readable error description. - -Note that the only function that cannot report all errors this way is `soci_create_session`, which returns `NULL` if it was not possible to create an internal object representing the session. However, if the proxy object was created, but the connection could not be established for whatever reason, the error message can be obtained in the regular way. - -```c -typedef void *blob_handle; -blob_handle soci_create_blob(session_handle s); -void soci_destroy_blob(blob_handle b); - -int soci_blob_get_len(blob_handle b); -int soci_blob_read(blob_handle b, int offset, char *buf, int toRead); -int soci_blob_write(blob_handle b, int offset, char const *buf, int toWrite); -int soci_blob_append(blob_handle b, char const *buf, int toWrite); -int soci_blob_trim(blob_handle b, int newLen); - -int soci_blob_state(blob_handle b); -char const * soci_blob_error_message(blob_handle b); -``` - -The functions above provide the *blob* abstraction with the help of opaque handle. The `soci_blob_state` function returns `1` if there was no error during the most recently executed function and `0` otherwise, in which case the `soci_session_error_message` can be used to obtain a human-readable error description. - -For easy error testing, functions `soci_blob_read`, `soci_blob_write`, `soci_blob_append`, and `soci_blob_trim` return `-1` in case of error and `soci_session_error_message` can be used to obtain a human-readable error description. - -Note that the only function that cannot report all errors this way is `soci_create_blob`, which returns `NULL` if it was not possible to create an internal object representing the blob. - -```c -typedef void * statement_handle; -statement_handle soci_create_statement(session_handle s); -void soci_destroy_statement(statement_handle st); - -int soci_statement_state(statement_handle s); -char const * soci_statement_error_message(statement_handle s); -``` - -The functions above create and destroy the statement object. If the statement cannot be created by the `soci_create_statement` function, the error condition is set up in the related session object; for all other functions the error condition is set in the statement object itself. - -```c -int soci_into_string (statement_handle st); -int soci_into_int (statement_handle st); -int soci_into_long_long(statement_handle st); -int soci_into_double (statement_handle st); -int soci_into_date (statement_handle st); -int soci_into_blob (statement_handle st); - -int soci_into_string_v (statement_handle st); -int soci_into_int_v (statement_handle st); -int soci_into_long_long_v(statement_handle st); -int soci_into_double_v (statement_handle st); -int soci_into_date_v (statement_handle st); -``` - -These functions create new data items for storing query results (*into elements*). These elements can be later identified by their position, which is counted from 0. For convenience, these function return the position of the currently added element. In case of error, `-1` is returned and the error condition is set in the statement object. - -The `_v` versions create a `vector` into elements, which can be used -to retrieve whole arrays of results. - -```c -int soci_get_into_state(statement_handle st, int position); -int soci_get_into_state_v(statement_handle st, int position, int index); -``` - -This function returns `1` if the into element at the given position has non-null value and `0` otherwise. The `_v` version works with `vector` elements and expects an array index. - -```c -char const * soci_get_into_string (statement_handle st, int position); -int soci_get_into_int (statement_handle st, int position); -long long soci_get_into_long_long(statement_handle st, int position); -double soci_get_into_double (statement_handle st, int position); -char const * soci_get_into_date (statement_handle st, int position); -blob_handle soci_get_into_blob (statement_handle st, int position); - -char const * soci_get_into_string_v (statement_handle st, int position, int index); -int soci_get_into_int_v (statement_handle st, int position, int index); -long long soci_get_into_long_long_v(statement_handle st, int position, int index); -double soci_get_into_double_v (statement_handle st, int position, int index); -char const * soci_get_into_date_v (statement_handle st, int position, int index); -``` - -The functions above allow to retrieve the current value of the given into element. - -**Note:** The `date` function returns the date value in the "`YYYY MM DD HH mm ss`" string format. - -```c -void soci_use_string (statement_handle st, char const * name); -void soci_use_int (statement_handle st, char const * name); -void soci_use_long_long(statement_handle st, char const * name); -void soci_use_double (statement_handle st, char const * name); -void soci_use_date (statement_handle st, char const * name); -void soci_use_blob (statement_handle st, char const * name); - -void soci_use_string_v (statement_handle st, char const * name); -void soci_use_int_v (statement_handle st, char const * name); -void soci_use_long_long_v(statement_handle st, char const * name); -void soci_use_double_v (statement_handle st, char const * name); -void soci_use_date_v (statement_handle st, char const * name); -``` - -The functions above allow to create new data elements that will be used to provide data to the query (*use elements*). The new elements can be later identified by given name, which must be unique for the given statement. - -```c -void soci_set_use_state(statement_handle st, char const * name, int state); -``` - -The `soci_set_use_state` function allows to set the state of the given use element. If the `state` parameter is set to non-zero the use element is considered non-null (which is also the default state after creating the use element). - -```c -int soci_use_get_size_v(statement_handle st); -void soci_use_resize_v (statement_handle st, int new_size); -``` - -These functions get and set the size of vector use elements (see comments for vector into elements above). - -```c -void soci_set_use_string (statement_handle st, char const * name, char const * val); -void soci_set_use_int (statement_handle st, char const * name, int val); -void soci_set_use_long_long(statement_handle st, char const * name, long long val); -void soci_set_use_double (statement_handle st, char const * name, double val); -void soci_set_use_date (statement_handle st, char const * name, char const * val); -void soci_set_use_blob (statement_handle st, char const * name, blob_handle blob); - -void soci_set_use_state_v (statement_handle st, char const * name, int index, int state); -void soci_set_use_string_v (statement_handle st, char const * name, int index, char const * val); -void soci_set_use_int_v (statement_handle st, char const * name, int index, int val); -void soci_set_use_long_long_v(statement_handle st, char const * name, int index, long long val); -void soci_set_use_double_v (statement_handle st, char const * name, int index, double val); -void soci_set_use_date_v (statement_handle st, char const * name, int index, char const * val); -``` - -The functions above set the value of the given use element, for both single and vector elements. - -**Note:** The expected format for the data values is "`YYYY MM DD HH mm ss`". - -```c -int soci_get_use_state (statement_handle st, char const * name); -char const * soci_get_use_string (statement_handle st, char const * name); -int soci_get_use_int (statement_handle st, char const * name); -long long soci_get_use_long_long(statement_handle st, char const * name); -double soci_get_use_double (statement_handle st, char const * name); -char const * soci_get_use_date (statement_handle st, char const * name); -blob_handle soci_get_use_blob (statement_handle st, char const * name); -``` - -These functions allow to inspect the state and value of named use elements. - -***Note:*** these functions are provide only for single use elements, not for vectors; the rationale for this is that modifiable use elements are not supported for bulk operations. - -```c -void soci_prepare(statement_handle st, char const * query); -int soci_execute(statement_handle st, int withDataExchange); -int soci_fetch(statement_handle st); -int soci_got_data(statement_handle st); -``` - -The functions above provide the core execution functionality for the statement object and their meaning is equivalent to the respective functions in the core C++ interface described above. diff --git a/src/soci/docs/backends/db2.md b/src/soci/docs/backends/db2.md deleted file mode 100644 index e1aef851b6..0000000000 --- a/src/soci/docs/backends/db2.md +++ /dev/null @@ -1,93 +0,0 @@ -# DB2 Backend Reference - -SOCI backend for accessing IBM DB2 database. - -## Prerequisites - -### Supported Versions - -See [Tested Platforms](#tested-platforms). - -### Tested Platforms - -|DB2 |OS|Compiler| -|--- |--- |--- | -|-|Linux PPC64|GCC| -|9.1|Linux|GCC| -|9.5|Linux|GCC| -|9.7|Linux|GCC| -|10.1|Linux|GCC| -|10.1|Windows 8|Visual Studio 2012| - -### Required Client Libraries - -The SOCI DB2 backend requires client library from the [IBM Data Server Driver Package (DS Driver)](https://www-01.ibm.com/support/docview.wss?uid=swg21385217). - -## Connecting to the Database - -On Unix, before using the DB2 backend please make sure, that you have sourced DB2 profile into your environment: - -```console -. ~/db2inst1/sqllib/db2profile -``` - -To establish a connection to the DB2 database, create a session object using the DB2 -backend factory together with the database file name: - -```cpp -soci::session sql(soci::db2, "your DB2 connection string here"); -``` - -## SOCI Feature Support - -### Dynamic Binding - -TODO - -### Bulk Operations - -Supported, but with caution as it hasn't been extensively tested. - -### Transactions - -Currently, not supported. - -### BLOB Data Type - -Currently, not supported. - -### Nested Statements - -Nesting statements are not processed by SOCI in any special way and they work as implemented -by the DB2 database. - -### Stored Procedures - -Stored procedures are supported, with `CALL` statement. - -## Native API Access - -TODO - -## Backend-specific extensions - -None. - -## Configuration options - -This backend supports `db2_option_driver_complete` option which can be passed to it via -`connection_parameters` class. The value of this option is passed to `SQLDriverConnect()` -function as "driver completion" parameter and so must be one of `SQL_DRIVER_XXX` values, -in the string form. The default value of this option is `SQL_DRIVER_PROMPT` meaning -that the driver will query the user for the user name and/or the password if they are -not stored together with the connection. If this is undesirable for some reason, -you can use `SQL_DRIVER_NOPROMPT` value for this option to suppress showing the message box: - -```cpp -connection_parameters parameters("db2", "DSN=sample"); -parameters.set_option(db2_option_driver_complete, "0" /* SQL_DRIVER_NOPROMPT */); -session sql(parameters); -``` - -Note, `db2_option_driver_complete` controls driver completion specific to the IBM DB2 driver -for ODBC and CLI. diff --git a/src/soci/docs/backends/firebird.md b/src/soci/docs/backends/firebird.md deleted file mode 100644 index 30275a7b20..0000000000 --- a/src/soci/docs/backends/firebird.md +++ /dev/null @@ -1,154 +0,0 @@ -# Firebird Backend Reference - -SOCI backend for accessing Firebird database. - -## Prerequisites - -### Supported Versions - -The SOCI Firebird backend supports versions of Firebird from 1.5 to 2.5 and can be used with -either the client-server or embedded Firebird libraries. -The former is the default, to select the latter set `SOCI_FIREBIRD_EMBEDDED` CMake option to `ON` -value when building. - -### Tested Platforms - -|Firebird |OS|Compiler| -|--- |--- |--- | -|1.5.2.4731|SunOS 5.10|g++ 3.4.3| -|1.5.2.4731|Windows XP|Visual C++ 8.0| -|1.5.3.4870|Windows XP|Visual C++ 8.0 Professional| -|2.5.2.26540|Debian GNU/Linux 7|g++ 4.7.2| - -### Required Client Libraries - -The Firebird backend requires Firebird's `libfbclient` client library. -For example, on Ubuntu Linux, for example, `firebird-dev` package and its dependencies are required. - -## Connecting to the Database - -To establish a connection to a Firebird database, create a Session object using the firebird -backend factory together with a connection string: - -```cpp -BackEndFactory const &backEnd = firebird; -session sql(backEnd, "service=/usr/local/firbird/db/test.fdb user=SYSDBA password=masterkey"); -``` - -or simply: - -```cpp -session sql(firebird, "service=/usr/local/firbird/db/test.fdb user=SYSDBA password=masterkey"); -``` - -The set of parameters used in the connection string for Firebird is: - -* service -* user -* password -* role -* charset - -The following parameters have to be provided as part of the connection string : *service*, *user*, -*password*. Role and charset parameters are optional. - -Once you have created a `session` object as shown above, you can use it to access the database, for example: - -```cpp -int count; -sql << "select count(*) from user_tables", into(count); -``` - -(See the [SOCI basics](../basics.html) and [exchanging data](../exchange.html) documentation -for general information on using the `session` class.) - -## SOCI Feature Support - -### Dynamic Binding - -The Firebird backend supports the use of the SOCI `row` class, which facilitates retrieval of data whose -type is not known at compile time. - -When calling `row::get()`, the type you should pass as T depends upon the underlying database type. -For the Firebird backend, this type mapping is: - -|Firebird Data Type|SOCI Data Type|`row::get` specializations| -|--- |--- |--- | -|numeric, decimal (where scale > 0)|eDouble|double| -|numeric, decimal [^1] (where scale = 0)|eInteger, eDouble|int, double| -|double precision, float|eDouble|double| -|smallint, integer|eInteger|int| -|char, varchar|eString|std::string| -|date, time, timestamp|eDate|std::tm| - -[^1] There is also 64bit integer type for larger values which is -currently not supported. - -(See the [dynamic resultset binding](../exchange.html#dynamic) documentation for general information -on using the `Row` class.) - -### Binding by Name - -In addition to [binding by position](../exchange.html#bind_position), the Firebird backend supports -[binding by name](../exchange.html#bind_name), via an overload of the `use()` function: - - int id = 7; - sql << "select name from person where id = :id", use(id, "id") - -It should be noted that parameter binding by name is supported only by means of emulation, -since the underlying API used by the backend doesn't provide this feature. - -### Bulk Operations - -The Firebird backend has full support for SOCI [bulk operations](../statements.html#bulk) interface. -This feature is also supported by emulation. - -### Transactions - -[Transactions](../statements.html#transactions) are also fully supported by the Firebird backend. -In fact, an implicit transaction is always started when using this backend if one hadn't been -started by explicitly calling `begin()` before. The current transaction is automatically -committed in `session` destructor. - -### BLOB Data Type - -The Firebird backend supports working with data stored in columns of type Blob, -via SOCI `[BLOB](../exchange.html#blob)` class. - -It should by noted, that entire Blob data is fetched from database to allow random read and write access. -This is because Firebird itself allows only writing to a new Blob or reading from existing one - -modifications of existing Blob means creating a new one. -Firebird backend hides those details from user. - -### RowID Data Type - -This feature is not supported by Firebird backend. - -### Nested Statements - -This feature is not supported by Firebird backend. - -### Stored Procedures - -Firebird stored procedures can be executed by using SOCI [Procedure](../statements.html#procedures) class. - -## Native API Access - -SOCI provides access to underlying datbabase APIs via several getBackEnd() functions, -as described in the [beyond SOCI](../beyond.html) documentation. - -The Firebird backend provides the following concrete classes for navite API access: - -|Accessor Function|Concrete Class| -|--- |--- | -|SessionBackEnd* Session::getBackEnd()|FirebirdSessionBackEnd| -|StatementBackEnd* Statement::getBackEnd()|FirebirdStatementBackEnd| -|BLOBBackEnd* BLOB::getBackEnd()|FirebirdBLOBBackEnd| -|RowIDBackEnd* RowID::getBackEnd()| - -## Backend-specific extensions - -### FirebirdSOCIError - -The Firebird backend can throw instances of class `FirebirdSOCIError`, which is publicly derived -from `SOCIError` and has an additional public `status_` member containing the Firebird status vector. diff --git a/src/soci/docs/backends/index.md b/src/soci/docs/backends/index.md deleted file mode 100644 index 84158b6a15..0000000000 --- a/src/soci/docs/backends/index.md +++ /dev/null @@ -1,14 +0,0 @@ -# Supported Backends and Features - -Follow the links to learn more about each backend and detailed supported features. - -|Oracle|PostgreSQL|MySQL|SQLite3|Firebird|ODBC|DB2| -|--- |--- |--- |--- |--- |--- |--- | -|Binding by Name|YES|YES (>=8.0)|YES|YES|YES|YES|YES| -|Dynamic Binding|YES|YES|YES|YES|YES|YES| -|Bulk Operations|YES|YES|YES|YES|YES|YES|YES| -|Transactions|YES|YES|YES (>=4.0)|YES|YES|YES|YES| -|BLOB Data Type|YES|YES|YES (mapped to `std::string`)|YES|YES|NO|NO| -|RowID Data Type|YES|YES|NO|NO|NO|NO|NO| -|Nested Statements|YES|NO|NO|NO|NO|NO|YES| -|Stored Procedures|YES|YES|NO (but stored functions, YES)|NO|YES|NO|YES| diff --git a/src/soci/docs/backends/mysql.md b/src/soci/docs/backends/mysql.md deleted file mode 100644 index 33df4e82f8..0000000000 --- a/src/soci/docs/backends/mysql.md +++ /dev/null @@ -1,130 +0,0 @@ -# MySQL Backend Reference - -SOCI backend for accessing MySQL database. - -## Prerequisites - -### Supported Versions - -The SOCI MySQL backend should in principle work with every version of MySQL 5.x. -Some of the features (transactions, stored functions) are not available when MySQL server doesn't support them. - -### Tested Platforms - -|MySQL|OS|Compiler| -|--- |--- |--- | -|8.0.1|Windows 10|Visual Studio 2017 (15.3.3)| -|5.5.28|OS X 10.8.2|Apple LLVM version 4.2 (clang-425.0.24)| -|5.0.96|Ubuntu 8.04.4 LTS (Hardy Heron)|g++ (GCC) 4.2.4 (Ubuntu 4.2.4-1ubuntu4)| - -### Required Client Libraries - -The SOCI MySQL backend requires MySQL's `libmysqlclient` client library from the [MySQL Connector/C](https://dev.mysql.com/downloads/connector/c/). - -Note that the SOCI library itself depends also on `libdl`, so the minimum set of libraries needed to compile a basic client program is: - - -lsoci_core -lsoci_mysql -ldl -lmysqlclient - -## Connecting to the Database - -To establish a connection to a MySQL server, create a `session` object using the `mysql` backend factory together with a connection string: - - session sql(mysql, "db=test user=root password='Ala ma kota'"); - - // or: - session sql("mysql", "db=test user=root password='Ala ma kota'"); - - // or: - session sql("mysql://db=test user=root password='Ala ma kota'"); - -The set of parameters used in the connection string for MySQL is: - -* `dbname` or `db` or `service` (required) -* `user` -* `password` or `pass` -* `host` -* `port` -* `unix_socket` -* `sslca` -* `sslcert` -* `local_infile` - should be `0` or `1`, `1` means `MYSQL_OPT_LOCAL_INFILE` will be set. -* `charset` - -Once you have created a `session` object as shown above, you can use it to access the database, for example: - - int count; - sql << "select count(*) from invoices", into(count); - -(See the [SOCI basics]("../basics.html) and [exchanging data](../exchange.html) documentation for general information on using the `session` class.) - -## SOCI Feature Support - -### Dynamic Binding - -The MySQL backend supports the use of the SOCI `row` class, which facilitates retrieval of data which type is not known at compile time. - -When calling `row::get<T>()`, the type you should pass as `T` depends upon the underlying database type. -For the MySQL backend, this type mapping is: - -|MySQL Data Type|SOCI Data Type|`row::get` specializations| -|--- |--- |--- | -|FLOAT, DOUBLE, DECIMAL and synonyms|dt_double|double| -|TINYINT, TINYINT UNSIGNED, SMALLINT, SMALLINT UNSIGNED, INT|dt_integer|int| -|INT UNSIGNED|dt_long_long|long long or unsigned| -|BIGINT|dt_long_long|long long| -|BIGINT UNSIGNED|dt_unsigned_long_long|unsigned long long| -|CHAR, VARCHAR, BINARY, VARBINARY, TINYBLOB, MEDIUMBLOB, BLOB,LONGBLOB, TINYTEXT, MEDIUMTEXT, TEXT, LONGTEXT, ENUM|dt_string|std::string| -|TIMESTAMP (works only with MySQL >= 5.0), DATE, TIME, DATETIME|dt_date|std::tm| - -(See the [dynamic resultset binding](../exchange.html#dynamic) documentation for general information on using the `Row` class.) - -### Binding by Name - -In addition to [binding by position](../exchange.html#bind_position), the MySQL backend supports -[binding by name](../exchange.html#bind_name), via an overload of the `use()` function: - - int id = 7; - sql << "select name from person where id = :id", use(id, "id") - -It should be noted that parameter binding of any kind is supported only by means of emulation, since the underlying API used by the backend doesn't provide this feature. - -### Bulk Operations - -[Transactions](../statements.html#transactions) are also supported by the MySQL backend. Please note, however, that transactions can only be used when the MySQL server supports them (it depends on options used during the compilation of the server; typically, but not always, servers >=4.0 support transactions and earlier versions do not) and only with appropriate table types. - -### BLOB Data Type - -SOCI `blob` interface is not supported by the MySQL backend. - -Note that this does not mean you cannot use MySQL's `BLOB` types. They can be selected using the usual SQL syntax and read into `std::string` on the C++ side, so no special interface is required. - -### RowID Data Type - -The `rowid` functionality is not supported by the MySQL backend. - -### Nested Statements - -Nested statements are not supported by the MySQL backend. - -### Stored Procedures - -MySQL version 5.0 and later supports two kinds of stored routines: stored procedures and stored functions (for details, please consult the [procedure MySQL documentation](http://dev.mysql.com/doc/refman/5.0/en/stored-procedures.html)). Stored functions can be executed by using SOCI's [procedure class](../statements.html#procedures). There is currently no support for stored procedures. - -## Native API Access - -SOCI provides access to underlying datbabase APIs via several `get_backend()` functions, as described in the [Beyond SOCI](../beyond.html) documentation. - -The MySQL backend provides the following concrete classes for native API access: - -|Accessor Function|Concrete Class| -|--- |--- | -|session_backend * session::get_backend()|mysql_session_backend| -|statement_backend * statement::get_backend()|mysql_statement_backend| - -## Backend-specific extensions - -None. - -## Configuration options - -None. diff --git a/src/soci/docs/backends/odbc.md b/src/soci/docs/backends/odbc.md deleted file mode 100644 index 013940512a..0000000000 --- a/src/soci/docs/backends/odbc.md +++ /dev/null @@ -1,173 +0,0 @@ -# ODBC Backend Reference - -SOCI backend for accessing variety of databases via ODBC API. - -## Prerequisites - -### Supported Versions - -The SOCI ODBC backend is supported for use with ODBC 3. - -### Tested Platforms - -|ODBC|OS|Compiler| -|--- |--- |--- | -|3|Linux (Ubuntu 12.04)|g++ 4.6.3| -|3|Linux (Ubuntu 12.04)|clang 3.2| -|3.8|Windows 8|Visual Studio 2012| -|3|Windows 7|Visual Studio 2010| -|3|Windows XP|Visual Studio 2005 (express)| -|3|Windows XP|Visual C++ 8.0 Professional| -|3|Windows XP|g++ 3.3.4 (Cygwin)| - -### Required Client Libraries - -The SOCI ODBC backend requires the ODBC client library. - -## Connecting to the Database - -To establish a connection to the ODBC database, create a Session object using the `ODBC` backend factory together with a connection string: - -```cpp -backend_factory const& backEnd = odbc; -session sql(backEnd, "filedsn=c:\\my.dsn"); -``` - -or simply: - -```cpp -session sql(odbc, "filedsn=c:\\my.dsn"); -``` - -The set of parameters used in the connection string for ODBC is the same as accepted by the [SQLDriverConnect](http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbcsql/od_odbc_d_4x4k.asp) function from the ODBC library. - -Once you have created a `session` object as shown above, you can use it to access the database, for example: - -```cpp -int count; -sql << "select count(*) from invoices", into(count); -``` - -(See the [SOCI basics](../basics.html) and [exchanging data](../exchange.html) documentation for general information on using the `session` class.) - -## SOCI Feature Support - -### Dynamic Binding - -The ODBC backend supports the use of the SOCI `row` class, which facilitates retrieval of data whose type is not known at compile time. - -When calling `row::get()`, the type you should pass as T depends upon the underlying database type. -For the ODBC backend, this type mapping is: - -|ODBC Data Type|SOCI Data Type|`row::get` specializations| -|--- |--- |--- | -|SQL_DOUBLE, SQL_DECIMAL, SQL_REAL, SQL_FLOAT, SQL_NUMERIC|dt_double|double| -|SQL_TINYINT, SQL_SMALLINT, SQL_INTEGER, SQL_BIGINT|dt_integer|int| -|SQL_CHAR, SQL_VARCHAR|dt_string|std::string| -|SQL_TYPE_DATE, SQL_TYPE_TIME, SQL_TYPE_TIMESTAMP|dt_date|std::tm| - -Not all ODBC drivers support all datatypes. - -(See the [dynamic resultset binding](../exchange.html#dynamic) documentation for general information on using the `row` class.) - -### Binding by Name - -In addition to [binding by position](../exchange.html#bind_position), the ODBC backend supports [binding by name](../exchange.html#bind_name), via an overload of the `use()` function: - -```cpp -int id = 7; -sql << "select name from person where id = :id", use(id, "id") -``` - -Apart from the portable "colon-name" syntax above, which is achieved by rewriting the query string, the backend also supports the ODBC ? syntax: - -```cpp -int i = 7; -int j = 8; -sql << "insert into t(x, y) values(?, ?)", use(i), use(j); -``` - -### Bulk Operations - -The ODBC backend has support for SOCI's [bulk operations](../statements.html#bulk) interface. Not all ODBC drivers support bulk operations, the following is a list of some tested backends: - -|ODBC Driver|Bulk Read|Bulk Insert| -|--- |--- |--- | -|MS SQL Server 2005|YES|YES| -|MS Access 2003|YES|NO| -|PostgresQL 8.1|YES|YES| -|MySQL 4.1|NO|NO| - -### Transactions - -[Transactions](../statements.html#transactions) are also fully supported by the ODBC backend, provided that they are supported by the underlying database. - -### BLOB Data Type - -Not currently supported. - -### RowID Data Type - -Not currently supported. - -### Nested Statements - -Not currently supported. - -### Stored Procedures - -Not currently supported. - -## Native API Access - -SOCI provides access to underlying datbabase APIs via several getBackEnd() functions, as described in the [beyond SOCI](../beyond.html) documentation. - -The ODBC backend provides the following concrete classes for navite API access: - -|Accessor Function|Concrete Class| -|--- |--- | -|session_backend* session::get_backend()|odbc_statement_backend| -|statement_backend* statement::get_backend()|odbc_statement_backend| -|rowid_backend* rowid::get_backend()|odbc_rowid_backend| - -## Backend-specific extensions - -### odbc_soci_error - -The ODBC backend can throw instances of class `odbc_soci_error`, which is publicly derived from `soci_error` and has additional public members containing the ODBC error code, the Native database error code, and the message returned from ODBC: - -```cpp -int main() -{ - try - { - // regular code - } - catch (soci::odbc_soci_error const& e) - { - cerr << "ODBC Error Code: " << e.odbc_error_code() << endl - << "Native Error Code: " << e.native_error_code() << endl - << "SOCI Message: " << e.what() << std::endl - << "ODBC Message: " << e.odbc_error_message() << endl; - } - catch (exception const &e) - { - cerr << "Some other error: " << e.what() << endl; - } -} -``` - -### get_connection_string() - -The `odbc_session_backend` class provides `std::string get_connection_string() const` method -that returns fully expanded connection string as returned by the `SQLDriverConnect` function. - -## Configuration options - -This backend supports `odbc_option_driver_complete` option which can be passed to it via `connection_parameters` class. The value of this option is passed to `SQLDriverConnect()` function as "driver completion" parameter and so must be one of `SQL_DRIVER_XXX` values, in the string form. The default value of this option is `SQL_DRIVER_PROMPT` meaning that the driver will query the user for the user name and/or the password if they are not stored together with the connection. If this is undesirable for some reason, you can use `SQL_DRIVER_NOPROMPT` value for this option to suppress showing the message box: - -```cpp -connection_parameters parameters("odbc", "DSN=mydb"); -parameters.set_option(odbc_option_driver_complete, "0" /* SQL_DRIVER_NOPROMPT */); -session sql(parameters); -``` diff --git a/src/soci/docs/backends/oracle.md b/src/soci/docs/backends/oracle.md deleted file mode 100644 index 3db6be01d9..0000000000 --- a/src/soci/docs/backends/oracle.md +++ /dev/null @@ -1,171 +0,0 @@ -# Oracle Backend Reference - -SOCI backend for accessing Oracle database. - -## Prerequisites - -### Supported Versions - -The SOCI Oracle backend is currently supported for use with Oracle 10 or later. -Older versions of Oracle may work as well, but they have not been tested by the SOCI team. - -### Tested Platforms - -|Oracle|OS|Compiler| -|--- |--- |--- | -|10.2.0 (XE)|RedHat 5|g++ 4.3| -|11.2.0 (XE)|Ubuntu 12.04|g++ 4.6.3| - -### Required Client Libraries - -The SOCI Oracle backend requires Oracle's `libclntsh` client library. Depending on the particular system, the `libnnz10` library might be needed as well. - -Note that the SOCI library itself depends also on `libdl`, so the minimum set of libraries needed to compile a basic client program is: - -```console --lsoci_core -lsoci_oracle -ldl -lclntsh -lnnz10 -``` - -### Connecting to the Database - -To establish a connection to an Oracle database, create a `session` object using the oracle backend factory together with a connection string: - -```cpp -session sql(oracle, "service=orcl user=scott password=tiger"); - -// or: -session sql("oracle", "service=orcl user=scott password=tiger"); - -// or: -session sql("oracle://service=orcl user=scott password=tiger"); - -// or: -session sql(oracle, "service=//your_host:1521/your_sid user=scott password=tiger"); -``` - -The set of parameters used in the connection string for Oracle is: - -* `service` -* `user` -* `password` -* `mode` (optional; valid values are `sysdba`, `sysoper` and `default`) -* `charset` and `ncharset` (optional; valid values are `utf8`, `utf16`, `we8mswin1252` and `win1252`) - -If both `user` and `password` are provided, the session will authenticate using the database credentials, whereas if none of them is set, then external Oracle credentials will be used - this allows integration with so called Oracle wallet authentication. - -Once you have created a `session` object as shown above, you can use it to access the database, for example: - -```cpp -int count; -sql << "select count(*) from user_tables", into(count); -``` - -(See the [SOCI basics](../basics.html) and [exchanging data](../exchange.html) documentation for general information on using the `session` class.)# - -## SOCI Feature Support - -### Dynamic Binding - -The Oracle backend supports the use of the SOCI `row` class, which facilitates retrieval of data which type is not known at compile time. - -When calling `row::get()`, the type you should pass as `T` depends upon the nderlying database type. For the Oracle backend, this type mapping is: - -|Oracle Data Type|SOCI Data Type|`row::get` specializations| -|--- |--- |--- | -|number (where scale > 0)|dt_double|double| -|number(where scale = 0 and precision ≤ `std::numeric_limits::digits10`)|dt_integer|int| -|number|dt_long_long|long long| -|char, varchar, varchar2|dt_string|std::string| -|date|dt_date|std::tm| - -(See the [dynamic resultset binding](../exchange.html#dynamic) documentation for general information on using the `row` class.) - -### Binding by Name - -In addition to [binding by position](../exchange.html#bind_position), the Oracle backend supports [binding by name](../exchange.html#bind_name), via an overload of the `use()` function: - -```cpp -int id = 7; -sql << "select name from person where id = :id", use(id, "id") -``` - -SOCI's use of ':' to indicate a value to be bound within a SQL string is consistant with the underlying Oracle client library syntax. - -### Bulk Operations - -The Oracle backend has full support for SOCI's [bulk operations](../statements.html#bulk) interface. - -### Transactions - -[Transactions](../statements.html#transactions) are also fully supported by the Oracle backend, -although transactions with non-default isolation levels have to be managed by explicit SQL statements. - -### blob Data Type - -The Oracle backend supports working with data stored in columns of type Blob, via SOCI's [blob](../exchange.html#blob) class. - -### rowid Data Type - -Oracle rowid's are accessible via SOCI's [rowid](../reference.html#rowid) class. - -### Nested Statements - -The Oracle backend supports selecting into objects of type `statement`, so that you may work with nested sql statements and PL/SQL cursors: - -```cpp -statement stInner(sql); -statement stOuter = (sql.prepare << - "select cursor(select name from person order by id)" - " from person where id = 1", - into(stInner)); -stInner.exchange(into(name)); -stOuter.execute(); -stOuter.fetch(); - -while (stInner.fetch()) -{ - std::cout << name << '\n'; -} -``` - -### Stored Procedures - -Oracle stored procedures can be executed by using SOCI's [procedure](../statements.html#procedures) class. - -## Native API Access - -SOCI provides access to underlying datbabase APIs via several `get_backend()` functions, as described in the [Beyond SOCI](../beyond.html) documentation. - -The Oracle backend provides the following concrete classes for navite API access: - -|Accessor Function|Concrete Class| -|--- |--- | -|session_backend * session::get_backend()|oracle_session_backend| -|statement_backend * statement::get_backend()|oracle_statement_backend| -|blob_backend * blob::get_backend()|oracle_blob_backend| -|rowid_backend * rowid::get_backend()|oracle_rowid_backend| - -## Backend-specific extensions - -### oracle_soci_error - -The Oracle backend can throw instances of class `oracle_soci_error`, which is publicly derived from `soci_error` and has an additional public `err_num_` member containing the Oracle error code: - -```cpp -int main() -{ - try - { - // regular code - } - catch (oracle_soci_error const & e) - { - cerr << "Oracle error: " << e.err_num_ - << " " << e.what() << endl; - } - catch (exception const &e) - { - cerr << "Some other error: "<< e.what() << endl; - } -} -``` diff --git a/src/soci/docs/backends/postgresql.md b/src/soci/docs/backends/postgresql.md deleted file mode 100644 index 998f30b920..0000000000 --- a/src/soci/docs/backends/postgresql.md +++ /dev/null @@ -1,171 +0,0 @@ -# PostgreSQL Backend Reference - -SOCI backend for accessing PostgreSQL database. - -## Prerequisites - -### Supported Versions - -The SOCI PostgreSQL backend is supported for use with PostgreSQL >= 7.3, although versions older than 8.0 will suffer from limited feature support. See below for details. - -### Tested Platforms - -|PostgreSQL|OS|Compiler| -|--- |--- |--- | -|9.6|Windows Server 2016|MSVC++ 14.1| -|9.4|Windows Server 2012 R2|MSVC++ 14.0| -|9.4|Windows Server 2012 R2|MSVC++ 12.0| -|9.4|Windows Server 2012 R2|MSVC++ 11.0| -|9.4|Windows Server 2012 R2|Mingw-w64/GCC 4.8| -|9.3|Ubuntu 12.04|g++ 4.6.3| -|9.0|Mac OS X 10.6.6|g++ 4.2| -|8.4|FreeBSD 8.2|g++ 4.1| -|8.4|Debian 6|g++ 4.3| -|8.4|RedHat 5|g++ 4.3| - -### Required Client Libraries - -The SOCI PostgreSQL backend requires PostgreSQL's `libpq` client library. - -Note that the SOCI library itself depends also on `libdl`, so the minimum set of libraries needed to compile a basic client program is: - -```console --lsoci_core -lsoci_postgresql -ldl -lpq -``` - -### Connecting to the Database - -To establish a connection to the PostgreSQL database, create a `session` object using the `postgresql` backend factory together with a connection string: - -```cpp -session sql(postgresql, "dbname=mydatabase"); - -// or: -session sql("postgresql", "dbname=mydatabase"); - -// or: -session sql("postgresql://dbname=mydatabase"); -``` - -The set of parameters used in the connection string for PostgreSQL is the same as accepted by the `[PQconnectdb](http://www.postgresql.org/docs/8.3/interactive/libpq.html#LIBPQ-CONNECT)` function from the `libpq` library. - -In addition to standard PostgreSQL connection parameters, the following can be set: - -* `singlerow` or `singlerows` - -For example: - -```cpp -session sql(postgresql, "dbname=mydatabase singlerows=true"); -``` - -If the `singlerows` parameter is set to `true` or `yes`, then queries will be executed in the single-row mode, which prevents the client library from loading full query result set into memory and instead fetches rows one by one, as they are requested by the statement's fetch() function. This mode can be of interest to those users who want to make their client applications more responsive (with more fine-grained operation) by avoiding potentially long blocking times when complete query results are loaded to client's memory. -Note that in the single-row operation: - -* bulk queries are not supported, and -* in order to fulfill the expectations of the underlying client library, the complete rowset has to be exhausted before executing further queries on the same session. - -Also please note that single rows mode requires PostgreSQL 9 or later, both at -compile- and run-time. If you need to support earlier versions of PostgreSQL, -you can define `SOCI_POSTGRESQL_NOSINLGEROWMODE` when building the library to -disable it. - -Once you have created a `session` object as shown above, you can use it to access the database, for example: - -```cpp -int count; -sql << "select count(*) from invoices", into(count); -``` - -(See the [exchanging data](../basics.html">SOCI basics and = 3.1 - -### Tested Platforms - -|SQLite3|OS|Compiler| -|--- |--- |--- | -|3.12.1|Windows Server 2016|MSVC++ 14.1| -|3.12.1|Windows Server 2012 R2|MSVC++ 14.0| -|3.12.1|Windows Server 2012 R2|MSVC++ 12.0| -|3.12.1|Windows Server 2012 R2|MSVC++ 11.0| -|3.12.1|Windows Server 2012 R2|Mingw-w64/GCC 4.8| -|3.7.9|Ubuntu 12.04|g++ 4.6.3| -|3.4.0|Windows XP|(cygwin) g++ 3.4.4| -|3.4.0|Windows XP|Visual C++ 2005 Express Edition| -|3.3.8|Windows XP|Visual C++ 2005 Professional| -|3.5.2|Mac OS X 10.5|g++ 4.0.1| -|3.3.4|Ubuntu 5.1|g++ 4.0.2| -|3.3.4|Windows XP|(cygwin) g++ 3.3.4| -|3.3.4|Windows XP|Visual C++ 2005 Express Edition| -|3.2.1|Linux i686 2.6.10-gentoo-r6|g++ 3.4.5| -|3.1.3|Mac OS X 10.4|g++ 4.0.1| - -### Required Client Libraries - -The SOCI SQLite3 backend requires SQLite3's `libsqlite3` client library. - -### Connecting to the Database - -To establish a connection to the SQLite3 database, create a Session object using the `SQLite3` backend factory together with the database file name: - -```cpp -session sql(sqlite3, "database_filename"); - -// or: - -session sql("sqlite3", "db=db.sqlite timeout=2 shared_cache=true"); -``` - -The set of parameters used in the connection string for SQLite is: - -* `dbname` or `db` -* `timeout` - set sqlite busy timeout (in seconds) ([link](http://www.sqlite.org/c3ref/busy_timeout.html) -* `synchronous` - set the pragma synchronous flag ([link](http://www.sqlite.org/pragma.html#pragma_synchronous)) -* `shared_cache` - should be `true` ([link](http://www.sqlite.org/c3ref/enable_shared_cache.html)) - -Once you have created a `session` object as shown above, you can use it to access the database, for example: - -```cpp -int count; -sql << "select count(*) from invoices", into(count); -``` - -(See the [SOCI basics](../basics.html) and [exchanging data](../exchange.html) documentation for general information on using the `session` class.) - -## SOCI Feature Support - -### Dynamic Binding - -The SQLite3 backend supports the use of the SOCI `row` class, which facilitates retrieval of data whose type is not known at compile time. - -When calling `row::get()`, the type you should pass as T depends upon the underlying database type. - -For the SQLite3 backend, this type mapping is complicated by the fact the SQLite3 does not enforce [types][INTEGER_PRIMARY_KEY] and makes no attempt to validate the type names used in table creation or alteration statements. SQLite3 will return the type as a string, SOCI will recognize the following strings and match them the corresponding SOCI types: - -|SQLite3 Data Type|SOCI Data Type|`row::get` specializations| -|--- |--- |--- | -|*float*, *double*|dt_double|double| -|*int8*, *bigint*|dt_long_long|long long| -|*unsigned big int*|dt_unsigned_long_long|unsigned long long| -|*int*, *boolean*|dt_integer|int| -|*text, *char*|dt_string|std::string| -|*date*, *time*|dt_date|std::tm| - -[INTEGER_PRIMARY_KEY] : There is one case where SQLite3 enforces type. If a column is declared as "integer primary key", then SQLite3 uses that as an alias to the internal ROWID column that exists for every table. Only integers are allowed in this column. - -(See the [dynamic resultset binding](../exchange.html#dynamic) documentation for general information on using the `row` class.) - -### Binding by Name - -In addition to [binding by position](../exchange.html#bind_position), the SQLite3 backend supports [binding by name](../exchange.html#bind_name), via an overload of the `use()` function: - -```cpp -int id = 7; -sql << "select name from person where id = :id", use(id, "id") -``` - -The backend also supports the SQLite3 native numbered syntax, "one or more literals can be replace by a parameter "?" or ":AAA" or "@AAA" or "$VVV" where AAA is an alphanumeric identifier and VVV is a variable name according to the syntax rules of the TCL programming language." [[1]](http://www.sqlite.org/capi3ref.html#sqlite3_bind_int): - -```cpp -int i = 7; -int j = 8; -sql << "insert into t(x, y) values(?, ?)", use(i), use(j); -``` - -### Bulk Operations - -The SQLite3 backend has full support for SOCI's [bulk operations](../statements.html#bulk) interface. However, this support is emulated and is not native. - -### Transactions - -[Transactions](../statements.html#transactions) are also fully supported by the SQLite3 backend. - -### BLOB Data Type - -The SQLite3 backend supports working with data stored in columns of type Blob, via SOCI's blob class. Because of SQLite3 general typelessness the column does not have to be declared any particular type. - -### RowID Data Type - -In SQLite3 RowID is an integer. "Each entry in an SQLite table has a unique integer key called the "rowid". The rowid is always available as an undeclared column named ROWID, OID, or _ROWID_. If the table has a column of type INTEGER PRIMARY KEY then that column is another an alias for the rowid."[[2]](http://www.sqlite.org/capi3ref.html#sqlite3_last_insert_rowid) - -### Nested Statements - -Nested statements are not supported by SQLite3 backend. - -### Stored Procedures - -Stored procedures are not supported by SQLite3 backend - -## Native API Access - -SOCI provides access to underlying datbabase APIs via several `get_backend()` functions, as described in the [beyond SOCI](../beyond.html) documentation. - -The SQLite3 backend provides the following concrete classes for navite API access: - -|Accessor Function|Concrete Class| -|--- |--- | -|session_backend* session::get_backend()|sqlie3_session_backend| -|statement_backend* statement::get_backend()|sqlite3_statement_backend| -|rowid_backend* rowid::get_backend()|sqlite3_rowid_backend| - -## Backend-specific extensions - -### SQLite3 result code support - -SQLite3 result code is provided via the backend specific `sqlite3_soci_error` class. Catching the backend specific error yields the value of SQLite3 result code via the `result()` method. - -## Configuration options - -None diff --git a/src/soci/docs/beyond.md b/src/soci/docs/beyond.md deleted file mode 100644 index 6a74defa66..0000000000 --- a/src/soci/docs/beyond.md +++ /dev/null @@ -1,89 +0,0 @@ -# Beyond standard SQL - -Sometimes the standard SQL is not enough and database-specific syntax needs to be used. -When possible and practical, SOCI provides wrappers hiding the differences between the backends and this section describes these wrappers. -And, if this is still not enough, you can use the backend-specific methods directly as described below. - -## Affected rows - -It can be useful to know how many rows were affected by the last SQL statement, most often when using `INSERT`, `UPDATE` or `DELETE`. -SOCI provides `statement::get_affected_rows()` method allowing to do this: - -```cpp -statement st = (sql.prepare << "update some_table ..."); -st.execute(true); - -if ( !st.get_affected_rows() ) -{ - ... investigate why no rows were modified ... -} -``` - -### Portability note - -This method behaviour in case of partially executed update, i.e. when some records were updated or inserted while some other have failed to be updated or inserted, depends on the exact backend and, in the case of ODBC backend, on the exact ODBC driver used. -It can return `-1`, meaning that the number of rows is unknown, the number of rows actually updated or the total number of affected rows. - -## Sequences - -It is common to have auto-incrementing database fields or fields whose value come from a sequence. -In the latter case you need to retrieve the value of the field for a new row before inserting it into the database. -In the former case, this is unnecessary but you may still want to know the value generated by the database, e.g. to use it as a foreign key in another table. -So it would be useful to have a way to obtain the value of such a field. -But, of course, to make life of database programmers more interesting, different products usually support either autoincrement fields or sequences but not both -- and they use different syntaxes for them, too. -SOCI tries to help to deal with this unfortunate situation by providing two functions: `session::get_next_sequence_value()` and `session::get_last_insert_id`. - -If you know which kind of database you use, you may use only one of them: when working with sequences, the first one allows to generate the next value in a sequence and when working with autoincrement fields, the second one retrieves the last value generated for such a field for the given table. - -However if you use multiple SOCI backends or even just a single ODBC backend but support connecting to databases of different types, you actually must use both of them in the following way to insert a row: - -```cpp -long id; -statement st; -if ( sql.get_next_sequence_value("table_sequence", id) ) -{ - st << "insert into table(id, f1, f2) values(:id, :f1, :f2)", - use(id), use(f1), use(f2); -} -else -{ - // We're not using sequences, so don't specify the value, - // it will be automatically generated by the database on insert. - st << "insert into table(f1, f2) value(:f1, :f2)", - use(f1), use(f2); - - // If the ID used for the above row is needed later, get it: - if ( !sql.get_last_insert_id("table", id) ) - ... unexpected error, handle appropriately ... -} -``` - -### Portability note - -These methods are currently only implemented in Firebird, MySQL, ODBC, PostgreSQL and SQLite3 backends. - -## Beyond SOCI API - -As the original name of the library (Simple Oracle Call Interface) clearly stated, SOCI is intended to be a *simple* library, targeting the majority of needs in regular C++ application. -We do not claim that *everything* can be done with SOCI and it was never the intent of the library. -What is important, though, is that the simplicity of the -library does *not* prevent the client applications from reaching into the low-level specifics of each database backend in order to achieve special configuration or performance goals. - -Most of the SOCI classes have the `getBackEnd` method, which returns the pointer to the actual backend object that implements the given functionality. -The knowledge of the actual backend allows the client application to get access to all low-level details that are involved. - -```cpp -blob b(sql); - -oracle_session_back_end * sessionBackEnd = static_cast(sql.get_back_end()); -oracle_blob_back_end * blobBackEnd = static_cast(b.get_back_end()); - -OCILobDisableBuffering(sessionBackEnd->svchp_, sessionBackEnd->errhp_, blobBackEnd->lobp_); -``` - -The above example retrieves the `rowid` ("something" that identifies the row in the table) from the table and uses the `get_back_end` function to extract the actual object that implements this functionality. -Assuming that it is the `"postgresql"` backend which is in use, the downcast is performed to use the `postgresql_rowid_back_end` interface to get the actual OID value that is a physical, low-level implementation of row identifier on PostgreSQL databases. - -In order for any of the above to compile, you have to explicitly `#include` the appropriate backend's header file. - -Please see the header file related to the given backend to learn what low-level handles and descriptors are available. diff --git a/src/soci/docs/binding.md b/src/soci/docs/binding.md deleted file mode 100644 index c3f0db1990..0000000000 --- a/src/soci/docs/binding.md +++ /dev/null @@ -1,184 +0,0 @@ -# Data Binding - -SOCI provides mechanisms to bind local buffers for input and output data. - -**Note:** The Oracle documentation uses two terms: *defining* (for instructing the library where the *output* data should go) and *binding* (for the *input* data and *input/output* PL/SQL parameters). For the sake of simplicity, SOCI uses the term *binding* for both of these. - -## Binding output data (into) - -The `into` expression is used to add binding information to -the statement: - -```cpp -int count; -sql << "select count(*) from person", into(count); - -string name; -sql << "select name from person where id = 7", into(name); -``` - -In the above examples, some data is retrieved from the database and transmitted *into* the given local variable. - -There should be as many `into` elements as there are expected columns in the result (see [dynamic resultset binding](#dynamic") for the exception to this rule). - -## Binding input data (use) - -The `use` expression associates the SQL placeholder (written with colon) with the local data: - -```cpp -int val = 7; -sql << "insert into numbers(val) values(:val)", use(val); -``` - -In the above statement, the first "val" is a column name (assuming that there is appropriate table `numbers` with this column), the second "val" (with colon) is a placeholder and its name is ignored here, and the third "val" is a name of local variable. - -To better understand the meaning of each "val" above, consider also: - -```cpp -int number = 7; -sql << "insert into numbers(val) values(:blabla)", use(number); -``` - -Both examples above will insert the value of some local variable into the table `numbers` - we say that the local variable is *used* in the SQL statement. - -There should be as many `use` elements as there are parameters used in the SQL query. - -### Object lifetime and immutability - -SOCI assumes that local variables provided as `use` elements live at least as long at it takes to execute the whole statement. -In short statement forms like above, the statement is executed *sometime* at the end of the full expression and the whole process is driven by the invisible temporary object handled by the library. -If the data provided by user comes from another temporary variable, it might be possible for the compiler to arrange them in a way that the user data will be destroyed *before* the statement will have its chance to execute, referencing objects that no longer exist: - -```cpp -// Dangerous code! - -string getNameFromSomewhere(); - -sql << "insert into person(name) values(:n)", use(getNameFromSomewhere()); -``` - -In the above example, the data passed to the database comes from the temporary variable that is a result of call to `getNameFromSomewhere` - this should be avoided and named variables should be used to ensure safe lifetime relations: - -```cpp -// Safe code - -string getNameFromSomewhere(); - -string name = getNameFromSomewhere(); -sql << "insert into person(name) values(:n)", use(name); -``` - -It is still possible to provide `const` data for use elements. - -Note that some database servers, like Oracle, allow PL/SQL procedures to modify their in/out parameters - this is detected by the SOCI library and an error is reported if the database attempts to modify the `use` element that holds `const` data. - -The above example can be ultimately written in the following way: - -```cpp -// Safe and efficient code - -string getNameFromSomewhere(); - -string const& name = getNameFromSomewhere(); -sql << "insert into person(name) values(:n)", use(name); -``` - -### Portability note - -Older versions of the PostgreSQL client API do not allow to use input parameters at all. -In order to compile SOCI with those old client libraries, define the `SOCI_POSTGRESQL_NOPARAMS` preprocessor name passing `-DSOCI_POSTGRESQL_NOPARAMS=ON` variable to CMake. - -## Binding by position - -If there is more output or input "holes" in the single statement, it is possible to use many `into` and `use` expressions, separated by commas, where each expression will be responsible for the consecutive "hole" in the statement: - -```cpp -string firstName = "John", lastName = "Smith"; -int personId = 7; - -sql << "insert into person(id, firstname, lastname) values(:id, :fn, :ln)", - use(personId), use(firstName), use(lastName); - -sql << "select firstname, lastname from person where id = :id", - into(firstName), into(lastName), use(personId); -``` - -In the code above, the order of "holes" in the SQL statement and the order of `into` and `use` expression should match. - -## Binding by name - -The SQL placeholders that have their names (with colon) can be bound by name to clearly associate the local variable with the given placeholder. - -This explicit naming allows to use different order of elements: - -```cpp -string firstName = "John", lastName = "Smith"; -int personId = 7; -sql << "insert into person(id, firstname, lastname) values(:id, :fn, :ln)", - use(firstName, "fn"), use(lastName, "ln"), use(personId, "id"); -``` - -or bind the same local data to many "holes" at the same time: - -```cpp -string addr = "..."; -sql << "update person" - " set mainaddress = :addr, contactaddress = :addr" - " where id = 7", - use(addr, "addr"); -``` - -### Portability notes - -The PostgreSQL backend allows to use the "native" PostgreSQL way of naming parameters in the query, which is by numbers like `$1`, `$2`, `$3`, etc. -In fact, the backend *rewrites* the given query to the native form - and this is also one of the very few places where SOCI intrudes into the SQL query. -For portability reasons, it is recommended to use named parameters, as shown in the examples above. - -The query rewriting can be switched off by compiling the backend with the `SOCI_POSTGRESQL_NOBINDBYNAME` name defined (pass `-DSOCI_POSTGRESQL_NOBINDBYNAME=ON` variable to CMake). -Note that in this case it is also necessary to define `SOCI_POSTGRESQL_NOPREPARE` (controlled by CMake variable `-DSOCI_POSTGRESQL_NOPREPARE=ON`), because statement preparation relies on successful query rewriting. - -In practice, both macros will be needed for PostgreSQL server older than 8.0. - -## Bulk operations - -Bulk operations allow the user to bind, as into or use element, whole vectors of objects. -This allows the database backend to optimize access and data transfer and benefit from the fact that `std::vector` stores data in contiguous memory blocks (the actual optimization depends on the backend and the capability of the underlying data base server). - -It is possible to `use` the vector as a data source: - -```cpp -std::vector v; -// ... -sql << "insert into t ...", use(v); -``` - -as well as a destination: - -```cpp -std::vector v; -v.resize(100); -sql << "select ...", into(v); -``` - -In the latter case the initial size of the vector defines the maximum number of data elements that the user is willing to accept and after executing the query the vector will be automatically resized to reflect that actual number of rows that were read and transmitted. -That is, the vector will be automatically shrunk if the amount of data that was available was smaller than requested. - -It is also possible to operate on the chosen sub-range of the vector: - -```cpp -std::vector v; -// ... -std::size_t begin = ...; -std::size_t end = ...; -sql << "insert into t ...", use(v, begin, end); - -// or: - -sql << "select ...", into(v, begin, end); -``` - -Above, only the sub-range of the vector is used for data transfer and in the case of `into` operation, the `end` variable will be automatically adjusted to reflect the amount of data that was actually transmitted, but the vector object as a whole will retain its initial size. - -Bulk operations can also involve indicators, see below. - -Bulk operations support user-defined data types, if they have appropriate conversion routines defined. diff --git a/src/soci/docs/boost.md b/src/soci/docs/boost.md deleted file mode 100644 index d0511e45f0..0000000000 --- a/src/soci/docs/boost.md +++ /dev/null @@ -1,83 +0,0 @@ -# Boost Integration - -The SOCI user code can be easily integrated with the [Boost library](http://www.boost.org/) thanks to the very flexible type conversion facility. - -The integration with Boost types is optional and is *not* enabled by default, which means that SOCI can also be compiled and used without any dependency on Boost. - -In order to enable the support for any of the above types, the user needs to either include one of these headers: - -```cpp -#include -#include -#include -#include -``` - -or to define the `SOCI_USE_BOOST` macro before including the `soci.h` main header file. - -## Boost.Optional - -`boost::optional` provides an alternative way to support the null data condition and as such relieves the user from necessity to handle separate indicator values. - -The `boost::optional` objects can be used everywhere where the regular user provided values are expected. - -Example: - -```cpp -boost::optional name; -sql << "select name from person where id = 7", into(name); - -if (name.is_initialized()) -{ - // OK, the name was retrieved and is not-null - cout << "The name is " << name.get(); -} -else -{ - // the name is null -} -``` - -The `boost::optional` objects are fully supported for both `into` and `use` elements, in both single and vector forms. They can be also used for user-defined data types. - -## Boost.Tuple - -`boost::tuple` allows to work with whole rows of information and in some cases can be more convenient to use than the more dynamically-oriented `row` type. - -```cpp -boost::tuple person; - -sql << "select name, phone, salary from persons where ...", - into(person); -``` - -Tuples are supported for both `into` and `use` elements. -They can be used with `rowset` as well. - -Tuples can be also composed with `boost::optional` - -```cpp -boost::tuple, int> person; - -sql << "select name, phone, salary from persons where ...", - into(person); - -if (person.get<1>().is_initialized()) -{ - // the given person has a phone number -} -else -{ - // this person does not have a phone number -} -``` - -## Boost.Fusion - -The `boost::fusion::vector` types are supported in the same way as tuples. - -**Note:** Support for `boost::fusion::vector` is enabled only if the detected Boost version is at least 1.35. - -## Boost.DateTime - -The `boost::gregorian::date` is provided as a conversion for base type `std::tm` and can be used as a replacement for it. diff --git a/src/soci/docs/connections.md b/src/soci/docs/connections.md deleted file mode 100644 index a1587bab6e..0000000000 --- a/src/soci/docs/connections.md +++ /dev/null @@ -1,162 +0,0 @@ -# Connections - -The `session` class encapsulates the database connection and other backend-related details, which are common to all the statements that will be later executed. It has a couple of overloaded constructors. - -## Using backend factory - -The most basic one expects two parameters: the requested backend factory object and the generic connection string, -which meaning is backend-dependent. - -Example: - -```cpp -session sql(oracle, "service=orcl user=scott password=tiger"); -``` - -Another example might be: - -```cpp -session sql(postgresql, "dbname=mydb"); -``` - -Above, the `sql` object is a local (automatic) object that encapsulates the connection. - -This `session` constructor either connects successfully, or throws an exception. - -### Portability note - -In case of SOCI linked against DLLs on Windows, the factory objects are not exported from the DLLs. -In order to avoid linker errors, access factory objects via dedicated backend functions -provided (eg. `factory_postgresql()`). - -## Using loadable backends - -Dynamically loadable backends are compiled as shared libraries and allow to select backends at run-time by name. - -The usage is similar to the above, but instead of providing the factory object, the backend name is expected: - -```cpp -session sql("postgresql", "dbname=mydb"); -``` - -For convenience, the URL-like form that combines both the backend name with connection parameters is supported as well: - -```cpp -session sql("postgresql://dbname=mydb"); -``` - -The last two constructors described above try to locate the shared library with the name `libsoci_ABC.so` (or `libsoci_ABC.dll` on Windows), where ABC is the backend name. -In the above examples, the expected library name will be `libsoci_postgresql.so` for Unix-like systems. - -The most general form of the constructor takes a single object of `connection_parameters` type which contains a pointer to the backend to use, the connection string and also any connection options. -Using this constructor is the only way to pass any non-default options to the backend. - -For example, to suppress any interactive prompts when using ODBC backend you could do: - -```cpp -connection_parameters parameters("odbc", "DSN=mydb"); -parameters.set_option(odbc_option_driver_complete, "0" /* SQL_DRIVER_NOPROMPT */); -session sql(parameters); -``` - -Notice that you need to `#include` to obtain the option name declaration. -The existing options are described in the backend-specific part of the documentation. - -IBM DB2 driver for ODBC and CLI also support the driver completion requests. -So, the DB2 backend provides similar option `db2_option_driver_complete` with `#include ` required to obtain the option name. - -### Environment configuration - -The `SOCI_BACKENDS_PATH` environment variable defines the set of paths where the shared libraries will be searched for. -There can be many paths, separated by colons, and they are used from left to right until the library with the appropriate name is found. If this variable is not set or is empty, the current directory is used as a default path for dynamically loaded backends. - -## Using registered backends - -The run-time selection of backends is also supported with libraries linked statically. - -Each backend provides a separate function of the form `register_factory_*name*`, where `*name*` is a backend name. Thus: - -```cpp -extern "C" void register_factory_postgresql(); -// ... -register_factory_postgresql(); -session sql("postgresql://dbname=mydb"); -``` - -The above example registers the backend for PostgreSQL and later creates the session object for that backend. -This form is provided for those projects that prefer static linking but still wish to benefit from run-time backend selection. - -An alternative way to set up the session is to create it in the disconnected state and connect later: - -```cpp -session sql; - -// some time later: -sql.open(postgresql, "dbname=mydb"); - -// or: -sql.open("postgresql://dbname=mydb"); - -// or also: -connection_parameters parameters("postgresql", "dbname=mydb"); -sql.open(parameters); -``` - -The rules for backend naming are the same as with the constructors described above. - -The session can be also explicitly `close`d and `reconnect`ed, which can help with basic session error recovery. -The `reconnect` function has no parameters and attempts to use the same values as those provided with earlier constructor or `open` calls. - -See also the page devoted to [multithreading](multithreading.html) for a detailed description of connection pools. - -It is possible to have many active `session`s at the same time, even using different backends. - -### Portability note - -The following backend factories are currently (as of 3.1.0 release) available: - -* [mysql](backends/mysql.html) (requires `#include "soci-mysql.h"`) -* [oracle](backends/oracle.html) (requires `#include "soci-oracle.h"`) -* [postgresql](backends/postgresql.html) (requires `#include "soci-postgresql.h"`) - -The following backends are also available, with various levels of completeness: - -* [sqlite3](backends/sqlite3.html) (requires `#include "soci-sqlite3.h"`) -* [odbc](backends/odbc.html) (requires `#include "soci-odbc.h"`) -* [firebird](backends/firebird.html) (requires `#include "soci-firebird.h"`) - -## Connection failover - -The `failover_callback` interface can be used as a callback channel for notifications of events that are automatically processed when the session is forcibly closed due to connectivity problems. The user can override the following methods: - -```cpp -// Called when the failover operation has started, -// after discovering connectivity problems. -virtual void started(); - -// Called after successful failover and creating a new connection; -// the sql parameter denotes the new connection and allows the user -// to replay any initial sequence of commands (like session configuration). -virtual void finished(session & sql); - -// Called when the attempt to reconnect failed, -// if the user code sets the retry parameter to true, -// then new connection will be attempted; -// the newTarget connection string is a hint that can be ignored -// by external means. -virtual void failed(bool & retry, std::string & newTarget); - -// Called when there was a failure that prevents further failover attempts. -virtual void aborted(); -``` - -The user-provided callback implementation can be installed (or reset) with: - -```cpp -sql.set_failover_callback(myCallback); -``` - -### Portability note - -The `failover_callback` functionality is currently supported only by PostgreSQL and Oracle backends (in the latter case the failover mechanism is governed by the Oracle-specific cluster configuration settings). -Other backends allow the callback object to be installed, but will ignore it and will not generate notification calls. diff --git a/src/soci/docs/errors.md b/src/soci/docs/errors.md deleted file mode 100644 index 81618e39ca..0000000000 --- a/src/soci/docs/errors.md +++ /dev/null @@ -1,99 +0,0 @@ -# Errors - -All DB-related errors manifest themselves as exceptions of type `soci_error`, which is derived from `std::runtime_error`. -This allows to handle database errors within the standard exception framework: - -```cpp -int main() -{ - try - { - // regular code - } - catch (std::exception const & e) - { - cerr << "Bang! " << e.what() << endl; - } -} -``` - -The `soci_error` class exposes two public functions: - -The `get_error_message() const` function returns `std::string` with a brief error message, without any additional information that can be present in the full error message returned by `what()`. - -The `get_error_category() const` function returns one of the `error_category` enumeration values, which allows the user to portably react to some subset of common errors. -For example, `connection_error` or `constraint_violation` have meanings that are common across different database backends, even though the actual mechanics might differ. - -## Portability - -Error categories are not universally supported and there is no claim that all possible errors that are reported by the database server are covered or interpreted. -If the error category is not recognized by the backend, it defaults to `unknown`. - -## MySQL - -The MySQL backend can throw instances of the `mysql_soci_error`, which is publicly derived from `soci_error` and has an additional public `err_num_` member containing the MySQL error code (as returned by `mysql_errno()`): - -```cpp -int main() -{ - try - { - // regular code - } - catch (soci::mysql_soci_error const & e) - { - cerr << "MySQL error: " << e.err_num_ - << " " << e.what() << endl; - } - catch (soci::exception const & e) - { - cerr << "Some other error: " << e.what() << endl; - } -} -``` - -## Oracle - -The Oracle backend can also throw the instances of the `oracle_soci_error`, which is publicly derived from `soci_error` and has an additional public `err_num_` member containing the Oracle error code: - -```cpp -int main() -{ - try - { - // regular code - } - catch (soci::oracle_soci_error const & e) - { - cerr << "Oracle error: " << e.err_num_ - << " " << e.what() << endl; - } - catch (soci::exception const & e) - { - cerr << "Some other error: " << e.what() << endl; - } -} -``` - -## PostgreSQL - -The PostgreSQL backend can also throw the instances of the `postgresql_soci_error`, which is publicly derived from `soci_error` and has an additional public `sqlstate()` member function returning the five-character "SQLSTATE" error code: - -```cpp -int main() -{ - try - { - // regular code - } - catch (soci::postgresql_soci_error const & e) - { - cerr << "PostgreSQL error: " << e.sqlstate() - << " " << e.what() << endl; - } - catch (soci::exception const & e) - { - cerr << "Some other error: " << e.what() << endl; - } -} -``` diff --git a/src/soci/docs/faq.md b/src/soci/docs/faq.md deleted file mode 100644 index 7ce91ab5de..0000000000 --- a/src/soci/docs/faq.md +++ /dev/null @@ -1,129 +0,0 @@ -# FAQ - -This part of the documentation is supposed to gather in a single place the usual questions (and answers) about SOCI with regard to the design decisions that have shaped it. - -## Q: Why "SOCI"? - -SOCI was initially developed in the environment where Oracle was the main database technology in use. As a wrapper for the native OCI API (Oracle Call Interface), the name "Simple Oracle Call Interface" was quite obvious - until the 2.0 release, when the internal architecture was largely redesigned to allow the use of *backends* that support other database servers. We have kept the same name to indicate that Oracle is the main supported technology in the sense that the library includes only those features that were naturally implemented in Oracle. With the 2.1 release of the library, two new backends were added (MySQL and SQLite3) and we decided to drop the original full name so that new users looking for a library supporting any of these simpler libraries are not discouraged by seeing "Oracle" somewhere in the name. - -The other possible interpretation was "Syntax Oriented Call Interface", which stresses the fact that SOCI was built to support the most natural and easy interface for the user that is similar to the Embedded SQL concept (see below). But on the other hand, SOCI also provides other features (like object-relational mapping) and as a whole it is not just "emulator" of the Embedded SQL. With all these considerations in mind, SOCI is just "SOCI - The C++ Database Access Library". - -Still, Oracle is considered to be the main driving server technology in terms of the set of features that are supported by the library. This also means that backends for other servers might need to work around some of the imposed idioms and protocols, but already available and well-working PostgreSQL, MySQL and SQLite3 backends show -that it's actually not that bad and the abstractions provided by the library are actually very universal. Of course, some of the features that were provided for Oracle might not be supported for all other servers, but we think that it's better to have one leading technology (where at least one group is fully happy) instead of some "common denominator" for all databases (where *nobody* is happy). - -## Q: Where the basic SOCI syntax comes from? - -The basic SOCI syntax was inspired by the Embedded SQL, which is part of the SQL standard, supported by the major DB technologies and even available as built-in part of the languages used in some DB-oriented integrated development environments. The term "Embedded SQL" is enough for Google to spit millions of references - one of the typical examples is: - -```cpp -{ - int a; - /* ... */ - EXEC SQL SELECT salary INTO :a - FROM Employee - WHERE SSN=876543210; - /* ... */ - printf("The salary is %d\n", a); - /* ... */ -} -``` - -The above is not a regular C (nor C++) code, of course. It's the mix of C and SQL and there is a separate, pecialized preprocessor needed to convert it to something that the actual C (or C++) compiler will be able to understand. This means that the compilation of the program using embedded SQL is two-phase: preprocess the embedded SQL part and compile the result. This two-phase development is quite troublesome, especially when it comes to debugging. Yet, the advantage of it is that the code expresses the programmer's intents in a very straightforward -way: read something from the database and put it into the local variable. Just like that. - -The SOCI library was born as an anwer to the following question: is it possible to have the same expressive power without the disadvantages of two-phase builds? - -The following was chosen to be the basic SOCI syntax that can mirror the above Embedded SQL example: - -```cpp -int a; -sql << "SELECT salary FROM Employee WHERE SSN=876543210", into(a); -``` - -(as you see, SOCI changes the order of elements a little bit, so that the SQL query is separate and not mixed with other elements) - -Apart from mimicking the Embedded SQL techniques in the regular, fully standard C++ code, the above syntax has the following benefit: it is *minimal* with respect to what has to be said. Every single piece above is needed and expresses something important, like: - -* which session should be used (the client can be connected to many databases at the same time) - here, the `sql` object encapsulates the session, -* what SQL query should be executed - here, it's the string literal, but it could be also a `std::string` variable, -* where to put the result - here, the local variable `a` will receive the result. - -Everything else is just a couple of operators that allow to treat the whole as a single expression. It's rather difficult to remove anything from this example. - -The fact that the basic SOCI syntax is minimal (but without being obscure at the same time, see below) means that the programmer does not need to bother with unnecessary noise that some other database libraries impose. We hope that after having written one line of code like above by themselves, most programmers will react with something -like "how obvious!" instead of "how advanced!". - -## Q: Why should I use SQL queries as strings in my program? I prefer the query to be generated or composed piece-by-piece by separate functions. - -First, you don't need to use SQL queries as string literals. In bigger projects it is a common practice to store SQL queries externally (in a file, or in a... database) and load them before use. This means that they are not necessarily expected to appear in the program code, as they do in our simple code examples and the advantage of separating them from the source code of the main program is, among others, the possibility to optimize and tune the SQL queries without recompilation and relinking of the whole program. - -What is the most important, though, is that SOCI does not try to mess with the text of the query (apart from very few cases), which means that the database server will get exactly the same text of the query as is used in the program. The advantage of this is that there is no new SQL-like (or even SQL-*un*like) syntax that you would need to learn, and also that it's much easier to convince a typical DBA to help with SQL tuning or other specialized activities, if he is given the material in the form that is not polluted with any foreign abstractions. - -## Q: Why not some stream-like interface, which is well-known to all C++ programmers? - -An example of the stream-like interface might be something like this (this is imaginary syntax, not supported by SOCI): - -```cpp -sql.exec("select a, b, c from some_table"); - -while (!sql.eof()) -{ - int a, b, c; - sql >> a >> b >> c; - // ... -} -``` - -We think that the data stored in the relational database should be treated as a set of relations - which is exactly what it is. This means that what is read from the database as a result of some SQL query is a *set of rows*. This set might be ordered, but it is still a set of rows, not a uniformly flat list of values. This distinction might seem to be unnecessarily low-level and that the uniform stream-like presentation of data is more preferable, but it's actually the other way round - the set of rows is something more structured - and that structure was *designed* into the database - than the flat stream and is therefore less prone to programming errors like miscounting the number of values that is expected in each row. - -Consider the following programming error: - -```cpp -sql.exec("select a, b from some_table"); // only TWO columns - -while (!sql.eof()) -{ - int a, b, c; - sql >> a >> b >> c; // this causes "row-tearing" - // ... -} -``` - -*"How to detect the end of each line in a file"* is a common beginner's question that relates to the use of IOStreams - and this common question clearly shows that for the record-oriented data the stream is not an optimal abstraction. Of course, we don't claim that IOStreams is bad - but we do insist that the record-oriented data is -better manipulated in a way that is also record-aware. - -Having said that, we *have* provided some form of the stream-like interface, but with the important limitation that the stream is always bound to the single row, so that the row-tearing effect is not possible. In other words, -data returned from the database is still structured into rows, but each row can be separately traversed like a stream. We hope that it provides a good balance between convenience and code safety. - -## Q: Why use indicators instead of some special value to discover that something is null? - -Some programmers are used to indicating the null value by using some special (which means: "unlikely" to be ever used) value - for example, to use the smallest integer value to indicate null integer. Or to use empty string to indicate null string. And so on. - -We think that it's *completely wrong*. Null (in the database sense) is an information *about* the data. It describes the *state* of the data and if it's null, then there's *no data at all*. Nothing. Null. It does not make any sense to talk about some special value if in fact there is *no* value at all - especially if we take into account that, for example, the smallest integer value (or whatever else you choose as the "special" value) might not be *that* special in the given application or domain. - -Thus, SOCI uses a separate indicators to describe the state of exchanged data. It also has an additional benefit of allowing the library to convey more than two states (null and not null). Indeed, the SOCI library uses indicators also to report that the data was read, but truncated (this applies to strings when reading to fixed-length character arrays). Truncation is also an information about the data and as such it's better to have it in addition to the data, not as part of it. - -Having said that, it is important to point at the [Integration with Boost](boost.html) that allows to use `boost::optional` to conveniently pack together the data and the information about its state. - -## Q: Overloaded comma operator is just obfuscation, I don't like it. - -Well, consider the following: - -"Send the query X to the server Y *and* put result into variable Z." - -Above, the "and" plays a role of the comma. Even if overloading the comma operator is not a very popular practice in C++, some libraries do this, achieving terse and easy to learn syntax. We are pretty sure that in SOCI the comma operator was overloaded with a good effect. - -## Q: The `operator<<` provides a bad abstraction for the "input" statements. - -Indeed, the `operator<<` in the basic SOCI syntax shows that something (the query) is *sent* somewhere (to the server). Some people don't like this, especially when the "select" statements are involved. If the high-level idea is to *read* data from somewhere, then `operator<<` seems unintuitive to the die-hard IOStreams users. The fact is, however, that the code containing SQL statement already indicates that there is a client-server relationship with some other software component (very likely remote). In such code it does not make any sense to pretend that the communication is one-way only, because it's clear that even the "select" statements need to be *sent* somewhere. This approach is also more uniform and allows to cover other statements like "drop table" or alike, where no data is expected to be exchanged at all (and therefore the IOStreams analogies for data exchange have no sense at all). No matter what is the kind of the SQL statement, it is *sent* to the server and this "sending" justifies the choice of `operator<<`. - -Using different operators (`operator>>` and `operator<<`) as a way of distinguishing between different high-level ideas (*reading* and *writing* from the data store, respectively) does make sense on much higher level of abstraction, where the SQL statement itself is already hidden - and we do encourage programmers to use SOCI for implementing such high-level abstractions. For this, the object-relational mapping facilities available in SOCI might prove to be a valuable tool as well, as an effective bridge -between the low-level world of SQL statements and the high-level world of user-defined abstract data types. - -## Q: Why the Boost license? - -We decided to use the [Boost license](http://www.boost.org/LICENSE_1_0.txt), because -it's well recognized in the C++ community, allows us to keep our minimum copyrights, and at the same time allows SOCI to be safely used in commercial projects, without imposing concerns (or just plainuncertainty) typical to other open source licenses, like GPL. We also hope that by choosing the Boost license we have made the life easier -for both us and our users. It saves us from answering law-related questions that were already answered on the [Boost license info page](http://www.boost.org/more/license_info.html) and it should also give more confidence to our users - especially to those of them, who already accepted the conditions of the Boost license - the just have one license less to analyze. - -Still, if for any reason the conditions of this license are not acceptable, we encourage the users to contact us directly (see [links](http://soci.sourceforge.net/people.html) on the relevant SOCI page) to discuss any remaining concerns. diff --git a/src/soci/docs/images/structure.png b/src/soci/docs/images/structure.png deleted file mode 100644 index 1694cb68715464bd7e21004cb38f1e3dca9f47af..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 26919 zcmZsBV|-=LwrzJh9jB9YY}-!9ww>(Qwr$(CjUB6F+qP{dFaLASyZ7DqyC2s2uu-+D zYOFcN9CL=sN{hfkVL*NR_6=4{R8aogx9>Y&R|*8k*WHL&xc}=5NE=Z#`)}WVjelKZ z-`(ElSHFETSr!xIQ*_BV>wwijTI~4zT+R;n8;;`@L=^K2Qy-$12sFPU!RKRYv3W%_ zVQ%m{2rg=6@`g?;kd0hIp+-pu-7adWFzv?tyD$LEVeMaqsF+SS1Bj}w9Nm+r1ToEn zDm20h4w--08yPtp^34=$aiYmK zI22&R$V6CBD5Hp+QS-99W>~)l+JJL5Bow9cg0fgmv6 zb|d>$9P@6*RgN8SjWPz`q_$dfWP+Ub|t>QgQ^goAYm01}-|8&>qy*6nc%;>pkjqpN-m7O-)Vn6IVHCLEG)ntdTl( z!n`gbLRYgH^hu6Z?2RRbJx3%1YHJ#Jvf zkt_Be?l8mL6;L|M!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w<_T`MYK!RmZ&HC7?&JeadDdahr| z(d70fC}=Z`;^XsF0{OMrJK87RN~N3ksQ8Doy?=O0@0$>NQ&M1LcL#Cf9YvST8%$!< zq#du1imbX1HDvoMP*Ek%BP>84wGrJzSo<#s<( z5($>IGhu4?+^*z+m|My3QXdYT{i#oSvu6!hTzfO7HrCw3g`;I7HM*bL7kGP#W&BxG zd=u%SXficFF&tRvt>JOHAv`r)x_F>duvfcL>0_|@Xyr)95TclA?)S_5Zf>R=su`{? zC?-Vje19LlI2?_&GpTg@PhN}otxx{$wV4tozTcjyn4~S~4k%&LnD8+0?RNM!sX_FQ zet2zrIo0>DdJ0I_TE}=4n+lk<{l}GTg8iUW?y(jni8uQSB zsK07vD5)u-yc!onbkQBJzr=>8JGaYYx%G=i_+#sX#OC8BEoA%7&gpT9yn%uR-L7!! z&Ax3Hl|+aMpbnfss1EKEo}*mPkk6=C0TA)Y&<+nu1bnOeqyc{K27kKS(2^O}-Q51m z(r)A|Tnb->BzJB*;C{ya54vlJYs003{&VwF*?enZ8NXk#5($Yp`!`=Qicm1E3;z`) zEFd&E^&QarvDm@pPGL?b95}Wszq~PRZ)u596SF|vX;gU8(lT~Zea&A&dVaKLr>yOe zC8{Dz5(WWpsP(Ws^#8aBn-0A`r}hnAgrNrSA7+T)NrC?ll}!2w2ZD_b+i|AOy zzty9uf}zpI9Y^lWORdB)_5n3>ZLmFC5+6Fm=X!)GqrA*xEC&4>59jjX{jbCF?g zyMc_qQ6MOp&cP<^CkM@;*_7l!a}mDQIBm_u&~{#j_IZT{VPVeV_i!!ZAsC%NH|pTKCzu z{NVjHR8>-vWRq*@!e{oo`gC^5f;HpQ+GF%)udsWEMwHbkN6GPq;ynJM_2F;S6vZ6% zF8*GZXEq3wx?ClGCw7cQJl(|t j0$Cn=(dH|@Qm|--(std::cout, "\n")); -``` - -SOCI offers also extensive [integration with Boost](boost.md) datatypes (optional, tuple and fusion) and flexible support for user-defined datatypes. - -## Database Backends - -Starting from its 2.0.0 release, SOCI uses the plug-in architecture for -backends - this allows to target various database servers. - -Currently (SOCI 4.0.0), backends for following database systems are supported: - -* [DB2](backends/db2.md) -* [Firebird](backends/firebird.md) -* [MySQL](backends/mysql.md) -* [ODBC](backends/odbc.md) (generic backend) -* [Oracle](backends/oracle.md) -* [PostgreSQL](backends/postgresql.md) -* [SQLite3](backends/sqlite3.md) - -The intent of the library is to cover as many database technologies as possible. -For this, the project has to rely on volunteer contributions from other programmers, -who have expertise with the existing database interfaces and would like to help -writing dedicated backends. - -## Langauge Bindings - -Even though SOCI is mainly a C++ library, it also allows to use it from other programming languages. -Currently the package contains the Ada binding, with more bindings likely to come in the future. diff --git a/src/soci/docs/indicators.md b/src/soci/docs/indicators.md deleted file mode 100644 index e020cafaf2..0000000000 --- a/src/soci/docs/indicators.md +++ /dev/null @@ -1,102 +0,0 @@ -# Data Indicators - -In order to support SQL NULL values and other conditions which are not real errors, the concept of *indicator* is provided. - -## Select with NULL values - -For example, when the following SQL query is executed: - -```sql -select name from person where id = 7 -``` - -there are three possible outcomes: - -1. there is a person with id = 7 and her name is returned -2. there is a person with id = 7, but she has no name (her name is null in the database table) -3. there is no such person - -Whereas the first alternative is easy to handle, the other two are more complex. -Moreover, they are not necessarily errors from the application's point of view and what's more interesting, they are *different* and the application may wish to detect which is the case. -The following example does this: - -```cpp -string name; -indicator ind; - -sql << "select name from person where id = 7", into(name, ind); - -if (sql.got_data()) -{ - switch (ind) - { - case i_ok: - // the data was returned without problems - break; - case i_null: - // there is a person, but he has no name (his name is null) - break; - case i_truncated: - // the name was returned only in part, - // because the provided buffer was too short - // (not possible with std::string, but possible with char* and char[]) - break; - } -} -else -{ - // no such person in the database -} -``` - -The use of indicator variable is optional, but if it is not used and the result would be `i_null`, -then the exception is thrown. -This means that you should use indicator variables everywhere where the application logic (and database schema) allow the "attribute not set" condition. - -## Insert with NULL values - -Indicator variables can be also used when binding input data, to control whether the data is to be used as provided, or explicitly overrided to be null: - -```cpp -int id = 7; -string name; -indicator ind = i_null; -sql << "insert into person(id, name) values(:id, :name)", - use(id), use(name, ind); -``` - -In the above example, the row is inserted with `name` attribute set to null. - -## Bulk operations with NULL values - -Indicator variables can also be used in conjunction with vector based insert, update, and select statements: - -```cpp -vector names(100); -vector inds; -sql << "select name from person where id = 7", into(names, inds); -``` - -The above example retrieves first 100 rows of data (or less). -The initial size of `names` vector provides the (maximum) number of rows that should be read. -Both vectors will be automatically resized according to the number of rows that were actually read. - -The following example inserts null for each value of name: - -```cpp -vector ids; -vector names; -vector nameIndicators; - -for (int i = 0; i != 10; ++i) -{ - ids.push_back(i); - names.push_back(""); - nameIndicators.push_back(i_null); -} - -sql << "insert into person(id, name) values(:id, :name)", - use(ids), use(name, nameIndicators); -``` - -See also [Integration with Boost](boost.html) to learn how the Boost.Optional library can be used to handle null data conditions in a more natural way. diff --git a/src/soci/docs/installation.md b/src/soci/docs/installation.md deleted file mode 100644 index a1f3e80090..0000000000 --- a/src/soci/docs/installation.md +++ /dev/null @@ -1,221 +0,0 @@ -# Installation - -## Requirements - -Below is an overall list of SOCI core: - -* C++ compiler: [GCC](http://gcc.gnu.org/), [Microsoft Visual C++](http://msdn.microsoft.com/en-us/visualc), [LLVM/clang](http://clang.llvm.org/) -* [CMake](http://www.cmake.org) 2.8+ - in order to use build configuration for CMake -* [Boost C++ Libraries](http://www.boost.org): DateTime, Fusion, Optional, Preprocessor, Tuple - -and backend-specific dependencies: - -* [DB2 Call Level Interface (CLI)](http://pic.dhe.ibm.com/infocenter/db2luw/v10r1/topic/com.ibm.swg.im.dbclient.install.doc/doc/c0023452.html) -* [Firebird client library](http://www.firebirdsql.org/manual/ufb-cs-clientlib.html) -* [mysqlclient](http://dev.mysql.com/doc/refman/5.6/en/c.html) - C API to MySQL -* ODBC (Open Database Connectivity) implementation: [Microsoft ODBC](http://msdn.microsoft.com/en-us/library/windows/desktop/ms710252.aspx) [iODBC](http://www.iodbc.org/), [unixODBC](http://www.unixodbc.org/) -* [Oracle Call Interface (OCI)](http://www.oracle.com/technetwork/database/features/oci/index.html) -* [libpq](http://www.postgresql.org/docs/8.4/static/libpq.html) - C API to PostgreSQL -* [SQLite 3](http://www.sqlite.org/) library - -## Downloads - -Download package with latest release of the SOCI source code: [soci-X.Y.Z](https://sourceforge.net/projects/soci/), where X.Y.Z is the version number. -Unpack the archive. - -You can always clone SOCI from the Git repository: - -```console -git clone git://github.com/SOCI/soci.git -``` - -## Building with CMake - -SOCI is configured to build using [CMake](http://cmake.org/) system in version 2.8+. - -The build configuration allows to control various aspects of compilation and installation by setting common CMake variables that change behaviour, describe system or control build (see [CMake help](http://cmake.org/cmake/help/documentation.html)) as well as SOCI-specific variables described below. -All these variables are available regardless of platform or compilation toolset used. - -Running CMake from the command line allows to set variables in the CMake cache with the following syntax: `-DVARIABLE:TYPE=VALUE`. -If you are new to CMake, you may find the tutorial [Running CMake](http://cmake.org/cmake/help/runningcmake.html") helpful. - -### Running CMake on Unix - -Steps outline using GNU Make makefiles: - -```console -mkdir build -cd build -cmake -G "Unix Makefiles" -DWITH_BOOST=OFF -DWITH_ORACLE=OFF (...) /path/to/soci-X.Y.Z -make -make install -``` - -### Running CMake on Windows - -Steps outline using Visual Studio 2010 and MSBuild: - -```console -mkdir build -cd build -cmake -G "Visual Studio 10" -DWITH_BOOST=OFF -DWITH_ORACLE=OFF (...) C:\path\to\soci-X.Y.Z -msbuild.exe SOCI.sln -``` - -### CMake configuration - -By default, CMake will try to determine availability of all depdendencies automatically. -If you are lucky, you will not need to specify any of the CMake variables explained below. -However, if CMake reports some of the core or backend-specific dependencies as missing, you will need specify relevant variables to tell CMake where to look for the required components. - -CMake configures SOCI build performing sequence of steps. -Each subsequent step is dependant on result of previous steps corresponding with particular feature. -First, CMake checks system platform and compilation toolset. -Next, CMake tries to find all external dependencies. -Then, depending on the results of the dependency check, CMake determines SOCI backends which are possible to build. -The SOCI-specific variables described below provide users with basic control of this behaviour. - -The following sections provide summary of variables accepted by CMake scripts configuring SOCI build. -The lists consist of common variables for SOCI core and all backends as well as variables specific to SOCI backends and their direct dependencies. - -List of a few essential CMake variables: - -* `CMAKE_BUILD_TYPE` - string - Specifies the build type for make based generators (see CMake [help](http://cmake.org/cmake/help/cmake-2-8-docs.html#variable:CMAKE_BUILD_TYPE)). -* `CMAKE_INSTALL_PREFIX` - path - Install directory used by install command (see CMake [help](http://cmake.org/cmake/help/cmake-2-8-docs.html#variable:CMAKE_INSTALL_PREFIX)). -* `CMAKE_VERBOSE_MAKEFILE` - boolean - If ON, create verbose makefile (see CMake [help](http://cmake.org/cmake/help/cmake-2-8-docs.html#variable:CMAKE_VERBOSE_MAKEFILE)). - -List of variables to control common SOCI features and dependencies: - -* `SOCI_STATIC` - boolean - Request to build static libraries, along with shared, of SOCI core and all successfully configured backends. -* `SOCI_TESTS` - boolean - Request to build regression tests for SOCI core and all successfully configured backends. -* `WITH_BOOST` - boolean - Should CMake try to detect [Boost C++ Libraries](http://www.boost.org/). If ON, CMake will try to find Boost headers and binaries of [Boost.Date_Time](http://www.boost.org/doc/libs/release/doc/html/date_time.html) library. - -#### Empty (sample backend) - -* `SOCI_EMPTY` - boolean - Builds the [sample backend](backends.html) called Empty. Always ON by default. -* `SOCI_EMPTY_TEST_CONNSTR` - string - Connection string used to run regression tests of the Empty backend. It is a dummy value. Example: `-DSOCI_EMPTY_TEST_CONNSTR="dummy connection"` - -#### IBM DB2 - -* `WITH_DB2` - boolean - Should CMake try to detect IBM DB2 Call Level Interface (CLI) library. -* `DB2_INCLUDE_DIR` - string - Path to DB2 CLI include directories where CMake should look for `sqlcli1.h` header. -* `DB2_LIBRARIES` - string - Full paths to `db2` or `db2api` libraries to link SOCI against to enable the backend support. -* `SOCI_DB2` - boolean - Requests to build [DB2](backends/db2.html) backend. Automatically switched on, if `WITH_DB2` is set to ON. -* `SOCI_DB2_TEST_CONNSTR` - string - See [DB2 backend reference](backends/db2.html) for details. Example: `-DSOCI_DB2_TEST_CONNSTR:STRING="DSN=SAMPLE;Uid=db2inst1;Pwd=db2inst1;autocommit=off"` - -#### Firebird - -* `WITH_FIREBIRD` - boolean - Should CMake try to detect Firebird client library. -* `FIREBIRD_INCLUDE_DIR` - string - Path to Firebird include directories where CMake should look for `ibase.h` header. -* `FIREBIRD_LIBRARIES` - string - Full paths to Firebird `fbclient` or `fbclient_ms` libraries to link SOCI against to enable the backend support. -* `SOCI_FIREBIRD` - boolean - Requests to build [Firebird](backends/firebird.html) backend. Automatically switched on, if `WITH_FIREBIRD` is set to ON. -* `SOCI_FIREBIRD_TEST_CONNSTR` - string - See [Firebird backend refernece](backends/firebird.html) for details. Example: `-DSOCI_FIREBIRD_TEST_CONNSTR:STRING="service=LOCALHOST:/tmp/soci_test.fdb user=SYSDBA password=masterkey"` - -#### MySQL - -* `WITH_MYSQL` - boolean - Should CMake try to detect [mysqlclient](http://dev.mysql.com/doc/refman/5.0/en/c.html) libraries providing MySQL C API. Note, currently the [mysql_config](http://dev.mysql.com/doc/refman/5.0/en/building-clients.html) program is not being used. -* `MYSQL_DIR` - string - Path to MySQL installation root directory. CMake will scan subdirectories `MYSQL_DIR/include` and `MYSQL_DIR/lib` respectively for MySQL headers and libraries. -* `MYSQL_INCLUDE_DIR` - string - Path to MySQL include directory where CMake should look for `mysql.h` header. -* `MYSQL_LIBRARIES` - string - Full paths to libraries to link SOCI against to enable the backend support. -* `SOCI_MYSQL` - boolean - Requests to build [MySQL](backends/mysql.html) backend. Automatically switched on, if `WITH_MYSQL` is set to ON. -* `SOCI_MYSQL_TEST_CONNSTR` - string - Connection string to MySQL test database. Format of the string is explained [MySQL backend refernece](backends/mysql.html). Example: `-DSOCI_MYSQL_TEST_CONNSTR:STRING="db=mydb user=mloskot password=secret"` - -#### ODBC - -* `WITH_ODBC` - boolean - Should CMake try to detect ODBC libraries. On Unix systems, CMake tries to find [unixODBC](http://www.unixodbc.org/) or [iODBC](http://www.iodbc.org/) implementations. -* `ODBC_INCLUDE_DIR` - string - Path to ODBC implementation include directories where CMake should look for `sql.h` header. -* `ODBC_LIBRARIES` - string - Full paths to libraries to link SOCI against to enable the backend support. -* `SOCI_ODBC` - boolean - Requests to build [ODBC](backends/odbc.html) backend. Automatically switched on, if `WITH_ODBC` is set to ON. -* `SOCI_ODBC_TEST_{database}_CONNSTR` - string - ODBC Data Source Name (DSN) or ODBC File Data Source Name (FILEDSN) to test database: Microsoft Access (.mdb), Microsoft SQL Server, MySQL, PostgreSQL or any other ODBC SQL data source. {database} is placeholder for name of database driver ACCESS, MYSQL, POSTGRESQL, etc. See [ODBC](backends/odbc.html) backend refernece for details. Example: `-DSOCI_ODBC_TEST_POSTGRESQL_CONNSTR="FILEDSN=/home/mloskot/soci/build/test-postgresql.dsn"` - -#### Oracle - -* `WITH_ORACLE` - boolean - Should CMake try to detect [Oracle Call Interface (OCI)](http://en.wikipedia.org/wiki/Oracle_Call_Interface) libraries. -* `ORACLE_INCLUDE_DIR` - string - Path to Oracle include directory where CMake should look for `oci.h` header. -* `ORACLE_LIBRARIES` - string - Full paths to libraries to link SOCI against to enable the backend support. -* `SOCI_ORACLE` - boolean - Requests to build [Oracle](backends/oracle.html) backend. Automatically switched on, if `WITH_ORACLE` is set to ON. -* `SOCI_ORACLE_TEST_CONNSTR` - string - Connection string to Oracle test database. Format of the string is explained [Oracle backend reference](backends/oracle.html). Example: `-DSOCI_ORACLE_TEST_CONNSTR:STRING="service=orcl user=scott password=tiger"` - -#### PostgreSQL - -* `WITH_POSTGRESQL` - boolean - Should CMake try to detect PostgreSQL client interface libraries. SOCI relies on [libpq](http://www.postgresql.org/docs/9.0/interactive/libpq.html") C library. -* `POSTGRESQL_INCLUDE_DIR` - string - Path to PostgreSQL include directory where CMake should look for `libpq-fe.h` header. -* `POSTGRESQL_LIBRARIES` - string - Full paths to libraries to link SOCI against to enable the backend support. -* `SOCI_POSTGRESQL` - boolean - Requests to build [PostgreSQL](backends/postgresql.html") backend. Automatically switched on, if `WITH_POSTGRESQL` is set to ON. -* `SOCI_POSTGRESQL_TEST_CONNSTR` - string - Connection string to PostgreSQL test database. Format of the string is explained PostgreSQL backend refernece. Example: `-DSOCI_POSTGRESQL_TEST_CONNSTR:STRING="dbname=mydb user=scott"` - -#### SQLite 3 - -* `WITH_SQLITE3` - boolean - Should CMak try to detect SQLite C/C++ library. As bonus, the configuration tries OSGeo4W distribution if OSGEO4W_ROOT environment variable is set. -* `SQLITE_INCLUDE_DIR` - string - Path to SQLite 3 include directory where CMake should look for `sqlite3.h` header. -* `SQLITE_LIBRARIES` - string - Full paths to libraries to link SOCI against to enable the backend support. -* `SOCI_SQLITE3` - boolean - Requests to build [SQLite3](backends/sqlite3.html) backend. Automatically switched on, if `WITH_SQLITE3` is set to ON. -* `SOCI_SQLITE3_TEST_CONNSTR` - string - Connection string is simply a file path where SQLite3 test database will be created (e.g. /home/john/soci_test.db). Check [SQLite3 backend reference](backends/sqlite3.html) for details. Example: `-DSOCI_SQLITE3_TEST_CONNSTR="my.db"` or `-DSOCI_SQLITE3_TEST_CONNSTR=":memory:"`. - -## Building with Makefiles on Unix - -*NOTE: These (classic) Makefiles have not been maintained for long time. -The officially maintained build configuration is CMake. -If you still want to use these Makefiles, you've been warned that you may need to patch them.* - -The classic set of Makefiles for Unix/Linux systems is provided for those users who need complete control over the whole processand who can benefit from the basic scaffolding that they can extend on their own. -In this sense, the basic Makefiles are supposed to provide a minimal starting point for custom experimentation and are not intended to be a complete build/installation solution. -At the same time, they are complete in the sense that they can compile the library with all test programs and for some users this level of support will be just fine. - -The `core` directory of the library distribution contains the `Makefile.basic` that can be used to compile the core part of the library. -Run `make -f Makefile.basic` or `make -f Makefile.basic shared` to get the static and shared versions, respectively. -Similarly, the `backends/name` directory contains the backend part for each supported backend with the appropriate `Makefile.basic` and the `backends/name/test` directory contains the test program for the given backend. - -For example, the simplest way to compile the static version of the library and the test program for PostgreSQL is: - -```console -cd src/core -make -f Makefile.basic -cd ../backends/postgresql -make -f Makefile.basic -cd test -make -f Makefile.basic -``` - -For each backend and its test program, the `Makefile.basic`s contain the variables that can have values specific to the given environment - they usually name the include and library paths. -These variables are placed at the beginning of the `Makefile.basic`s. -Please review their values in case of any compilation problems. - -The Makefiles for test programs can be a good starting point to find out correct compiler and linker options. - -## Running tests - -The process of running regression tests highly depends on user's environment and build configuration, so it may be quite involving process. -The CMake configuration provides variables to allow users willing to run the tests to configure build and specify database connection parameters (see the lists above for variable names). - -In order to run regression tests, configure and build desired SOCI backends and prepare working database instances for them. - -While configuring build with CMake, specify `SOCI_TESTS=ON` to enable building regression tests. -Also, specify `SOCI_{backend name}_TEST_CONNSTR` variables to tell the tests runner how to connect with your test databases. - -Dedicated `make test` target can be used to execute regression tests on build completion: - -```console -mkdir build -cd build -cmake -G "Unix Makefiles" \ - -DWITH_BOOST=OFF \ - -DSOCI_TESTS=ON \ - -DSOCI_EMPTY_TEST_CONNSTR="dummy connection" \ - -DSOCI_SQLITE3_TEST_CONNSTR="test.db" \ - (...) - ../soci-X.Y.Z -make -make test -make install -``` - -In the example above, regression tests for the sample Empty backend and SQLite 3 backend are configured for execution by `make test` target. - -## Using library - -CMake build produces set of shared and static libraries for SOCI core and backends separately. -On Unix, for example, `build/lib` directory will consist of the static libraries named like `libsoci_core.a`, `libsoci_sqlite3.a` and shared libraries with names like `libsoci_core.so.4.0.0`, `libsoci_sqlite3.so.4.0.0`, and so on. - -In order to use SOCI in your program, you need to specify your project build configuration with paths to SOCI headers and libraries. -Then, tell the linker to link against the libraries you want to use in your program. diff --git a/src/soci/docs/interfaces.md b/src/soci/docs/interfaces.md deleted file mode 100644 index 144222257c..0000000000 --- a/src/soci/docs/interfaces.md +++ /dev/null @@ -1,84 +0,0 @@ -# Interfaces - -One of the major features of SOCI, although not immediately visible, is the variety of interfaces (APIs) that are available for the user. These can be divided into *sugar*, *core* and *simple*. - -## Sugar - -The most exposed and promoted interface supports the syntax sugar that makes SOCI similar in look and feel to embedded SQL. -The example of application code using this interface is: - -```cpp -session sql("postgresql://dbname=mydb"); - -int id = 123; -string name; - -sql << "select name from persons where id = :id", into(name), use(id); -``` - -## Core - -The above example is equivalent to the following, more explicit sequence of calls: - -```cpp -session sql("postgresql://dbname=mydb"); - -int id = 123; -string name; - -statement st(sql); -st.exchange(into(name)); -st.exchange(use(id)); -st.alloc(); -st.prepare("select name from persons where id = :id"); -st.define_and_bind(); -st.execute(true); -``` - -The value of the *core* interface is that it is the basis for all other interfaces, and can be also used by developers to easily prepare their own convenience interfaces. -Users who cannot or for some reason do not want to use the natural *sugar* interface should try the *core* one as the foundation and access point to all SOCI functionality. - -Note that the *sugar* interface wraps only those parts of the *core* that are related to data binding and query streaming. - -## Simple - -The *simple* interface is provided specifically to allow easy integration of the SOCI library with other languages that have the ability to link with binaries using the "C" calling convention. -To facilitate this integration, the *simple* interface does not use any pointers to data except C-style strings and opaque handles, but the consequence of this is that user data is managed by SOCI and not by user code. -To avoid exceptions passing the module boundaries, all errors are reported as state variables of relevant objects. - -The above examples can be rewritten as (without error-handling): - -```cpp -#include - -// ... -session_handle sql = soci_create_session("postgresql://dbname=mydb"); - -statement_handle st = soci_create_statement(sql); - -soci_use_int(st, "id"); -soci_set_use_int(st, "id", 123); - -int namePosition = soci_into_string(st); - -soci_prepare(st, "select name from persons where id = :id"); - -soci_execute(st, true); - -char const * name = soci_get_into_string(st, namePosition); - -printf("name is %s\n", name); - -soci_destroy_statement(st); -soci_destroy_session(sql); -``` - -The *simple* interface supports single and bulk data exchange for static binding. -Dynamic row description is not supported in this release. - -See [Simple client interface](/reference.html#simpleclient) reference documentation for more details. - -## Low-level backend interface - -The low-level backend interface allows to interact with backends directly and in principle allows to access the database without involving any other component. -There is no particular reason to use this interface in the user code. diff --git a/src/soci/docs/languages/ada/concepts.md b/src/soci/docs/languages/ada/concepts.md deleted file mode 100644 index 28443ca1ba..0000000000 --- a/src/soci/docs/languages/ada/concepts.md +++ /dev/null @@ -1,29 +0,0 @@ -# Ada Concepts - -The SOCI-Ada library borrows its concepts and naming from the main SOCI project. They are shortly explained here in the bottom-up fashion. - -One of the main properties of the library is that the data objects which are bound for transfer to and from the database server are managed by the library itself and are not directly visible from the user code. This ensures that no aliasing of objects occurs between Ada and underlying C++ code, which makes the inter-language interface easier and more resilient to the differences in how compilers handle the linkage. As a direct result of this design choice, users of SOCI-Ada need to instruct the library to internally create all objects that will be subject to data transfer. - -There are two kinds of objects that can be managed by the SOCI-Ada library: - -* *Into elements*, which are data objects that are transferred from the database to the user program as a result of executing a query. There are single into elements for binding single rows of results and vector into elements for binding whole bunches of data corresponding to whole result sets or their subranges. The into elements are identified by their *position*. - -* *Use elements*, which are data objects that are transferred from the user program to the database as parameters of the query (and, if supported by the target database, that can be modified by the database server and transferred back to the user program). There are single use elements for binding parameters of single-row queries and vector use elements for binding whole bunches of data for transfer. The use elements are identified by their *name*. - -The user program can read the current value of into and use elements and assign new values to use elements. Elements are strongly typed and the following types are currently supported: - -* `String` -* `SOCI.DB_Integer`, which is defined by the library in terms of `Interfaces.C.int` -* `SOCI.DB_Long_Long_Integer`, which is defined in terms of `Interfaces.Integer_64` -* `SOCI.DB_Long_Float`, which is defined in terms of `Interfaces.C.double` -* `Ada.Calendar.Time` - -Both into and use elements are managed for a single *statement*, which can be prepared once and executed once or many times, with data transfer handled during execution or fetch phase. - -Statements can be managed explicitly, which is required if they are to be used repeteadly or when data transfer is needed or implicitly, which is a shorthand notation that is particularly useful with simple queries or DDL commands. - -All statements are handled within the context of some *session*, which also supports *transactions*. - -Sessions can be managed in isolation or as a group called *connection pool*, which helps to decouple tasking design choices from the concurrency policies at the database connection level. Sessions are *leased* from the pool for some time during which no other task can access them and returned back when no longer needed, where they can be acquired again by other tasks. - -All potential problems are signalled via exceptions that have some descriptive message attached to them. diff --git a/src/soci/docs/languages/ada/idioms.md b/src/soci/docs/languages/ada/idioms.md deleted file mode 100644 index e210aa1dc7..0000000000 --- a/src/soci/docs/languages/ada/idioms.md +++ /dev/null @@ -1,242 +0,0 @@ -# Ada Idioms - -As any other library, SOCI-Ada has its set of idioms that ensure optimal work in terms of performance and resource usage. Still, the optimal use will depend on the concrete usage scenario - the places where programmer choices are needed will be described explicitly. - -The idioms below are provided as *complete programs* with the intent to make them more understandable and to give complete context of use for each idiom. The programs assume that the target database is PostgreSQL, but this can be changed by a different connection string in each place where the sessions are established. The programs use the Ada 2005 interface and some minor changes will be required to adapt them for Ada 95 compilers. - -## Single query without data transfer - -This type of query is useful for DDL commands and can be executed directly on the given session, without explicit statement management. - -```ada -with SOCI; - -procedure My_Program is - - SQL : SOCI.Session := SOCI.Make_Session ("postgresql://dbname=my_database"); - -begin - - SQL.Execute ("drop table some_table"); - -end My_Program; - -``` - -Note: The session object is initialized by a constructor function call. An alternative would be to declare it without initialization and later use the `Open` operation to establish a physical connection with the database. - -## Simple query without parameters resulting in one row of data - -This type of query requires only single into elements, which together with the statement have to be manipulated explicitly. - -```ada -with SOCI; -with Ada.Text_IO; - -procedure My_Program is - - SQL : SOCI.Session := SOCI.Make_Session ("postgresql://dbname=my_database"); - St : SOCI.Statement := SOCI.Make_Statement (SQL); - Pos : SOCI.Into_Position; - - Num_Of_Persons : SOCI.DB_Integer; - -begin - - Pos := St.Into_Integer; - St.Prepare ("select count(*) from persons"); - St.Execute (True); - - Num_Of_Persons := St.Get_Into_Integer (Pos); - - Ada.Text_IO.Put_Line ("Number of persons: " & SOCI.DB_Integer'Image (Num_Of_Persons)); - -end My_Program; -``` - -Note: The into element is inspected by providing the position value that was obtained at the time if was created. No operations are defined for the position type. There can be many into elements with a single query. - -## Simple query with parameters and without results - -This type of query requires only use elements. - -```ada -with SOCI; - -procedure My_Program is - - SQL : SOCI.Session := SOCI.Make_Session ("postgresql://dbname=my_database"); - St : SOCI.Statement := SOCI.Make_Statement (SQL); - -begin - - St.Use_Integer ("increase"); - St.Set_Use_Integer ("increase", 1000); - - St.Prepare ("update persons set salary = salary + :increase"); - St.Execute (True); - -end My_Program; -``` - -Note: The "`:increase`" in the query is a placeholder variable. There can be many such variables and each of them needs to be filled in by respective use element. - -## Repeated query with parameters and without results - -This type of query requires only use elements, but they can be set differently for each statement execution. - -```ada -with SOCI; - -procedure My_Program is - - SQL : SOCI.Session := SOCI.Make_Session ("postgresql://dbname=my_database"); - St : SOCI.Statement := SOCI.Make_Statement (SQL); - -begin - - St.Use_String ("name"); - - St.Prepare ("insert into countries(country_name) values(:name)"); - - St.Set_Use_String ("name", "Poland"); - St.Execute (True); - - St.Set_Use_String ("name", "Switzerland"); - St.Execute (True); - - St.Set_Use_String ("name", "France"); - St.Execute (True); - -end My_Program; -``` - -Note: Each time the query is executed, the *current* values of use elements are transferred to the database. - -## Batch query with parameters and without results - -This type of query requires vector use elements. Compare with the previous example. - -```ada -with SOCI; - -procedure My_Program is - - SQL : SOCI.Session := SOCI.Make_Session ("postgresql://dbname=my_database"); - St : SOCI.Statement := SOCI.Make_Statement (SQL); - First : SOCI.Vector_Index; - - use type SOCI.Vector_Index; - -begin - - St.Use_Vector_String ("name"); - - St.Use_Vectors_Resize (3); - - First := St.Use_Vectors_First_Index; - - St.Set_Use_Vector_String ("name", First + 0, "Poland"); - St.Set_Use_Vector_String ("name", First + 1, "Switzerland"); - St.Set_Use_Vector_String ("name", First + 2, "France"); - - St.Prepare ("insert into countries(country_name) values(:name)"); - St.Execute (True); - -end My_Program; -``` - -Note: - -The whole bunch of data is transferred to the database if the target database server supports it and the statement is automatically repeated otherwise. This is the preferred way to transfer many rows of data to the server when the data for all rows are known before executing the query. - -Note: - -The query can be executed many times and each time a new batch of data can be transferred to the server. The size of the batch (set by calling `Use_Vectors_Resize`) can be different each time the query is executed, but cannot be larger than the size that was used the first time. The size of the batch defines a tradeoff between the amount of data being transmitted in a single step (this influences the memory used by the user program and the time of a single call) and the number of executions required to handle big data sets. The optimal size of the batch will therefore differ depending on the application, but in general tens of thousands is a reasonable limit for a batch size - the performance of the whole operation is usually not affected above this value so there is no need to imply higher memory usage at the client side. - -## Simple query with many rows of results - -This type of query requires simple into elements. - -```ada -with SOCI; -with Ada.Text_IO; - -procedure My_Program is - - SQL : SOCI.Session := SOCI.Make_Session ("postgresql://dbname=my_database"); - St : SOCI.Statement := SOCI.Make_Statement (SQL); - Pos : SOCI.Into_Position; - -begin - - Pos := St.Into_String; - - St.Prepare ("select country_name from countries"); - St.Execute; - - while St.Fetch loop - - Ada.Text_IO.Put_Line (St.Get_Into_String (Pos)); - - end loop; - -end My_Program; -``` - -Note: - -The loop above executes as many times as there are rows in the result. After each row is read, the into elements contain the respective values from that row. The `Execute` operation is called without parameter, which is `False` by default, meaning that no data transfer is intended. The data is being transferred only during the `Fetch` operation, which returns `False` when no data has been retrieved and the result is exhausted. - -This type of query can have simple parameters which are fixed at the execution time. - -## Batch query with many rows of results - -This type of query requires vector into elements. Compare with previous example. - -```ada -with SOCI; -with Ada.Text_IO; - -procedure My_Program is - - SQL : SOCI.Session := SOCI.Make_Session ("postgresql://dbname=my_database"); - St : SOCI.Statement := SOCI.Make_Statement (SQL); - Pos : SOCI.Into_Position; - - Batch_Size : constant := 10; - -begin - - Pos := St.Into_Vector_String; - St.Into_Vectors_Resize (Batch_Size); - - St.Prepare ("select country_name from countries"); - St.Execute; - - while St.Fetch loop - - for I in St.Into_Vectors_First_Index .. St.Into_Vectors_Last_Index loop - - Ada.Text_IO.Put_Line (St.Get_Into_Vector_String (Pos, I)); - - end loop; - - St.Into_Vectors_Resize (Batch_Size); - - end loop; - -end My_Program; -``` - -Note: - -The loop above is nested. The outer `while` loop fetches consecutive batches of rows from the database with requested batch size; the returned batch can be smaller than requested (the into vector elements are downsized automatically if needed) and the intended batch size is requested again before repeating the `Fetch` operation. For each returned batch, the into vector elements are inspected in the inner `for` loop. This scheme ensures correct operation independently on the size of returned batch and is therefore a recommended idiom for efficiently returning many rows of data. - -There is a tradeoff between efficiency and memory usage and this tradeoff is controlled by the requested batch size. Similarly to one of the examples above, there is no benefit from using batches bigger than tens of thousands of rows. - -This type of query can have simple (not vectors) parameters that are fixed at execution time. - -## Final note - -Follow good database usage principles and avoid constructing queries by concatenating strings computed at run-time. Thanks to a good type system Ada is much better in preventing various SQL-injection attacks than weaker languages like PHP, but there is still a potential for vulnerability or at least performance loss. As a rule of thumb, rely on *use elements* to parameterize your queries and to provide clean separation between data and code. This will prevent many security vulnerabilities and will allow some servers to optimize their work by reusing already cached execution plans. diff --git a/src/soci/docs/languages/ada/index.md b/src/soci/docs/languages/ada/index.md deleted file mode 100644 index afebb2ce46..0000000000 --- a/src/soci/docs/languages/ada/index.md +++ /dev/null @@ -1,37 +0,0 @@ -# Ada Bindings - -* [Concepts](concepts.md) -* [Idioms](idioms.md) -* [API Reference](reference.md) - -## Introduction - -SOCI-Ada is a database access library for Ada. - -The library itself is a wrapper for the selected functionality of the SOCI library, which is a C++ database access library recognized for its high quality and innovative interface. - -The SOCI-Ada library offers the following features to the Ada community: - -* Modular design based on dynamic backend loading. Thanks to this feature, new backends implemented within the context of the main SOCI project are immediately available for Ada programmers without any additional work. A large community of C++ users can help ensure that the new backends are well tested in a variety of environments and usage scenarios. -* Native backends for major database servers ensure optimal performance and minimize configuration overhead and complexity that is usually associated with other database access methods. -* Direct support for bulk operations allow to achieve high performance with queries that operate on large data sets. -* Very liberal open-source license ([Boost, accepted by Open Source Initiative](http://www.opensource.org/licenses/bsl1.0.html)) that encourages both commercial and non-commercial use. -* Easy to use and compact interface. - -Currently the following database servers are directly supported via their native interfaces: - -* Oracle -* PostgreSQL -* MySQL - -Other backends exist in the SOCI Git repository and can be provided with future version of the library. - -## Compilation - -In order to use SOCI-Ada, compile the C++ parts first (core and required backends). - -*Note:* SOCI header files are not needed to use SOCI-Ada, only compiled SOCI libraries (core and relevant backend) need to exist to build and use SOCI-Ada programs. - -The SOCI-Ada library itself is a single package named `SOCI`. This package can be just imported in the target project as is or pre-built to the binary form if required. - -In order to link the user programs the `-lsoci_core -lstdc++` linker options need to be provided on the Unix/Linux platforms. diff --git a/src/soci/docs/languages/ada/reference.md b/src/soci/docs/languages/ada/reference.md deleted file mode 100644 index e27196854a..0000000000 --- a/src/soci/docs/languages/ada/reference.md +++ /dev/null @@ -1,522 +0,0 @@ -# Ada API Reference - -The SOCI-Ada library is entirely implemented as a single package named `SOCI`. Additional child packages contain single procedures for static registration of backends - these child packages are not necessary for typical use, but can be useful to force static linking of backend code. - -The following describes all publicly visible elements of this package: - -```ada --- --- General exception related to database and library usage. --- - -Database_Error : exception; -``` - -Each problem related to the interaction with the database or to the incorrect usage of the library itself is signalled by raising this exception. Each occurrence of this exception has some human-readable error message that can be obtained by a call to `Ada.Exceptions.Exception_Message`. - -```ada --- --- Session. --- - -type Session is tagged limited private; - -not overriding -function Make_Session (Connection_String : in String) return Session; - -not overriding -procedure Open (This : in out Session; Connection_String : in String); - -not overriding -procedure Close (This : in out Session); - -not overriding -function Is_Open (This : in Session) return Boolean; -``` - -The `Session` object can exist in two states: "connected" (or "open") and "disconnected". It can be created as connected at initialization time with a call to the constructor function `Make_Session` or left default-initialized in the disconnected state and later changed to connected with `Open` (the latter option is the only that is available in the Ada 95 version of the library). `Session` objects can be also associated with the connection pool, see below. - -The `Connection_String` should have the form `"backendname://parameters"`, where `backendname` is used to construct the name of the dynamically loadable library that will be used to provide specific database services. Backends included in the current distribution of the main SOCI library are: - -* `oracle` (implemented as `libsoci_oracle.so` or `libsoci_oracle.dll`) -* `postgresql` (implemented as `libsoci_postgresql.so` or `libsoci_postgresql.dll`) -* `mysql` (implemented as `libsoci_mysql.so` or `libsoci_mysql.dll`) - -Other backends can be added to the library in the future or by the user himself, please see the documentation of the main SOCI library for details. - -The `parameters` component of the `Connection_String` depends on the given backend, please see the documentation of the main SOCI project for the meaning and recognized options. The web pages related to the backends above are: - -* [Oracle](http://soci.sourceforge.net/doc/backends/oracle.html) -* [PostgreSQL](http://soci.sourceforge.net/doc/backends/postgresql.html) -* [MySQL](http://soci.sourceforge.net/doc/backends/mysql.html) - -The `Open` operation can be called only in the disconnected state (which changes the state of `Session` object to connected). The `Close` operation can be called in any state (provided that the session is not associated with the connection pool, see below) and after that the `Session` is in the disconnected state. - -`Session` objects are closed automatically as part of their finalization. If the `Session` object is associated with the connection pool, the finalizer detaches from the pool without closing the connection. - -```ada --- Transaction management. - -not overriding -procedure Start (This : in Session); - -not overriding -procedure Commit (This : in Session); - -not overriding -procedure Rollback (This : in Session); -``` - -These operations handle transactions. The exact meaning of transactions and whether transactions are automatic for some kinds of statements (and which ones) depend on the target database. - -```ada --- Immediate query execution. -not overriding -procedure Execute (This : in Session; Query : in String); -``` - -This operation allows to create implicit statement, prepare it for the given `Query` and execute it. - -```ada --- --- Connection pool management. --- - -type Connection_Pool (Size : Positive) is tagged limited private; - -not overriding -procedure Open - (This : in out Connection_Pool; - Position : in Positive; - Connection_String : in String); - -not overriding -procedure Close (This : in out Connection_Pool; Position : in Positive); - -not overriding -procedure Lease (This : in out Connection_Pool; S : in out Session'Class); -``` - -The `Connection_Pool` encapsulates a fixed-size collection of sessions. Individual sessions are indexed from `1` to `Size` (provided as discriminant) and can be `Open`ed and `Close`d explicitly. Each connection in the pool can be created with different `Connection_String`, if needed. - -The `Lease` operation allows to associate a given `Session` object (that has to be in the disconnected state itself) with one connection from the pool. The pool guarantees that at most one task can lease a given connection from the pool. If there are no free connections in the pool, the `Lease` operation will block waiting until some connection is freed. - -The `Session` object that is associated with a connection from the pool automatically gives it back to pool as part of the `Session`'s finalizer. There is no other way to "detach" from the pool. - -Note: - -It is assumed that the lifetime of `Connection_Pool` encloses the lifetimes of all `Session` objects that are leased from it. There is no particular protection against it and it is possible to construct a code example with allocators that create partially overlapping `Connection_Pool` and `Session`, but this is considered obscure and not representative to the actual use scenarios. To avoid any potential problems, create `Connection_Pool` in the scope that encloses the scopes of leased `Session`s. - -```ada --- --- Statement. --- - -type Statement (<>) is tagged limited private; - -type Data_State is (Data_Null, Data_Not_Null); - -type Into_Position is private; - -type Vector_Index is new Natural; -``` - -The `Statement` type and supporting types. `Data_State` is used to indicate null values in the database sense - each value of into or use elements has a state from this type. - -```ada --- Statement preparation and execution. - -not overriding -procedure Prepare (This : in Statement; Query : in String); - -not overriding -procedure Execute - (This : in Statement; - With_Data_Exchange : in Boolean := False); - -not overriding -function Execute - (This : in Statement; - With_Data_Exchange : in Boolean := False) return Boolean; - -not overriding -function Fetch (This : in Statement) return Boolean; - -not overriding -function Got_Data (This : in Statement) return Boolean; -``` - -The `Prepare` operation needs to be called before any other operation in the above group and it prepares the execution for the given `Query`. No into and use elements can be created after this operation is called. - -The `Execute` operations cause the statement to execute, which might be combined with data exchange if requested. The function version of this operation returns `True` if some data has been returned back from the database server. - -The `Fetch` function is used to transfer next portion of data (a single row or a whole bunch) from the database server and returns `True` if some data has been fetched. If this function returns `False` it means that no new data will be ever fetched for this statement and indicates the end-of-row condition. - -The `Got_Data` function returns `True` if the last execution or fetch resulted in some data being transmitted from the database server. - -```ada --- --- Data items handling. --- - --- Database-specific types. --- These types are most likely identical to standard Integer, --- Long_Long_Integer and Long_Float, but are defined distinctly --- to avoid interfacing problems with other compilers. - -type DB_Integer is new Interfaces.C.int; -type DB_Long_Long_Integer is new Interfaces.Integer_64; -type DB_Long_Float is new Interfaces.C.double; -``` - -The data types used for interaction with the database are: - -* `String` -* `DB_Integer`, defined above -* `DB_Long_Long_Integer`, defined above -* `DB_Long_Float`, defined above -* `Ada.Calendar.Time` - -```ada --- Creation of single into elements. - -not overriding -function Into_String (This : in Statement) return Into_Position; - -not overriding -function Into_Integer (This : in Statement) return Into_Position; - -not overriding -function Into_Long_Long_Integer (This : in Statement) return Into_Position; - -not overriding -function Into_Long_Float (This : in Statement) return Into_Position; - -not overriding -function Into_Time (This : in Statement) return Into_Position; -``` - -These functions instruct the library to create internal simple into elements of the relevant type. They return the position of the into element, which can be later used to identify it. - -Note: Simple into elements cannot be created together with vector into elements for the same statement. - -Note: Simple into elements cannot be created together with vector into elements for the same statement. - -```ada --- Inspection of single into elements. - -not overriding -function Get_Into_State - (This : in Statement; - Position : in Into_Position) - return Data_State; - -not overriding -function Get_Into_String - (This : in Statement; - Position : in Into_Position) - return String; - -not overriding -function Get_Into_Integer - (This : in Statement; - Position : in Into_Position) - return DB_Integer; - -not overriding -function Get_Into_Long_Long_Integer - (This : in Statement; - Position : in Into_Position) - return DB_Long_Long_Integer; - -not overriding -function Get_Into_Long_Float - (This : in Statement; - Position : in Into_Position) - return DB_Long_Float; - -not overriding -function Get_Into_Time - (This : in Statement; - Position : in Into_Position) - return Ada.Calendar.Time; -``` - -These functions allow to inspect the state and value of the simple into element identified by its position. If the state of the given element is `Data_Null`, the data-reading functions raise exceptions for that element. - -```ada --- Inspection of vector into elements. - -not overriding -function Get_Into_Vectors_Size (This : in Statement) return Natural; - -not overriding -function Into_Vectors_First_Index (This : in Statement) return Vector_Index; - -not overriding -function Into_Vectors_Last_Index (This : in Statement) return Vector_Index; - -not overriding -procedure Into_Vectors_Resize (This : in Statement; New_Size : in Natural); -``` - -The `Get_Into_Vectors_Size` returns the number of entries in any of the vector into elements for the given statement. - -The `Into_Vectors_First_Index` returns the lowest index value for vector into elements (which is always `0`, even if the vectors are empty). The `Into_Vectors_Last_Index` returns the last index of into vectors, and raises the `CONSTRAINT_ERROR` exception if the vectors are empty. - -The `Into_Vectors_Resize` procedure allows to change the size of all use vectors for the given statement. - -```ada -not overriding -function Get_Into_Vector_State - (This : in Statement; - Position : in Into_Position; - Index : in Vector_Index) - return Data_State; - -not overriding -function Get_Into_Vector_String - (This : in Statement; - Position : in Into_Position; - Index : in Vector_Index) - return String; - -not overriding -function Get_Into_Vector_Integer - (This : in Statement; - Position : in Into_Position; - Index : in Vector_Index) - return DB_Integer; - -not overriding -function Get_Into_Vector_Long_Long_Integer - (This : in Statement; - Position : in Into_Position; - Index : in Vector_Index) - return DB_Long_Long_Integer; - -not overriding -function Get_Into_Vector_Long_Float - (This : in Statement; - Position : in Into_Position; - Index : in Vector_Index) - return DB_Long_Float; - -not overriding -function Get_Into_Vector_Time - (This : in Statement; - Position : in Into_Position; - Index : in Vector_Index) - return Ada.Calendar.Time; -``` - -These functions allow to inspect the state and value of the vector use element identified by its position and index. If the state of the given element is `Data_Null`, the data-reading functions raise exceptions for that element. - -```ada --- Creation of single use elements. - -not overriding -procedure Use_String (This : in Statement; Name : in String); - -not overriding -procedure Use_Integer (This : in Statement; Name : in String); - -not overriding -procedure Use_Long_Long_Integer (This : in Statement; Name : in String); - -not overriding -procedure Use_Long_Float (This : in Statement; Name : in String); - -not overriding -procedure Use_Time (This : in Statement; Name : in String); -``` - -These functions instruct the library to create internal simple use elements of the relevant type, identified by the given `Name`. - -Note: - -* Simple use elements cannot be created together with vector use elements for the same statement. -* Vector use elements cannot be created together with any into elements for the same statement. - -```ada --- Creation of vector use elements. - -not overriding -procedure Use_Vector_String (This : in Statement; Name : in String); - -not overriding -procedure Use_Vector_Integer (This : in Statement; Name : in String); - -not overriding -procedure Use_Vector_Long_Long_Integer (This : in Statement; Name : in String); - -not overriding -procedure Use_Vector_Long_Float (This : in Statement; Name : in String); - -not overriding -procedure Use_Vector_Time (This : in Statement; Name : in String); -``` - -These functions instruct the library to create internal vector use elements of the relevant type, identified by the given `Name`. - -Note: - -* Simple use elements cannot be created together with vector use elements for the same statement. -* Vector use elements cannot be created together with any into elements for the same statement. - -```ada --- Modifiers for single use elements. - -not overriding -procedure Set_Use_State - (This : in Statement; - Name : in String; - State : in Data_State); - -not overriding -procedure Set_Use_String - (This : in Statement; - Name : in String; - Value : in String); - -not overriding -procedure Set_Use_Integer - (This : in Statement; - Name : in String; - Value : in DB_Integer); - -not overriding -procedure Set_Use_Long_Long_Integer - (This : in Statement; - Name : in String; - Value : in DB_Long_Long_Integer); - -not overriding -procedure Set_Use_Long_Float - (This : in Statement; - Name : in String; - Value : in DB_Long_Float); - -not overriding -procedure Set_Use_Time - (This : in Statement; - Name : in String; - Value : in Ada.Calendar.Time); -``` - -These operations allow to modify the state and value of simple use elements. Setting the value of use element automatically sets its state to `Data_Not_Null`. - -```ada --- Modifiers for vector use elements. - -not overriding -function Get_Use_Vectors_Size (This : in Statement) return Natural; - -not overriding -function Use_Vectors_First_Index (This : in Statement) return Vector_Index; - -not overriding -function Use_Vectors_Last_Index (This : in Statement) return Vector_Index; - -not overriding -procedure Use_Vectors_Resize (This : in Statement; New_Size : in Natural); -``` - -The `Get_Use_Vectors_Size` returns the number of entries in any of the vector use elements for the given statement. - -The `Use_Vectors_First_Index` returns the lowest index value for vector use elements (which is always `0`, even if the vectors are empty). The `Use_Vectors_Last_Index` returns the last index of use vectors, and raises the `CONSTRAINT_ERROR` exception if the vectors are empty. - -The `Use_Vectors_Resize` procedure allows to change the size of all use vectors for the given statement. - -```ada -not overriding -procedure Set_Use_Vector_State - (This : in Statement; - Name : in String; - Index : in Vector_Index; - State : in Data_State); - -not overriding -procedure Set_Use_Vector_String - (This : in Statement; - Name : in String; - Index : in Vector_Index; - Value : in String); - -not overriding -procedure Set_Use_Vector_Integer - (This : in Statement; - Name : in String; - Index : in Vector_Index; - Value : in DB_Integer); - -not overriding -procedure Set_Use_Vector_Long_Long_Integer - (This : in Statement; - Name : in String; - Index : in Vector_Index; - Value : in DB_Long_Long_Integer); - -not overriding -procedure Set_Use_Vector_Long_Float - (This : in Statement; - Name : in String; - Index : in Vector_Index; - Value : in DB_Long_Float); - -not overriding -procedure Set_Use_Vector_Time - (This : in Statement; - Name : in String; - Index : in Vector_Index; - Value : in Ada.Calendar.Time); -``` - -These operations allow to modify the state and value of vector use elements. Setting the value of use element automatically sets its state to `Data_Not_Null`. - -```ada --- Inspection of single use elements. --- --- Note: Use elements can be modified by the database if they --- are bound to out and inout parameters of stored procedures --- (although this is not supported by all database backends). --- This feature is available only for single use elements. - -not overriding -function Get_Use_State - (This : in Statement; - Name : in String) - return Data_State; - -not overriding -function Get_Use_String - (This : in Statement; - Name : in String) - return String; - -not overriding -function Get_Use_Integer - (This : in Statement; - Name : in String) - return DB_Integer; - -not overriding -function Get_Use_Long_Long_Integer - (This : in Statement; - Name : in String) - return DB_Long_Long_Integer; - -not overriding -function Get_Use_Long_Float - (This : in Statement; - Name : in String) - return DB_Long_Float; - -not overriding -function Get_Use_Time - (This : in Statement; - Name : in String) - return Ada.Calendar.Time; -``` - -These functions allow to inspect the state and value of the simple use element identified by its name. If the state of the given element is `Data_Null`, the data-reading functions raise exceptions for that element. diff --git a/src/soci/docs/languages/index.md b/src/soci/docs/languages/index.md deleted file mode 100644 index cf09638157..0000000000 --- a/src/soci/docs/languages/index.md +++ /dev/null @@ -1,3 +0,0 @@ -# Language bindings - -* [Ada](ada/index.md) diff --git a/src/soci/docs/license.md b/src/soci/docs/license.md deleted file mode 100644 index 18aef88a57..0000000000 --- a/src/soci/docs/license.md +++ /dev/null @@ -1,29 +0,0 @@ -# License - -The SOCI library is distributed under the terms of the [Boost Software License](http://www.boost.org/LICENSE_1_0.txt). - -## Boost Software License - -Version 1.0 - August 17th, 2003 - -Permission is hereby granted, free of charge, to any person or organization -obtaining a copy of the software and accompanying documentation covered by -this license (the "Software") to use, reproduce, display, distribute, -execute, and transmit the Software, and to prepare derivative works of the -Software, and to permit third-parties to whom the Software is furnished to -do so, all subject to the following: - -The copyright notices in the Software and this entire statement, including -the above license grant, this restriction and the following disclaimer, -must be included in all copies of the Software, in whole or in part, and -all derivative works of the Software, unless such copies or derivative -works are solely in the form of machine-executable object code generated by -a source language processor. - -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, TITLE AND NON-INFRINGEMENT. IN NO EVENT -SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE -FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/src/soci/docs/lobs.md b/src/soci/docs/lobs.md deleted file mode 100644 index a6273262c1..0000000000 --- a/src/soci/docs/lobs.md +++ /dev/null @@ -1,71 +0,0 @@ -# Large Objects (LOBs) - -## Binary (BLOBs) - -The SOCI library provides also an interface for basic operations on large objects (BLOBs - Binary Large OBjects). - - blob b(sql); // sql is a session object - sql << "select mp3 from mymusic where id = 123", into(b); - -The following functions are provided in the `blob` interface, mimicking the file-like operations: - -* `std::size_t get_len();` -* `std::size_t read_from_start(char * buf, std::size_t toRead, std::size_t offset = 0);` -* `std::size_t write_from_start(const char * buf, std::size_t toWrite, std::size_t offset = 0);` -* `std::size_t append(char const *buf, std::size_t toWrite);` -* `void trim(std::size_t newLen);` - -The `offset` parameter is always counted from the beginning of the BLOB's data. - -### Portability notes - -* The way to define BLOB table columns and create or destroy BLOB objects in the database varies between different database engines. - Please see the SQL documentation relevant for the given server to learn how this is actually done. The test programs provided with the SOCI library can be also a simple source of full working examples. -* The `trim` function is not currently available for the PostgreSQL backend. - -## Long strings and XML - -The SOCI library recognizes the fact that long string values are not handled portably and in some databases long string values need to be stored as a different data type. -Similar concerns relate to the use of XML values, which are essentially strings at the application level, but can be stored in special database-level field types. - -In order to facilitate handling of long strings and XML values the following wrapper types are defined: - - struct xml_type - { - std::string value; - }; - - struct long_string - { - std::string value; - }; - -Values of these wrapper types can be used with `into` and `use` elements with the database target type that is specifically intended to handle XML and long strings data types. - -For Oracle, these database-side types are, respectively: - -* `XMLType`, -* `CLOB` - -For PostgreSQL, these types are: - -* `XML` -* `text` - -For Firebird, there is no special XML support, but `BLOB SUB_TYPE TEXT` can be -used for storing it, as well as long strings. - -For ODBC backend, these types depend on the type of the database connected to. -In particularly important special case of Microsoft SQL Server, these types -are: - -* `xml` -* `text` - -When using ODBC backend to connect to a PostgreSQL database, please be aware -that by default PostgreSQL ODBC driver truncates all "unknown" types, such as -XML, to maximal varchar type size which is just 256 bytes and so is often -insufficient for XML values in practice. It is advised to set the -`UnknownsAsLongVarchar` connection option to 1 to avoid truncating XML strings -or use PostgreSQL ODBC driver 9.6.300 or later, which allows the backend to set -this option to 1 automatically on connection. diff --git a/src/soci/docs/logging.md b/src/soci/docs/logging.md deleted file mode 100644 index 31799efd0c..0000000000 --- a/src/soci/docs/logging.md +++ /dev/null @@ -1,26 +0,0 @@ -# Logging - -SOCI provides a very basic logging facility. - -The following members of the `session` class support the basic logging functionality: - -* `void set_log_stream(std::ostream * s);` -* `std::ostream * get_log_stream() const;` -* `std::string get_last_query() const;` - -The first two functions allow to set the user-provided output stream object for logging. -The `NULL` value, which is the default, means that there is no logging. - -An example use might be: - - session sql(oracle, "..."); - - ofstream file("my_log.txt"); - sql.set_log_stream(&file); - - // ... - -Each statement logs its query string before the preparation step (whether explicit or implicit) and therefore logging is effective whether the query succeeds or not. -Note that each prepared query is logged only once, independent on how many times it is executed. - -The `get_last_query` function allows to retrieve the last used query. diff --git a/src/soci/docs/multithreading.md b/src/soci/docs/multithreading.md deleted file mode 100644 index 7fcd51aed9..0000000000 --- a/src/soci/docs/multithreading.md +++ /dev/null @@ -1,47 +0,0 @@ -# Multithreading - -The general rule for multithreading is that SOCI classes are *not* thread-safe, meaning that their instances should not be used concurrently by multiple threads. - -The simplest solution for multithreaded code is to set up a separate `session` object for each thread that needs to inteact with the database. -Depending on the design of the client application this might be also the most straightforward approach. - -For some applications, however, it might be preferable to decouple the set of threads from the set of sessions, so that they can be optimized separately with different resources in mind. -The `connection_pool` class is provided for this purpose: - -```cpp -// phase 1: preparation - -const size_t poolSize = 10; -connection_pool pool(poolSize); - -for (size_t i = 0; i != poolSize; ++i) -{ - session & sql = pool.at(i); - - sql.open("postgresql://dbname=mydb"); -} - -// phase 2: usage from working threads - -{ - session sql(pool); - - sql << "select something from somewhere..."; - -} // session is returned to the pool automatically -``` - -The `connection_pool`'s constructor expects the size of the pool and internally creates an array of `session`s in the disconnected state. -Later, the `at` function provides *non-synchronized* access to each element of the array. -Note that this function is *not* thread-safe and exists only to make it easier to set up the pool in the initialization phase. - -Note that it is not obligatory to use the same connection parameters for all sessions in the pool, although this will be most likely the usual case. - -The working threads that need to *lease* a single session from the pool use the dedicated constructor of the `session` class - this constructor blocks until some session object becomes available in the pool and attaches to it, so that all further uses will be forwarded to the `session` object managed by the pool. -As long as the local `session` object exists, the associated session in the pool is *locked* and no other thread will gain access to it. -When the local `session` variable goes out of scope, the related entry in the pool's internal array is released, so that it can be used by other threads. -This way, the connection pool guarantees that its session objects are never used by more than one thread at a time. - -Note that the above scheme is the simplest way to use the connection pool, but it is also constraining in the fact that the `session`'s constructor can *block* waiting for the availability of some entry in the pool. -For more demanding users there are also low-level functions that allow to lease sessions from the pool with timeout on wait. -Please consult the [reference](reference.html) for details. diff --git a/src/soci/docs/procedures.md b/src/soci/docs/procedures.md deleted file mode 100644 index b7473b936d..0000000000 --- a/src/soci/docs/procedures.md +++ /dev/null @@ -1,20 +0,0 @@ -# Stored Procedures - -The `procedure` class provides a convenient mechanism for calling stored procedures: - -```cpp -sql << "create or replace procedure echo(output out varchar2," - "input in varchar2) as " - "begin output := input; end;"; - -std::string in("my message"); -std::string out; -procedure proc = (sql.prepare << "echo(:output, :input)", use(out, "output"), use(in, "input")); -proc.execute(true); -assert(out == "my message"); -``` - -## Portability note - -The above way of calling stored procedures is provided for portability of the code that might need it. -It is of course still possible to call procedures or functions using the syntax supported by the given database server. diff --git a/src/soci/docs/queries.md b/src/soci/docs/queries.md deleted file mode 100644 index 65f12d931a..0000000000 --- a/src/soci/docs/queries.md +++ /dev/null @@ -1,94 +0,0 @@ -# Queries - -## Simple SQL statements - -In many cases, the SQL query is intended to be executed only once, which means that statement parsing and execution can go together. The `session` class provides a special `once` member, which triggers parsing and execution of such one-time statements: - -```cpp -sql.once << "drop table persons"; -``` - -For shorter syntax, the following form is also allowed: - -```cpp -sql << "drop table persons"; -``` - -The IOStream-like interface is exactly what it looks like, so that the statement text can be composed of many parts, involving anything that is *streamable* (including custom classes, if they have appropriate `operator<<`): - -```cpp -string tableName = "persons"; -sql << "drop table " << tableName; - -int id = 123; -sql << "delete from companies where id = " << id; -``` - -## Query transformation - -In SOCI 3.2.0, query transformation mechanism was introduced. - -Query transformation is specified as user-defined unary function or callable function object with input parameter of type `std::string` which returns object of type `std::string` as well. - -The query transformation function is registered for current database session using dedicated `session::set_query_transformation` method. Then, the transformation function is called with query string as argument just before the query is sent to database backend for execution or for preparation. - -For one-time statements, query transformation is performed before each execution of statement. For prepared statements, query is transformed only once, before preparation, regardless how many times it is executed. - -A few short examples how to use query transformation: - -* defined as free function: - -```cpp -std::string less_than_ten(std::string query) -{ - return query + " WHERE price < 10"; -} - -session sql(postgresql, "dbname=mydb"); -sql.set_query_transformation(less_than_ten); -sql << "DELETE FROM item"; -``` - -* defined as function object: - -```cpp -struct order : std::unary_function -#include -#include -#include -#include - -using namespace soci; -using namespace std; - -bool get_name(string &name) { - cout << "Enter name: "; - return cin >> name; -} - -int main() -{ - try - { - session sql(oracle, "service=mydb user=john password=secret"); - - int count; - sql << "select count(*) from phonebook", into(count); - - cout << "We have " << count << " entries in the phonebook.\n"; - - string name; - while (get_name(name)) - { - string phone; - indicator ind; - sql << "select phone from phonebook where name = :name", - into(phone, ind), use(name); - - if (ind == i_ok) - { - cout << "The phone number is " << phone << '\n'; - } - else - { - cout << "There is no phone for " << name << '\n'; - } - } - } - catch (exception const &e) - { - cerr << "Error: " << e.what() << '\n'; - } -} -``` diff --git a/src/soci/docs/statements.md b/src/soci/docs/statements.md deleted file mode 100644 index c2b9f4181b..0000000000 --- a/src/soci/docs/statements.md +++ /dev/null @@ -1,249 +0,0 @@ -# Statements - -## Prepared statement - -Consider the following examples: - -```cpp -// Example 1. -for (int i = 0; i != 100; ++i) -{ - sql << "insert into numbers(value) values(" << i << ")"; -} - -// Example 2. -for (int i = 0; i != 100; ++i) -{ - sql << "insert into numbers(value) values(:val)", use(i); -} -``` - -Both examples will populate the table `numbers` with the values from `0` to `99`. - -The problem is that in both examples, not only the statement execution is repeated 100 times, but also the statement parsing and preparation. -This means unnecessary overhead, even if some of the database servers are likely to optimize the second case. -In fact, more complicated queries are likely to suffer in terms of lower performance, because finding the optimal execution plan is quite expensive and here it would be needlessly repeated. - -### Statement preparation - -The following example uses the class `statement` explicitly, by preparing the statement only once and repeating its execution with changing data (note the use of `prepare` member of `session` class): - -```cpp -int i; -statement st = (sql.prepare << - "insert into numbers(value) values(:val)", - use(i)); -for (i = 0; i != 100; ++i) -{ - st.execute(true); -} -``` - -The `true` parameter given to the `execute` method indicates that the actual data exchange is wanted, so that the meaning of the whole example is - -> "prepare the statement and exchange the data for each value of variable `i`". - -### Portability note: - -The above syntax is supported for all backends, even if some database server does not actually provide this functionality - in which case the library will internally execute the query in a single phase, without really separating the statement preparation from execution. - -For PostgreSQL servers older than 8.0 it is necessary to define the `SOCI_POSTGRESQL_NOPREPARE` macro while compiling the library to fall back to this one-phase behaviour. -Simply, pass `-DSOCI_POSTGRESQL_NOPREPARE=ON` variable to CMake. - -## Rowset and iterator - -The `rowset` class provides an alternative means of executing queries and accessing results using STL-like iterator interface. - -The `rowset_iterator` type is compatible with requirements defined for input iterator category and is available via `iterator` and `const_iterator` definitions in the `rowset` class. - -The `rowset` itself can be used only with select queries. - -The following example creates an instance of the `rowset` class and binds query results into elements of `int` type - in this query only one result column is expected. -After executing the query the code iterates through the query result using `rowset_iterator`: - -```cpp -rowset rs = (sql.prepare << "select values from numbers"); - -for (rowset::const_iterator it = rs.begin(); it != rs.end(); ++it) -{ - cout << *it << '\n'; -} -``` - -Another example shows how to retrieve more complex results, where `rowset` elements are of type `row` and therefore use [dynamic bindings](exchange.html#dynamic): - -```cpp -// person table has 4 columns - -rowset rs = (sql.prepare << "select id, firstname, lastname, gender from person"); - -// iteration through the resultset: -for (rowset::const_iterator it = rs.begin(); it != rs.end(); ++it) -{ - row const& row = *it; - - // dynamic data extraction from each row: - cout << "Id: " << row.get(0) << '\n' - << "Name: " << row.get(1) << " " << row.get(2) << '\n' - << "Gender: " << row.get(3) << endl; -} -``` - -The `rowset_iterator` can be used with standard algorithms as well: - -```cpp -rowset rs = (sql.prepare << "select firstname from person"); - -std::copy(rs.begin(), rs.end(), std::ostream_iterator(std::cout, "\n")); -``` - -Above, the query result contains a single column which is bound to `rowset` element of type of `std::string`. -All records are sent to standard output using the `std::copy` algorithm. - -## Bulk operations - -When using some databases, further performance improvements may be possible by having the underlying database API group operations together to reduce network roundtrips. -SOCI makes such bulk operations possible by supporting `std::vector` based types. - -The following example presents how to insert 100 records in 4 batches. -It is also important to note, that size of vector remains equal in every batch interaction. -This ensures vector is not reallocated and, what's crucial for the bulk trick, new data should be pushed to the vector before every call to `statement::execute`: - -```cpp -// Example 3. -void fill_ids(std::vector& ids) -{ - for (std::size_t i = 0; i < ids.size(); ++i) - ids[i] = i; // mimics source of a new ID -} - -const int BATCH_SIZE = 25; -std::vector ids(BATCH_SIZE); - -statement st = (sql.prepare << "insert into numbers(value) values(:val)", use(ids)); -for (int i = 0; i != 4; ++i) -{ - fill_ids(ids); - st.execute(true); -} -``` - -Given batch size is 25, this example should insert 4 x 25 = 100 records. - -(Of course, the size of the vector that will achieve optimum performance will vary, depending on many environmental factors, such as network speed.) - -It is also possible to read all the numbers written in the above examples: - -```cpp -int i; -statement st = (sql.prepare << "select value from numbers order by value", into(i)); -st.execute(); -while (st.fetch()) -{ - cout << i << '\n'; -} -``` - -In the above example, the `execute` method is called with the default parameter `false`. -This means that the statement should be executed, but the actual data exchange will be performed later. - -Further `fetch` calls perform the actual data retrieval and cursor traversal. -The *end-of-cursor* condition is indicated by the `fetch` function returning `false`. - -The above code example should be treated as an idiomatic way of reading many rows of data, *one at a time*. - -It is further possible to select records in batches into `std::vector` based types, with the size of the vector specifying the number of records to retrieve in each round trip: - -```cpp -std::vector valsOut(100); -sql << "select val from numbers", into(valsOut); -``` - -Above, the value `100` indicates that no more values should be retrieved, even if it would be otherwise possible. -If there are less rows than asked for, the vector will be appropriately down-sized. - -The `statement::execute()` and `statement::fetch()` functions can also be used to repeatedly select all rows returned by a query into a vector based type: - -```cpp -const int BATCH_SIZE = 30; -std::vector valsOut(BATCH_SIZE); -statement st = (sql.prepare << - "select value from numbers", - into(valsOut)); -st.execute(); -while (st.fetch()) -{ - std::vector::iterator pos; - for(pos = valsOut.begin(); pos != valsOut.end(); ++pos) - { - cout << *pos << '\n'; - } - - valsOut.resize(BATCH_SIZE); -} -``` - -Assuming there are 100 rows returned by the query, the above code will retrieve and print all of them. -Since the output vector was created with size 30, it will take (at least) 4 calls to `fetch()` to retrieve all 100 values. -Each call to `fetch()` can potentially resize the vector to a size less than its initial size - how often this happens depends on the underlying database implementation. -This explains why the `resize(BATCH_SIZE)` operation is needed - it is there to ensure that each time the `fetch()` is called, the vector is ready to accept the next bunch of values. -Without this operation, the vector *might* be getting smaller with subsequent iterations of the loop, forcing more iterations to be performed (because *all* rows will be read anyway), than really needed. - -Note the following details about the above examples: - -* After performing `fetch()`, the vector's size might be *less* than requested, but `fetch()` returning true means that there was *at least one* row retrieved. -* It is forbidden to manually resize the vector to the size *higher* than it was initially (this can cause the vector to reallocate its internal buffer and the library can lose track of it). - -Taking these points under consideration, the above code example should be treated as an idiomatic way of reading many rows by bunches of requested size. - -### Portability note - -Actually, all supported backends guarantee that the requested number of rows will be read with each fetch and that the vector will never be down-sized, unless for the last fetch, when the end of rowset condition is met. -This means that the manual vector resizing is in practice not needed - the vector will keep its size until the end of rowset. -The above idiom, however, is provided with future backends in mind, where the constant size of the vector might be too expensive to guarantee and where allowing `fetch` to down-size the vector even before reaching the end of rowset might buy some performance gains. - -## Statement caching - -Some backends have some facilities to improve statement parsing and compilation to limit overhead when creating commonly used query. -But for backends that does not support this kind optimization you can keep prepared statement and use it later with new references. -To do such, prepare a statement as usual, you have to use `exchange` to bind new variables to statement object, then `execute` statement and finish by cleaning bound references with `bind_clean_up`. - -```cpp -sql << "CREATE TABLE test(a INTEGER)"; - -{ - // prepare statement - soci::statement stmt = (db.prepare << "INSERT INTO numbers(value) VALUES(:val)"); - - { - // first insert - int a0 = 0; - - // update reference - stmt.exchange(soci::use(a0)); - - stmt.define_and_bind(); - stmt.execute(true); - stmt.bind_clean_up(); - } - - { - // come later, second insert - int a1 = 1; - - // update reference - stmt.exchange(soci::use(a1)); - - stmt.define_and_bind(); - stmt.execute(true); - stmt.bind_clean_up(); - } -} - -{ - std::vector v(10); - db << "SELECT value FROM numbers", soci::into(v); - for (int i = 0; i < v.size(); ++i) - std::cout << "value " << i << ": " << v[i] << std::endl; -} -``` diff --git a/src/soci/docs/structure.md b/src/soci/docs/structure.md deleted file mode 100644 index b1f5bf4537..0000000000 --- a/src/soci/docs/structure.md +++ /dev/null @@ -1,27 +0,0 @@ -# Structure - -The picture below presents the structure of the library, together with its clients and servers. -The boxes filled with cyan represent components that are part of the library distribution. - -![Structure Chart](images/structure.png) - -The SOCI library is extensible in the following ways: - -* More backends can be added to target various database servers. -* More interfaces can be defined on top of common backend interface. -* Other languages can use the [simple interface](interfaces.md), which was designed specifically for the "C" calling convention to ensure easy binding. - -The core part of the library and the backend interface definition are placed in the `core` directory of the library distribution. The `soci-backend.h` file is an internal abstract interface to the actual backends, which are needed to perform operations on the given database server. Normally, the C++ client program needs to interface with the `soci.h` header and the header(s) relevant to the given backend(s) (for example, `soci-oracle.h`), although with dynamic backend loading this can be avoided. It is possible for the same program to use many backends at the same time. - -Everything in SOCI is declared in the namespace `soci`. All code examples presented in this documentation assume that your code begins with something like: - -```cpp -#include "soci.h" -// other includes if necessary - -using namespace soci; - -// ... -``` - -Note: In simple programs, `#include` for the relevant backend is needed only in the file where the `session` object is created with explicit name of the backend factory. The example program on the [previous page](index.html) shows the appropriate `#include` directive for the Oracle backend. It is also possible to name backends at run-time as part of the connection string, in which case no backend-specific `#include` directive is necessary. diff --git a/src/soci/docs/transactions.md b/src/soci/docs/transactions.md deleted file mode 100644 index fc250859ec..0000000000 --- a/src/soci/docs/transactions.md +++ /dev/null @@ -1,45 +0,0 @@ -# Transactions - -The SOCI library provides the following members of the `session` class for transaction management: - -* `void begin();` -* `void commit();` -* `void rollback();` - -In addition to the above there is a RAII wrapper that allows to associate the transaction with the given scope of code: - -```cpp -class transaction -{ -public: - explicit transaction(session & sql); - - ~transaction(); - - void commit(); - void rollback(); - -private: - // ... -}; -``` - -The object of class `transaction` will roll back automatically when the object is destroyed -(usually as a result of leaving the scope) *and* when the transaction was not explicitly committed before that. - -A typical usage pattern for this class might be: - -```cpp -{ - transaction tr(sql); - - sql << "insert into ..."; - sql << "more sql queries ..."; - // ... - - tr.commit(); -} -``` - -With the above pattern the transaction is committed only when the code successfully reaches the end of block. -If some exception is thrown before that, the scope will be left without reaching the final statement and the transaction object will automatically roll back in its destructor. diff --git a/src/soci/docs/types.md b/src/soci/docs/types.md deleted file mode 100644 index 3308b94f4b..0000000000 --- a/src/soci/docs/types.md +++ /dev/null @@ -1,292 +0,0 @@ -# Data Types - -## Static binding - -The static binding for types is most useful when the types used in the database are known at compile time - this was already presented above with the help of `into` and `use` functions. - -The following types are currently supported for use with `into` and `use` expressions: - -* `char` (for character values) -* `short`, `int`, `unsigned long`, `long long`, `double` (for numeric values) -* `std::string` (for string values) -* `std::tm``` (for datetime values) -* `soci::statement` (for nested statements and PL/SQL cursors) -* `soci::blob` (for Binary Large OBjects) -* `soci::row_id` (for row identifiers) - -See the test code that accompanies the library to see how each of these types is used. - -### Static binding for bulk operations - -Bulk inserts, updates, and selects are supported through the following `std::vector` based into and use types: - -* `std::vector` -* `std::vector` -* `std::vector` -* `std::vector` -* `std::vector` -* `std::vector` -* `std::vector` -* `std::vector` - -Use of the vector based types mirrors that of the standard types, with the size of the vector used to specify the number of records to process at a time. -See below for examples. - -Bulk operations are supported also for `std::vector`s of the user-provided types that have appropriate conversion routines defines. - -## Dynamic binding - -For certain applications it is desirable to be able to select data from arbitrarily structured tables (e.g. via "`select * from ...`") and format the resulting data based upon its type. - -SOCI supports binding dynamic resultset through the `soci::row` and `soci::column_properties` classes. - -Data is selected into a `row` object, which holds `column_properties` objects describing the attributes of data contained in each column. -Once the data type for each column is known, the data can be formatted appropriately. - -For example, the code below creates an XML document from a selected row of data from an arbitrary table: - -```cpp -row r; -sql << "select * from some_table", into(r); - -std::ostringstream doc; -doc << "" << std::endl; -for(std::size_t i = 0; i != r.size(); ++i) -{ - const column_properties & props = r.get_properties(i); - - doc << '<' << props.get_name() << '>'; - - switch(props.get_data_type()) - { - case dt_string: - doc << r.get(i); - break; - case dt_double: - doc << r.get(i); - break; - case dt_integer: - doc << r.get(i); - break; - case dt_long_long: - doc << r.get(i); - break; - case dt_unsigned_long_long: - doc << r.get(i); - break; - case dt_date: - std::tm when = r.get(i); - doc << asctime(&when); - break; - } - - doc << "' << std::endl; -} -doc << ""; -``` - -The type `T` parameter that should be passed to `row::get()` depends on the SOCI data type that is returned from `column_properties::get_data_type()`. - -`row::get()` throws an exception of type `std::bad_cast` if an incorrect type `T` is requested. - -| SOCI Data Type | `row::get` specialization | -|----------------|------------------------------| -| `dt_double` | `double` | -| `dt_integer` | `int` | -| `dt_long_long` | `long long` | -| `dt_unsigned_long_long` | `unsigned long long`| -| `dt_string` | `std::string` | -| `dt_date` | `std::tm` | - -The mapping of underlying database column types to SOCI datatypes is database specific. -See the [backend documentation](backends/index.html) for details. - -The `row` also provides access to indicators for each column: - -```cpp -row r; -sql << "select name from some_table where id = 1", into(r); -if (r.get_indicator(0) != soci::i_null) -{ - std::cout << r.get(0); -} -``` - -It is also possible to extract data from the `row` object using its stream-like interface, where each extracted variable should have matching type respective to its position in the chain: - -```cpp -row r; -sql << "select name, address, age from persons where id = 123", into(r); - -string name, address; -int age; - -r >> name >> address >> age; -``` - -Note, however, that this interface is *not* compatible with the standard `std::istream` class and that it is only possible to extract a single row at a time - for "safety" reasons the row boundary is preserved and it is necessary to perform the `fetch` operation explicitly for each consecutive row. - -## User-defined C++ types - -SOCI can be easily extended with support for user-defined datatypes. - -The extension mechanism relies on appropriate specialization of the `type_conversion` structure that converts to and from one of the following SOCI base types: - -* `double` -* `int` -* `long long` -* `unsigned long long` -* `std::string` -* `char` -* `std::tm` - -There are three required class members for a valid `type_conversion` specialization: - -* the `base_type` type definition, aliasing either one of the base types *or another ser-defined type* -* the `from_base()` static member function, converting from the base type -* the `to_base()` static member function, converting to the base type - -Note that no database-specific code is required to define user conversion. - -The following example shows how the user can extend SOCI to support his own type `MyInt`, which here is some wrapper for the fundamental `int` type: - -```cpp -class MyInt -{ -public: - MyInt() {} - MyInt(int i) : i_(i) {} - - void set(int i) { i_ = i; } - int get() const { return i_; } - -private: - int i_; -}; - -namespace soci -{ - template << - struct type_conversion - { - typedef int base_type; - - static void from_base(int i, indicator ind, MyInt & mi) - { - if (ind == i_null) - { - throw soci_error("Null value not allowed for this type"); - } - - mi.set(i); - } - - static void to_base(const MyInt & mi, int & i, indicator & ind) - { - i = mi.get(); - ind = i_ok; - } - }; -} -``` - -The above specialization for `soci::type_conversion` is enough to enable the following: - -```cpp -MyInt i; - -sql << "select count(*) from person", into(i); - -cout << "We have " << i.get() << " persons in the database.\n"; -``` - -Note that there is a number of types from the Boost library integrated with SOCI out of the box, see [Integration with Boost](boost.html) for complete description. Use these as examples of conversions for more complext data types. - -Another possibility to extend SOCI with custom data types is to use the `into_type - struct type_conversion - { - typedef values base_type; - - static void from_base(values const & v, indicator /* ind */, Person & p) - { - p.id = v.get("ID"); - p.firstName = v.get("FIRST_NAME"); - p.lastName = v.get("LAST_NAME"); - - // p.gender will be set to the default value "unknown" - // when the column is null: - p.gender = v.get("GENDER", "unknown"); - - // alternatively, the indicator can be tested directly: - // if (v.indicator("GENDER") == i_null) - // { - // p.gender = "unknown"; - // } - // else - // { - // p.gender = v.get("GENDER"); - // } - } - - static void to_base(const Person & p, values & v, indicator & ind) - { - v.set("ID", p.id); - v.set("FIRST_NAME", p.firstName); - v.set("LAST_NAME", p.lastName); - v.set("GENDER", p.gender, p.gender.empty() ? i_null : i_ok); - ind = i_ok; - } - }; -} -``` - -With the above `type_conversion` specialization in place, it is possible to use `Person` directly with SOCI: - -```cpp -session sql(oracle, "service=db1 user=scott password=tiger"); - -Person p; -p.id = 1; -p.lastName = "Smith"; -p.firstName = "Pat"; -sql << "insert into person(id, first_name, last_name) " - "values(:ID, :FIRST_NAME, :LAST_NAME)", use(p); - -Person p1; -sql << "select * from person", into(p1); -assert(p1.id == 1); -assert(p1.firstName + p.lastName == "PatSmith"); -assert(p1.gender == "unknown"); - -p.firstName = "Patricia"; -sql << "update person set first_name = :FIRST_NAME " - "where id = :ID", use(p); -``` - -Note: The `values` class is currently not suited for use outside of `type_conversion`specializations. -It is specially designed to facilitate object-relational mapping when used as shown above. diff --git a/src/soci/docs/utilities.md b/src/soci/docs/utilities.md deleted file mode 100644 index 110f0e19b1..0000000000 --- a/src/soci/docs/utilities.md +++ /dev/null @@ -1,151 +0,0 @@ -# Utilities - -SOCI provides a portable abstraction for selection of database queries. - -## DDL - -SOCI supports some basic methods to construct portable DDL queries. That is, instead of writing explicit SQL statement for creating or modifying tables, it is possible to use dedicated SOCI functions, which prepare appropriate DDL statements behind the scenes, thus enabling the user application to create basic database structures in a way that is portable across different database servers. Note that the actual support for these functions depends on the actual backend implementation. - -It is possible to create a new table in a single statement: - -```cpp -sql.create_table("t1").column("i", soci::dt_integer).column("j", soci::dt_integer); -``` - -Above, table "t1" will be created with two columns ("i", "j") of type integer. - -It is also possible to build similar statements piece by piece, which is useful if the table structure is computed dynamically: - -```cpp -{ - soci::ddl_type ddl = sql.create_table("t2"); - ddl.column("i", soci::dt_integer); - ddl.column("j", soci::dt_integer); - ddl.column("k", soci::dt_integer)("not null"); - ddl.primary_key("t2_pk", "j"); -} -``` - -The actual statement is executed at the end of above block, when the ddl object goes out of scope. The "not null" constraint was added to the definition of column "k" explicitly and in fact any piece of SQL can be inserted this way - with the obvious caveat of having limited portability (the "not null" piece seems to be universaly portable). - -Columns can be added to and dropped from already existing tables as well: - -```cpp -sql.add_column("t1", "k", soci::dt_integer); -// or with constraint: -//sql.add_column("t1", "k", soci::dt_integer)("not null"); - -sql.drop_column("t1", "i"); -``` - -If needed, precision and scale can be defined with additional integer arguments to functions that create columns: - -```cpp -sql.add_column("t1", "s", soci::dt_string, precision); -sql.add_column("t1", "d", soci::dt_double, precision, scale); -``` - -Tables with foreign keys to each other can be also created: - -```cpp -{ - soci::ddl_type ddl = sql.create_table("t3"); - ddl.column("x", soci::dt_integer); - ddl.column("y", soci::dt_integer); - ddl.foreign_key("t3_fk", "x", "t2", "j"); -} -``` - -Tables can be dropped, too: - -```cpp -sql.drop_table("t1"); -sql.drop_table("t3"); -sql.drop_table("t2"); -``` - -Note that due to the differences in the set of types that are actually supported on the target database server, the type mappings, as well as precision and scales, might be different, even in the way that makes them impossible to portably recover with metadata queries. - -In the category of portability utilities, the following functions are also available: - -```cpp -sql.empty_blob() -``` - -the above call returns the string containing expression that represents an empty BLOB value in the given target backend. This expression can be used as part of a bigger SQL statement, for example: - -```cpp -sql << "insert into my_table (x) values (" + sql.empty_blob() + ")"; -``` - -and: - -```cpp -sql.nvl() -``` - -the above call returns the string containing the name of the SQL function that implements the NVL or COALESCE operation in the given target backend, for example: - -```cpp -sql << "select name, " + sql.nvl() + "(phone, \'UNKNOWN\') from phone_book"; -``` - -Note: `empty_blob` and `nvl` are implemented in Oracle, PostgreSQL and SQLite3 backends; for other backends their behaviour is as for PostgreSQL. - -## DML - -Only two related functions are currently available in this category: -`get_dummy_from_clause()` can be used to construct select statements that don't -operate on any table in a portable way, as while some databases allow simply -omitting the from clause in this case, others -- e.g. Oracle -- still require -providing some syntactically valid from clause even if it is not used. To use -this function, simply append the result of this function to the statement: - -```cpp -double databasePi; -session << ("select 4*atan(1)" + session.get_dummy_from_clause()), - into(databasePi); -``` - -If just the name of the dummy table is needed, and not the full clause, you can -use `get_dummy_from_table()` to obtain it. - -Notice that both functions require the session to be connected as their result -depends on the database it is connected to. - -## Database Metadata - -It is possible to portably query the database server to obtain basic metadata information. - -In order to get the list of table names in the current schema: - -```cpp -std::vector names(100); -sql.get_table_names(), into(names); -``` - -alternatively: - -```cpp -std::string name; -soci::statement st = (sql.prepare_table_names(), into(name)); - -st.execute(); -while (st.fetch()) -{ - // ... -} -``` - -Similarly, to get the description of all columns in the given table: - -```cpp -soci::column_info ci; -soci::statement st = (sql.prepare_column_descriptions(table_name), into(ci)); - -st.execute(); -while (st.fetch()) -{ - // ci fields describe each column in turn -} -``` diff --git a/src/soci/docs/vagrant.md b/src/soci/docs/vagrant.md deleted file mode 100644 index b933b11021..0000000000 --- a/src/soci/docs/vagrant.md +++ /dev/null @@ -1,125 +0,0 @@ -# Vagrant SOCI - -[Vagrant](https://www.vagrantup.com/) used to build and provision -virtual environments for **hassle-free** SOCI development. - -## Features - -* Ubuntu 14.04 (Trusty) virtual machine -* Multi-machine set-up with three VMs: `soci`, `oracle`, `db2`. -* Support networking between the configured machines. -* `soci.vm`: - * hostname: `vmsoci.local` - * build essentials - * core dependencies - * backend dependencies - * FOSS databases installed with sample `soci` user and instance pre-configured - * during provision, automatically clones and builds SOCI from `master` branch. -* `db2.vm`: - * hostname: `vmdb2.local` - * IBM DB2 Express-C 9.7 installed from [archive.canonical.com](http://archive.canonical.com) packages. -* `oracle.vm`: - * *TODO*: provision with Oracle XE -* SOCI local git repository (aka `$SOCI_HOME`) is automatically shared on host - and all guest machines. - -## Prerequisites - -* Speedy broadband, time and coffee. -* Recommended 4GB or much more RAM (tested with 16GB only). - -### SOCI DB2 backend - -The `soci.vm` will be configured properly to build the DB2 backend only if -it is provisioned with complete DB2 CLI client (libraries and headers). -You need to download "IBM Data Server Driver Package (DS Driver)" manually -and make it visible to Vagrant: - -1. Go to [IBM Data Server Client Packages](http://www-01.ibm.com/support/docview.wss?uid=swg21385217). -2. Download "IBM Data Server Driver Package (DS Driver)". -3. Copy the package to `${SOCI_HOME}/tmp` directory, on host machine. - -## Usage - -Below, simple and easy development workflow with Vagrant is outlined: - -* [Boot](https://docs.vagrantup.com/v2/getting-started/up.html) - -```console -vagrant up -``` - -or boot VMs selectively: - -```console -vagrant up {soci|db2} -``` - -First time you run it, be patient as Vagrant downloads VM box and -provisions it installing all the necessary packages. - -* You can SSH into the machine - -```console -vagrant ssh {soci|db2} -``` - -* Run git commands can either from host or VM `soci` (once connected via SSH) - -```console -cd /vagrant # aka $SOCI_HOME -git pull origin master -``` - -* You can edit source code on both, on host or VM `soci`. -* For example, edit in your favourite editor on host machine, then build, run, test and debug on guest machine from command line. -* Alternatively, edit and build on host machine using your favourite IDE, then test and debug connecting to DBs on guest machines via network. - -* Build on VM `soci` - -```console -vagrant ssh soci -cd /vagrant # aka $SOCI_HOME -cd soci-build # aka $SOCI_BUILD -make -``` - -You can also execute the `build.h` script provided to run CMake and make - -```console -vagrant ssh soci -cd $SOCI_BUILD -/vagrant/scripts/vagrant/build.sh -``` - -* Debug, only on VM `soci`, for example, with gdb or remotely Visual Studio 2017. - -* [Teardown](https://docs.vagrantup.com/v2/getting-started/teardown.html) - -```console -vagrant {suspend|halt|destroy} {soci|db2} -``` - -Check Vagrant [command-line interface](https://docs.vagrantup.com/v2/cli/index.html) for complete list of commands. - -### Environment variables - -All variables available to the `vagrant` user on the VMs are defined in and sourced from `/vagrant/scripts/vagrant/common.env`: - -* `SOCI_HOME` where SOCI master is cloned (`/vagrant` on VM `soci`) -* `SOCI_BUILD` where CMake generates build configuration (`/home/vagrant/soci-build` on VM `soci`) -* `SOCI_HOST` network accessible VM `soci` hostname (`ping vmsoci.local`) -* `SOCI_USER` default database user and database name -* `SOCI_PASS` default database password for both, `SOCI_USER` and root/sysdba - of particular database. -* `SOCI_DB2_HOST` network accessible VM `db2` hostname (`ping vmdb2.local`) -* `SOCI_DB2_USER` admin username to DB2 instance. -* `SOCI_DB2_USER` admin password to DB2 instance. - -Note, those variables are also used by provision scripts to set up databases. - -## Troubleshooting - -* Analyze `vagrant up` output. -* On Windows, prefer `vagrant ssh` from inside MinGW Shell where `ssh.exe` is available or learn how to use Vagrant with PuTTY. -* If you modify any of `scripts/vagrant/*.sh` scripts, **ensure** they have unified end-of-line characters to `LF` only. Otherwise, provisioning steps may fail. diff --git a/src/soci/include/private/README.md b/src/soci/include/private/README.md deleted file mode 100644 index 7d46ec5872..0000000000 --- a/src/soci/include/private/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# soci/include/private - -Private headers do not define any parts of public interface, -are not installed in user's filesystem. -Private headers only define common features used internally. diff --git a/src/soci/include/private/firebird/common.h b/src/soci/include/private/firebird/common.h deleted file mode 100644 index 636090724d..0000000000 --- a/src/soci/include/private/firebird/common.h +++ /dev/null @@ -1,271 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, Rafal Bobrowski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_FIREBIRD_COMMON_H_INCLUDED -#define SOCI_FIREBIRD_COMMON_H_INCLUDED - -#include "soci/firebird/soci-firebird.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace soci -{ - -namespace details -{ - -namespace firebird -{ - -char * allocBuffer(XSQLVAR* var); - -void tmEncode(short type, std::tm * src, void * dst); - -void tmDecode(short type, void * src, std::tm * dst); - -void setTextParam(char const * s, std::size_t size, char * buf_, - XSQLVAR * var); - -std::string getTextParam(XSQLVAR const *var); - -template -const char *str2dec(const char * s, IntType &out, short &scale) -{ - int sign = 1; - if ('+' == *s) - ++s; - else if ('-' == *s) - { - sign = -1; - ++s; - } - scale = 0; - bool period = false; - IntType res = 0; - for (out = 0; *s; ++s, out = res) - { - if (*s == '.') - { - if (period) - return s; - period = true; - continue; - } - int d = *s - '0'; - if (d < 0 || d > 9) - return s; - res = res * 10 + static_cast(d * sign); - if (1 == sign) - { - if (res < out) - return s; - } - else - { - if (res > out) - return s; - } - if (period) - ++scale; - } - return s; -} - -template -inline -T round_for_isc(T value) -{ - return value; -} - -inline -double round_for_isc(double value) -{ - // Unfortunately all the rounding functions are C99 and so are not supported - // by MSVC, so do it manually. - return value < 0 ? value - 0.5 : value + 0.5; -} - -//helper template to generate proper code based on compile time type check -template struct cond_to_isc {}; -template<> struct cond_to_isc -{ - static void checkInteger(short scale, short type) - { - if( scale >= 0 && (type == SQL_SHORT || type == SQL_LONG || type == SQL_INT64) ) - throw soci_error("Can't convert non-integral value to integral column type"); - } -}; -template<> struct cond_to_isc -{ - static void checkInteger(short scale,short type) { SOCI_UNUSED(scale) SOCI_UNUSED(type) } -}; - -template -void to_isc(void * val, XSQLVAR * var, short x_scale = 0) -{ - T1 value = *reinterpret_cast(val); - short scale = var->sqlscale + x_scale; - short type = var->sqltype & ~1; - long long divisor = 1, multiplier = 1; - - cond_to_isc::is_integer>::checkInteger(scale,type); - - for (int i = 0; i > scale; --i) - multiplier *= 10; - for (int i = 0; i < scale; ++i) - divisor *= 10; - - switch (type) - { - case SQL_SHORT: - { - short tmp = static_cast(round_for_isc(value*multiplier)/divisor); - std::memcpy(var->sqldata, &tmp, sizeof(short)); - } - break; - case SQL_LONG: - { - int tmp = static_cast(round_for_isc(value*multiplier)/divisor); - std::memcpy(var->sqldata, &tmp, sizeof(int)); - } - break; - case SQL_INT64: - { - long long tmp = static_cast(round_for_isc(value*multiplier)/divisor); - std::memcpy(var->sqldata, &tmp, sizeof(long long)); - } - break; - case SQL_FLOAT: - { - float sql_value = static_cast(value); - std::memcpy(var->sqldata, &sql_value, sizeof(float)); - } - break; - case SQL_DOUBLE: - { - double sql_value = static_cast(value); - std::memcpy(var->sqldata, &sql_value, sizeof(double)); - } - break; - default: - throw soci_error("Incorrect data type for numeric conversion"); - } -} - -template -void parse_decimal(void * val, XSQLVAR * var, const char * s) -{ - short scale; - UIntType t1; - IntType t2; - if (!*str2dec(s, t1, scale)) - std::memcpy(val, &t1, sizeof(t1)); - else if (!*str2dec(s, t2, scale)) - std::memcpy(val, &t2, sizeof(t2)); - else - throw soci_error("Could not parse decimal value."); - to_isc(val, var, scale); -} - -template -std::string format_decimal(const void *sqldata, int sqlscale) -{ - IntType x = *reinterpret_cast(sqldata); - std::stringstream out; - out << x; - std::string r = out.str(); - if (sqlscale < 0) - { - if (static_cast(r.size()) - (x < 0) <= -sqlscale) - { - r = std::string(size_t(x < 0), '-') + - std::string(-sqlscale - (r.size() - (x < 0)) + 1, '0') + - r.substr(size_t(x < 0), std::string::npos); - } - return r.substr(0, r.size() + sqlscale) + '.' + - r.substr(r.size() + sqlscale, std::string::npos); - } - return r + std::string(sqlscale, '0'); -} - - -template struct cond_from_isc {}; -template<> struct cond_from_isc { - static void checkInteger(short scale) - { - std::ostringstream msg; - msg << "Can't convert value with scale " << -scale - << " to integral type"; - throw soci_error(msg.str()); - } -}; -template<> struct cond_from_isc -{ - static void checkInteger(short scale) { SOCI_UNUSED(scale) } -}; - -template -T1 from_isc(XSQLVAR * var) -{ - short scale = var->sqlscale; - T1 tens = 1; - - if (scale < 0) - { - cond_from_isc::is_integer>::checkInteger(scale); - for (int i = 0; i > scale; --i) - { - tens *= 10; - } - } - - switch (var->sqltype & ~1) - { - case SQL_SHORT: - return static_cast(*reinterpret_cast(var->sqldata)/tens); - case SQL_LONG: - return static_cast(*reinterpret_cast(var->sqldata)/tens); - case SQL_INT64: - return static_cast(*reinterpret_cast(var->sqldata)/tens); - case SQL_FLOAT: - return static_cast(*reinterpret_cast(var->sqldata)); - case SQL_DOUBLE: - return static_cast(*reinterpret_cast(var->sqldata)); - default: - throw soci_error("Incorrect data type for numeric conversion"); - } -} - -template -std::size_t getVectorSize(void *p) -{ - std::vector *v = static_cast *>(p); - return v->size(); -} - -template -void resizeVector(void *p, std::size_t sz) -{ - std::vector *v = static_cast *>(p); - v->resize(sz); -} - -} // namespace firebird - -} // namespace details - -} // namespace soci - -#endif // SOCI_FIREBIRD_COMMON_H_INCLUDED diff --git a/src/soci/include/private/firebird/error-firebird.h b/src/soci/include/private/firebird/error-firebird.h deleted file mode 100644 index b793d83a2e..0000000000 --- a/src/soci/include/private/firebird/error-firebird.h +++ /dev/null @@ -1,35 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, Rafal Bobrowski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_FIREBIRD_ERROR_H_INCLUDED -#define SOCI_FIREBIRD_ERROR_H_INCLUDED - -#include "soci/firebird/soci-firebird.h" -#include - -namespace soci -{ - -namespace details -{ - -namespace firebird -{ - -void SOCI_FIREBIRD_DECL get_iscerror_details(ISC_STATUS * status_vector, std::string &msg); - -bool SOCI_FIREBIRD_DECL check_iscerror(ISC_STATUS const * status_vector, long errNum); - -void SOCI_FIREBIRD_DECL throw_iscerror(ISC_STATUS * status_vector); - -} // namespace firebird - -} // namespace details - -} // namespace soci - -#endif // SOCI_FIREBIRD_ERROR_H_INCLUDED diff --git a/src/soci/include/private/soci-compiler.h b/src/soci/include/private/soci-compiler.h deleted file mode 100644 index 42e52b5903..0000000000 --- a/src/soci/include/private/soci-compiler.h +++ /dev/null @@ -1,39 +0,0 @@ -// -// Copyright (C) 2015 Vadim Zeitlin -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_PRIVATE_SOCI_COMPILER_H_INCLUDED -#define SOCI_PRIVATE_SOCI_COMPILER_H_INCLUDED - -#include "soci-cpp.h" - -// CHECK_GCC(major,minor) evaluates to 1 when using g++ of at least this -// version or 0 when using g++ of lesser version or not using g++ at all. -#if defined(__GNUC__) && defined(__GNUC_MINOR__) -# define CHECK_GCC(major, minor) \ - ((__GNUC__ > (major)) \ - || (__GNUC__ == (major) && __GNUC_MINOR__ >= (minor))) -#else -# define CHECK_GCC(major, minor) 0 -#endif - -// GCC_WARNING_{SUPPRESS,RESTORE} macros can be used to bracket the code -// producing a specific warning to disable it. -// -// They only work with g++ 4.6+ or clang, warnings are not disabled for earlier -// g++ versions. -#if defined(__clang__) || CHECK_GCC(4, 6) -# define GCC_WARNING_SUPPRESS(x) \ - _Pragma (SOCI_STRINGIZE(GCC diagnostic push)) \ - _Pragma (SOCI_STRINGIZE(GCC diagnostic ignored SOCI_STRINGIZE(SOCI_CONCAT(-W,x)))) -# define GCC_WARNING_RESTORE(x) \ - _Pragma (SOCI_STRINGIZE(GCC diagnostic pop)) -#else /* gcc < 4.6 or not gcc and not clang at all */ -# define GCC_WARNING_SUPPRESS(x) -# define GCC_WARNING_RESTORE(x) -#endif - -#endif // SOCI_PRIVATE_SOCI_COMPILER_H_INCLUDED diff --git a/src/soci/include/private/soci-cpp.h b/src/soci/include/private/soci-cpp.h deleted file mode 100644 index 71121247a7..0000000000 --- a/src/soci/include/private/soci-cpp.h +++ /dev/null @@ -1,30 +0,0 @@ -// -// Copyright (C) 2015 Vadim Zeitlin -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_PRIVATE_SOCI_CPP_H_INCLUDED -#define SOCI_PRIVATE_SOCI_CPP_H_INCLUDED - -// Some very common preprocessor helpers. - -// SOCI_CONCAT() pastes together two tokens after expanding them. -#define SOCI_CONCAT_IMPL(x, y) x ## y -#define SOCI_CONCAT(x, y) SOCI_CONCAT_IMPL(x, y) - -// SOCI_STRINGIZE() makes a string of its argument after expanding it. -#define SOCI_STRINGIZE_IMPL(x) #x -#define SOCI_STRINGIZE(x) SOCI_STRINGIZE_IMPL(x) - -// SOCI_MAKE_UNIQUE_NAME() creates a uniquely named identifier with the given -// prefix. -// -// It uses __COUNTER__ macro to avoid problems with broken __LINE__ in MSVC -// when using "Edit and Continue" (/ZI) option as there are no compilers known -// to work with SOCI and not support it. If one such is ever discovered, we -// should use __LINE__ for it instead. -#define SOCI_MAKE_UNIQUE_NAME(name) SOCI_CONCAT(name, __COUNTER__) - -#endif // SOCI_PRIVATE_SOCI_CPP_H_INCLUDED diff --git a/src/soci/include/private/soci-cstrtod.h b/src/soci/include/private/soci-cstrtod.h deleted file mode 100644 index 63b88f2baf..0000000000 --- a/src/soci/include/private/soci-cstrtod.h +++ /dev/null @@ -1,80 +0,0 @@ -// -// Copyright (C) 2014 Vadim Zeitlin. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_PRIVATE_SOCI_CSTRTOD_H_INCLUDED -#define SOCI_PRIVATE_SOCI_CSTRTOD_H_INCLUDED - -#include "soci/error.h" - -#include -#include - -namespace soci -{ - -namespace details -{ - -// Locale-independent, i.e. always using "C" locale, function for converting -// strings to numbers. -// -// The string must contain a floating point number in "C" locale, i.e. using -// point as decimal separator, and nothing but it. If it does, the converted -// number is returned, otherwise an exception is thrown. -inline -double cstring_to_double(char const* s) -{ - // Unfortunately there is no clean way to parse a number in C locale - // without this hack: normally, using std::istringstream with classic - // locale should work, but some standard library implementations are buggy - // and handle non-default locale in thread-unsafe way, by changing the - // global C locale which is unacceptable as it introduces subtle bugs in - // multi-thread programs. So we rely on just the standard C functions and - // try to make them work by tweaking the input into the form appropriate - // for the current locale. - - // First try with the original input. - char* end; - double d = strtod(s, &end); - - bool parsedOK; - if (*end == '.') - { - // Parsing may have stopped because the current locale uses something - // different from the point as decimal separator, retry with a comma. - // - // In principle, values other than point or comma are possible but they - // don't seem to be used in practice, so for now keep things simple. - size_t const bufSize = strlen(s) + 1; - char* const buf = new char[bufSize]; - strcpy(buf, s); - buf[end - s] = ','; - d = strtod(buf, &end); - parsedOK = end != buf && *end == '\0'; - delete [] buf; - } - else - { - // Notice that we must detect false positives as well: parsing a string - // using decimal comma should fail when using this function. - parsedOK = end != s && *end == '\0' && !strchr(s, ','); - } - - if (!parsedOK) - { - throw soci_error(std::string("Cannot convert data: string \"") + s + "\" " - "is not a number."); - } - - return d; -} - -} // namespace details - -} // namespace soci - -#endif // SOCI_PRIVATE_SOCI_CSTRTOD_H_INCLUDED diff --git a/src/soci/include/private/soci-dtocstr.h b/src/soci/include/private/soci-dtocstr.h deleted file mode 100644 index bcf9098f07..0000000000 --- a/src/soci/include/private/soci-dtocstr.h +++ /dev/null @@ -1,58 +0,0 @@ -// -// Copyright (C) 2014 Vadim Zeitlin. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_PRIVATE_SOCI_DTOCSTR_H_INCLUDED -#define SOCI_PRIVATE_SOCI_DTOCSTR_H_INCLUDED - -#include "soci/soci-platform.h" -#include "soci/error.h" - -#include -#include - -namespace soci -{ - -namespace details -{ - -// Locale-independent, i.e. always using "C" locale, function for converting -// floating point number to string. -// -// The resulting string will contain the floating point number in "C" locale, -// i.e. will always use point as decimal separator independently of the current -// locale. -inline -std::string double_to_cstring(double d) -{ - // See comments in cstring_to_double() in soci-cstrtod.h, we're dealing - // with the same issues here. - - static size_t const bufSize = 32; - char buf[bufSize]; - snprintf(buf, bufSize, "%.20g", d); - - // Replace any commas which can be used as decimal separator with points. - for (char* p = buf; *p != '\0'; p++ ) - { - if (*p == ',') - { - *p = '.'; - - // There can be at most one comma in this string anyhow. - break; - } - } - - return buf; -} - -} // namespace details - -} // namespace soci - -#endif // SOCI_PRIVATE_SOCI_DTOCSTR_H_INCLUDED diff --git a/src/soci/include/private/soci-exchange-cast.h b/src/soci/include/private/soci-exchange-cast.h deleted file mode 100644 index 9f5b6cfdda..0000000000 --- a/src/soci/include/private/soci-exchange-cast.h +++ /dev/null @@ -1,97 +0,0 @@ -// -// Copyright (C) 2015 Vadim Zeitlin -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_EXCHANGE_CAST_H_INCLUDED -#define SOCI_EXCHANGE_CAST_H_INCLUDED - -#include "soci/soci-backend.h" -#include "soci/type-wrappers.h" - -#include - -namespace soci -{ - -namespace details -{ - -// cast the given non-null untyped pointer to its corresponding type -template struct exchange_type_traits; - -template <> -struct exchange_type_traits -{ - typedef char value_type; -}; - -template <> -struct exchange_type_traits -{ - typedef std::string value_type; -}; - -template <> -struct exchange_type_traits -{ - typedef short value_type; -}; - -template <> -struct exchange_type_traits -{ - typedef int value_type; -}; - -template <> -struct exchange_type_traits -{ - typedef long long value_type; -}; - -template <> -struct exchange_type_traits -{ - typedef unsigned long long value_type; -}; - -template <> -struct exchange_type_traits -{ - typedef double value_type; -}; - -template <> -struct exchange_type_traits -{ - typedef std::tm value_type; -}; - -template <> -struct exchange_type_traits -{ - typedef long_string value_type; -}; - -template <> -struct exchange_type_traits -{ - typedef xml_type value_type; -}; - -// exchange_type_traits not defined for x_statement, x_rowid and x_blob here. - -template -typename exchange_type_traits::value_type& exchange_type_cast(void *data) -{ - return *static_cast::value_type*>(data); -} - -} // namespace details - -} // namespace soci - -#endif // SOCI_EXCHANGE_CAST_H_INCLUDED diff --git a/src/soci/include/private/soci-mktime.h b/src/soci/include/private/soci-mktime.h deleted file mode 100644 index a354ee3cb3..0000000000 --- a/src/soci/include/private/soci-mktime.h +++ /dev/null @@ -1,51 +0,0 @@ -// -// Copyright (C) 2015 Vadim Zeitlin. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_PRIVATE_SOCI_MKTIME_H_INCLUDED -#define SOCI_PRIVATE_SOCI_MKTIME_H_INCLUDED - -// Not because we also want to get timegm() if available. -#include - -namespace soci -{ - -namespace details -{ - -// Fill the provided struct tm with the values corresponding to the given date -// in UTC. -// -// Notice that both years and months are normal human 1-based values here and -// not 1900 or 0-based as in struct tm itself. -inline -void -mktime_from_ymdhms(tm& t, - int year, int month, int day, - int hour, int minute, int second) -{ - t.tm_isdst = -1; - 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; - - mktime(&t); -} - -// Helper function for parsing datetime values. -// -// Throws if the string in buf couldn't be parsed as a date or a time string. -SOCI_DECL void parse_std_tm(char const *buf, std::tm &t); - -} // namespace details - -} // namespace soci - -#endif // SOCI_PRIVATE_SOCI_MKTIME_H_INCLUDED diff --git a/src/soci/include/private/soci-static-assert.h b/src/soci/include/private/soci-static-assert.h deleted file mode 100644 index ecb79b2acd..0000000000 --- a/src/soci/include/private/soci-static-assert.h +++ /dev/null @@ -1,19 +0,0 @@ -// -// Copyright (C) 2015 Vadim Zeitlin. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_PRIVATE_STATIC_ASSERT_H_INCLUDED -#define SOCI_PRIVATE_STATIC_ASSERT_H_INCLUDED - -#include "soci-cpp.h" - -// This is a simple approximation for C++11 static_assert: generate a -// compile-time error if the given expression evaluates to 0 and make the -// identifier (not string!) msg appear in the error message. -#define SOCI_STATIC_ASSERT(expr) \ - struct SOCI_MAKE_UNIQUE_NAME(SociAssert) { unsigned msg: expr; } - -#endif // SOCI_PRIVATE_STATIC_ASSERT_H_INCLUDED diff --git a/src/soci/include/soci/backend-loader.h b/src/soci/include/soci/backend-loader.h deleted file mode 100644 index f7dc6fa78c..0000000000 --- a/src/soci/include/soci/backend-loader.h +++ /dev/null @@ -1,37 +0,0 @@ -// -// Copyright (C) 2008 Maciej Sobczak with contributions from Artyom Tonkikh -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_BACKEND_LOADER_H_INCLUDED -#define SOCI_BACKEND_LOADER_H_INCLUDED - -#include "soci/soci-backend.h" -// std -#include -#include - -namespace soci -{ - -namespace dynamic_backends -{ - -// used internally by session -backend_factory const & get(std::string const & name); - -// provided for advanced user-level management -SOCI_DECL std::vector & search_paths(); -SOCI_DECL void register_backend(std::string const & name, std::string const & shared_object = std::string()); -SOCI_DECL void register_backend(std::string const & name, backend_factory const & factory); -SOCI_DECL std::vector list_all(); -SOCI_DECL void unload(std::string const & name); -SOCI_DECL void unload_all(); - -} // namespace dynamic_backends - -} // namespace soci - -#endif // SOCI_BACKEND_LOADER_H_INCLUDED diff --git a/src/soci/include/soci/bind-values.h b/src/soci/include/soci/bind-values.h deleted file mode 100644 index eee416e839..0000000000 --- a/src/soci/include/soci/bind-values.h +++ /dev/null @@ -1,197 +0,0 @@ -#ifndef SOCI_BIND_VALUES_H_INCLUDED -#define SOCI_BIND_VALUES_H_INCLUDED - -#include "soci/soci-platform.h" -#include "exchange-traits.h" -#include "into-type.h" -#include "into.h" -#include "soci-backend.h" -#include "use-type.h" -#include "use.h" - - -#ifdef SOCI_HAVE_BOOST -# include -# include -#endif // SOCI_HAVE_BOOST -#include - -namespace soci -{ -namespace details -{ - -class use_type_vector: public std::vector -{ -public: - ~use_type_vector() - { - for(iterator iter = begin(), _end = end(); - iter != _end; iter++) - delete *iter; - } - - void exchange(use_type_ptr const& u) { push_back(u.get()); u.release(); } - - template - void exchange(use_container const &uc) - { -#ifdef SOCI_HAVE_BOOST - exchange_(uc, (typename boost::fusion::traits::is_sequence::type *)NULL); -#else - exchange_(uc, NULL); -#endif // SOCI_HAVE_BOOST - } - -private: -#ifdef SOCI_HAVE_BOOST - template - struct use_sequence - { - use_sequence(use_type_vector &_p, Indicator &_ind) - :p(_p), ind(_ind) {} - - template - void operator()(T2 &t2) const - { - p.exchange(use(t2, ind)); - } - - use_type_vector &p; - Indicator &ind; - private: - SOCI_NOT_COPYABLE(use_sequence) - }; - - template - struct use_sequence - { - use_sequence(use_type_vector &_p) - :p(_p) {} - - template - void operator()(T2 &t2) const - { - p.exchange(use(t2)); - } - - use_type_vector &p; - private: - SOCI_NOT_COPYABLE(use_sequence) - }; - - template - void exchange_(use_container const &uc, boost::mpl::true_ * /* fusion sequence */) - { - boost::fusion::for_each(uc.t, use_sequence(*this, uc.ind)); - } - - template - void exchange_(use_container const &uc, boost::mpl::true_ * /* fusion sequence */) - { - boost::fusion::for_each(uc.t, use_sequence(*this)); - } - -#endif // SOCI_HAVE_BOOST - - template - void exchange_(use_container const &uc, ...) - { exchange(do_use(uc.t, uc.ind, uc.name, typename details::exchange_traits::type_family())); } - - template - void exchange_(use_container const &uc, ...) - { exchange(do_use(uc.t, uc.name, typename details::exchange_traits::type_family())); } - - template - void exchange_(use_container const &uc, ...) - { exchange(do_use(uc.t, uc.ind, uc.name, typename details::exchange_traits::type_family())); } - - template - void exchange_(use_container const &uc, ...) - { exchange(do_use(uc.t, uc.name, typename details::exchange_traits::type_family())); } -}; - -class into_type_vector: public std::vector -{ -public: - ~into_type_vector() - { - for(iterator iter = begin(), _end = end(); - iter != _end; iter++) - delete *iter; - } - - void exchange(into_type_ptr const& i) { push_back(i.get()); i.release(); } - - template - void exchange(into_container const &ic) - { -#ifdef SOCI_HAVE_BOOST - exchange_(ic, (typename boost::fusion::traits::is_sequence::type *)NULL); -#else - exchange_(ic, NULL); -#endif // SOCI_HAVE_BOOST - } - -private: -#ifdef SOCI_HAVE_BOOST - template - struct into_sequence - { - into_sequence(into_type_vector &_p, Indicator &_ind) - :p(_p), ind(_ind) {} - - template - void operator()(T2 &t2) const - { - p.exchange(into(t2, ind)); - } - - into_type_vector &p; - Indicator &ind; - private: - SOCI_NOT_COPYABLE(into_sequence) - }; - - template - struct into_sequence - { - into_sequence(into_type_vector &_p) - :p(_p) {} - - template - void operator()(T2 &t2) const - { - p.exchange(into(t2)); - } - - into_type_vector &p; - private: - SOCI_NOT_COPYABLE(into_sequence) - }; - - template - void exchange_(into_container const &ic, boost::mpl::true_ * /* fusion sequence */) - { - boost::fusion::for_each(ic.t, into_sequence(*this, ic.ind)); - } - - template - void exchange_(into_container const &ic, boost::mpl::true_ * /* fusion sequence */) - { - boost::fusion::for_each(ic.t, into_sequence(*this)); - } -#endif // SOCI_HAVE_BOOST - - template - void exchange_(into_container const &ic, ...) - { exchange(do_into(ic.t, ic.ind, typename details::exchange_traits::type_family())); } - - template - void exchange_(into_container const &ic, ...) - { exchange(do_into(ic.t, typename details::exchange_traits::type_family())); } -}; - -} // namespace details -}// namespace soci -#endif // SOCI_BIND_VALUES_H_INCLUDED diff --git a/src/soci/include/soci/blob-exchange.h b/src/soci/include/soci/blob-exchange.h deleted file mode 100644 index a9e8679bc0..0000000000 --- a/src/soci/include/soci/blob-exchange.h +++ /dev/null @@ -1,59 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_BLOB_EXCHANGE_H_INCLUDED -#define SOCI_BLOB_EXCHANGE_H_INCLUDED - -#include "soci/blob.h" -#include "soci/into-type.h" -#include "soci/use-type.h" -// std -#include - -namespace soci -{ - -namespace details -{ - -template <> -class into_type : public standard_into_type -{ -public: - into_type(blob & b) : standard_into_type(&b, x_blob) {} - into_type(blob & b, indicator & ind) - : standard_into_type(&b, x_blob, ind) {} -}; - -template <> -class use_type : public standard_use_type -{ -public: - use_type(blob & b, std::string const & name = std::string()) - : standard_use_type(&b, x_blob, false, name) {} - use_type(blob const & b, std::string const & name = std::string()) - : standard_use_type(const_cast(&b), x_blob, true, name) {} - use_type(blob & b, indicator & ind, - std::string const & name = std::string()) - : standard_use_type(&b, x_blob, ind, false, name) {} - use_type(blob const & b, indicator & ind, - std::string const & name = std::string()) - : standard_use_type(const_cast(&b), x_blob, ind, true, name) {} -}; - -template <> -struct exchange_traits -{ - typedef basic_type_tag type_family; - enum { x_type = x_blob }; -}; - -} // namespace details - -} // namespace soci - -#endif // SOCI_BLOB_EXCHANGE_H_INCLUDED diff --git a/src/soci/include/soci/blob.h b/src/soci/include/soci/blob.h deleted file mode 100644 index 054777124c..0000000000 --- a/src/soci/include/soci/blob.h +++ /dev/null @@ -1,61 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_BLOB_H_INCLUDED -#define SOCI_BLOB_H_INCLUDED - -#include "soci/soci-platform.h" -// std -#include - -namespace soci -{ -// basic blob operations - -class session; - -namespace details -{ -class blob_backend; -} // namespace details - -class SOCI_DECL blob -{ -public: - explicit blob(session & s); - ~blob(); - - std::size_t get_len(); - - // offset is backend-specific - std::size_t read(std::size_t offset, char * buf, std::size_t toRead); - - // offset starts from 0 - std::size_t read_from_start(char * buf, std::size_t toRead, - std::size_t offset = 0); - - // offset is backend-specific - std::size_t write(std::size_t offset, char const * buf, - std::size_t toWrite); - - // offset starts from 0 - std::size_t write_from_start(const char * buf, std::size_t toWrite, - std::size_t offset = 0); - - std::size_t append(char const * buf, std::size_t toWrite); - - void trim(std::size_t newLen); - - details::blob_backend * get_backend() { return backEnd_; } - -private: - details::blob_backend * backEnd_; -}; - -} // namespace soci - -#endif diff --git a/src/soci/include/soci/boost-fusion.h b/src/soci/include/soci/boost-fusion.h deleted file mode 100644 index f235b18431..0000000000 --- a/src/soci/include/soci/boost-fusion.h +++ /dev/null @@ -1,28 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_BOOST_FUSION_H_INCLUDED -#define SOCI_BOOST_FUSION_H_INCLUDED - -#ifndef SOCI_MAX_FUSION_SEQUENCE_LENGTH -#define SOCI_MAX_FUSION_SEQUENCE_LENGTH 10 -#endif - -#include "values.h" -#include "type-conversion-traits.h" -// boost -#include -#include -#include -#include -#include -#include -#include -#include - - -#endif // SOCI_BOOST_FUSION_H_INCLUDED diff --git a/src/soci/include/soci/boost-gregorian-date.h b/src/soci/include/soci/boost-gregorian-date.h deleted file mode 100644 index 66321c5291..0000000000 --- a/src/soci/include/soci/boost-gregorian-date.h +++ /dev/null @@ -1,47 +0,0 @@ -// -// Copyright (C) 2008 Maciej Sobczak -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_BOOST_GREGORIAN_DATE_H_INCLUDED -#define SOCI_BOOST_GREGORIAN_DATE_H_INCLUDED - -#include "soci/type-conversion-traits.h" -// boost -#include -#include -// std -#include - -namespace soci -{ - -template<> -struct type_conversion -{ - typedef std::tm base_type; - - static void from_base( - base_type const & in, indicator ind, boost::gregorian::date & out) - { - if (ind == i_null) - { - throw soci_error("Null value not allowed for this type"); - } - - out = boost::gregorian::date_from_tm(in); - } - - static void to_base( - boost::gregorian::date const & in, base_type & out, indicator & ind) - { - out = boost::gregorian::to_tm(in); - ind = i_ok; - } -}; - -} // namespace soci - -#endif // SOCI_BOOST_GREGORIAN_DATE_H_INCLUDED diff --git a/src/soci/include/soci/boost-optional.h b/src/soci/include/soci/boost-optional.h deleted file mode 100644 index a9322b12cd..0000000000 --- a/src/soci/include/soci/boost-optional.h +++ /dev/null @@ -1,56 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_BOOST_OPTIONAL_H_INCLUDED -#define SOCI_BOOST_OPTIONAL_H_INCLUDED - -#include "soci/type-conversion-traits.h" -// boost -#include -#include - -namespace soci -{ - -// simple fall-back for boost::optional -template -struct type_conversion > -{ - typedef typename type_conversion::base_type base_type; - - static void from_base(base_type const & in, indicator ind, - boost::optional & out) - { - if (ind == i_null) - { - out.reset(); - } - else - { - T tmp = T(); - type_conversion::from_base(in, ind, tmp); - out = tmp; - } - } - - static void to_base(boost::optional const & in, - base_type & out, indicator & ind) - { - if (in.is_initialized()) - { - type_conversion::to_base(in.get(), out, ind); - } - else - { - ind = i_null; - } - } -}; - -} // namespace soci - -#endif // SOCI_BOOST_OPTIONAL_H_INCLUDED diff --git a/src/soci/include/soci/boost-tuple.h b/src/soci/include/soci/boost-tuple.h deleted file mode 100644 index 37547367b4..0000000000 --- a/src/soci/include/soci/boost-tuple.h +++ /dev/null @@ -1,18 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_BOOST_TUPLE_H_INCLUDED -#define SOCI_BOOST_TUPLE_H_INCLUDED - -#include "values.h" -#include "type-conversion-traits.h" - -// boost -#include -#include - -#endif // SOCI_BOOST_TUPLE_H_INCLUDED diff --git a/src/soci/include/soci/callbacks.h b/src/soci/include/soci/callbacks.h deleted file mode 100644 index 85825ad1b6..0000000000 --- a/src/soci/include/soci/callbacks.h +++ /dev/null @@ -1,47 +0,0 @@ -// -// Copyright (C) 2015 Maciej Sobczak -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_CALLBACKS_H_INCLUDED -#define SOCI_CALLBACKS_H_INCLUDED - -namespace soci -{ - -class session; - -// Simple callback interface for reporting failover events. -// The meaning of each operation is intended to be portable, -// but the behaviour details and parameters can be backend-specific. -class SOCI_DECL failover_callback -{ -public: - - // Called when the failover operation has started, - // after discovering connectivity problems. - virtual void started() {} - - // Called after successful failover and creating a new connection; - // the sql parameter denotes the new connection and allows the user - // to replay any initial sequence of commands (like session configuration). - virtual void finished(session & /* sql */) {} - - // Called when the attempt to reconnect failed, - // if the user code sets the retry parameter to true, - // then new connection will be attempted; - // the newTarget connection string is a hint that can be ignored - // by external means. - virtual void failed(bool & /* out */ /* retry */, - std::string & /* out */ /* newTarget */) {} - - // Called when there was a failure that prevents further failover attempts. - virtual void aborted() {} -}; - -} // namespace soci - -#endif // SOCI_CALLBACKS_H_INCLUDED - diff --git a/src/soci/include/soci/column-info.h b/src/soci/include/soci/column-info.h deleted file mode 100644 index 15e1529d29..0000000000 --- a/src/soci/include/soci/column-info.h +++ /dev/null @@ -1,123 +0,0 @@ -// -// Copyright (C) 2016 Maciej Sobczak -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_COLUMN_INFO_H_INCLUDED -#define SOCI_COLUMN_INFO_H_INCLUDED - -#include "soci/soci-backend.h" -#include "soci/type-conversion.h" -#include "soci/values.h" - -namespace soci -{ - -struct SOCI_DECL column_info -{ - std::string name; - data_type type; - std::size_t length; // meaningful for text columns only - std::size_t precision; - std::size_t scale; - bool nullable; -}; - -template <> -struct type_conversion -{ - typedef values base_type; - - static std::size_t get_numeric_value(const values & v, - const std::string & field_name) - { - data_type dt = v.get_properties(field_name).get_data_type(); - switch (dt) - { - case dt_double: - return static_cast( - v.get(field_name, 0.0)); - case dt_integer: - return static_cast( - v.get(field_name, 0)); - case dt_long_long: - return static_cast( - v.get(field_name, 0ll)); - case dt_unsigned_long_long: - return static_cast( - v.get(field_name, 0ull)); - break; - default: - return 0u; - } - } - - static void from_base(values const & v, indicator /* ind */, column_info & ci) - { - ci.name = v.get("COLUMN_NAME"); - - ci.length = get_numeric_value(v, "CHARACTER_MAXIMUM_LENGTH"); - ci.precision = get_numeric_value(v, "NUMERIC_PRECISION"); - ci.scale = get_numeric_value(v, "NUMERIC_SCALE"); - - const std::string & type_name = v.get("DATA_TYPE"); - if (type_name == "text" || type_name == "TEXT" || - type_name == "clob" || type_name == "CLOB" || - type_name.find("char") != std::string::npos || - type_name.find("CHAR") != std::string::npos) - { - ci.type = dt_string; - } - else if (type_name == "integer" || type_name == "INTEGER") - { - ci.type = dt_integer; - } - else if (type_name.find("number") != std::string::npos || - type_name.find("NUMBER") != std::string::npos || - type_name.find("numeric") != std::string::npos || - type_name.find("NUMERIC") != std::string::npos) - { - if (ci.scale != 0) - { - ci.type = dt_double; - } - else - { - ci.type = dt_integer; - } - } - else if (type_name.find("time") != std::string::npos || - type_name.find("TIME") != std::string::npos || - type_name.find("date") != std::string::npos || - type_name.find("DATE") != std::string::npos) - { - ci.type = dt_date; - } - else if (type_name.find("blob") != std::string::npos || - type_name.find("BLOB") != std::string::npos || - type_name.find("oid") != std::string::npos || - type_name.find("OID") != std::string::npos) - { - ci.type = dt_blob; - } - else if (type_name.find("xml") != std::string::npos || - type_name.find("XML") != std::string::npos) - { - ci.type = dt_xml; - } - else - { - // this seems to be a safe default - ci.type = dt_string; - } - - const std::string & nullable_s = v.get("IS_NULLABLE"); - ci.nullable = (nullable_s == "YES"); - } -}; - -} // namespace soci - -#endif // SOCI_COLUMN_INFO_H_INCLUDED diff --git a/src/soci/include/soci/connection-parameters.h b/src/soci/include/soci/connection-parameters.h deleted file mode 100644 index 6955a67c8d..0000000000 --- a/src/soci/include/soci/connection-parameters.h +++ /dev/null @@ -1,69 +0,0 @@ -// -// Copyright (C) 2013 Vadim Zeitlin -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_CONNECTION_PARAMETERS_H_INCLUDED -#define SOCI_CONNECTION_PARAMETERS_H_INCLUDED - -#include "soci/soci-platform.h" - -#include -#include - -namespace soci -{ - -class backend_factory; - -// Simple container for the information used when opening a session. -class SOCI_DECL connection_parameters -{ -public: - connection_parameters(); - connection_parameters(backend_factory const & factory, std::string const & connectString); - connection_parameters(std::string const & backendName, std::string const & connectString); - explicit connection_parameters(std::string const & fullConnectString); - - // Default copy ctor, assignment operator and dtor are all OK for us. - - - // Retrieve the backend and the connection strings specified in the ctor. - backend_factory const * get_factory() const { return factory_; } - void set_connect_string(const std::string & connectString) { connectString_ = connectString; } - std::string const & get_connect_string() const { return connectString_; } - - // Set the value of the given option, overwriting any previous value. - void set_option(const char * name, std::string const & value) - { - options_[name] = value; - } - - // Return true if the option with the given name was found and fill the - // provided parameter with its value. - bool get_option(const char * name, std::string & value) const - { - Options::const_iterator const it = options_.find(name); - if (it == options_.end()) - return false; - - value = it->second; - - return true; - } - -private: - // The backend and connection string specified in our ctor. - backend_factory const * factory_; - std::string connectString_; - - // We store all the values as strings for simplicity. - typedef std::map Options; - Options options_; -}; - -} // namespace soci - -#endif // SOCI_CONNECTION_PARAMETERS_H_INCLUDED diff --git a/src/soci/include/soci/connection-pool.h b/src/soci/include/soci/connection-pool.h deleted file mode 100644 index 00215e2470..0000000000 --- a/src/soci/include/soci/connection-pool.h +++ /dev/null @@ -1,41 +0,0 @@ -// -// Copyright (C) 2008 Maciej Sobczak -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_CONNECTION_POOL_H_INCLUDED -#define SOCI_CONNECTION_POOL_H_INCLUDED - -#include "soci/soci-platform.h" -// std -#include - -namespace soci -{ - -class session; - -class SOCI_DECL connection_pool -{ -public: - explicit connection_pool(std::size_t size); - ~connection_pool(); - - session & at(std::size_t pos); - - std::size_t lease(); - bool try_lease(std::size_t & pos, int timeout); - void give_back(std::size_t pos); - -private: - struct connection_pool_impl; - connection_pool_impl * pimpl_; - - SOCI_NOT_COPYABLE(connection_pool) -}; - -} - -#endif // SOCI_CONNECTION_POOL_H_INCLUDED diff --git a/src/soci/include/soci/db2/soci-db2.h b/src/soci/include/soci/db2/soci-db2.h deleted file mode 100644 index 9e61eaa27e..0000000000 --- a/src/soci/include/soci/db2/soci-db2.h +++ /dev/null @@ -1,300 +0,0 @@ -// -// Copyright (C) 2011-2013 Denis Chapligin -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_DB2_H_INCLUDED -#define SOCI_DB2_H_INCLUDED - -#ifdef _WIN32 -# ifdef SOCI_DLL -# ifdef SOCI_DB2_SOURCE -# define SOCI_DB2_DECL __declspec(dllexport) -# else -# define SOCI_DB2_DECL __declspec(dllimport) -# endif // SOCI_DB2_SOURCE -# endif // SOCI_DLL -#endif // _WIN32 -// -// If SOCI_DB2_DECL isn't defined yet define it now -#ifndef SOCI_DB2_DECL -# define SOCI_DB2_DECL -#endif - -#include - -#include -#include -#include -#include -#include -#include -#include - -#include - -namespace soci -{ - namespace details { namespace db2 - { - enum binding_method - { - BOUND_BY_NONE, - BOUND_BY_NAME, - BOUND_BY_POSITION - }; - - inline SQLPOINTER int_as_ptr(int n) - { - union - { - SQLPOINTER p; - int n; - } u; - u.n = n; - return u.p; - } - }} - - static const std::size_t maxBuffer = 1024 * 1024 * 1024; //CLI limit is about 3 GB, but 1GB should be enough - -class SOCI_DB2_DECL db2_soci_error : public soci_error { -public: - db2_soci_error(std::string const & msg, SQLRETURN rc) : soci_error(msg),errorCode(rc) {}; - ~db2_soci_error() throw() SOCI_OVERRIDE { }; - - //We have to extract error information before exception throwing, cause CLI handles could be broken at the construction time - static const std::string sqlState(std::string const & msg,const SQLSMALLINT htype,const SQLHANDLE hndl); - - SQLRETURN errorCode; -}; - -// Option allowing to specify the "driver completion" parameter of -// SQLDriverConnect(). Its possible values are the same as the allowed values -// for this parameter in the official DB2 CLI, i.e. one of SQL_DRIVER_XXX -// (in string form as all options are strings currently). -extern SOCI_DB2_DECL char const * db2_option_driver_complete; - -struct db2_statement_backend; - -struct SOCI_DB2_DECL db2_standard_into_type_backend : details::standard_into_type_backend -{ - db2_standard_into_type_backend(db2_statement_backend &st) - : statement_(st),buf(NULL) - {} - - void define_by_pos(int& position, void* data, details::exchange_type type) SOCI_OVERRIDE; - - void pre_fetch() SOCI_OVERRIDE; - void post_fetch(bool gotData, bool calledFromFetch, indicator* ind) SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - db2_statement_backend& statement_; - - char* buf; - void *data; - details::exchange_type type; - int position; - SQLSMALLINT cType; - SQLLEN valueLen; -}; - -struct SOCI_DB2_DECL db2_vector_into_type_backend : details::vector_into_type_backend -{ - db2_vector_into_type_backend(db2_statement_backend &st) - : statement_(st),buf(NULL) - {} - - void define_by_pos(int& position, void* data, details::exchange_type type) SOCI_OVERRIDE; - - void pre_fetch() SOCI_OVERRIDE; - void post_fetch(bool gotData, indicator* ind) SOCI_OVERRIDE; - - void resize(std::size_t sz) SOCI_OVERRIDE; - std::size_t size() SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - db2_statement_backend& statement_; - - void prepare_indicators(std::size_t size); - - SQLLEN *indptr; - std::vector indVec; - void *data; - char *buf; - int position_; - details::exchange_type type; - SQLSMALLINT cType; - std::size_t colSize; -}; - -struct SOCI_DB2_DECL db2_standard_use_type_backend : details::standard_use_type_backend -{ - db2_standard_use_type_backend(db2_statement_backend &st) - : statement_(st),buf(NULL),ind(0) - {} - - void bind_by_pos(int& position, void* data, details::exchange_type type, bool readOnly) SOCI_OVERRIDE; - void bind_by_name(std::string const& name, void* data, details::exchange_type type, bool readOnly) SOCI_OVERRIDE; - - void pre_use(indicator const* ind) SOCI_OVERRIDE; - void post_use(bool gotData, indicator* ind) SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - db2_statement_backend& statement_; - - void *prepare_for_bind(void *data, SQLLEN &size, SQLSMALLINT &sqlType, SQLSMALLINT &cType); - - void *data; - details::exchange_type type; - int position; - std::string name; - char* buf; - SQLLEN ind; -}; - -struct SOCI_DB2_DECL db2_vector_use_type_backend : details::vector_use_type_backend -{ - db2_vector_use_type_backend(db2_statement_backend &st) - : statement_(st),buf(NULL) {} - - void bind_by_pos(int& position, void* data, details::exchange_type type) SOCI_OVERRIDE; - void bind_by_name(std::string const& name, void* data, details::exchange_type type) SOCI_OVERRIDE; - - void pre_use(indicator const* ind) SOCI_OVERRIDE; - - std::size_t size() SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - db2_statement_backend& statement_; - - void prepare_indicators(std::size_t size); - void prepare_for_bind(void *&data, SQLUINTEGER &size,SQLSMALLINT &sqlType, SQLSMALLINT &cType); - void bind_helper(int &position, void *data, details::exchange_type type); - - SQLLEN *indptr; - std::vector indVec; - void *data; - char *buf; - details::exchange_type type; - std::size_t colSize; -}; - -struct db2_session_backend; -struct SOCI_DB2_DECL db2_statement_backend : details::statement_backend -{ - db2_statement_backend(db2_session_backend &session); - - void alloc() SOCI_OVERRIDE; - void clean_up() SOCI_OVERRIDE; - void prepare(std::string const& query, details::statement_type eType) SOCI_OVERRIDE; - - exec_fetch_result execute(int number) SOCI_OVERRIDE; - exec_fetch_result fetch(int number) SOCI_OVERRIDE; - - long long get_affected_rows() SOCI_OVERRIDE; - int get_number_of_rows() SOCI_OVERRIDE; - std::string get_parameter_name(int index) const SOCI_OVERRIDE; - - std::string rewrite_for_procedure_call(std::string const& query) SOCI_OVERRIDE; - - int prepare_for_describe() SOCI_OVERRIDE; - void describe_column(int colNum, data_type& dtype, std::string& columnName) SOCI_OVERRIDE; - size_t column_size(int col); - - db2_standard_into_type_backend* make_into_type_backend() SOCI_OVERRIDE; - db2_standard_use_type_backend* make_use_type_backend() SOCI_OVERRIDE; - db2_vector_into_type_backend* make_vector_into_type_backend() SOCI_OVERRIDE; - db2_vector_use_type_backend* make_vector_use_type_backend() SOCI_OVERRIDE; - - db2_session_backend& session_; - - SQLHANDLE hStmt; - std::string query_; - std::vector names_; - bool hasVectorUseElements; - SQLUINTEGER numRowsFetched; - details::db2::binding_method use_binding_method_; -}; - -struct db2_rowid_backend : details::rowid_backend -{ - db2_rowid_backend(db2_session_backend &session); - - ~db2_rowid_backend() SOCI_OVERRIDE; -}; - -struct db2_blob_backend : details::blob_backend -{ - db2_blob_backend(db2_session_backend& session); - - ~db2_blob_backend() SOCI_OVERRIDE; - - std::size_t get_len() SOCI_OVERRIDE; - std::size_t read(std::size_t offset, char* buf, std::size_t toRead) SOCI_OVERRIDE; - std::size_t write(std::size_t offset, char const* buf, std::size_t toWrite) SOCI_OVERRIDE; - std::size_t append(char const* buf, std::size_t toWrite) SOCI_OVERRIDE; - void trim(std::size_t newLen) SOCI_OVERRIDE; - - db2_session_backend& session_; -}; - -struct db2_session_backend : details::session_backend -{ - db2_session_backend(connection_parameters const& parameters); - - ~db2_session_backend() SOCI_OVERRIDE; - - void begin() SOCI_OVERRIDE; - void commit() SOCI_OVERRIDE; - void rollback() SOCI_OVERRIDE; - - std::string get_dummy_from_table() const SOCI_OVERRIDE { return "sysibm.sysdummy1"; } - - std::string get_backend_name() const SOCI_OVERRIDE { return "DB2"; } - - void clean_up(); - - db2_statement_backend* make_statement_backend() SOCI_OVERRIDE; - db2_rowid_backend* make_rowid_backend() SOCI_OVERRIDE; - db2_blob_backend* make_blob_backend() SOCI_OVERRIDE; - - void parseConnectString(std::string const &); - void parseKeyVal(std::string const &); - - std::string connection_string_; - bool autocommit; - bool in_transaction; - - SQLHANDLE hEnv; /* Environment handle */ - SQLHANDLE hDbc; /* Connection handle */ -}; - -struct SOCI_DB2_DECL db2_backend_factory : backend_factory -{ - db2_backend_factory() {} - db2_session_backend* make_session( - connection_parameters const & parameters) const SOCI_OVERRIDE; -}; - -extern SOCI_DB2_DECL db2_backend_factory const db2; - -extern "C" -{ - -// for dynamic backend loading -SOCI_DB2_DECL backend_factory const* factory_db2(); -SOCI_DB2_DECL void register_factory_db2(); - -} // extern "C" - -} // namespace soci - -#endif // SOCI_DB2_H_INCLUDED diff --git a/src/soci/include/soci/empty/soci-empty.h b/src/soci/include/soci/empty/soci-empty.h deleted file mode 100644 index a428872bc7..0000000000 --- a/src/soci/include/soci/empty/soci-empty.h +++ /dev/null @@ -1,196 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_EMPTY_H_INCLUDED -#define SOCI_EMPTY_H_INCLUDED - -#ifdef _WIN32 -# ifdef SOCI_DLL -# ifdef SOCI_EMPTY_SOURCE -# define SOCI_EMPTY_DECL __declspec(dllexport) -# else -# define SOCI_EMPTY_DECL __declspec(dllimport) -# endif // SOCI_EMPTY_SOURCE -# endif // SOCI_DLL -#endif // _WIN32 -// -// If SOCI_EMPTY_DECL isn't defined yet define it now -#ifndef SOCI_EMPTY_DECL -# define SOCI_EMPTY_DECL -#endif - -#include - -#include -#include - -namespace soci -{ - -struct empty_statement_backend; - -struct SOCI_EMPTY_DECL empty_standard_into_type_backend : details::standard_into_type_backend -{ - empty_standard_into_type_backend(empty_statement_backend &st) - : statement_(st) - {} - - void define_by_pos(int& position, void* data, details::exchange_type type) SOCI_OVERRIDE; - - void pre_fetch() SOCI_OVERRIDE; - void post_fetch(bool gotData, bool calledFromFetch, indicator* ind) SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - empty_statement_backend& statement_; -}; - -struct SOCI_EMPTY_DECL empty_vector_into_type_backend : details::vector_into_type_backend -{ - empty_vector_into_type_backend(empty_statement_backend &st) - : statement_(st) - {} - - void define_by_pos(int& position, void* data, details::exchange_type type) SOCI_OVERRIDE; - - void pre_fetch() SOCI_OVERRIDE; - void post_fetch(bool gotData, indicator* ind) SOCI_OVERRIDE; - - void resize(std::size_t sz) SOCI_OVERRIDE; - std::size_t size() SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - empty_statement_backend& statement_; -}; - -struct SOCI_EMPTY_DECL empty_standard_use_type_backend : details::standard_use_type_backend -{ - empty_standard_use_type_backend(empty_statement_backend &st) - : statement_(st) - {} - - void bind_by_pos(int& position, void* data, details::exchange_type type, bool readOnly) SOCI_OVERRIDE; - void bind_by_name(std::string const& name, void* data, details::exchange_type type, bool readOnly) SOCI_OVERRIDE; - - void pre_use(indicator const* ind) SOCI_OVERRIDE; - void post_use(bool gotData, indicator* ind) SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - empty_statement_backend& statement_; -}; - -struct SOCI_EMPTY_DECL empty_vector_use_type_backend : details::vector_use_type_backend -{ - empty_vector_use_type_backend(empty_statement_backend &st) - : statement_(st) {} - - void bind_by_pos(int& position, void* data, details::exchange_type type) SOCI_OVERRIDE; - void bind_by_name(std::string const& name, void* data, details::exchange_type type) SOCI_OVERRIDE; - - void pre_use(indicator const* ind) SOCI_OVERRIDE; - - std::size_t size() SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - empty_statement_backend& statement_; -}; - -struct empty_session_backend; -struct SOCI_EMPTY_DECL empty_statement_backend : details::statement_backend -{ - empty_statement_backend(empty_session_backend &session); - - void alloc() SOCI_OVERRIDE; - void clean_up() SOCI_OVERRIDE; - void prepare(std::string const& query, details::statement_type eType) SOCI_OVERRIDE; - - exec_fetch_result execute(int number) SOCI_OVERRIDE; - exec_fetch_result fetch(int number) SOCI_OVERRIDE; - - long long get_affected_rows() SOCI_OVERRIDE; - int get_number_of_rows() SOCI_OVERRIDE; - std::string get_parameter_name(int index) const SOCI_OVERRIDE; - - std::string rewrite_for_procedure_call(std::string const& query) SOCI_OVERRIDE; - - int prepare_for_describe() SOCI_OVERRIDE; - void describe_column(int colNum, data_type& dtype, std::string& columnName) SOCI_OVERRIDE; - - empty_standard_into_type_backend* make_into_type_backend() SOCI_OVERRIDE; - empty_standard_use_type_backend* make_use_type_backend() SOCI_OVERRIDE; - empty_vector_into_type_backend* make_vector_into_type_backend() SOCI_OVERRIDE; - empty_vector_use_type_backend* make_vector_use_type_backend() SOCI_OVERRIDE; - - empty_session_backend& session_; -}; - -struct empty_rowid_backend : details::rowid_backend -{ - empty_rowid_backend(empty_session_backend &session); - - ~empty_rowid_backend() SOCI_OVERRIDE; -}; - -struct empty_blob_backend : details::blob_backend -{ - empty_blob_backend(empty_session_backend& session); - - ~empty_blob_backend() SOCI_OVERRIDE; - - std::size_t get_len() SOCI_OVERRIDE; - std::size_t read(std::size_t offset, char* buf, std::size_t toRead) SOCI_OVERRIDE; - std::size_t write(std::size_t offset, char const* buf, std::size_t toWrite) SOCI_OVERRIDE; - std::size_t append(char const* buf, std::size_t toWrite) SOCI_OVERRIDE; - void trim(std::size_t newLen) SOCI_OVERRIDE; - - empty_session_backend& session_; -}; - -struct empty_session_backend : details::session_backend -{ - empty_session_backend(connection_parameters const& parameters); - - ~empty_session_backend() SOCI_OVERRIDE; - - void begin() SOCI_OVERRIDE; - void commit() SOCI_OVERRIDE; - void rollback() SOCI_OVERRIDE; - - std::string get_dummy_from_table() const SOCI_OVERRIDE { return std::string(); } - - std::string get_backend_name() const SOCI_OVERRIDE { return "empty"; } - - void clean_up(); - - empty_statement_backend* make_statement_backend() SOCI_OVERRIDE; - empty_rowid_backend* make_rowid_backend() SOCI_OVERRIDE; - empty_blob_backend* make_blob_backend() SOCI_OVERRIDE; -}; - -struct SOCI_EMPTY_DECL empty_backend_factory : backend_factory -{ - empty_backend_factory() {} - empty_session_backend* make_session(connection_parameters const& parameters) const SOCI_OVERRIDE; -}; - -extern SOCI_EMPTY_DECL empty_backend_factory const empty; - -extern "C" -{ - -// for dynamic backend loading -SOCI_EMPTY_DECL backend_factory const* factory_empty(); -SOCI_EMPTY_DECL void register_factory_empty(); - -} // extern "C" - -} // namespace soci - -#endif // SOCI_EMPTY_H_INCLUDED diff --git a/src/soci/include/soci/error.h b/src/soci/include/soci/error.h deleted file mode 100644 index 1de84dbf44..0000000000 --- a/src/soci/include/soci/error.h +++ /dev/null @@ -1,66 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak -// Copyright (C) 2015 Vadim Zeitlin -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_ERROR_H_INCLUDED -#define SOCI_ERROR_H_INCLUDED - -#include "soci/soci-platform.h" -// std -#include -#include - -namespace soci -{ - -class SOCI_DECL soci_error : public std::runtime_error -{ -public: - explicit soci_error(std::string const & msg); - - soci_error(soci_error const& e); - soci_error& operator=(soci_error const& e); - - ~soci_error() throw() SOCI_OVERRIDE; - - // Returns just the error message itself, without the context. - std::string get_error_message() const; - - // Returns the full error message combining the message given to the ctor - // with all the available context records. - char const* what() const throw() SOCI_OVERRIDE; - - // This is used only by SOCI itself to provide more information about the - // exception as it bubbles up. It can be called multiple times, with the - // first call adding the lowest level context and the last one -- the - // highest level context. - void add_context(std::string const& context); - - // Basic error classes. - enum error_category - { - connection_error, - invalid_statement, - no_privilege, - no_data, - constraint_violation, - unknown_transaction_state, - system_error, - unknown - }; - - // Basic error classification support - virtual error_category get_error_category() const { return unknown; } - -private: - // Optional extra information (currently just the context data). - class soci_error_extra_info* info_; -}; - -} // namespace soci - -#endif // SOCI_ERROR_H_INCLUDED diff --git a/src/soci/include/soci/exchange-traits.h b/src/soci/include/soci/exchange-traits.h deleted file mode 100644 index 77f5586980..0000000000 --- a/src/soci/include/soci/exchange-traits.h +++ /dev/null @@ -1,155 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_EXCHANGE_TRAITS_H_INCLUDED -#define SOCI_EXCHANGE_TRAITS_H_INCLUDED - -#include "soci/type-conversion-traits.h" -#include "soci/soci-backend.h" -#include "soci/type-wrappers.h" -// std -#include -#include -#include - -namespace soci -{ - -namespace details -{ - -struct basic_type_tag {}; -struct user_type_tag {}; - -template -struct exchange_traits -{ - // this is used for tag-dispatch between implementations for basic types - // and user-defined types - typedef user_type_tag type_family; - - enum // anonymous - { - x_type = - exchange_traits - < - typename type_conversion::base_type - >::x_type - }; -}; - -template <> -struct exchange_traits -{ - typedef basic_type_tag type_family; - enum { x_type = x_short }; -}; - -template <> -struct exchange_traits : exchange_traits -{ -}; - -template <> -struct exchange_traits -{ - typedef basic_type_tag type_family; - enum { x_type = x_integer }; -}; - -template <> -struct exchange_traits : exchange_traits -{ -}; - -template <> -struct exchange_traits -{ - typedef basic_type_tag type_family; - enum { x_type = x_char }; -}; - -template <> -struct exchange_traits -{ - typedef basic_type_tag type_family; - enum { x_type = x_long_long }; -}; - -template <> -struct exchange_traits -{ - typedef basic_type_tag type_family; - enum { x_type = x_unsigned_long_long }; -}; - -// long must be mapped either to x_integer or x_long_long: -template struct long_traits_helper; -template<> struct long_traits_helper<4> { enum { x_type = x_integer }; }; -template<> struct long_traits_helper<8> { enum { x_type = x_long_long }; }; - -template <> -struct exchange_traits -{ - typedef basic_type_tag type_family; - enum { x_type = long_traits_helper::x_type }; -}; - -template <> -struct exchange_traits : exchange_traits -{ -}; - -template <> -struct exchange_traits -{ - typedef basic_type_tag type_family; - enum { x_type = x_double }; -}; - -template <> -struct exchange_traits -{ - typedef basic_type_tag type_family; - enum { x_type = x_stdstring }; -}; - -template <> -struct exchange_traits -{ - typedef basic_type_tag type_family; - enum { x_type = x_stdtm }; -}; - -template -struct exchange_traits > -{ - typedef typename exchange_traits::type_family type_family; - enum { x_type = exchange_traits::x_type }; -}; - -// handling of wrapper types - -template <> -struct exchange_traits -{ - typedef basic_type_tag type_family; - enum { x_type = x_xmltype }; -}; - -template <> -struct exchange_traits -{ - typedef basic_type_tag type_family; - enum { x_type = x_longstring }; -}; - -} // namespace details - -} // namespace soci - -#endif // SOCI_EXCHANGE_TRAITS_H_INCLUDED diff --git a/src/soci/include/soci/firebird/soci-firebird.h b/src/soci/include/soci/firebird/soci-firebird.h deleted file mode 100644 index 9b0f0912f1..0000000000 --- a/src/soci/include/soci/firebird/soci-firebird.h +++ /dev/null @@ -1,365 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, Rafal Bobrowski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// - -#ifndef SOCI_FIREBIRD_H_INCLUDED -#define SOCI_FIREBIRD_H_INCLUDED - -#ifdef _WIN32 -# ifdef SOCI_DLL -# ifdef SOCI_FIREBIRD_SOURCE -# define SOCI_FIREBIRD_DECL __declspec(dllexport) -# else -# define SOCI_FIREBIRD_DECL __declspec(dllimport) -# endif // SOCI_DLL -# endif // SOCI_FIREBIRD_SOURCE -#endif // _WIN32 - -// -// If SOCI_FIREBIRD_DECL isn't defined yet define it now -#ifndef SOCI_FIREBIRD_DECL -# define SOCI_FIREBIRD_DECL -#endif - -#ifdef _WIN32 -#include // To understand and/or/not on MSVC9 -#endif -#include -#include // FireBird -#include -#include -#include - -namespace soci -{ - -std::size_t const stat_size = 20; - -// size of buffer for error messages. All examples use this value. -// Anyone knows, where it is stated that 512 bytes is enough ? -std::size_t const SOCI_FIREBIRD_ERRMSG = 512; - -class SOCI_FIREBIRD_DECL firebird_soci_error : public soci_error -{ -public: - firebird_soci_error(std::string const & msg, - ISC_STATUS const * status = 0); - - ~firebird_soci_error() throw() SOCI_OVERRIDE {}; - - std::vector status_; -}; - -enum BuffersType -{ - eStandard, eVector -}; - -struct firebird_blob_backend; -struct firebird_statement_backend; -struct firebird_standard_into_type_backend : details::standard_into_type_backend -{ - firebird_standard_into_type_backend(firebird_statement_backend &st) - : statement_(st), data_(NULL), type_(), position_(0), buf_(NULL), indISCHolder_(0) - {} - - void define_by_pos(int &position, - void *data, details::exchange_type type) SOCI_OVERRIDE; - - void pre_fetch() SOCI_OVERRIDE; - void post_fetch(bool gotData, bool calledFromFetch, - indicator *ind) SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - firebird_statement_backend &statement_; - virtual void exchangeData(); - - void *data_; - details::exchange_type type_; - int position_; - - char *buf_; - short indISCHolder_; - -private: - // Copy contents of a BLOB (represented by its id) in buf_ into the given - // string. - void copy_from_blob(std::string& out); -}; - -struct firebird_vector_into_type_backend : details::vector_into_type_backend -{ - firebird_vector_into_type_backend(firebird_statement_backend &st) - : statement_(st), data_(NULL), type_(), position_(0), buf_(NULL), indISCHolder_(0) - {} - - void define_by_pos(int &position, - void *data, details::exchange_type type) SOCI_OVERRIDE; - - void pre_fetch() SOCI_OVERRIDE; - void post_fetch(bool gotData, indicator *ind) SOCI_OVERRIDE; - - void resize(std::size_t sz) SOCI_OVERRIDE; - std::size_t size() SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - firebird_statement_backend &statement_; - virtual void exchangeData(std::size_t row); - - void *data_; - details::exchange_type type_; - int position_; - - char *buf_; - short indISCHolder_; -}; - -struct firebird_standard_use_type_backend : details::standard_use_type_backend -{ - firebird_standard_use_type_backend(firebird_statement_backend &st) - : statement_(st), data_(NULL), type_(), position_(0), buf_(NULL), indISCHolder_(0), - blob_(NULL) - {} - - void bind_by_pos(int &position, - void *data, details::exchange_type type, bool readOnly) SOCI_OVERRIDE; - void bind_by_name(std::string const &name, - void *data, details::exchange_type type, bool readOnly) SOCI_OVERRIDE; - - void pre_use(indicator const *ind) SOCI_OVERRIDE; - void post_use(bool gotData, indicator *ind) SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - firebird_statement_backend &statement_; - virtual void exchangeData(); - - void *data_; - details::exchange_type type_; - int position_; - - char *buf_; - short indISCHolder_; - -private: - // Allocate a temporary blob, fill it with the data from the provided - // string and copy its ID into buf_. - void copy_to_blob(const std::string& in); - - // This is used for types mapping to CLOB. - firebird_blob_backend* blob_; -}; - -struct firebird_vector_use_type_backend : details::vector_use_type_backend -{ - firebird_vector_use_type_backend(firebird_statement_backend &st) - : statement_(st), data_(NULL), type_(), position_(0), buf_(NULL), indISCHolder_(0) - {} - - void bind_by_pos(int &position, - void *data, details::exchange_type type) SOCI_OVERRIDE; - void bind_by_name(std::string const &name, - void *data, details::exchange_type type) SOCI_OVERRIDE; - - void pre_use(indicator const *ind) SOCI_OVERRIDE; - - std::size_t size() SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - firebird_statement_backend &statement_; - virtual void exchangeData(std::size_t row); - - void *data_; - details::exchange_type type_; - int position_; - indicator const *inds_; - - char *buf_; - short indISCHolder_; -}; - -struct firebird_session_backend; -struct firebird_statement_backend : details::statement_backend -{ - firebird_statement_backend(firebird_session_backend &session); - - void alloc() SOCI_OVERRIDE; - void clean_up() SOCI_OVERRIDE; - void prepare(std::string const &query, - details::statement_type eType) SOCI_OVERRIDE; - - exec_fetch_result execute(int number) SOCI_OVERRIDE; - exec_fetch_result fetch(int number) SOCI_OVERRIDE; - - long long get_affected_rows() SOCI_OVERRIDE; - int get_number_of_rows() SOCI_OVERRIDE; - std::string get_parameter_name(int index) const SOCI_OVERRIDE; - - std::string rewrite_for_procedure_call(std::string const &query) SOCI_OVERRIDE; - - int prepare_for_describe() SOCI_OVERRIDE; - void describe_column(int colNum, data_type &dtype, - std::string &columnName) SOCI_OVERRIDE; - - firebird_standard_into_type_backend * make_into_type_backend() SOCI_OVERRIDE; - firebird_standard_use_type_backend * make_use_type_backend() SOCI_OVERRIDE; - firebird_vector_into_type_backend * make_vector_into_type_backend() SOCI_OVERRIDE; - firebird_vector_use_type_backend * make_vector_use_type_backend() SOCI_OVERRIDE; - - firebird_session_backend &session_; - - isc_stmt_handle stmtp_; - XSQLDA * sqldap_; - XSQLDA * sqlda2p_; - - bool boundByName_; - bool boundByPos_; - - friend struct firebird_vector_into_type_backend; - friend struct firebird_standard_into_type_backend; - friend struct firebird_vector_use_type_backend; - friend struct firebird_standard_use_type_backend; - -protected: - int rowsFetched_; - bool endOfRowSet_; - - long long rowsAffectedBulk_; // number of rows affected by the last bulk operation - - virtual void exchangeData(bool gotData, int row); - virtual void prepareSQLDA(XSQLDA ** sqldap, short size = 10); - virtual void rewriteQuery(std::string const & query, - std::vector & buffer); - virtual void rewriteParameters(std::string const & src, - std::vector & dst); - - BuffersType intoType_; - BuffersType useType_; - - std::vector > inds_; - std::vector intos_; - std::vector uses_; - - // named parameters - std::map names_; - - bool procedure_; -}; - -struct firebird_blob_backend : details::blob_backend -{ - firebird_blob_backend(firebird_session_backend &session); - - ~firebird_blob_backend() SOCI_OVERRIDE; - - std::size_t get_len() SOCI_OVERRIDE; - std::size_t read(std::size_t offset, char *buf, - std::size_t toRead) SOCI_OVERRIDE; - std::size_t write(std::size_t offset, char const *buf, - std::size_t toWrite) SOCI_OVERRIDE; - std::size_t append(char const *buf, std::size_t toWrite) SOCI_OVERRIDE; - void trim(std::size_t newLen) SOCI_OVERRIDE; - - firebird_session_backend &session_; - - virtual void save(); - virtual void assign(ISC_QUAD const & bid) - { - cleanUp(); - - bid_ = bid; - from_db_ = true; - } - - // BLOB id from in database - ISC_QUAD bid_; - - // BLOB id was fetched from database (true) - // or this is new BLOB - bool from_db_; - - // BLOB handle - isc_blob_handle bhp_; - -protected: - - virtual void open(); - virtual long getBLOBInfo(); - virtual void load(); - virtual void writeBuffer(std::size_t offset, char const * buf, - std::size_t toWrite); - virtual void cleanUp(); - - // buffer for BLOB data - std::vector data_; - - bool loaded_; - long max_seg_size_; -}; - -struct firebird_session_backend : details::session_backend -{ - firebird_session_backend(connection_parameters const & parameters); - - ~firebird_session_backend() SOCI_OVERRIDE; - - void begin() SOCI_OVERRIDE; - void commit() SOCI_OVERRIDE; - void rollback() SOCI_OVERRIDE; - - bool get_next_sequence_value(session & s, - std::string const & sequence, long & value) SOCI_OVERRIDE; - - std::string get_dummy_from_table() const SOCI_OVERRIDE { return "rdb$database"; } - - std::string get_backend_name() const SOCI_OVERRIDE { return "firebird"; } - - void cleanUp(); - - firebird_statement_backend * make_statement_backend() SOCI_OVERRIDE; - details::rowid_backend* make_rowid_backend() SOCI_OVERRIDE; - firebird_blob_backend * make_blob_backend() SOCI_OVERRIDE; - - bool get_option_decimals_as_strings() { return decimals_as_strings_; } - - // Returns the pointer to the current transaction handle, starting a new - // transaction if necessary. - // - // The returned pointer should - isc_tr_handle* current_transaction(); - - isc_db_handle dbhp_; - -private: - isc_tr_handle trhp_; - bool decimals_as_strings_; -}; - -struct firebird_backend_factory : backend_factory -{ - firebird_backend_factory() {} - firebird_session_backend * make_session( - connection_parameters const & parameters) const SOCI_OVERRIDE; -}; - -extern SOCI_FIREBIRD_DECL firebird_backend_factory const firebird; - -extern "C" -{ - -// for dynamic backend loading -SOCI_FIREBIRD_DECL backend_factory const * factory_firebird(); -SOCI_FIREBIRD_DECL void register_factory_firebird(); - -} // extern "C" - -} // namespace soci - -#endif // SOCI_FIREBIRD_H_INCLUDED diff --git a/src/soci/include/soci/into-type.h b/src/soci/include/soci/into-type.h deleted file mode 100644 index 1573eabc53..0000000000 --- a/src/soci/include/soci/into-type.h +++ /dev/null @@ -1,207 +0,0 @@ -// -// Copyright (C) 2004-2016 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_INTO_TYPE_H_INCLUDED -#define SOCI_INTO_TYPE_H_INCLUDED - -#include "soci/soci-backend.h" -#include "soci/type-ptr.h" -#include "soci/exchange-traits.h" -// std -#include -#include - -namespace soci -{ - -class session; - -namespace details -{ - -class prepare_temp_type; -class standard_into_type_backend; -class vector_into_type_backend; -class statement_impl; - -// this is intended to be a base class for all classes that deal with -// defining output data -class into_type_base -{ -public: - virtual ~into_type_base() {} - - virtual void define(statement_impl & st, int & position) = 0; - virtual void pre_exec(int num) = 0; - virtual void pre_fetch() = 0; - virtual void post_fetch(bool gotData, bool calledFromFetch) = 0; - virtual void clean_up() = 0; - - virtual std::size_t size() const = 0; // returns the number of elements - virtual void resize(std::size_t /* sz */) {} // used for vectors only -}; - -typedef type_ptr into_type_ptr; - -// standard types - -class SOCI_DECL standard_into_type : public into_type_base -{ -public: - standard_into_type(void * data, exchange_type type) - : data_(data), type_(type), ind_(NULL), backEnd_(NULL) {} - standard_into_type(void * data, exchange_type type, indicator & ind) - : data_(data), type_(type), ind_(&ind), backEnd_(NULL) {} - - ~standard_into_type() SOCI_OVERRIDE; - -protected: - void post_fetch(bool gotData, bool calledFromFetch) SOCI_OVERRIDE; - -private: - void define(statement_impl & st, int & position) SOCI_OVERRIDE; - void pre_exec(int num) SOCI_OVERRIDE; - void pre_fetch() SOCI_OVERRIDE; - void clean_up() SOCI_OVERRIDE; - - std::size_t size() const SOCI_OVERRIDE { return 1; } - - // conversion hook (from base type to arbitrary user type) - virtual void convert_from_base() {} - - void * data_; - exchange_type type_; - indicator * ind_; - - standard_into_type_backend * backEnd_; -}; - -// into type base class for vectors -class SOCI_DECL vector_into_type : public into_type_base -{ -public: - vector_into_type(void * data, exchange_type type) - : data_(data), type_(type), indVec_(NULL), - begin_(0), end_(NULL), backEnd_(NULL) {} - - vector_into_type(void * data, exchange_type type, - std::size_t begin, std::size_t * end) - : data_(data), type_(type), indVec_(NULL), - begin_(begin), end_(end), backEnd_(NULL) {} - - vector_into_type(void * data, exchange_type type, - std::vector & ind) - : data_(data), type_(type), indVec_(&ind), - begin_(0), end_(NULL), backEnd_(NULL) {} - - vector_into_type(void * data, exchange_type type, - std::vector & ind, - std::size_t begin, std::size_t * end) - : data_(data), type_(type), indVec_(&ind), - begin_(begin), end_(end), backEnd_(NULL) {} - - ~vector_into_type() SOCI_OVERRIDE; - -protected: - void post_fetch(bool gotData, bool calledFromFetch) SOCI_OVERRIDE; - - void define(statement_impl & st, int & position) SOCI_OVERRIDE; - void pre_exec(int num) SOCI_OVERRIDE; - void pre_fetch() SOCI_OVERRIDE; - void clean_up() SOCI_OVERRIDE; - void resize(std::size_t sz) SOCI_OVERRIDE; - std::size_t size() const SOCI_OVERRIDE; - - void * data_; - exchange_type type_; - std::vector * indVec_; - std::size_t begin_; - std::size_t * end_; - - vector_into_type_backend * backEnd_; - - virtual void convert_from_base() {} -}; - -// implementation for the basic types (those which are supported by the library -// out of the box without user-provided conversions) - -template -class into_type : public standard_into_type -{ -public: - into_type(T & t) - : standard_into_type(&t, - static_cast(exchange_traits::x_type)) {} - into_type(T & t, indicator & ind) - : standard_into_type(&t, - static_cast(exchange_traits::x_type), ind) {} -}; - -template -class into_type > : public vector_into_type -{ -public: - into_type(std::vector & v) - : vector_into_type(&v, - static_cast(exchange_traits::x_type)) {} - - into_type(std::vector & v, std::size_t begin, std::size_t * end) - : vector_into_type(&v, - static_cast(exchange_traits::x_type), - begin, end) {} - - into_type(std::vector & v, std::vector & ind) - : vector_into_type(&v, - static_cast(exchange_traits::x_type), ind) {} - - into_type(std::vector & v, std::vector & ind, - std::size_t begin, std::size_t * end) - : vector_into_type(&v, - static_cast(exchange_traits::x_type), ind, - begin, end) {} -}; - -// helper dispatchers for basic types - -template -into_type_ptr do_into(T & t, basic_type_tag) -{ - return into_type_ptr(new into_type(t)); -} - -template -into_type_ptr do_into(T & t, indicator & ind, basic_type_tag) -{ - return into_type_ptr(new into_type(t, ind)); -} - -template -into_type_ptr do_into(T & t, std::vector & ind, basic_type_tag) -{ - return into_type_ptr(new into_type(t, ind)); -} - -template -into_type_ptr do_into(std::vector & t, - std::size_t begin, std::size_t * end, basic_type_tag) -{ - return into_type_ptr(new into_type >(t, begin, end)); -} - -template -into_type_ptr do_into(std::vector & t, std::vector & ind, - std::size_t begin, std::size_t * end, basic_type_tag) -{ - return into_type_ptr(new into_type >(t, ind, begin, end)); -} - -} // namespace details - -} // namespace soci - -#endif // SOCI_INTO_TYPE_H_INCLUDED diff --git a/src/soci/include/soci/into.h b/src/soci/include/soci/into.h deleted file mode 100644 index a341ede616..0000000000 --- a/src/soci/include/soci/into.h +++ /dev/null @@ -1,90 +0,0 @@ -// -// Copyright (C) 2004-2016 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_INTO_H_INCLUDED -#define SOCI_INTO_H_INCLUDED - -#include "soci/into-type.h" -#include "soci/exchange-traits.h" -#include "soci/type-conversion.h" -// std -#include -#include - -namespace soci -{ - -// the into function is a helper for defining output variables -// these helpers work with both basic and user-defined types thanks to -// the tag-dispatching, as defined in exchange_traits template - -namespace details -{ -template -struct into_container -{ - into_container(T &_t, Indicator &_ind) - : t(_t), ind(_ind) {} - - T &t; - Indicator &ind; -private: - SOCI_NOT_ASSIGNABLE(into_container) -}; - -typedef void no_indicator; -template -struct into_container -{ - into_container(T &_t) - : t(_t) {} - - T &t; -private: - SOCI_NOT_ASSIGNABLE(into_container) -}; - -} // namespace details - -template -details::into_container - into(T &t) -{ return details::into_container(t); } - -template -details::into_container - into(T &t, Indicator &ind) -{ return details::into_container(t, ind); } - -// for char buffer with run-time size information -template -details::into_type_ptr into(T & t, std::size_t bufSize) -{ - return details::into_type_ptr(new details::into_type(t, bufSize)); -} - -// vectors with index ranges - -template -details::into_type_ptr into(std::vector & t, - std::size_t begin, std::size_t & end) -{ - return details::do_into(t, begin, &end, - typename details::exchange_traits >::type_family()); -} - -template -details::into_type_ptr into(std::vector & t, std::vector & ind, - std::size_t begin, std::size_t & end) -{ - return details::do_into(t, ind, begin, &end, - typename details::exchange_traits >::type_family()); -} - -} // namespace soci - -#endif // SOCI_INTO_H_INCLUDED diff --git a/src/soci/include/soci/mysql/soci-mysql.h b/src/soci/include/soci/mysql/soci-mysql.h deleted file mode 100644 index 01d7375263..0000000000 --- a/src/soci/include/soci/mysql/soci-mysql.h +++ /dev/null @@ -1,280 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// MySQL backend copyright (C) 2006 Pawel Aleksander Fedorynski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_MYSQL_H_INCLUDED -#define SOCI_MYSQL_H_INCLUDED - -#ifdef _WIN32 -# ifdef SOCI_DLL -# ifdef SOCI_MYSQL_SOURCE -# define SOCI_MYSQL_DECL __declspec(dllexport) -# else -# define SOCI_MYSQL_DECL __declspec(dllimport) -# endif // SOCI_DLL -# endif // SOCI_MYSQL_SOURCE -#endif // _WIN32 -// -// If SOCI_MYSQL_DECL isn't defined yet define it now -#ifndef SOCI_MYSQL_DECL -# define SOCI_MYSQL_DECL -#endif - -#include -#ifdef _WIN32 -#include // SOCKET -#endif // _WIN32 -#include // MySQL Client -#include - - -namespace soci -{ - -class SOCI_MYSQL_DECL mysql_soci_error : public soci_error -{ -public: - mysql_soci_error(std::string const & msg, int errNum) - : soci_error(msg), err_num_(errNum) {} - - unsigned int err_num_; -}; - -struct mysql_statement_backend; -struct mysql_standard_into_type_backend : details::standard_into_type_backend -{ - mysql_standard_into_type_backend(mysql_statement_backend &st) - : statement_(st) {} - - void define_by_pos(int &position, - void *data, details::exchange_type type) SOCI_OVERRIDE; - - void pre_fetch() SOCI_OVERRIDE; - void post_fetch(bool gotData, bool calledFromFetch, - indicator *ind) SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - mysql_statement_backend &statement_; - - void *data_; - details::exchange_type type_; - int position_; -}; - -struct mysql_vector_into_type_backend : details::vector_into_type_backend -{ - mysql_vector_into_type_backend(mysql_statement_backend &st) - : statement_(st) {} - - void define_by_pos(int &position, - void *data, details::exchange_type type) SOCI_OVERRIDE; - - void pre_fetch() SOCI_OVERRIDE; - void post_fetch(bool gotData, indicator *ind) SOCI_OVERRIDE; - - void resize(std::size_t sz) SOCI_OVERRIDE; - std::size_t size() SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - mysql_statement_backend &statement_; - - void *data_; - details::exchange_type type_; - int position_; -}; - -struct mysql_standard_use_type_backend : details::standard_use_type_backend -{ - mysql_standard_use_type_backend(mysql_statement_backend &st) - : statement_(st), position_(0), buf_(NULL) {} - - void bind_by_pos(int &position, - void *data, details::exchange_type type, bool readOnly) SOCI_OVERRIDE; - void bind_by_name(std::string const &name, - void *data, details::exchange_type type, bool readOnly) SOCI_OVERRIDE; - - void pre_use(indicator const *ind) SOCI_OVERRIDE; - void post_use(bool gotData, indicator *ind) SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - mysql_statement_backend &statement_; - - void *data_; - details::exchange_type type_; - int position_; - std::string name_; - char *buf_; -}; - -struct mysql_vector_use_type_backend : details::vector_use_type_backend -{ - mysql_vector_use_type_backend(mysql_statement_backend &st) - : statement_(st), position_(0) {} - - void bind_by_pos(int &position, - void *data, details::exchange_type type) SOCI_OVERRIDE; - void bind_by_name(std::string const &name, - void *data, details::exchange_type type) SOCI_OVERRIDE; - - void pre_use(indicator const *ind) SOCI_OVERRIDE; - - std::size_t size() SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - mysql_statement_backend &statement_; - - void *data_; - details::exchange_type type_; - int position_; - std::string name_; - std::vector buffers_; -}; - -struct mysql_session_backend; -struct mysql_statement_backend : details::statement_backend -{ - mysql_statement_backend(mysql_session_backend &session); - - void alloc() SOCI_OVERRIDE; - void clean_up() SOCI_OVERRIDE; - void prepare(std::string const &query, - details::statement_type eType) SOCI_OVERRIDE; - - exec_fetch_result execute(int number) SOCI_OVERRIDE; - exec_fetch_result fetch(int number) SOCI_OVERRIDE; - - long long get_affected_rows() SOCI_OVERRIDE; - int get_number_of_rows() SOCI_OVERRIDE; - std::string get_parameter_name(int index) const SOCI_OVERRIDE; - - std::string rewrite_for_procedure_call(std::string const &query) SOCI_OVERRIDE; - - int prepare_for_describe() SOCI_OVERRIDE; - void describe_column(int colNum, data_type &dtype, - std::string &columnName) SOCI_OVERRIDE; - - mysql_standard_into_type_backend * make_into_type_backend() SOCI_OVERRIDE; - mysql_standard_use_type_backend * make_use_type_backend() SOCI_OVERRIDE; - mysql_vector_into_type_backend * make_vector_into_type_backend() SOCI_OVERRIDE; - mysql_vector_use_type_backend * make_vector_use_type_backend() SOCI_OVERRIDE; - - mysql_session_backend &session_; - - MYSQL_RES *result_; - - // The query is split into chunks, separated by the named parameters; - // e.g. for "SELECT id FROM ttt WHERE name = :foo AND gender = :bar" - // we will have query chunks "SELECT id FROM ttt WHERE name = ", - // "AND gender = " and names "foo", "bar". - std::vector queryChunks_; - std::vector names_; // list of names for named binds - - long long rowsAffectedBulk_; // number of rows affected by the last bulk operation - - int numberOfRows_; // number of rows retrieved from the server - int currentRow_; // "current" row number to consume in postFetch - int rowsToConsume_; // number of rows to be consumed in postFetch - - bool justDescribed_; // to optimize row description with immediately - // following actual statement execution - - // Prefetch the row offsets in order to use mysql_row_seek() for - // random access to rows, since mysql_data_seek() is expensive. - std::vector resultRowOffsets_; - - bool hasIntoElements_; - bool hasVectorIntoElements_; - bool hasUseElements_; - bool hasVectorUseElements_; - - // the following maps are used for finding data buffers according to - // use elements specified by the user - - typedef std::map UseByPosBuffersMap; - UseByPosBuffersMap useByPosBuffers_; - - typedef std::map UseByNameBuffersMap; - UseByNameBuffersMap useByNameBuffers_; -}; - -struct mysql_rowid_backend : details::rowid_backend -{ - mysql_rowid_backend(mysql_session_backend &session); - - ~mysql_rowid_backend() SOCI_OVERRIDE; -}; - -struct mysql_blob_backend : details::blob_backend -{ - mysql_blob_backend(mysql_session_backend &session); - - ~mysql_blob_backend() SOCI_OVERRIDE; - - std::size_t get_len() SOCI_OVERRIDE; - std::size_t read(std::size_t offset, char *buf, - std::size_t toRead) SOCI_OVERRIDE; - std::size_t write(std::size_t offset, char const *buf, - std::size_t toWrite) SOCI_OVERRIDE; - std::size_t append(char const *buf, std::size_t toWrite) SOCI_OVERRIDE; - void trim(std::size_t newLen) SOCI_OVERRIDE; - - mysql_session_backend &session_; -}; - -struct mysql_session_backend : details::session_backend -{ - mysql_session_backend(connection_parameters const & parameters); - - ~mysql_session_backend() SOCI_OVERRIDE; - - void begin() SOCI_OVERRIDE; - void commit() SOCI_OVERRIDE; - void rollback() SOCI_OVERRIDE; - - bool get_last_insert_id(session&, std::string const&, long&) SOCI_OVERRIDE; - - // Note that MySQL supports both "SELECT 2+2" and "SELECT 2+2 FROM DUAL" - // syntaxes, but there doesn't seem to be any reason to use the longer one. - std::string get_dummy_from_table() const SOCI_OVERRIDE { return std::string(); } - - std::string get_backend_name() const SOCI_OVERRIDE { return "mysql"; } - - void clean_up(); - - mysql_statement_backend * make_statement_backend() SOCI_OVERRIDE; - mysql_rowid_backend * make_rowid_backend() SOCI_OVERRIDE; - mysql_blob_backend * make_blob_backend() SOCI_OVERRIDE; - - MYSQL *conn_; -}; - - -struct mysql_backend_factory : backend_factory -{ - mysql_backend_factory() {} - mysql_session_backend * make_session( - connection_parameters const & parameters) const SOCI_OVERRIDE; -}; - -extern SOCI_MYSQL_DECL mysql_backend_factory const mysql; - -extern "C" -{ - -// for dynamic backend loading -SOCI_MYSQL_DECL backend_factory const * factory_mysql(); -SOCI_MYSQL_DECL void register_factory_mysql(); - -} // extern "C" - -} // namespace soci - -#endif // SOCI_MYSQL_H_INCLUDED diff --git a/src/soci/include/soci/noreturn.h b/src/soci/include/soci/noreturn.h deleted file mode 100644 index 26d8cc7b33..0000000000 --- a/src/soci/include/soci/noreturn.h +++ /dev/null @@ -1,22 +0,0 @@ -// -// Copyright (C) 2015 Vadim Zeitlin -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_NORETURN_H_INCLUDED -#define SOCI_NORETURN_H_INCLUDED - -// Define a portable SOCI_NORETURN macro. -// -// TODO-C++11: Use [[noreturn]] attribute. -#if defined(__GNUC__) -# define SOCI_NORETURN __attribute__((noreturn)) void -#elif defined(_MSC_VER) -# define SOCI_NORETURN __declspec(noreturn) void -#else -# define SOCI_NORETURN void -#endif - -#endif // SOCI_NORETURN_H_INCLUDED diff --git a/src/soci/include/soci/odbc/soci-odbc.h b/src/soci/include/soci/odbc/soci-odbc.h deleted file mode 100644 index 5159af9fc0..0000000000 --- a/src/soci/include/soci/odbc/soci-odbc.h +++ /dev/null @@ -1,476 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_ODBC_H_INCLUDED -#define SOCI_ODBC_H_INCLUDED - -#ifdef _WIN32 -# ifdef SOCI_DLL -# ifdef SOCI_ODBC_SOURCE -# define SOCI_ODBC_DECL __declspec(dllexport) -# else -# define SOCI_ODBC_DECL __declspec(dllimport) -# endif // SOCI_ODBC_SOURCE -# endif // SOCI_DLL -#endif // _WIN32 -// -// If SOCI_ODBC_DECL isn't defined yet define it now -#ifndef SOCI_ODBC_DECL -# define SOCI_ODBC_DECL -#endif - -#include "soci/soci-platform.h" -#include -#include -#include -#if defined(_MSC_VER) || defined(__MINGW32__) -#include -#endif -#include // ODBC -#include // strcpy() - -#ifndef SQL_SS_LENGTH_UNLIMITED -#define SQL_SS_LENGTH_UNLIMITED 0 -#endif - -namespace soci -{ - -namespace details -{ - // TODO: Do we want to make it a part of public interface? --mloskot - std::size_t const odbc_max_buffer_length = 100 * 1024 * 1024; - - // select max size from following MSDN article - // https://msdn.microsoft.com/en-us/library/ms130896.aspx - SQLLEN const ODBC_MAX_COL_SIZE = 8000; - - // This cast is only used to avoid compiler warnings when passing strings - // to ODBC functions, the returned string may *not* be really modified. - inline SQLCHAR* sqlchar_cast(std::string const& s) - { - return reinterpret_cast(const_cast(s.c_str())); - } -} - -// Option allowing to specify the "driver completion" parameter of -// SQLDriverConnect(). Its possible values are the same as the allowed values -// for this parameter in the official ODBC, i.e. one of SQL_DRIVER_XXX (in -// string form as all options are strings currently). -extern SOCI_ODBC_DECL char const * odbc_option_driver_complete; - -struct odbc_statement_backend; - -// Helper of into and use backends. -class odbc_standard_type_backend_base -{ -protected: - odbc_standard_type_backend_base(odbc_statement_backend &st) - : statement_(st) {} - - // Check if we need to pass 64 bit integers as strings to the database as - // some drivers don't support them directly. - inline bool use_string_for_bigint() const; - - // If we do need to use strings for 64 bit integers, this constant defines - // the maximal string length needed. - enum - { - // This is the length of decimal representation of UINT64_MAX + 1. - max_bigint_length = 21 - }; - - odbc_statement_backend &statement_; -private: - SOCI_NOT_COPYABLE(odbc_standard_type_backend_base) -}; - -struct odbc_standard_into_type_backend : details::standard_into_type_backend, - private odbc_standard_type_backend_base -{ - odbc_standard_into_type_backend(odbc_statement_backend &st) - : odbc_standard_type_backend_base(st), buf_(0) - {} - - void define_by_pos(int &position, - void *data, details::exchange_type type) SOCI_OVERRIDE; - - void pre_fetch() SOCI_OVERRIDE; - void post_fetch(bool gotData, bool calledFromFetch, - indicator *ind) SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - char *buf_; // generic buffer - void *data_; - details::exchange_type type_; - int position_; - SQLSMALLINT odbcType_; - SQLLEN valueLen_; -private: - SOCI_NOT_COPYABLE(odbc_standard_into_type_backend) -}; - -struct odbc_vector_into_type_backend : details::vector_into_type_backend, - private odbc_standard_type_backend_base -{ - odbc_vector_into_type_backend(odbc_statement_backend &st) - : odbc_standard_type_backend_base(st), indHolders_(NULL), - data_(NULL), buf_(NULL) {} - - void define_by_pos(int &position, - void *data, details::exchange_type type) SOCI_OVERRIDE; - - void pre_fetch() SOCI_OVERRIDE; - void post_fetch(bool gotData, indicator *ind) SOCI_OVERRIDE; - - void resize(std::size_t sz) SOCI_OVERRIDE; - std::size_t size() SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - // helper function for preparing indicators - // (as part of the define_by_pos) - void prepare_indicators(std::size_t size); - - - SQLLEN *indHolders_; - std::vector indHolderVec_; - void *data_; - char *buf_; // generic buffer - details::exchange_type type_; - std::size_t colSize_; // size of the string column (used for strings) - SQLSMALLINT odbcType_; -}; - -struct odbc_standard_use_type_backend : details::standard_use_type_backend, - private odbc_standard_type_backend_base -{ - odbc_standard_use_type_backend(odbc_statement_backend &st) - : odbc_standard_type_backend_base(st), - position_(-1), data_(0), buf_(0), indHolder_(0) {} - - void bind_by_pos(int &position, - void *data, details::exchange_type type, bool readOnly) SOCI_OVERRIDE; - void bind_by_name(std::string const &name, - void *data, details::exchange_type type, bool readOnly) SOCI_OVERRIDE; - - void pre_use(indicator const *ind) SOCI_OVERRIDE; - void post_use(bool gotData, indicator *ind) SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - // Return the pointer to the buffer containing data to be used by ODBC. - // This can be either data_ itself or buf_, that is allocated by this - // function if necessary. - // - // Also fill in the size of the data and SQL and C types of it. - void* prepare_for_bind(SQLLEN &size, - SQLSMALLINT &sqlType, SQLSMALLINT &cType); - - int position_; - void *data_; - details::exchange_type type_; - char *buf_; - SQLLEN indHolder_; - -private: - // Copy string data to buf_ and set size, sqlType and cType to the values - // appropriate for strings. - void copy_from_string(std::string const& s, - SQLLEN& size, - SQLSMALLINT& sqlType, - SQLSMALLINT& cType); - -}; - -struct odbc_vector_use_type_backend : details::vector_use_type_backend, - private odbc_standard_type_backend_base -{ - odbc_vector_use_type_backend(odbc_statement_backend &st) - : odbc_standard_type_backend_base(st), indHolders_(NULL), - data_(NULL), buf_(NULL) {} - - // helper function for preparing indicators - // (as part of the define_by_pos) - void prepare_indicators(std::size_t size); - - // common part for bind_by_pos and bind_by_name - void prepare_for_bind(void *&data, SQLUINTEGER &size, SQLSMALLINT &sqlType, SQLSMALLINT &cType); - void bind_helper(int &position, - void *data, details::exchange_type type); - - void bind_by_pos(int &position, - void *data, details::exchange_type type) SOCI_OVERRIDE; - void bind_by_name(std::string const &name, - void *data, details::exchange_type type) SOCI_OVERRIDE; - - void pre_use(indicator const *ind) SOCI_OVERRIDE; - - std::size_t size() SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - - SQLLEN *indHolders_; - std::vector indHolderVec_; - void *data_; - details::exchange_type type_; - char *buf_; // generic buffer - std::size_t colSize_; // size of the string column (used for strings) - // used for strings only - std::size_t maxSize_; -}; - -struct odbc_session_backend; -struct odbc_statement_backend : details::statement_backend -{ - odbc_statement_backend(odbc_session_backend &session); - - void alloc() SOCI_OVERRIDE; - void clean_up() SOCI_OVERRIDE; - void prepare(std::string const &query, - details::statement_type eType) SOCI_OVERRIDE; - - exec_fetch_result execute(int number) SOCI_OVERRIDE; - exec_fetch_result fetch(int number) SOCI_OVERRIDE; - - long long get_affected_rows() SOCI_OVERRIDE; - int get_number_of_rows() SOCI_OVERRIDE; - std::string get_parameter_name(int index) const SOCI_OVERRIDE; - - std::string rewrite_for_procedure_call(std::string const &query) SOCI_OVERRIDE; - - int prepare_for_describe() SOCI_OVERRIDE; - void describe_column(int colNum, data_type &dtype, - std::string &columnName) SOCI_OVERRIDE; - - // helper for defining into vector - std::size_t column_size(int position); - - odbc_standard_into_type_backend * make_into_type_backend() SOCI_OVERRIDE; - odbc_standard_use_type_backend * make_use_type_backend() SOCI_OVERRIDE; - odbc_vector_into_type_backend * make_vector_into_type_backend() SOCI_OVERRIDE; - odbc_vector_use_type_backend * make_vector_use_type_backend() SOCI_OVERRIDE; - - odbc_session_backend &session_; - SQLHSTMT hstmt_; - SQLULEN numRowsFetched_; - bool hasVectorUseElements_; - bool boundByName_; - bool boundByPos_; - - long long rowsAffected_; // number of rows affected by the last operation - - std::string query_; - std::vector names_; // list of names for named binds - -}; - -struct odbc_rowid_backend : details::rowid_backend -{ - odbc_rowid_backend(odbc_session_backend &session); - - ~odbc_rowid_backend() SOCI_OVERRIDE; -}; - -struct odbc_blob_backend : details::blob_backend -{ - odbc_blob_backend(odbc_session_backend &session); - - ~odbc_blob_backend() SOCI_OVERRIDE; - - std::size_t get_len() SOCI_OVERRIDE; - std::size_t read(std::size_t offset, char *buf, - std::size_t toRead) SOCI_OVERRIDE; - std::size_t write(std::size_t offset, char const *buf, - std::size_t toWrite) SOCI_OVERRIDE; - std::size_t append(char const *buf, std::size_t toWrite) SOCI_OVERRIDE; - void trim(std::size_t newLen) SOCI_OVERRIDE; - - odbc_session_backend &session_; -}; - -struct odbc_session_backend : details::session_backend -{ - odbc_session_backend(connection_parameters const & parameters); - - ~odbc_session_backend() SOCI_OVERRIDE; - - void begin() SOCI_OVERRIDE; - void commit() SOCI_OVERRIDE; - void rollback() SOCI_OVERRIDE; - - bool get_next_sequence_value(session & s, - std::string const & sequence, long & value) SOCI_OVERRIDE; - bool get_last_insert_id(session & s, - std::string const & table, long & value) SOCI_OVERRIDE; - - std::string get_dummy_from_table() const SOCI_OVERRIDE; - - std::string get_backend_name() const SOCI_OVERRIDE { return "odbc"; } - - void configure_connection(); - void reset_transaction(); - - void clean_up(); - - odbc_statement_backend * make_statement_backend() SOCI_OVERRIDE; - odbc_rowid_backend * make_rowid_backend() SOCI_OVERRIDE; - odbc_blob_backend * make_blob_backend() SOCI_OVERRIDE; - - enum database_product - { - prod_uninitialized, // Never returned by get_database_product(). - prod_firebird, - prod_mssql, - prod_mysql, - prod_oracle, - prod_postgresql, - prod_sqlite, - prod_unknown = -1 - }; - - // Determine the type of the database we're connected to. - database_product get_database_product() const; - - // Return full ODBC connection string. - std::string get_connection_string() const { return connection_string_; } - - SQLHENV henv_; - SQLHDBC hdbc_; - - std::string connection_string_; - -private: - mutable database_product product_; -}; - -class SOCI_ODBC_DECL odbc_soci_error : public soci_error -{ - SQLCHAR message_[SQL_MAX_MESSAGE_LENGTH + 1]; - SQLCHAR sqlstate_[SQL_SQLSTATE_SIZE + 1]; - SQLINTEGER sqlcode_; - -public: - odbc_soci_error(SQLSMALLINT htype, - SQLHANDLE hndl, - std::string const & msg) - : soci_error(interpret_odbc_error(htype, hndl, msg)) - { - } - - SQLCHAR const * odbc_error_code() const - { - return sqlstate_; - } - SQLINTEGER native_error_code() const - { - return sqlcode_; - } - SQLCHAR const * odbc_error_message() const - { - return message_; - } -private: - std::string interpret_odbc_error(SQLSMALLINT htype, SQLHANDLE hndl, std::string const& msg) - { - const char* socierror = NULL; - - SQLSMALLINT length, i = 1; - switch ( SQLGetDiagRecA(htype, hndl, i, sqlstate_, &sqlcode_, - message_, SQL_MAX_MESSAGE_LENGTH + 1, - &length) ) - { - case SQL_SUCCESS: - // The error message was successfully retrieved. - break; - - case SQL_INVALID_HANDLE: - socierror = "[SOCI]: Invalid handle."; - break; - - case SQL_ERROR: - socierror = "[SOCI]: SQLGetDiagRec() error."; - break; - - case SQL_SUCCESS_WITH_INFO: - socierror = "[SOCI]: Error message too long."; - break; - - case SQL_NO_DATA: - socierror = "[SOCI]: No error."; - break; - - default: - socierror = "[SOCI]: Unexpected SQLGetDiagRec() return value."; - break; - } - - if (socierror) - { - // Use our own error message if we failed to retrieve the ODBC one. - strcpy(reinterpret_cast(message_), socierror); - - // Use "General warning" SQLSTATE code. - strcpy(reinterpret_cast(sqlstate_), "01000"); - - sqlcode_ = 0; - } - - std::ostringstream ss; - ss << "Error " << msg << ": " << message_ << " (SQL state " << sqlstate_ << ")"; - - return ss.str(); - } -}; - -inline bool is_odbc_error(SQLRETURN rc) -{ - if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO && rc != SQL_NO_DATA) - { - return true; - } - else - { - return false; - } -} - -inline bool odbc_standard_type_backend_base::use_string_for_bigint() const -{ - // Oracle ODBC driver doesn't support SQL_C_[SU]BIGINT data types - // (see appendix G.1 of Oracle Database Administrator's reference at - // http://docs.oracle.com/cd/B19306_01/server.102/b15658/app_odbc.htm), - // so we need a special workaround for this case and we represent 64 - // bit integers as strings and rely on ODBC driver for transforming - // them to SQL_NUMERIC. - return statement_.session_.get_database_product() - == odbc_session_backend::prod_oracle; -} - -struct odbc_backend_factory : backend_factory -{ - odbc_backend_factory() {} - odbc_session_backend * make_session( - connection_parameters const & parameters) const SOCI_OVERRIDE; -}; - -extern SOCI_ODBC_DECL odbc_backend_factory const odbc; - -extern "C" -{ - -// for dynamic backend loading -SOCI_ODBC_DECL backend_factory const * factory_odbc(); -SOCI_ODBC_DECL void register_factory_odbc(); - -} // extern "C" - -} // namespace soci - -#endif // SOCI_EMPTY_H_INCLUDED diff --git a/src/soci/include/soci/once-temp-type.h b/src/soci/include/soci/once-temp-type.h deleted file mode 100644 index f1940f8314..0000000000 --- a/src/soci/include/soci/once-temp-type.h +++ /dev/null @@ -1,160 +0,0 @@ -// -// Copyright (C) 2004-2016 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_ONCE_TEMP_TYPE_H_INCLUDED -#define SOCI_ONCE_TEMP_TYPE_H_INCLUDED - -#include "soci/soci-platform.h" -#include "soci/ref-counted-statement.h" -#include "soci/prepare-temp-type.h" - -namespace soci -{ - -class session; - -namespace details -{ - -class ref_counted_statement; - -// this needs to be lightweight and copyable -class SOCI_DECL once_temp_type -{ -public: - - once_temp_type(session & s); - once_temp_type(once_temp_type const & o); - once_temp_type & operator=(once_temp_type const & o); - - ~once_temp_type() SOCI_NOEXCEPT_FALSE; - - template - once_temp_type & operator<<(T const & t) - { - rcst_->accumulate(t); - return *this; - } - - once_temp_type & operator,(into_type_ptr const &); - once_temp_type & operator,(use_type_ptr const &); - - template - once_temp_type &operator,(into_container const &ic) - { - rcst_->exchange(ic); - return *this; - } - template - once_temp_type &operator,(use_container const &uc) - { - rcst_->exchange(uc); - return *this; - } - -private: - ref_counted_statement * rcst_; -}; - -// this needs to be lightweight and copyable -class once_type -{ -public: - once_type() : session_(NULL) {} - once_type(session * s) : session_(s) {} - - void set_session(session * s) - { - session_ = s; - } - - template - once_temp_type operator<<(T const & t) - { - once_temp_type o(*session_); - o << t; - return o; - } - -private: - session * session_; -}; - - -// this needs to be lightweight and copyable -class prepare_type -{ -public: - prepare_type() : session_(NULL) {} - prepare_type(session * s) : session_(s) {} - - void set_session(session * s) - { - session_ = s; - } - - template - prepare_temp_type operator<<(T const & t) - { - prepare_temp_type p(*session_); - p << t; - return p; - } - -private: - session * session_; -}; - -} // namespace details - -// Note: ddl_type is intended to be used just as once_temp_type, -// but since it can be also used directly (explicitly) by the user code, -// it is declared outside of the namespace details. -class SOCI_DECL ddl_type -{ -public: - - ddl_type(session & s); - ddl_type(const ddl_type & d); - ddl_type & operator=(const ddl_type & d); - - ~ddl_type() SOCI_NOEXCEPT_FALSE; - - void create_table(const std::string & tableName); - void add_column(const std::string & tableName, - const std::string & columnName, data_type dt, - int precision, int scale); - void alter_column(const std::string & tableName, - const std::string & columnName, data_type dt, - int precision, int scale); - void drop_column(const std::string & tableName, - const std::string & columnName); - ddl_type & column(const std::string & columnName, data_type dt, - int precision = 0, int scale = 0); - ddl_type & unique(const std::string & name, - const std::string & columnNames); - ddl_type & primary_key(const std::string & name, - const std::string & columnNames); - ddl_type & foreign_key(const std::string & name, - const std::string & columnNames, - const std::string & refTableName, - const std::string & refColumnNames); - - ddl_type & operator()(const std::string & arbitrarySql); - - // helper function for handling delimiters - // between various parts of DDL statements - void set_tail(const std::string & tail); - -private: - session * s_; - details::ref_counted_statement * rcst_; -}; - -} // namespace soci - -#endif diff --git a/src/soci/include/soci/oracle/soci-oracle.h b/src/soci/include/soci/oracle/soci-oracle.h deleted file mode 100644 index 5af13f81d8..0000000000 --- a/src/soci/include/soci/oracle/soci-oracle.h +++ /dev/null @@ -1,481 +0,0 @@ -// -// Copyright (C) 2004-2016 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_ORACLE_H_INCLUDED -#define SOCI_ORACLE_H_INCLUDED - -#ifdef _WIN32 -# ifdef SOCI_DLL -# ifdef SOCI_ORACLE_SOURCE -# define SOCI_ORACLE_DECL __declspec(dllexport) -# else -# define SOCI_ORACLE_DECL __declspec(dllimport) -# endif // SOCI_ORACLE_SOURCE -# endif // SOCI_DLL -#endif // _WIN32 -// -// If SOCI_ORACLE_DECL isn't defined yet define it now -#ifndef SOCI_ORACLE_DECL -# define SOCI_ORACLE_DECL -#endif - -#include -#include // OCI -#include -#include - -#ifdef _MSC_VER -#pragma warning(disable:4512 4511) -#endif - - -namespace soci -{ - -class SOCI_ORACLE_DECL oracle_soci_error : public soci_error -{ -public: - oracle_soci_error(std::string const & msg, int errNum = 0); - - error_category get_error_category() const SOCI_OVERRIDE { return cat_; } - - int err_num_; - error_category cat_; -}; - - -struct oracle_statement_backend; -struct oracle_standard_into_type_backend : details::standard_into_type_backend -{ - oracle_standard_into_type_backend(oracle_statement_backend &st) - : statement_(st), defnp_(NULL), indOCIHolder_(0), - data_(NULL), buf_(NULL) {} - - void define_by_pos(int &position, - void *data, details::exchange_type type) SOCI_OVERRIDE; - - void read_from_lob(OCILobLocator * lobp, std::string & value); - - void pre_exec(int num) SOCI_OVERRIDE; - void pre_fetch() SOCI_OVERRIDE; - void post_fetch(bool gotData, bool calledFromFetch, - indicator *ind) SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - oracle_statement_backend &statement_; - - OCIDefine *defnp_; - sb2 indOCIHolder_; - void *data_; - void *ociData_; - char *buf_; // generic buffer - details::exchange_type type_; - - ub2 rCode_; -}; - -struct oracle_vector_into_type_backend : details::vector_into_type_backend -{ - oracle_vector_into_type_backend(oracle_statement_backend &st) - : statement_(st), defnp_(NULL), indOCIHolders_(NULL), - data_(NULL), buf_(NULL), user_ranges_(true) {} - - void define_by_pos(int &position, - void *data, details::exchange_type type) SOCI_OVERRIDE - { - user_ranges_ = false; - define_by_pos_bulk(position, data, type, 0, &end_var_); - } - - void define_by_pos_bulk( - int & position, void * data, details::exchange_type type, - std::size_t begin, std::size_t * end) SOCI_OVERRIDE; - - void pre_fetch() SOCI_OVERRIDE; - void post_fetch(bool gotData, indicator *ind) SOCI_OVERRIDE; - - void resize(std::size_t sz) SOCI_OVERRIDE; - std::size_t size() SOCI_OVERRIDE; - std::size_t full_size(); - - void clean_up() SOCI_OVERRIDE; - - // helper function for preparing indicators and sizes_ vectors - // (as part of the define_by_pos) - void prepare_indicators(std::size_t size); - - oracle_statement_backend &statement_; - - OCIDefine *defnp_; - sb2 *indOCIHolders_; - std::vector indOCIHolderVec_; - void *data_; - char *buf_; // generic buffer - details::exchange_type type_; - std::size_t begin_; - std::size_t * end_; - std::size_t end_var_; - bool user_ranges_; - std::size_t colSize_; // size of the string column (used for strings) - std::vector sizes_; // sizes of data fetched (used for strings) - - std::vector rCodes_; -}; - -struct oracle_standard_use_type_backend : details::standard_use_type_backend -{ - oracle_standard_use_type_backend(oracle_statement_backend &st) - : statement_(st), bindp_(NULL), indOCIHolder_(0), - data_(NULL), buf_(NULL) {} - - void bind_by_pos(int &position, - void *data, details::exchange_type type, bool readOnly) SOCI_OVERRIDE; - void bind_by_name(std::string const &name, - void *data, details::exchange_type type, bool readOnly) SOCI_OVERRIDE; - - // common part for bind_by_pos and bind_by_name - void prepare_for_bind(void *&data, sb4 &size, ub2 &oracleType, bool readOnly); - - // common helper for pre_use for LOB-directed wrapped types - void write_to_lob(OCILobLocator * lobp, const std::string & value); - - // common lazy initialization of the temporary LOB object - void lazy_temp_lob_init(); - - void pre_exec(int num) SOCI_OVERRIDE; - void pre_use(indicator const *ind) SOCI_OVERRIDE; - void post_use(bool gotData, indicator *ind) SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - oracle_statement_backend &statement_; - - OCIBind *bindp_; - sb2 indOCIHolder_; - void *data_; - void *ociData_; - bool readOnly_; - char *buf_; // generic buffer - details::exchange_type type_; -}; - -struct oracle_vector_use_type_backend : details::vector_use_type_backend -{ - oracle_vector_use_type_backend(oracle_statement_backend &st) - : statement_(st), bindp_(NULL), indOCIHolders_(NULL), - data_(NULL), buf_(NULL) {} - - void bind_by_pos(int & position, - void * data, details::exchange_type type) SOCI_OVERRIDE - { - bind_by_pos_bulk(position, data, type, 0, &end_var_); - } - - void bind_by_pos_bulk(int & position, - void * data, details::exchange_type type, - std::size_t begin, std::size_t * end) SOCI_OVERRIDE; - - void bind_by_name(const std::string & name, - void * data, details::exchange_type type) SOCI_OVERRIDE - { - bind_by_name_bulk(name, data, type, 0, &end_var_); - } - - void bind_by_name_bulk(std::string const &name, - void *data, details::exchange_type type, - std::size_t begin, std::size_t * end) SOCI_OVERRIDE; - - // common part for bind_by_pos and bind_by_name - void prepare_for_bind(void *&data, sb4 &size, ub2 &oracleType); - - // helper function for preparing indicators and sizes_ vectors - // (as part of the bind_by_pos and bind_by_name) - void prepare_indicators(std::size_t size); - - void pre_use(indicator const *ind) SOCI_OVERRIDE; - - std::size_t size() SOCI_OVERRIDE; // active size (might be lower than full vector size) - std::size_t full_size(); // actual size of the user-provided vector - - void clean_up() SOCI_OVERRIDE; - - oracle_statement_backend &statement_; - - OCIBind *bindp_; - std::vector indOCIHolderVec_; - sb2 *indOCIHolders_; - void *data_; - char *buf_; // generic buffer - details::exchange_type type_; - std::size_t begin_; - std::size_t * end_; - std::size_t end_var_; - - // used for strings only - std::vector sizes_; - std::size_t maxSize_; -}; - -struct oracle_session_backend; -struct oracle_statement_backend : details::statement_backend -{ - oracle_statement_backend(oracle_session_backend &session); - - void alloc() SOCI_OVERRIDE; - void clean_up() SOCI_OVERRIDE; - void prepare(std::string const &query, - details::statement_type eType) SOCI_OVERRIDE; - - exec_fetch_result execute(int number) SOCI_OVERRIDE; - exec_fetch_result fetch(int number) SOCI_OVERRIDE; - - long long get_affected_rows() SOCI_OVERRIDE; - int get_number_of_rows() SOCI_OVERRIDE; - std::string get_parameter_name(int index) const SOCI_OVERRIDE; - - std::string rewrite_for_procedure_call(std::string const &query) SOCI_OVERRIDE; - - int prepare_for_describe() SOCI_OVERRIDE; - void describe_column(int colNum, data_type &dtype, - std::string &columnName) SOCI_OVERRIDE; - - // helper for defining into vector - std::size_t column_size(int position); - - oracle_standard_into_type_backend * make_into_type_backend() SOCI_OVERRIDE; - oracle_standard_use_type_backend * make_use_type_backend() SOCI_OVERRIDE; - oracle_vector_into_type_backend * make_vector_into_type_backend() SOCI_OVERRIDE; - oracle_vector_use_type_backend * make_vector_use_type_backend() SOCI_OVERRIDE; - - oracle_session_backend &session_; - - OCIStmt *stmtp_; - - bool boundByName_; - bool boundByPos_; - bool noData_; -}; - -struct oracle_rowid_backend : details::rowid_backend -{ - oracle_rowid_backend(oracle_session_backend &session); - - ~oracle_rowid_backend() SOCI_OVERRIDE; - - OCIRowid *rowidp_; -}; - -struct oracle_blob_backend : details::blob_backend -{ - oracle_blob_backend(oracle_session_backend &session); - - ~oracle_blob_backend() SOCI_OVERRIDE; - - std::size_t get_len() SOCI_OVERRIDE; - - std::size_t read(std::size_t offset, char *buf, - std::size_t toRead) SOCI_OVERRIDE; - - std::size_t read_from_start(char * buf, std::size_t toRead, - std::size_t offset) SOCI_OVERRIDE - { - return read(offset + 1, buf, toRead); - } - - std::size_t write(std::size_t offset, char const *buf, - std::size_t toWrite) SOCI_OVERRIDE; - - std::size_t write_from_start(const char * buf, std::size_t toWrite, - std::size_t offset) SOCI_OVERRIDE - { - return write(offset + 1, buf, toWrite); - } - - std::size_t append(char const *buf, std::size_t toWrite) SOCI_OVERRIDE; - - void trim(std::size_t newLen) SOCI_OVERRIDE; - - oracle_session_backend &session_; - - OCILobLocator *lobp_; -}; - -struct oracle_session_backend : details::session_backend -{ - oracle_session_backend(std::string const & serviceName, - std::string const & userName, - std::string const & password, - int mode, - bool decimals_as_strings = false, - int charset = 0, - int ncharset = 0); - - ~oracle_session_backend() SOCI_OVERRIDE; - - void begin() SOCI_OVERRIDE; - void commit() SOCI_OVERRIDE; - void rollback() SOCI_OVERRIDE; - - std::string get_table_names_query() const SOCI_OVERRIDE - { - return "select table_name" - " from user_tables"; - } - - std::string get_column_descriptions_query() const SOCI_OVERRIDE - { - return "select column_name," - " data_type," - " char_length as character_maximum_length," - " data_precision as numeric_precision," - " data_scale as numeric_scale," - " decode(nullable, 'Y', 'YES', 'N', 'NO') as is_nullable" - " from user_tab_columns" - " where table_name = :t"; - } - - std::string create_column_type(data_type dt, - int precision, int scale) SOCI_OVERRIDE - { - // Oracle-specific SQL syntax: - - std::string res; - switch (dt) - { - case dt_string: - { - std::ostringstream oss; - - if (precision == 0) - { - oss << "clob"; - } - else - { - oss << "varchar(" << precision << ")"; - } - - res += oss.str(); - } - break; - - case dt_date: - res += "timestamp"; - break; - - case dt_double: - { - std::ostringstream oss; - if (precision == 0) - { - oss << "number"; - } - else - { - oss << "number(" << precision << ", " << scale << ")"; - } - - res += oss.str(); - } - break; - - case dt_integer: - res += "integer"; - break; - - case dt_long_long: - res += "number"; - break; - - case dt_unsigned_long_long: - res += "number"; - break; - - case dt_blob: - res += "blob"; - break; - - case dt_xml: - res += "xmltype"; - break; - - default: - throw soci_error("this data_type is not supported in create_column"); - } - - return res; - } - std::string add_column(const std::string & tableName, - const std::string & columnName, data_type dt, - int precision, int scale) SOCI_OVERRIDE - { - return "alter table " + tableName + " add " + - columnName + " " + create_column_type(dt, precision, scale); - } - std::string alter_column(const std::string & tableName, - const std::string & columnName, data_type dt, - int precision, int scale) SOCI_OVERRIDE - { - return "alter table " + tableName + " modify " + - columnName + " " + create_column_type(dt, precision, scale); - } - std::string empty_blob() SOCI_OVERRIDE - { - return "empty_blob()"; - } - std::string nvl() SOCI_OVERRIDE - { - return "nvl"; - } - - std::string get_dummy_from_table() const SOCI_OVERRIDE { return "dual"; } - - std::string get_backend_name() const SOCI_OVERRIDE { return "oracle"; } - - void clean_up(); - - oracle_statement_backend * make_statement_backend() SOCI_OVERRIDE; - oracle_rowid_backend * make_rowid_backend() SOCI_OVERRIDE; - oracle_blob_backend * make_blob_backend() SOCI_OVERRIDE; - - bool get_option_decimals_as_strings() { return decimals_as_strings_; } - - // Return either SQLT_FLT or SQLT_BDOUBLE as the type to use when binding - // values of C type "double" (the latter is preferable but might not be - // always available). - ub2 get_double_sql_type() const; - - OCIEnv *envhp_; - OCIServer *srvhp_; - OCIError *errhp_; - OCISvcCtx *svchp_; - OCISession *usrhp_; - bool decimals_as_strings_; -}; - -struct oracle_backend_factory : backend_factory -{ - oracle_backend_factory() {} - oracle_session_backend * make_session( - connection_parameters const & parameters) const SOCI_OVERRIDE; -}; - -extern SOCI_ORACLE_DECL oracle_backend_factory const oracle; - -extern "C" -{ - -// for dynamic backend loading -SOCI_ORACLE_DECL backend_factory const * factory_oracle(); -SOCI_ORACLE_DECL void register_factory_oracle(); - -} // extern "C" - -} // namespace soci - -#endif diff --git a/src/soci/include/soci/postgresql/soci-postgresql.h b/src/soci/include/soci/postgresql/soci-postgresql.h deleted file mode 100644 index 0710b05905..0000000000 --- a/src/soci/include/soci/postgresql/soci-postgresql.h +++ /dev/null @@ -1,421 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Copyright (C) 2011 Gevorg Voskanyan -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_POSTGRESQL_H_INCLUDED -#define SOCI_POSTGRESQL_H_INCLUDED - -#ifdef _WIN32 -# ifdef SOCI_DLL -# ifdef SOCI_POSTGRESQL_SOURCE -# define SOCI_POSTGRESQL_DECL __declspec(dllexport) -# else -# define SOCI_POSTGRESQL_DECL __declspec(dllimport) -# endif // SOCI_POSTGRESQL_SOURCE -# endif // SOCI_DLL -#endif // _WIN32 -// -// If SOCI_POSTGRESQL_DECL isn't defined yet define it now -#ifndef SOCI_POSTGRESQL_DECL -# define SOCI_POSTGRESQL_DECL -#endif - -#include -#include -#include - -namespace soci -{ - -class SOCI_POSTGRESQL_DECL postgresql_soci_error : public soci_error -{ -public: - postgresql_soci_error(std::string const & msg, char const * sqlst); - - std::string sqlstate() const; - - error_category get_error_category() const SOCI_OVERRIDE { return cat_; } - -private: - char sqlstate_[ 5 ]; // not std::string to keep copy-constructor no-throw - error_category cat_; -}; - -struct postgresql_session_backend; - -namespace details -{ - -// A class thinly encapsulating PGresult. Its main purpose is to ensure that -// PQclear() is always called, avoiding result memory leaks. -class postgresql_result -{ -public: - // Creates a wrapper for the given, possibly NULL, result. The wrapper - // object takes ownership of the result object and will call PQclear() on it. - explicit postgresql_result( - postgresql_session_backend & sessionBackend, - PGresult * result) - : sessionBackend_(sessionBackend) - { - init(result); - } - - // Frees any currently stored result pointer and takes ownership of the - // given one. - void reset(PGresult* result = NULL) - { - free(); - init(result); - } - - // Check whether the status is PGRES_COMMAND_OK and throw an exception if - // it is different. Notice that if the query can return any results, - // check_for_data() below should be used instead to verify whether anything - // was returned or not. - // - // The provided error message is used only for the exception being thrown - // and should describe the operation which yielded this result. - void check_for_errors(char const* errMsg) const; - - // Check whether the status indicates successful query completion, either - // with the return results (in which case true is returned) or without them - // (then false is returned). If the status corresponds to an error, throws - // an exception, just as check_for_errors(). - bool check_for_data(char const* errMsg) const; - - // Implicit conversion to const PGresult: this is somewhat dangerous but - // allows us to avoid changing the existing code that uses PGresult and - // avoids the really bad problem with calling PQclear() twice accidentally - // as this would require a conversion to non-const pointer that we do not - // provide. - operator const PGresult*() const { return result_; } - - // Get the associated result (which may be NULL). Unlike the implicit - // conversion above, this one returns a non-const pointer, so you should be - // careful to avoid really modifying it. - PGresult* get_result() const { return result_; } - - // Dtor frees the result. - ~postgresql_result() { free(); } - -private: - void init(PGresult* result) - { - result_ = result; - } - - void free() - { - // Notice that it is safe to call PQclear() with NULL pointer, it - // simply does nothing in this case. - PQclear(result_); - } - - postgresql_session_backend & sessionBackend_; - PGresult* result_; - - SOCI_NOT_COPYABLE(postgresql_result) -}; - -} // namespace details - -struct postgresql_statement_backend; -struct postgresql_standard_into_type_backend : details::standard_into_type_backend -{ - postgresql_standard_into_type_backend(postgresql_statement_backend & st) - : statement_(st) {} - - void define_by_pos(int & position, - void * data, details::exchange_type type) SOCI_OVERRIDE; - - void pre_fetch() SOCI_OVERRIDE; - void post_fetch(bool gotData, bool calledFromFetch, - indicator * ind) SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - postgresql_statement_backend & statement_; - - void * data_; - details::exchange_type type_; - int position_; -}; - -struct postgresql_vector_into_type_backend : details::vector_into_type_backend -{ - postgresql_vector_into_type_backend(postgresql_statement_backend & st) - : statement_(st), user_ranges_(true) {} - - void define_by_pos(int & position, - void * data, details::exchange_type type) SOCI_OVERRIDE - { - user_ranges_ = false; - define_by_pos_bulk(position, data, type, 0, &end_var_); - } - - void define_by_pos_bulk(int & position, - void * data, details::exchange_type type, - std::size_t begin, std::size_t * end) SOCI_OVERRIDE; - - void pre_fetch() SOCI_OVERRIDE; - void post_fetch(bool gotData, indicator * ind) SOCI_OVERRIDE; - - void resize(std::size_t sz) SOCI_OVERRIDE; - std::size_t size() SOCI_OVERRIDE; // active size (might be lower than full vector size) - std::size_t full_size(); // actual size of the user-provided vector - - void clean_up() SOCI_OVERRIDE; - - postgresql_statement_backend & statement_; - - void * data_; - details::exchange_type type_; - std::size_t begin_; - std::size_t * end_; - std::size_t end_var_; - bool user_ranges_; - int position_; -}; - -struct postgresql_standard_use_type_backend : details::standard_use_type_backend -{ - postgresql_standard_use_type_backend(postgresql_statement_backend & st) - : statement_(st), position_(0), buf_(NULL) {} - - void bind_by_pos(int & position, - void * data, details::exchange_type type, bool readOnly) SOCI_OVERRIDE; - void bind_by_name(std::string const & name, - void * data, details::exchange_type type, bool readOnly) SOCI_OVERRIDE; - - void pre_use(indicator const * ind) SOCI_OVERRIDE; - void post_use(bool gotData, indicator * ind) SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - postgresql_statement_backend & statement_; - - void * data_; - details::exchange_type type_; - int position_; - std::string name_; - char * buf_; - -private: - // Allocate buf_ of appropriate size and copy string data into it. - void copy_from_string(std::string const& s); -}; - -struct postgresql_vector_use_type_backend : details::vector_use_type_backend -{ - postgresql_vector_use_type_backend(postgresql_statement_backend & st) - : statement_(st), position_(0) {} - - void bind_by_pos(int & position, - void * data, details::exchange_type type) SOCI_OVERRIDE - { - bind_by_pos_bulk(position, data, type, 0, &end_var_); - } - - void bind_by_pos_bulk(int & position, - void * data, details::exchange_type type, - std::size_t begin, std::size_t * end) SOCI_OVERRIDE; - - void bind_by_name(std::string const & name, - void * data, details::exchange_type type) SOCI_OVERRIDE - { - bind_by_name_bulk(name, data, type, 0, &end_var_); - } - - void bind_by_name_bulk(const std::string & name, - void * data, details::exchange_type type, - std::size_t begin, std::size_t * end) SOCI_OVERRIDE; - - void pre_use(indicator const * ind) SOCI_OVERRIDE; - - std::size_t size() SOCI_OVERRIDE; // active size (might be lower than full vector size) - std::size_t full_size(); // actual size of the user-provided vector - - void clean_up() SOCI_OVERRIDE; - - postgresql_statement_backend & statement_; - - void * data_; - details::exchange_type type_; - std::size_t begin_; - std::size_t * end_; - std::size_t end_var_; - int position_; - std::string name_; - std::vector buffers_; -}; - -struct postgresql_statement_backend : details::statement_backend -{ - postgresql_statement_backend(postgresql_session_backend & session, - bool single_row_mode); - ~postgresql_statement_backend() SOCI_OVERRIDE; - - void alloc() SOCI_OVERRIDE; - void clean_up() SOCI_OVERRIDE; - void prepare(std::string const & query, - details::statement_type stType) SOCI_OVERRIDE; - - exec_fetch_result execute(int number) SOCI_OVERRIDE; - exec_fetch_result fetch(int number) SOCI_OVERRIDE; - - long long get_affected_rows() SOCI_OVERRIDE; - int get_number_of_rows() SOCI_OVERRIDE; - std::string get_parameter_name(int index) const SOCI_OVERRIDE; - - std::string rewrite_for_procedure_call(std::string const & query) SOCI_OVERRIDE; - - int prepare_for_describe() SOCI_OVERRIDE; - void describe_column(int colNum, data_type & dtype, - std::string & columnName) SOCI_OVERRIDE; - - postgresql_standard_into_type_backend * make_into_type_backend() SOCI_OVERRIDE; - postgresql_standard_use_type_backend * make_use_type_backend() SOCI_OVERRIDE; - postgresql_vector_into_type_backend * make_vector_into_type_backend() SOCI_OVERRIDE; - postgresql_vector_use_type_backend * make_vector_use_type_backend() SOCI_OVERRIDE; - - postgresql_session_backend & session_; - - bool single_row_mode_; - - details::postgresql_result result_; - std::string query_; - details::statement_type stType_; - std::string statementName_; - std::vector names_; // list of names for named binds - - long long rowsAffectedBulk_; // number of rows affected by the last bulk operation - - int numberOfRows_; // number of rows retrieved from the server - int currentRow_; // "current" row number to consume in postFetch - int rowsToConsume_; // number of rows to be consumed in postFetch - - bool justDescribed_; // to optimize row description with immediately - // following actual statement execution - - bool hasIntoElements_; - bool hasVectorIntoElements_; - bool hasUseElements_; - bool hasVectorUseElements_; - - // the following maps are used for finding data buffers according to - // use elements specified by the user - - typedef std::map UseByPosBuffersMap; - UseByPosBuffersMap useByPosBuffers_; - - typedef std::map UseByNameBuffersMap; - UseByNameBuffersMap useByNameBuffers_; -}; - -struct postgresql_rowid_backend : details::rowid_backend -{ - postgresql_rowid_backend(postgresql_session_backend & session); - - ~postgresql_rowid_backend() SOCI_OVERRIDE; - - unsigned long value_; -}; - -struct postgresql_blob_backend : details::blob_backend -{ - postgresql_blob_backend(postgresql_session_backend & session); - - ~postgresql_blob_backend() SOCI_OVERRIDE; - - std::size_t get_len() SOCI_OVERRIDE; - - std::size_t read(std::size_t offset, char * buf, - std::size_t toRead) SOCI_OVERRIDE; - - std::size_t read_from_start(char * buf, std::size_t toRead, - std::size_t offset) SOCI_OVERRIDE - { - return read(offset, buf, toRead); - } - - std::size_t write(std::size_t offset, char const * buf, - std::size_t toWrite) SOCI_OVERRIDE; - - std::size_t write_from_start(const char * buf, std::size_t toWrite, - std::size_t offset) SOCI_OVERRIDE - { - return write(offset, buf, toWrite); - } - - std::size_t append(char const * buf, std::size_t toWrite) SOCI_OVERRIDE; - - void trim(std::size_t newLen) SOCI_OVERRIDE; - - postgresql_session_backend & session_; - - unsigned long oid_; // oid of the large object - int fd_; // descriptor of the large object -}; - -struct postgresql_session_backend : details::session_backend -{ - postgresql_session_backend(connection_parameters const & parameters, - bool single_row_mode); - - ~postgresql_session_backend() SOCI_OVERRIDE; - - void connect(connection_parameters const & parameters); - - void begin() SOCI_OVERRIDE; - void commit() SOCI_OVERRIDE; - void rollback() SOCI_OVERRIDE; - - void deallocate_prepared_statement(const std::string & statementName); - - bool get_next_sequence_value(session & s, - std::string const & sequence, long & value) SOCI_OVERRIDE; - - std::string get_dummy_from_table() const SOCI_OVERRIDE { return std::string(); } - - std::string get_backend_name() const SOCI_OVERRIDE { return "postgresql"; } - - void clean_up(); - - postgresql_statement_backend * make_statement_backend() SOCI_OVERRIDE; - postgresql_rowid_backend * make_rowid_backend() SOCI_OVERRIDE; - postgresql_blob_backend * make_blob_backend() SOCI_OVERRIDE; - - std::string get_next_statement_name(); - - int statementCount_; - bool single_row_mode_; - PGconn * conn_; -}; - - -struct postgresql_backend_factory : backend_factory -{ - postgresql_backend_factory() {} - postgresql_session_backend * make_session( - connection_parameters const & parameters) const SOCI_OVERRIDE; -}; - -extern SOCI_POSTGRESQL_DECL postgresql_backend_factory const postgresql; - -extern "C" -{ - -// for dynamic backend loading -SOCI_POSTGRESQL_DECL backend_factory const * factory_postgresql(); -SOCI_POSTGRESQL_DECL void register_factory_postgresql(); - -} // extern "C" - -} // namespace soci - -#endif // SOCI_POSTGRESQL_H_INCLUDED diff --git a/src/soci/include/soci/prepare-temp-type.h b/src/soci/include/soci/prepare-temp-type.h deleted file mode 100644 index 52c183d4e9..0000000000 --- a/src/soci/include/soci/prepare-temp-type.h +++ /dev/null @@ -1,65 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_PREPARE_TEMP_TYPE_INCLUDED -#define SOCI_PREPARE_TEMP_TYPE_INCLUDED - -#include "soci/into-type.h" -#include "soci/use-type.h" -#include "soci/use.h" -#include "soci/ref-counted-prepare-info.h" - -namespace soci -{ - -namespace details -{ - -// this needs to be lightweight and copyable -class SOCI_DECL prepare_temp_type -{ -public: - prepare_temp_type(session &); - prepare_temp_type(prepare_temp_type const &); - prepare_temp_type & operator=(prepare_temp_type const &); - - ~prepare_temp_type(); - - template - prepare_temp_type & operator<<(T const & t) - { - rcpi_->accumulate(t); - return *this; - } - - prepare_temp_type & operator,(into_type_ptr const & i); - - template - prepare_temp_type &operator,(into_container const &ic) - { - rcpi_->exchange(ic); - return *this; - } - template - prepare_temp_type &operator,(use_container const &uc) - { - rcpi_->exchange(uc); - return *this; - } - - ref_counted_prepare_info * get_prepare_info() const { return rcpi_; } - - -private: - ref_counted_prepare_info * rcpi_; -}; - -} // namespace details - -} // namespace soci - -#endif diff --git a/src/soci/include/soci/procedure.h b/src/soci/include/soci/procedure.h deleted file mode 100644 index ec50ddad1c..0000000000 --- a/src/soci/include/soci/procedure.h +++ /dev/null @@ -1,90 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_PROCEDURE_H_INCLUDED -#define SOCI_PROCEDURE_H_INCLUDED - -#include "soci/statement.h" - -namespace soci -{ - -namespace details -{ - -class SOCI_DECL procedure_impl : public statement_impl -{ -public: - procedure_impl(session & s) : statement_impl(s), refCount_(1) {} - procedure_impl(prepare_temp_type const & prep); - - void inc_ref() { ++refCount_; } - void dec_ref() - { - if (--refCount_ == 0) - { - delete this; - } - } - -private: - int refCount_; -}; - -} // namespace details - -class SOCI_DECL procedure -{ -public: - // this is a conversion constructor - procedure(details::prepare_temp_type const & prep) - : impl_(new details::procedure_impl(prep)), gotData_(false) {} - - ~procedure() { impl_->dec_ref(); } - - // copy is supported here - procedure(procedure const & other) - : impl_(other.impl_), gotData_(other.gotData_) - { - impl_->inc_ref(); - } - void operator=(procedure const & other) - { - other.impl_->inc_ref(); - impl_->dec_ref(); - impl_ = other.impl_; - gotData_ = other.gotData_; - } - - // forwarders to procedure_impl - // (or rather to its base interface from statement_impl) - - bool execute(bool withDataExchange = false) - { - gotData_ = impl_->execute(withDataExchange); - return gotData_; - } - - bool fetch() - { - gotData_ = impl_->fetch(); - return gotData_; - } - - bool got_data() const - { - return gotData_; - } - -private: - details::procedure_impl * impl_; - bool gotData_; -}; - -} // namespace soci - -#endif diff --git a/src/soci/include/soci/query_transformation.h b/src/soci/include/soci/query_transformation.h deleted file mode 100644 index 72582a8ec6..0000000000 --- a/src/soci/include/soci/query_transformation.h +++ /dev/null @@ -1,59 +0,0 @@ -// -// Copyright (C) 2013 Mateusz Loskot -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_QUERY_TRANSFORMATION_H_INCLUDED -#define SOCI_QUERY_TRANSFORMATION_H_INCLUDED - -#include "soci/soci-platform.h" -#include -#include - -namespace soci -{ - -namespace details -{ - -// Query transformation is a mechanism that enables user to apply -// any string-to-string transformation to SQL statement just -// before it is executed. -// Transformation procedure is specified by user, -// be it a function or an arbitrary type as long as it -// defines operator() with the appropriate signature: -// unary function takes any type converible-to std::string -// and returns std::string. - -class query_transformation_function - : public std::unary_function -{ -public: - virtual ~query_transformation_function() {} - virtual result_type operator()(argument_type a) const = 0; -}; - -template -class query_transformation : public query_transformation_function -{ -public: - query_transformation(T callback) - : callback_(callback) - {} - - result_type operator()(argument_type query) const SOCI_OVERRIDE - { - return callback_(query); - } - -private: - T callback_; -}; - -} // namespace details - -} // namespace soci - -#endif // SOCI_QUERY_TRANSFORMATION_H_INCLUDED diff --git a/src/soci/include/soci/ref-counted-prepare-info.h b/src/soci/include/soci/ref-counted-prepare-info.h deleted file mode 100644 index 10bafaaaeb..0000000000 --- a/src/soci/include/soci/ref-counted-prepare-info.h +++ /dev/null @@ -1,66 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_REF_COUNTED_PREPARE_INFO_INCLUDED -#define SOCI_REF_COUNTED_PREPARE_INFO_INCLUDED - -#include "soci/bind-values.h" -#include "soci/ref-counted-statement.h" -// std -#include -#include - -namespace soci -{ - -class session; - -namespace details -{ - -class procedure_impl; -class statement_impl; -class into_type_base; - -// this class conveys only the statement text and the bind/define info -// it exists only to be passed to statement's constructor -class ref_counted_prepare_info : public ref_counted_statement_base -{ -public: - ref_counted_prepare_info(session& s) - : ref_counted_statement_base(s) - {} - - void exchange(use_type_ptr const& u) { uses_.exchange(u); } - - template - void exchange(use_container const &uc) - { uses_.exchange(uc); } - - void exchange(into_type_ptr const& i) { intos_.exchange(i); } - - template - void exchange(into_container const &ic) - { intos_.exchange(ic); } - - void final_action() SOCI_OVERRIDE; - -private: - friend class statement_impl; - friend class procedure_impl; - - into_type_vector intos_; - use_type_vector uses_; - - std::string get_query() const; -}; - -} // namespace details - -} // namespace soci - -#endif diff --git a/src/soci/include/soci/ref-counted-statement.h b/src/soci/include/soci/ref-counted-statement.h deleted file mode 100644 index 365b3ba463..0000000000 --- a/src/soci/include/soci/ref-counted-statement.h +++ /dev/null @@ -1,102 +0,0 @@ -// -// Copyright (C) 2004-2016 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_REF_COUNTED_STATEMENT_H_INCLUDED -#define SOCI_REF_COUNTED_STATEMENT_H_INCLUDED - -#include "soci/statement.h" -#include "soci/into-type.h" -#include "soci/use-type.h" -// std -#include - -namespace soci -{ - -namespace details -{ - -// this class is a base for both "once" and "prepare" statements -class SOCI_DECL ref_counted_statement_base -{ -public: - ref_counted_statement_base(session& s); - - virtual ~ref_counted_statement_base() {} - - virtual void final_action() = 0; - - void inc_ref() { ++refCount_; } - void dec_ref() - { - if (--refCount_ == 0) - { - try - { - if (tail_.empty() == false) - { - accumulate(tail_); - } - - final_action(); - } - catch (...) - { - delete this; - throw; - } - - delete this; - } - } - - template - void accumulate(T const & t) { get_query_stream() << t; } - - void set_tail(const std::string & tail) { tail_ = tail; } - void set_need_comma(bool need_comma) { need_comma_ = need_comma; } - bool get_need_comma() const { return need_comma_; } - -protected: - // this function allows to break the circular dependenc - // between session and this class - std::ostringstream & get_query_stream(); - - int refCount_; - - session & session_; - - // used mainly for portable ddl - std::string tail_; - bool need_comma_; - -private: - SOCI_NOT_COPYABLE(ref_counted_statement_base) -}; - -// this class is supposed to be a vehicle for the "once" statements -// it executes the whole statement in its destructor -class ref_counted_statement : public ref_counted_statement_base -{ -public: - ref_counted_statement(session & s) - : ref_counted_statement_base(s), st_(s) {} - - void final_action() SOCI_OVERRIDE; - - template - void exchange(T &t) { st_.exchange(t); } - -private: - statement st_; -}; - -} // namespace details - -} // namespace soci - -#endif diff --git a/src/soci/include/soci/row-exchange.h b/src/soci/include/soci/row-exchange.h deleted file mode 100644 index b94337fc4b..0000000000 --- a/src/soci/include/soci/row-exchange.h +++ /dev/null @@ -1,80 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_INTO_ROW_H_INCLUDED -#define SOCI_INTO_ROW_H_INCLUDED - -#include "soci/into-type.h" -#include "soci/exchange-traits.h" -#include "soci/row.h" -#include "soci/statement.h" -// std -#include - -namespace soci -{ - -namespace details -{ - -// Support selecting into a row for dynamic queries - -template <> -class into_type - : public into_type_base // bypass the standard_into_type -{ -public: - into_type(row & r) : r_(r) {} - into_type(row & r, indicator &) : r_(r) {} - -private: - // special handling for Row - void define(statement_impl & st, int & /* position */) SOCI_OVERRIDE - { - st.set_row(&r_); - - // actual row description is performed - // as part of the statement execute - } - - void pre_exec(int /* num */) SOCI_OVERRIDE {} - void pre_fetch() SOCI_OVERRIDE {} - void post_fetch(bool gotData, bool /* calledFromFetch */) SOCI_OVERRIDE - { - r_.reset_get_counter(); - - if (gotData) - { - // this is used only to re-dispatch to derived class, if any - // (the derived class might be generated automatically by - // user conversions) - convert_from_base(); - } - } - - void clean_up() SOCI_OVERRIDE {} - - std::size_t size() const SOCI_OVERRIDE { return 1; } - - virtual void convert_from_base() {} - - row & r_; - - SOCI_NOT_COPYABLE(into_type) -}; - -template <> -struct exchange_traits -{ - typedef basic_type_tag type_family; -}; - -} // namespace details - -} // namespace soci - -#endif diff --git a/src/soci/include/soci/row.h b/src/soci/include/soci/row.h deleted file mode 100644 index 02cb60eff3..0000000000 --- a/src/soci/include/soci/row.h +++ /dev/null @@ -1,140 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_ROW_H_INCLUDED -#define SOCI_ROW_H_INCLUDED - -#include "soci/type-holder.h" -#include "soci/soci-backend.h" -#include "soci/type-conversion.h" -// std -#include -#include -#include -#include - -namespace soci -{ - -class SOCI_DECL column_properties -{ - // use getters/setters in case we want to make some - // of the getters lazy in the future -public: - - std::string get_name() const { return name_; } - data_type get_data_type() const { return dataType_; } - - void set_name(std::string const& name) { name_ = name; } - void set_data_type(data_type dataType) { dataType_ = dataType; } - -private: - std::string name_; - data_type dataType_; -}; - -class SOCI_DECL row -{ -public: - row(); - ~row(); - - void uppercase_column_names(bool forceToUpper); - void add_properties(column_properties const& cp); - std::size_t size() const; - void clean_up(); - - indicator get_indicator(std::size_t pos) const; - indicator get_indicator(std::string const& name) const; - - template - inline void add_holder(T* t, indicator* ind) - { - holders_.push_back(new details::type_holder(t)); - indicators_.push_back(ind); - } - - column_properties const& get_properties(std::size_t pos) const; - column_properties const& get_properties(std::string const& name) const; - - template - T get(std::size_t pos) const - { - typedef typename type_conversion::base_type base_type; - base_type const& baseVal = holders_.at(pos)->get(); - - T ret; - type_conversion::from_base(baseVal, *indicators_.at(pos), ret); - return ret; - } - - template - T get(std::size_t pos, T const &nullValue) const - { - if (i_null == *indicators_.at(pos)) - { - return nullValue; - } - - return get(pos); - } - - template - T get(std::string const &name) const - { - std::size_t const pos = find_column(name); - return get(pos); - } - - template - T get(std::string const &name, T const &nullValue) const - { - std::size_t const pos = find_column(name); - - if (i_null == *indicators_[pos]) - { - return nullValue; - } - - return get(pos); - } - - template - row const& operator>>(T& value) const - { - value = get(currentPos_); - ++currentPos_; - return *this; - } - - void skip(std::size_t num = 1) const - { - currentPos_ += num; - } - - void reset_get_counter() const - { - currentPos_ = 0; - } - -private: - SOCI_NOT_COPYABLE(row) - - std::size_t find_column(std::string const& name) const; - - std::vector columns_; - std::vector holders_; - std::vector indicators_; - std::map index_; - - bool uppercaseColumnNames_; - mutable std::size_t currentPos_; -}; - -} // namespace soci - -#endif // SOCI_ROW_H_INCLUDED diff --git a/src/soci/include/soci/rowid-exchange.h b/src/soci/include/soci/rowid-exchange.h deleted file mode 100644 index 2d1a85914b..0000000000 --- a/src/soci/include/soci/rowid-exchange.h +++ /dev/null @@ -1,59 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_ROWID_EXCHANGE_H_INCLUDED -#define SOCI_ROWID_EXCHANGE_H_INCLUDED - -#include "soci/rowid.h" -#include "soci/into-type.h" -#include "soci/use-type.h" -#include "soci/exchange-traits.h" -// std -#include - -namespace soci -{ - -namespace details -{ - -template <> -class use_type : public standard_use_type -{ -public: - use_type(rowid & rid, std::string const & name = std::string()) - : standard_use_type(&rid, x_rowid, false, name) {} - use_type(rowid const & rid, std::string const & name = std::string()) - : standard_use_type(const_cast(&rid), x_rowid, true, name) {} - use_type(rowid & rid, indicator & ind, - std::string const & name = std::string()) - : standard_use_type(&rid, x_rowid, ind, false, name) {} - use_type(rowid const & rid, indicator & ind, - std::string const & name = std::string()) - : standard_use_type(const_cast(&rid), x_rowid, ind, true, name) {} -}; - -template <> -class into_type : public standard_into_type -{ -public: - into_type(rowid & rid) : standard_into_type(&rid, x_rowid) {} - into_type(rowid & rid, indicator & ind) - :standard_into_type(&rid, x_rowid, ind) {} -}; - -template <> -struct exchange_traits -{ - typedef basic_type_tag type_family; -}; - -} // namespace details - -} // namespace soci - -#endif // SOCI_ROWID_EXCHANGE_H_INCLUDED diff --git a/src/soci/include/soci/rowid.h b/src/soci/include/soci/rowid.h deleted file mode 100644 index f045eaf1ef..0000000000 --- a/src/soci/include/soci/rowid.h +++ /dev/null @@ -1,41 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_ROWID_H_INCLUDED -#define SOCI_ROWID_H_INCLUDED - -#include "soci/soci-platform.h" - -namespace soci -{ - -class session; - -namespace details -{ - -class rowid_backend; - -} // namespace details - -// ROWID support - -class SOCI_DECL rowid -{ -public: - explicit rowid(session & s); - ~rowid(); - - details::rowid_backend * get_backend() { return backEnd_; } - -private: - details::rowid_backend *backEnd_; -}; - -} // namespace soci - -#endif diff --git a/src/soci/include/soci/rowset.h b/src/soci/include/soci/rowset.h deleted file mode 100644 index c15b3abbeb..0000000000 --- a/src/soci/include/soci/rowset.h +++ /dev/null @@ -1,220 +0,0 @@ -// -// Copyright (C) 2006-2008 Mateusz Loskot -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_ROWSET_H_INCLUDED -#define SOCI_ROWSET_H_INCLUDED - -#include "soci/soci-platform.h" -#include "soci/statement.h" -// std -#include -#include - -namespace soci -{ - -// -// rowset iterator of input category. -// -template -class rowset_iterator -{ -public: - - // Standard iterator traits - - typedef std::input_iterator_tag iterator_category; - typedef T value_type; - typedef T * pointer; - typedef T & reference; - typedef ptrdiff_t difference_type; - - // Constructors - - rowset_iterator() - : st_(0), define_(0) - {} - - rowset_iterator(statement & st, T & define) - : st_(&st), define_(&define) - { - // Fetch first row to properly initialize iterator - ++(*this); - } - - // Access operators - - reference operator*() const - { - return (*define_); - } - - pointer operator->() const - { - return &(operator*()); - } - - // Iteration operators - - rowset_iterator & operator++() - { - // Fetch next row from dataset - - if (st_->fetch() == false) - { - // Set iterator to non-derefencable state (pass-the-end) - st_ = 0; - define_ = 0; - } - - return (*this); - } - - rowset_iterator operator++(int) - { - rowset_iterator tmp(*this); - ++(*this); - return tmp; - } - - // Comparison operators - - bool operator==(rowset_iterator const & rhs) const - { - return (st_== rhs.st_ && define_ == rhs.define_); - } - - bool operator!=(rowset_iterator const & rhs) const - { - return ((*this == rhs) == false); - } - -private: - - statement * st_; - T * define_; - -}; // class rowset_iterator - -namespace details -{ - -// -// Implementation of rowset -// -template -class rowset_impl -{ -public: - - typedef rowset_iterator iterator; - - rowset_impl(details::prepare_temp_type const & prep) - : refs_(1), st_(new statement(prep)), define_(new T()) - { - st_->exchange_for_rowset(into(*define_)); - st_->execute(); - } - - void incRef() - { - ++refs_; - } - - void decRef() - { - if (--refs_ == 0) - { - delete this; - } - } - - iterator begin() const - { - // No ownership transfer occurs here - return iterator(*st_, *define_); - } - - iterator end() const - { - return iterator(); - } - -private: - - unsigned int refs_; - - const cxx_details::auto_ptr st_; - const cxx_details::auto_ptr define_; - SOCI_NOT_COPYABLE(rowset_impl) -}; // class rowset_impl - -} // namespace details - - -// -// rowset is a thin wrapper on statement and provides access to STL-like input iterator. -// The rowset_iterator can be used to easily loop through statement results and -// use STL algorithms accepting input iterators. -// -template -class rowset -{ -public: - - typedef T value_type; - typedef rowset_iterator iterator; - typedef rowset_iterator const_iterator; - - // this is a conversion constructor - rowset(details::prepare_temp_type const& prep) - : pimpl_(new details::rowset_impl(prep)) - { - } - - rowset(rowset const & other) - : pimpl_(other.pimpl_) - { - pimpl_->incRef(); - } - - ~rowset() - { - pimpl_->decRef(); - } - - rowset& operator=(rowset const& rhs) - { - if (&rhs != this) - { - rhs.pimpl_->incRef(); - pimpl_->decRef(); - pimpl_ = rhs.pimpl_; - } - return *this; - } - - const_iterator begin() const - { - return pimpl_->begin(); - } - - const_iterator end() const - { - return pimpl_->end(); - } - -private: - - // Pointer to implementation - the body - details::rowset_impl* pimpl_; - -}; // class rowset - -} // namespace soci - -#endif // SOCI_ROWSET_H_INCLUDED diff --git a/src/soci/include/soci/session.h b/src/soci/include/soci/session.h deleted file mode 100644 index 04af650f5e..0000000000 --- a/src/soci/include/soci/session.h +++ /dev/null @@ -1,203 +0,0 @@ -// -// Copyright (C) 2004-2016 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_SESSION_H_INCLUDED -#define SOCI_SESSION_H_INCLUDED - -#include "soci/soci-platform.h" -#include "soci/once-temp-type.h" -#include "soci/query_transformation.h" -#include "soci/connection-parameters.h" - -// std -#include -#include -#include -#include -#include - -namespace soci -{ -class values; -class backend_factory; - -namespace details -{ - -class session_backend; -class statement_backend; -class rowid_backend; -class blob_backend; - -} // namespace details - -class connection_pool; -class failover_callback; - -class SOCI_DECL session -{ -private: - - void set_query_transformation_(cxx_details::auto_ptr& qtf); - - - -public: - session(); - explicit session(connection_parameters const & parameters); - session(backend_factory const & factory, std::string const & connectString); - session(std::string const & backendName, std::string const & connectString); - explicit session(std::string const & connectString); - explicit session(connection_pool & pool); - - ~session(); - - void open(connection_parameters const & parameters); - void open(backend_factory const & factory, std::string const & connectString); - void open(std::string const & backendName, std::string const & connectString); - void open(std::string const & connectString); - void close(); - void reconnect(); - - void begin(); - void commit(); - void rollback(); - - // once and prepare are for syntax sugar only - details::once_type once; - details::prepare_type prepare; - - // even more sugar - template - details::once_temp_type operator<<(T const & t) { return once << t; } - - std::ostringstream & get_query_stream(); - std::string get_query() const; - - template - void set_query_transformation(T callback) - { - - cxx_details::auto_ptr qtf(new details::query_transformation(callback)); - set_query_transformation_(qtf); - } - - // support for basic logging - void set_log_stream(std::ostream * s); - std::ostream * get_log_stream() const; - - void log_query(std::string const & query); - std::string get_last_query() const; - - void set_got_data(bool gotData); - bool got_data() const; - - void uppercase_column_names(bool forceToUpper); - - bool get_uppercase_column_names() const; - - // Functions for dealing with sequence/auto-increment values. - - // If true is returned, value is filled with the next value from the given - // sequence. Otherwise either the sequence is invalid (doesn't exist) or - // the current backend doesn't support sequences. If you use sequences for - // automatically generating primary key values, you should use - // get_last_insert_id() after the insertion in this case. - bool get_next_sequence_value(std::string const & sequence, long & value); - - // If true is returned, value is filled with the last auto-generated value - // for this table (although some backends ignore the table argument and - // return the last value auto-generated in this session). - bool get_last_insert_id(std::string const & table, long & value); - - // Returns once_temp_type for the internally composed query - // for the list of tables in the current schema. - // Since this query usually returns multiple results (for multiple tables), - // it makes sense to bind std::vector for the single output field. - details::once_temp_type get_table_names(); - - // Returns prepare_temp_type for the internally composed query - // for the list of tables in the current schema. - // Since this is intended for use with statement objects, where results are obtained one row after another, - // it makes sense to bind std::string for the output field. - details::prepare_temp_type prepare_table_names(); - - // Returns prepare_temp_type for the internally composed query - // for the list of column descriptions. - // Since this is intended for use with statement objects, where results are obtained one row after another, - // it makes sense to bind either std::string for each output field or soci::column_info for the whole row. - // Note: table_name is a non-const reference to prevent temporary objects, - // this argument is bound as a regular "use" element. - details::prepare_temp_type prepare_column_descriptions(std::string & table_name); - - // Functions for basic portable DDL statements. - - ddl_type create_table(const std::string & tableName); - void drop_table(const std::string & tableName); - void truncate_table(const std::string & tableName); - ddl_type add_column(const std::string & tableName, - const std::string & columnName, data_type dt, - int precision = 0, int scale = 0); - ddl_type alter_column(const std::string & tableName, - const std::string & columnName, data_type dt, - int precision = 0, int scale = 0); - ddl_type drop_column(const std::string & tableName, - const std::string & columnName); - std::string empty_blob(); - std::string nvl(); - - // And some functions to help with writing portable DML statements. - - // Get the name of the dummy table that needs to be used in the FROM clause - // of a SELECT statement not operating on any tables, e.g. "dual" for - // Oracle. The returned string is empty if no such table is needed. - std::string get_dummy_from_table() const; - - // Returns a possibly empty string that needs to be used as a FROM clause - // of a SELECT statement not operating on any tables, e.g. " FROM DUAL" - // (notice the leading space). - std::string get_dummy_from_clause() const; - - - // Sets the failover callback object. - void set_failover_callback(failover_callback & callback); - - // for diagnostics and advanced users - // (downcast it to expected back-end session class) - details::session_backend * get_backend() { return backEnd_; } - - std::string get_backend_name() const; - - details::statement_backend * make_statement_backend(); - details::rowid_backend * make_rowid_backend(); - details::blob_backend * make_blob_backend(); - -private: - SOCI_NOT_COPYABLE(session) - - std::ostringstream query_stream_; - details::query_transformation_function* query_transformation_; - - std::ostream * logStream_; - std::string lastQuery_; - - connection_parameters lastConnectParameters_; - - bool uppercaseColumnNames_; - - details::session_backend * backEnd_; - - bool gotData_; - - bool isFromPool_; - std::size_t poolPosition_; - connection_pool * pool_; -}; - -} // namespace soci - -#endif // SOCI_SESSION_H_INCLUDED diff --git a/src/soci/include/soci/soci-backend.h b/src/soci/include/soci/soci-backend.h deleted file mode 100644 index 583041bf52..0000000000 --- a/src/soci/include/soci/soci-backend.h +++ /dev/null @@ -1,483 +0,0 @@ -// -// Copyright (C) 2004-2016 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_BACKEND_H_INCLUDED -#define SOCI_BACKEND_H_INCLUDED - -#include "soci/soci-platform.h" -#include "soci/error.h" -// std -#include -#include -#include -#include - -namespace soci -{ - -// data types, as seen by the user -enum data_type -{ - dt_string, dt_date, dt_double, dt_integer, dt_long_long, dt_unsigned_long_long, - dt_blob, dt_xml -}; - -// the enum type for indicator variables -enum indicator { i_ok, i_null, i_truncated }; - -class session; -class failover_callback; - -namespace details -{ - -// data types, as used to describe exchange format -enum exchange_type -{ - x_char, - x_stdstring, - x_short, - x_integer, - x_long_long, - x_unsigned_long_long, - x_double, - x_stdtm, - x_statement, - x_rowid, - x_blob, - - x_xmltype, - x_longstring -}; - -// type of statement (used for optimizing statement preparation) -enum statement_type -{ - st_one_time_query, - st_repeatable_query -}; - -// polymorphic into type backend - -class standard_into_type_backend -{ -public: - standard_into_type_backend() {} - virtual ~standard_into_type_backend() {} - - virtual void define_by_pos(int& position, void* data, exchange_type type) = 0; - - virtual void pre_exec(int /* num */) {} - virtual void pre_fetch() = 0; - virtual void post_fetch(bool gotData, bool calledFromFetch, indicator* ind) = 0; - - virtual void clean_up() = 0; - -private: - SOCI_NOT_COPYABLE(standard_into_type_backend) -}; - -class vector_into_type_backend -{ -public: - - vector_into_type_backend() {} - virtual ~vector_into_type_backend() {} - - virtual void define_by_pos_bulk( - int & /* position */, void * /* data */, exchange_type /* type */, - std::size_t /* begin */, std::size_t * /* end */) - { - throw soci_error("into bulk iterators are not supported with this backend"); - } - - virtual void define_by_pos(int& position, void* data, exchange_type type) = 0; - - virtual void pre_exec(int /* num */) {} - virtual void pre_fetch() = 0; - virtual void post_fetch(bool gotData, indicator* ind) = 0; - - virtual void resize(std::size_t sz) = 0; - virtual std::size_t size() = 0; - - virtual void clean_up() = 0; - -private: - SOCI_NOT_COPYABLE(vector_into_type_backend) -}; - -// polymorphic use type backend - -class standard_use_type_backend -{ -public: - standard_use_type_backend() {} - virtual ~standard_use_type_backend() {} - - virtual void bind_by_pos(int& position, void* data, - exchange_type type, bool readOnly) = 0; - virtual void bind_by_name(std::string const& name, - void* data, exchange_type type, bool readOnly) = 0; - - virtual void pre_exec(int /* num */) {} - virtual void pre_use(indicator const* ind) = 0; - virtual void post_use(bool gotData, indicator * ind) = 0; - - virtual void clean_up() = 0; - -private: - SOCI_NOT_COPYABLE(standard_use_type_backend) -}; - -class vector_use_type_backend -{ -public: - vector_use_type_backend() {} - virtual ~vector_use_type_backend() {} - - virtual void bind_by_pos(int& position, void* data, exchange_type type) = 0; - virtual void bind_by_pos_bulk(int& /* position */, void* /* data */, exchange_type /* type */, - std::size_t /* begin */, std::size_t * /* end */) - { - throw soci_error("use bulk iterators are not supported with this backend"); - } - - virtual void bind_by_name(std::string const& name, - void* data, exchange_type type) = 0; - - virtual void bind_by_name_bulk(std::string const& /* name */, - void* /* data */, exchange_type /* type */, - std::size_t /* begin */, std::size_t * /* end */) - { - throw soci_error("use bulk iterators are not supported with this backend"); - } - - virtual void pre_exec(int /* num */) {} - virtual void pre_use(indicator const* ind) = 0; - - virtual std::size_t size() = 0; - - virtual void clean_up() = 0; - -private: - SOCI_NOT_COPYABLE(vector_use_type_backend) -}; - -// polymorphic statement backend - -class statement_backend -{ -public: - statement_backend() {} - virtual ~statement_backend() {} - - virtual void alloc() = 0; - virtual void clean_up() = 0; - - virtual void prepare(std::string const& query, statement_type eType) = 0; - - enum exec_fetch_result - { - ef_success, - ef_no_data - }; - - virtual exec_fetch_result execute(int number) = 0; - virtual exec_fetch_result fetch(int number) = 0; - - virtual long long get_affected_rows() = 0; - virtual int get_number_of_rows() = 0; - - virtual std::string get_parameter_name(int index) const = 0; - - virtual std::string rewrite_for_procedure_call(std::string const& query) = 0; - - virtual int prepare_for_describe() = 0; - virtual void describe_column(int colNum, data_type& dtype, - std::string& column_name) = 0; - - virtual standard_into_type_backend* make_into_type_backend() = 0; - virtual standard_use_type_backend* make_use_type_backend() = 0; - virtual vector_into_type_backend* make_vector_into_type_backend() = 0; - virtual vector_use_type_backend* make_vector_use_type_backend() = 0; - -private: - SOCI_NOT_COPYABLE(statement_backend) -}; - -// polymorphic RowID backend - -class rowid_backend -{ -public: - virtual ~rowid_backend() {} -}; - -// polymorphic blob backend - -class blob_backend -{ -public: - blob_backend() {} - virtual ~blob_backend() {} - - virtual std::size_t get_len() = 0; - - virtual std::size_t read(std::size_t offset, char* buf, - std::size_t toRead) = 0; - - virtual std::size_t read_from_start(char * /* buf */, std::size_t /* toRead */, - std::size_t /* offset */) - { - throw soci_error("read_from_start is not implemented for this backend"); - } - - virtual std::size_t write(std::size_t offset, char const* buf, - std::size_t toWrite) = 0; - - virtual std::size_t write_from_start(const char * /* buf */, std::size_t /* toWrite */, - std::size_t /* offset */) - { - throw soci_error("write_from_start is not implemented for this backend"); - } - - virtual std::size_t append(char const* buf, std::size_t toWrite) = 0; - - virtual void trim(std::size_t newLen) = 0; - -private: - SOCI_NOT_COPYABLE(blob_backend) -}; - -// polymorphic session backend - -class session_backend -{ -public: - session_backend() : failoverCallback_(NULL), session_(NULL) {} - virtual ~session_backend() {} - - virtual void begin() = 0; - virtual void commit() = 0; - virtual void rollback() = 0; - - // At least one of these functions is usually not implemented for any given - // backend as RDBMS support either sequences or auto-generated values, so - // we don't declare them as pure virtuals to avoid having to define trivial - // versions of them in the derived classes. However every backend should - // define at least one of them to allow the code using auto-generated values - // to work. - virtual bool get_next_sequence_value(session&, std::string const&, long&) - { - return false; - } - virtual bool get_last_insert_id(session&, std::string const&, long&) - { - return false; - } - - // There is a set of standard SQL metadata structures that can be - // queried in a portable way - backends that are standard compliant - // do not need to override the following methods, which are intended - // to return a proper query for basic metadata statements. - - // Returns a parameterless query for the list of table names in the current schema. - virtual std::string get_table_names_query() const - { - return "select table_name as \"TABLE_NAME\"" - " from information_schema.tables" - " where table_schema = 'public'"; - } - - // Returns a query with a single parameter (table name) for the list - // of columns and their properties. - virtual std::string get_column_descriptions_query() const - { - return "select column_name as \"COLUMN_NAME\"," - " data_type as \"DATA_TYPE\"," - " character_maximum_length as \"CHARACTER_MAXIMUM_LENGTH\"," - " numeric_precision as \"NUMERIC_PRECISION\"," - " numeric_scale as \"NUMERIC_SCALE\"," - " is_nullable as \"IS_NULLABLE\"" - " from information_schema.columns" - " where table_schema = 'public' and table_name = :t"; - } - - virtual std::string create_table(const std::string & tableName) - { - return "create table " + tableName + " ("; - } - virtual std::string drop_table(const std::string & tableName) - { - return "drop table " + tableName; - } - virtual std::string truncate_table(const std::string & tableName) - { - return "truncate table " + tableName; - } - virtual std::string create_column_type(data_type dt, - int precision, int scale) - { - // PostgreSQL was selected as a baseline for the syntax: - - std::string res; - switch (dt) - { - case dt_string: - { - std::ostringstream oss; - - if (precision == 0) - { - oss << "text"; - } - else - { - oss << "varchar(" << precision << ")"; - } - - res += oss.str(); - } - break; - - case dt_date: - res += "timestamp"; - break; - - case dt_double: - { - std::ostringstream oss; - if (precision == 0) - { - oss << "numeric"; - } - else - { - oss << "numeric(" << precision << ", " << scale << ")"; - } - - res += oss.str(); - } - break; - - case dt_integer: - res += "integer"; - break; - - case dt_long_long: - res += "bigint"; - break; - - case dt_unsigned_long_long: - res += "bigint"; - break; - - case dt_blob: - res += "oid"; - break; - - case dt_xml: - res += "xml"; - break; - - default: - throw soci_error("this data_type is not supported in create_column"); - } - - return res; - } - virtual std::string add_column(const std::string & tableName, - const std::string & columnName, data_type dt, - int precision, int scale) - { - return "alter table " + tableName + " add column " + columnName + - " " + create_column_type(dt, precision, scale); - } - virtual std::string alter_column(const std::string & tableName, - const std::string & columnName, data_type dt, - int precision, int scale) - { - return "alter table " + tableName + " alter column " + - columnName + " type " + - create_column_type(dt, precision, scale); - } - virtual std::string drop_column(const std::string & tableName, - const std::string & columnName) - { - return "alter table " + tableName + - " drop column " + columnName; - } - virtual std::string constraint_unique(const std::string & name, - const std::string & columnNames) - { - return "constraint " + name + - " unique (" + columnNames + ")"; - } - virtual std::string constraint_primary_key(const std::string & name, - const std::string & columnNames) - { - return "constraint " + name + - " primary key (" + columnNames + ")"; - } - virtual std::string constraint_foreign_key(const std::string & name, - const std::string & columnNames, - const std::string & refTableName, - const std::string & refColumnNames) - { - return "constraint " + name + - " foreign key (" + columnNames + ")" + - " references " + refTableName + " (" + refColumnNames + ")"; - } - virtual std::string empty_blob() - { - return "lo_creat(-1)"; - } - virtual std::string nvl() - { - return "coalesce"; - } - - virtual std::string get_dummy_from_table() const = 0; - - void set_failover_callback(failover_callback & callback, session & sql) - { - failoverCallback_ = &callback; - session_ = &sql; - } - - virtual std::string get_backend_name() const = 0; - - virtual statement_backend* make_statement_backend() = 0; - virtual rowid_backend* make_rowid_backend() = 0; - virtual blob_backend* make_blob_backend() = 0; - - failover_callback * failoverCallback_; - session * session_; - -private: - SOCI_NOT_COPYABLE(session_backend) -}; - -} // namespace details - -// simple base class for the session back-end factory - -class connection_parameters; - -class SOCI_DECL backend_factory -{ -public: - backend_factory() {} - virtual ~backend_factory() {} - - virtual details::session_backend* make_session( - connection_parameters const& parameters) const = 0; -}; - -} // namespace soci - -#endif // SOCI_BACKEND_H_INCLUDED diff --git a/src/soci/include/soci/soci-config.h b/src/soci/include/soci/soci-config.h deleted file mode 100644 index 1b1680da1f..0000000000 --- a/src/soci/include/soci/soci-config.h +++ /dev/null @@ -1,49 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCICONFIG_H_INCLUDED -#define SOCICONFIG_H_INCLUDED - -// -// SOCI has been build with support for: -// - -// Boost library -#define SOCI_HAVE_BOOST - -// Boost date_time library -/* #undef SOCI_HAVE_BOOST_DATE_TIME */ - -// Enables C++11 support -/* #undef SOCI_HAVE_CXX_C11 */ - -// DB2 backend -/* #undef SOCI_HAVE_DB2 */ - -// EMPTY backend -#define SOCI_HAVE_EMPTY - -// FIREBIRD backend -/* #undef SOCI_HAVE_FIREBIRD */ - -// MYSQL backend -/* #undef SOCI_HAVE_MYSQL */ - -// ODBC backend -/* #undef SOCI_HAVE_ODBC */ - -// ORACLE backend -/* #undef SOCI_HAVE_ORACLE */ - -// POSTGRESQL backend -/* #undef SOCI_HAVE_POSTGRESQL */ - -// SQLITE3 backend -#define SOCI_HAVE_SQLITE3 - - -#endif // SOCICONFIG_H_INCLUDED diff --git a/src/soci/include/soci/soci-config.h.in b/src/soci/include/soci/soci-config.h.in deleted file mode 100644 index 77fff775db..0000000000 --- a/src/soci/include/soci/soci-config.h.in +++ /dev/null @@ -1,16 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCICONFIG_H_INCLUDED -#define SOCICONFIG_H_INCLUDED - -// -// SOCI has been build with support for: -// -@CONFIGURED_VARIABLES@ - -#endif // SOCICONFIG_H_INCLUDED diff --git a/src/soci/include/soci/soci-platform.h b/src/soci/include/soci/soci-platform.h deleted file mode 100644 index 0b13374af5..0000000000 --- a/src/soci/include/soci/soci-platform.h +++ /dev/null @@ -1,143 +0,0 @@ -// -// Copyright (C) 2006-2008 Mateusz Loskot -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_PLATFORM_H_INCLUDED -#define SOCI_PLATFORM_H_INCLUDED - -//disable MSVC deprecated warnings -#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) -#define _CRT_SECURE_NO_WARNINGS -#endif - -#include -#include -#include -#include -#include -#include -#include - -#include "soci/soci-config.h" // for SOCI_HAVE_CXX_C11 - -#if defined(_MSC_VER) -#define LL_FMT_FLAGS "I64" -#else -#define LL_FMT_FLAGS "ll" -#endif - -// Portability hacks for Microsoft Visual C++ compiler -#ifdef _MSC_VER -#include - -//Disables warnings about STL objects need to have dll-interface and/or -//base class must have dll interface -#pragma warning(disable:4251 4275) - - -// Define if you have the vsnprintf variants. -#if _MSC_VER < 1500 -# define vsnprintf _vsnprintf -#endif - -// Define if you have the snprintf variants. -#define snprintf _snprintf - -// Define if you have the strtoll and strtoull variants. -#if _MSC_VER < 1300 -# error "Visual C++ versions prior 1300 don't support _strtoi64 and _strtoui64" -#elif _MSC_VER >= 1300 && _MSC_VER < 1800 -namespace std { - inline long long strtoll(char const* str, char** str_end, int base) - { - return _strtoi64(str, str_end, base); - } - - inline unsigned long long strtoull(char const* str, char** str_end, int base) - { - return _strtoui64(str, str_end, base); - } -} -#endif // _MSC_VER < 1800 -#endif // _MSC_VER - -#if defined(__CYGWIN__) || defined(__MINGW32__) -#include -namespace std { - using ::strtoll; - using ::strtoull; -} -#endif - -//define DLL import/export on WIN32 -#ifdef _WIN32 -# ifndef _WIN32_WINNT -# define _WIN32_WINNT 0x0502 //_WIN32_WINNT_WS03, VS2015 support: https://msdn.microsoft.com/de-de/library/6sehtctf.aspx -# endif // _WIN32_WINNT -# ifdef SOCI_DLL -# ifdef SOCI_SOURCE -# define SOCI_DECL __declspec(dllexport) -# else -# define SOCI_DECL __declspec(dllimport) -# endif // SOCI_SOURCE -# endif // SOCI_DLL -#endif // _WIN32 -// -// If SOCI_DECL isn't defined yet define it now -#ifndef SOCI_DECL -# define SOCI_DECL -#endif - -// C++11 features are always available in MSVS as it has no separate C++98 -// mode, we just need to check for the minimal compiler version supporting them -// (see https://msdn.microsoft.com/en-us/library/hh567368.aspx). - -#if defined(SOCI_HAVE_CXX_C11) || (defined(_MSC_VER) && _MSC_VER >= 1800) -# define SOCI_OVERRIDE override -#else -# define SOCI_OVERRIDE -#endif - -namespace soci -{ - -namespace cxx_details -{ - -#if defined(SOCI_HAVE_CXX_C11) || (defined(_MSC_VER) && _MSC_VER >= 1800) - template - using auto_ptr = std::unique_ptr; -#else // std::unique_ptr<> not available - using std::auto_ptr; -#endif - -} // namespace cxx_details - -} // namespace soci - -#if defined(SOCI_HAVE_CXX_C11) || (defined(_MSC_VER) && _MSC_VER >= 1800) - #define SOCI_NOT_ASSIGNABLE(classname) \ - classname& operator=(const classname&) = delete; - #define SOCI_NOT_COPYABLE(classname) \ - classname(const classname&) = delete; \ - SOCI_NOT_ASSIGNABLE(classname) -#else // no C++11 deleted members support - #define SOCI_NOT_ASSIGNABLE(classname) \ - classname& operator=(const classname&); - #define SOCI_NOT_COPYABLE(classname) \ - classname(const classname&); \ - SOCI_NOT_ASSIGNABLE(classname) -#endif // C++11 deleted members available - -#define SOCI_UNUSED(x) (void)x; - -#if defined(SOCI_HAVE_CXX_C11) || (defined(_MSC_VER) && _MSC_VER >= 1900) - #define SOCI_NOEXCEPT_FALSE noexcept(false) -#else - #define SOCI_NOEXCEPT_FALSE -#endif - -#endif // SOCI_PLATFORM_H_INCLUDED diff --git a/src/soci/include/soci/soci-simple.h b/src/soci/include/soci/soci-simple.h deleted file mode 100644 index 5eb1e6b5bd..0000000000 --- a/src/soci/include/soci/soci-simple.h +++ /dev/null @@ -1,159 +0,0 @@ -// -// Copyright (C) 2008 Maciej Sobczak -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_SIMPLE_H_INCLUDED -#define SOCI_SIMPLE_H_INCLUDED - -#include "soci/soci-platform.h" - -#ifdef __cplusplus -extern "C" -{ -#endif // __cplusplus - -// session - -typedef void * session_handle; -SOCI_DECL session_handle soci_create_session(char const * connectionString); -SOCI_DECL void soci_destroy_session(session_handle s); - -SOCI_DECL void soci_begin(session_handle s); -SOCI_DECL void soci_commit(session_handle s); -SOCI_DECL void soci_rollback(session_handle s); - -SOCI_DECL int soci_session_state(session_handle s); -SOCI_DECL char const * soci_session_error_message(session_handle s); - - -// blob - -typedef void *blob_handle; -SOCI_DECL blob_handle soci_create_blob(session_handle s); -SOCI_DECL void soci_destroy_blob(blob_handle b); - -SOCI_DECL int soci_blob_get_len(blob_handle b); -SOCI_DECL int soci_blob_read(blob_handle b, int offset, char *buf, int toRead); -SOCI_DECL int soci_blob_write(blob_handle b, int offset, char const *buf, int toWrite); -SOCI_DECL int soci_blob_append(blob_handle b, char const *buf, int toWrite); -SOCI_DECL int soci_blob_trim(blob_handle b, int newLen); - -SOCI_DECL int soci_blob_state(blob_handle b); -SOCI_DECL char const * soci_blob_error_message(blob_handle b); - - -// statement - -typedef void * statement_handle; -SOCI_DECL statement_handle soci_create_statement(session_handle s); -SOCI_DECL void soci_destroy_statement(statement_handle st); - -// positional bind of into elments (the functions return the position for convenience) -SOCI_DECL int soci_into_string (statement_handle st); -SOCI_DECL int soci_into_int (statement_handle st); -SOCI_DECL int soci_into_long_long(statement_handle st); -SOCI_DECL int soci_into_double (statement_handle st); -SOCI_DECL int soci_into_date (statement_handle st); -SOCI_DECL int soci_into_blob (statement_handle st); - -// vector versions -SOCI_DECL int soci_into_string_v (statement_handle st); -SOCI_DECL int soci_into_int_v (statement_handle st); -SOCI_DECL int soci_into_long_long_v(statement_handle st); -SOCI_DECL int soci_into_double_v (statement_handle st); -SOCI_DECL int soci_into_date_v (statement_handle st); - -// positional read of into elements -SOCI_DECL int soci_get_into_state (statement_handle st, int position); -SOCI_DECL char const * soci_get_into_string (statement_handle st, int position); -SOCI_DECL int soci_get_into_int (statement_handle st, int position); -SOCI_DECL long long soci_get_into_long_long(statement_handle st, int position); -SOCI_DECL double soci_get_into_double (statement_handle st, int position); -SOCI_DECL char const * soci_get_into_date (statement_handle st, int position); -SOCI_DECL blob_handle soci_get_into_blob (statement_handle st, int position); - -// positional (re)size of vectors -SOCI_DECL int soci_into_get_size_v(statement_handle st); -SOCI_DECL void soci_into_resize_v (statement_handle st, int new_size); - -// positional read of vectors -SOCI_DECL int soci_get_into_state_v (statement_handle st, int position, int index); -SOCI_DECL char const * soci_get_into_string_v (statement_handle st, int position, int index); -SOCI_DECL int soci_get_into_int_v (statement_handle st, int position, int index); -SOCI_DECL long long soci_get_into_long_long_v(statement_handle st, int position, int index); -SOCI_DECL double soci_get_into_double_v (statement_handle st, int position, int index); -SOCI_DECL char const * soci_get_into_date_v (statement_handle st, int position, int index); - - -// named bind of use elements -SOCI_DECL void soci_use_string (statement_handle st, char const * name); -SOCI_DECL void soci_use_int (statement_handle st, char const * name); -SOCI_DECL void soci_use_long_long(statement_handle st, char const * name); -SOCI_DECL void soci_use_double (statement_handle st, char const * name); -SOCI_DECL void soci_use_date (statement_handle st, char const * name); -SOCI_DECL void soci_use_blob (statement_handle st, char const * name); - -// vector versions -SOCI_DECL void soci_use_string_v (statement_handle st, char const * name); -SOCI_DECL void soci_use_int_v (statement_handle st, char const * name); -SOCI_DECL void soci_use_long_long_v(statement_handle st, char const * name); -SOCI_DECL void soci_use_double_v (statement_handle st, char const * name); -SOCI_DECL void soci_use_date_v (statement_handle st, char const * name); - - -// named write of use elements -SOCI_DECL void soci_set_use_state (statement_handle st, char const * name, int state); -SOCI_DECL void soci_set_use_string (statement_handle st, char const * name, char const * val); -SOCI_DECL void soci_set_use_int (statement_handle st, char const * name, int val); -SOCI_DECL void soci_set_use_long_long(statement_handle st, char const * name, long long val); -SOCI_DECL void soci_set_use_double (statement_handle st, char const * name, double val); -SOCI_DECL void soci_set_use_date (statement_handle st, char const * name, char const * val); -SOCI_DECL void soci_set_use_blob (statement_handle st, char const * name, blob_handle blob); - -// positional (re)size of vectors -SOCI_DECL int soci_use_get_size_v(statement_handle st); -SOCI_DECL void soci_use_resize_v (statement_handle st, int new_size); - -// named write of use vectors -SOCI_DECL void soci_set_use_state_v(statement_handle st, - char const * name, int index, int state); -SOCI_DECL void soci_set_use_string_v(statement_handle st, - char const * name, int index, char const * val); -SOCI_DECL void soci_set_use_int_v(statement_handle st, - char const * name, int index, int val); -SOCI_DECL void soci_set_use_long_long_v(statement_handle st, - char const * name, int index, long long val); -SOCI_DECL void soci_set_use_double_v(statement_handle st, - char const * name, int index, double val); -SOCI_DECL void soci_set_use_date_v(statement_handle st, - char const * name, int index, char const * val); - - -// named read of use elements (for modifiable use values) -SOCI_DECL int soci_get_use_state (statement_handle st, char const * name); -SOCI_DECL char const * soci_get_use_string (statement_handle st, char const * name); -SOCI_DECL int soci_get_use_int (statement_handle st, char const * name); -SOCI_DECL long long soci_get_use_long_long(statement_handle st, char const * name); -SOCI_DECL double soci_get_use_double (statement_handle st, char const * name); -SOCI_DECL char const * soci_get_use_date (statement_handle st, char const * name); -SOCI_DECL blob_handle soci_get_use_blob (statement_handle st, char const * name); - - -// statement preparation and execution -SOCI_DECL void soci_prepare(statement_handle st, char const * query); -SOCI_DECL int soci_execute(statement_handle st, int withDataExchange); -SOCI_DECL long long soci_get_affected_rows(statement_handle st); -SOCI_DECL int soci_fetch(statement_handle st); -SOCI_DECL int soci_got_data(statement_handle st); - -SOCI_DECL int soci_statement_state(statement_handle s); -SOCI_DECL char const * soci_statement_error_message(statement_handle s); - -#ifdef __cplusplus -} // extern "C" -#endif // __cplusplus - -#endif // SOCI_SIMPLE_H_INCLUDED diff --git a/src/soci/include/soci/soci.h b/src/soci/include/soci/soci.h deleted file mode 100644 index 9057abf08b..0000000000 --- a/src/soci/include/soci/soci.h +++ /dev/null @@ -1,58 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_H_INCLUDED -#define SOCI_H_INCLUDED - -// namespace soci -#include "soci/soci-platform.h" -#include "soci/backend-loader.h" -#include "soci/blob.h" -#include "soci/blob-exchange.h" -#include "soci/column-info.h" -#include "soci/connection-pool.h" -#include "soci/error.h" -#include "soci/exchange-traits.h" -#include "soci/into.h" -#include "soci/into-type.h" -#include "soci/once-temp-type.h" -#include "soci/prepare-temp-type.h" -#include "soci/procedure.h" -#include "soci/ref-counted-prepare-info.h" -#include "soci/ref-counted-statement.h" -#include "soci/row.h" -#include "soci/row-exchange.h" -#include "soci/rowid.h" -#include "soci/rowid-exchange.h" -#include "soci/rowset.h" -#include "soci/session.h" -#include "soci/soci-backend.h" -#include "soci/statement.h" -#include "soci/transaction.h" -#include "soci/type-conversion.h" -#include "soci/type-conversion-traits.h" -#include "soci/type-holder.h" -#include "soci/type-ptr.h" -#include "soci/type-wrappers.h" -#include "soci/unsigned-types.h" -#include "soci/use.h" -#include "soci/use-type.h" -#include "soci/values.h" -#include "soci/values-exchange.h" - -// namespace boost -#ifdef SOCI_USE_BOOST -#include -#if defined(BOOST_VERSION) && BOOST_VERSION >= 103500 -#include "soci/boost-fusion.h" -#endif // BOOST_VERSION -#include "soci/boost-optional.h" -#include "soci/boost-tuple.h" -#include "soci/boost-gregorian-date.h" -#endif // SOCI_USE_BOOST - -#endif // SOCI_H_INCLUDED diff --git a/src/soci/include/soci/sqlite3/soci-sqlite3.h b/src/soci/include/soci/sqlite3/soci-sqlite3.h deleted file mode 100644 index a93b321d90..0000000000 --- a/src/soci/include/soci/sqlite3/soci-sqlite3.h +++ /dev/null @@ -1,358 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_SQLITE3_H_INCLUDED -#define SOCI_SQLITE3_H_INCLUDED - -#ifdef _WIN32 -# ifdef SOCI_DLL -# ifdef SOCI_SQLITE3_SOURCE -# define SOCI_SQLITE3_DECL __declspec(dllexport) -# else -# define SOCI_SQLITE3_DECL __declspec(dllimport) -# endif // SOCI_SQLITE3_SOURCE -# endif // SOCI_DLL -#endif // _WIN32 -// -// If SOCI_SQLITE3_DECL isn't defined yet define it now -#ifndef SOCI_SQLITE3_DECL -# define SOCI_SQLITE3_DECL -#endif - -#include -#include -#include - -// Disable flood of nonsense warnings generated for SQLite -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4510 4512 4610) -#endif - -namespace sqlite_api -{ - -#if SQLITE_VERSION_NUMBER < 3003010 -// The sqlite3_destructor_type typedef introduced in 3.3.10 -// http://www.sqlite.org/cvstrac/tktview?tn=2191 -typedef void (*sqlite3_destructor_type)(void*); -#endif - -#include - -} // namespace sqlite_api - -#undef SQLITE_STATIC -#define SQLITE_STATIC ((sqlite_api::sqlite3_destructor_type)0) - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -namespace soci -{ - -class SOCI_SQLITE3_DECL sqlite3_soci_error : public soci_error -{ -public: - sqlite3_soci_error(std::string const & msg, int result); - - int result() const; - -private: - int result_; -}; - -struct sqlite3_statement_backend; -struct sqlite3_standard_into_type_backend : details::standard_into_type_backend -{ - sqlite3_standard_into_type_backend(sqlite3_statement_backend &st) - : statement_(st), data_(0), type_(), position_(0) - { - } - - void define_by_pos(int &position, - void *data, details::exchange_type type) SOCI_OVERRIDE; - - void pre_fetch() SOCI_OVERRIDE; - void post_fetch(bool gotData, bool calledFromFetch, - indicator *ind) SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - sqlite3_statement_backend &statement_; - - void *data_; - details::exchange_type type_; - int position_; -}; - -struct sqlite3_vector_into_type_backend : details::vector_into_type_backend -{ - sqlite3_vector_into_type_backend(sqlite3_statement_backend &st) - : statement_(st), data_(0), type_(), position_(0) - { - } - - void define_by_pos(int& position, void* data, details::exchange_type type) SOCI_OVERRIDE; - - void pre_fetch() SOCI_OVERRIDE; - void post_fetch(bool gotData, indicator* ind) SOCI_OVERRIDE; - - void resize(std::size_t sz) SOCI_OVERRIDE; - std::size_t size() SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - sqlite3_statement_backend& statement_; - - void *data_; - details::exchange_type type_; - int position_; -}; - -struct sqlite3_standard_use_type_backend : details::standard_use_type_backend -{ - sqlite3_standard_use_type_backend(sqlite3_statement_backend &st); - - void bind_by_pos(int &position, - void *data, details::exchange_type type, bool readOnly) SOCI_OVERRIDE; - void bind_by_name(std::string const &name, - void *data, details::exchange_type type, bool readOnly) SOCI_OVERRIDE; - - void pre_use(indicator const *ind) SOCI_OVERRIDE; - void post_use(bool gotData, indicator *ind) SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - sqlite3_statement_backend &statement_; - - void *data_; // pointer to used data: soci::use(myvariable) --> data_ = &myvariable - details::exchange_type type_; // type of data_ - int position_; // binding position - std::string name_; // binding name -}; - -struct sqlite3_vector_use_type_backend : details::vector_use_type_backend -{ - sqlite3_vector_use_type_backend(sqlite3_statement_backend &st) - : statement_(st), data_(0), type_(), position_(0) - { - } - - void bind_by_pos(int &position, - void *data, details::exchange_type type) SOCI_OVERRIDE; - void bind_by_name(std::string const &name, - void *data, details::exchange_type type) SOCI_OVERRIDE; - - void pre_use(indicator const *ind) SOCI_OVERRIDE; - - std::size_t size() SOCI_OVERRIDE; - - void clean_up() SOCI_OVERRIDE; - - sqlite3_statement_backend &statement_; - - void *data_; - details::exchange_type type_; - int position_; - std::string name_; -}; - -struct sqlite3_column_buffer -{ - std::size_t size_; - union - { - const char *constData_; - char *data_; - }; -}; - -struct sqlite3_column -{ - bool isNull_; - data_type type_; - - union - { - sqlite3_column_buffer buffer_; - int int32_; - sqlite_api::sqlite3_int64 int64_; - double double_; - }; -}; - -typedef std::vector sqlite3_row; -typedef std::vector sqlite3_recordset; - - -struct sqlite3_column_info -{ - data_type type_; - std::string name_; -}; -typedef std::vector sqlite3_column_info_list; - -struct sqlite3_session_backend; -struct sqlite3_statement_backend : details::statement_backend -{ - sqlite3_statement_backend(sqlite3_session_backend &session); - - void alloc() SOCI_OVERRIDE; - void clean_up() SOCI_OVERRIDE; - void prepare(std::string const &query, - details::statement_type eType) SOCI_OVERRIDE; - void reset_if_needed(); - void reset(); - - exec_fetch_result execute(int number) SOCI_OVERRIDE; - exec_fetch_result fetch(int number) SOCI_OVERRIDE; - - long long get_affected_rows() SOCI_OVERRIDE; - int get_number_of_rows() SOCI_OVERRIDE; - std::string get_parameter_name(int index) const SOCI_OVERRIDE; - - std::string rewrite_for_procedure_call(std::string const &query) SOCI_OVERRIDE; - - int prepare_for_describe() SOCI_OVERRIDE; - void describe_column(int colNum, data_type &dtype, - std::string &columnName) SOCI_OVERRIDE; - - sqlite3_standard_into_type_backend * make_into_type_backend() SOCI_OVERRIDE; - sqlite3_standard_use_type_backend * make_use_type_backend() SOCI_OVERRIDE; - sqlite3_vector_into_type_backend * make_vector_into_type_backend() SOCI_OVERRIDE; - sqlite3_vector_use_type_backend * make_vector_use_type_backend() SOCI_OVERRIDE; - - sqlite3_session_backend &session_; - sqlite_api::sqlite3_stmt *stmt_; - sqlite3_recordset dataCache_; - sqlite3_recordset useData_; - bool databaseReady_; - bool boundByName_; - bool boundByPos_; - sqlite3_column_info_list columns_; - - - long long rowsAffectedBulk_; // number of rows affected by the last bulk operation - -private: - exec_fetch_result load_rowset(int totalRows); - exec_fetch_result load_one(); - exec_fetch_result bind_and_execute(int number); -}; - -struct sqlite3_rowid_backend : details::rowid_backend -{ - sqlite3_rowid_backend(sqlite3_session_backend &session); - - ~sqlite3_rowid_backend() SOCI_OVERRIDE; - - unsigned long value_; -}; - -struct sqlite3_blob_backend : details::blob_backend -{ - sqlite3_blob_backend(sqlite3_session_backend &session); - - ~sqlite3_blob_backend() SOCI_OVERRIDE; - - std::size_t get_len() SOCI_OVERRIDE; - std::size_t read(std::size_t offset, char *buf, - std::size_t toRead) SOCI_OVERRIDE; - std::size_t write(std::size_t offset, char const *buf, - std::size_t toWrite) SOCI_OVERRIDE; - std::size_t append(char const *buf, std::size_t toWrite) SOCI_OVERRIDE; - void trim(std::size_t newLen) SOCI_OVERRIDE; - - sqlite3_session_backend &session_; - - std::size_t set_data(char const *buf, std::size_t toWrite); - const char *get_buffer() const { return buf_; } - -private: - char *buf_; - size_t len_; -}; - -struct sqlite3_session_backend : details::session_backend -{ - sqlite3_session_backend(connection_parameters const & parameters); - - ~sqlite3_session_backend() SOCI_OVERRIDE; - - void begin() SOCI_OVERRIDE; - void commit() SOCI_OVERRIDE; - void rollback() SOCI_OVERRIDE; - - bool get_last_insert_id(session&, std::string const&, long&) SOCI_OVERRIDE; - - std::string empty_blob() SOCI_OVERRIDE - { - return "x\'\'"; - } - - std::string get_dummy_from_table() const SOCI_OVERRIDE { return std::string(); } - - std::string get_backend_name() const SOCI_OVERRIDE { return "sqlite3"; } - - void clean_up(); - - sqlite3_statement_backend * make_statement_backend() SOCI_OVERRIDE; - sqlite3_rowid_backend * make_rowid_backend() SOCI_OVERRIDE; - sqlite3_blob_backend * make_blob_backend() SOCI_OVERRIDE; - std::string get_table_names_query() const SOCI_OVERRIDE - { - return "select name as \"TABLE_NAME\"" - " from sqlite_master where type = 'table'"; - } - std::string create_column_type(data_type dt, - int , int ) SOCI_OVERRIDE - { - switch (dt) - { - case dt_xml: - case dt_string: - return "text"; - case dt_double: - return "real"; - case dt_date: - case dt_integer: - case dt_long_long: - case dt_unsigned_long_long: - return "integer"; - case dt_blob: - return "blob"; - default: - throw soci_error("this data_type is not supported in create_column"); - } - - } - sqlite_api::sqlite3 *conn_; -}; - -struct sqlite3_backend_factory : backend_factory -{ - sqlite3_backend_factory() {} - sqlite3_session_backend * make_session( - connection_parameters const & parameters) const SOCI_OVERRIDE; -}; - -extern SOCI_SQLITE3_DECL sqlite3_backend_factory const sqlite3; - -extern "C" -{ - -// for dynamic backend loading -SOCI_SQLITE3_DECL backend_factory const * factory_sqlite3(); -SOCI_SQLITE3_DECL void register_factory_sqlite3(); - -} // extern "C" - -} // namespace soci - -#endif // SOCI_SQLITE3_H_INCLUDED diff --git a/src/soci/include/soci/statement.h b/src/soci/include/soci/statement.h deleted file mode 100644 index b1cfe7d1f6..0000000000 --- a/src/soci/include/soci/statement.h +++ /dev/null @@ -1,323 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_STATEMENT_H_INCLUDED -#define SOCI_STATEMENT_H_INCLUDED - -#include "soci/bind-values.h" -#include "soci/into-type.h" -#include "soci/into.h" -#include "soci/noreturn.h" -#include "soci/use-type.h" -#include "soci/use.h" -#include "soci/soci-backend.h" -#include "soci/row.h" -// std -#include -#include -#include - -namespace soci -{ - -class session; -class values; - -namespace details -{ - -class into_type_base; -class use_type_base; -class prepare_temp_type; - -class SOCI_DECL statement_impl -{ -public: - explicit statement_impl(session & s); - explicit statement_impl(prepare_temp_type const & prep); - ~statement_impl(); - - void alloc(); - void bind(values & v); - - void exchange(into_type_ptr const & i) { intos_.exchange(i); } - template - void exchange(into_container const &ic) - { intos_.exchange(ic); } - - void exchange(use_type_ptr const & u) { uses_.exchange(u); } - template - void exchange(use_container const &uc) - { uses_.exchange(uc); } - - - void clean_up(); - void bind_clean_up(); - - void prepare(std::string const & query, - statement_type eType = st_repeatable_query); - void define_and_bind(); - void undefine_and_bind(); - bool execute(bool withDataExchange = false); - long long get_affected_rows(); - bool fetch(); - void describe(); - void set_row(row * r); - void exchange_for_rowset(into_type_ptr const & i) { exchange_for_rowset_(i); } - template - void exchange_for_rowset(into_container const &ic) - { exchange_for_rowset_(ic); } - - // for diagnostics and advanced users - // (downcast it to expected back-end statement class) - statement_backend * get_backend() { return backEnd_; } - - standard_into_type_backend * make_into_type_backend(); - standard_use_type_backend * make_use_type_backend(); - vector_into_type_backend * make_vector_into_type_backend(); - vector_use_type_backend * make_vector_use_type_backend(); - - void inc_ref(); - void dec_ref(); - - session & session_; - - std::string rewrite_for_procedure_call(std::string const & query); - -protected: - into_type_vector intos_; - use_type_vector uses_; - std::vector indicators_; - -private: - // Call this method from a catch clause (only!) to rethrow the exception - // after adding the context in which it happened, including the provided - // description of the operation that failed, the SQL query and, if - // applicable, its parameters. - SOCI_NORETURN rethrow_current_exception_with_context(char const* operation); - - int refCount_; - - row * row_; - std::size_t fetchSize_; - std::size_t initialFetchSize_; - std::string query_; - - into_type_vector intosForRow_; - int definePositionForRow_; - - template - void exchange_for_rowset_(Into const &i) - { - if (intos_.empty() == false) - { - throw soci_error("Explicit into elements not allowed with rowset."); - } - - intos_.exchange(i); - - int definePosition = 1; - for(into_type_vector::iterator iter = intos_.begin(), - end = intos_.end(); - iter != end; iter++) - { (*iter)->define(*this, definePosition); } - definePositionForRow_ = definePosition; - } - - - template - void exchange_for_row(into_container const &ic) - { intosForRow_.exchange(ic); } - void exchange_for_row(into_type_ptr const & i) { intosForRow_.exchange(i); } - void define_for_row(); - - template - void into_row() - { - T * t = new T(); - indicator * ind = new indicator(i_ok); - row_->add_holder(t, ind); - exchange_for_row(into(*t, *ind)); - } - - template - void bind_into(); - - bool alreadyDescribed_; - - std::size_t intos_size(); - std::size_t uses_size(); - void pre_exec(int num); - void pre_fetch(); - void pre_use(); - void post_fetch(bool gotData, bool calledFromFetch); - void post_use(bool gotData); - bool resize_intos(std::size_t upperBound = 0); - void truncate_intos(); - - soci::details::statement_backend * backEnd_; - - SOCI_NOT_COPYABLE(statement_impl) -}; - -} // namespace details - -// Statement is a handle class for statement_impl -// (this provides copyability to otherwise non-copyable type) -class SOCI_DECL statement -{ -public: - statement(session & s) - : impl_(new details::statement_impl(s)) {} - statement(details::prepare_temp_type const & prep) - : impl_(new details::statement_impl(prep)) {} - ~statement() { impl_->dec_ref(); } - - // copy is supported for this handle class - statement(statement const & other) - : impl_(other.impl_) - { - impl_->inc_ref(); - } - - void operator=(statement const & other) - { - other.impl_->inc_ref(); - impl_->dec_ref(); - impl_ = other.impl_; - } - - void alloc() { impl_->alloc(); } - void bind(values & v) { impl_->bind(v); } - void exchange(details::into_type_ptr const & i) { impl_->exchange(i); } - template - void exchange(details::into_container const &ic) { impl_->exchange(ic); } - void exchange(details::use_type_ptr const & u) { impl_->exchange(u); } - template - void exchange(details::use_container const &uc) { impl_->exchange(uc); } - void clean_up() { impl_->clean_up(); } - void bind_clean_up() { impl_->bind_clean_up(); } - - void prepare(std::string const & query, - details::statement_type eType = details::st_repeatable_query) - { - impl_->prepare(query, eType); - } - - void define_and_bind() { impl_->define_and_bind(); } - void undefine_and_bind() { impl_->undefine_and_bind(); } - bool execute(bool withDataExchange = false) - { - gotData_ = impl_->execute(withDataExchange); - return gotData_; - } - - long long get_affected_rows() - { - return impl_->get_affected_rows(); - } - - bool fetch() - { - gotData_ = impl_->fetch(); - return gotData_; - } - - bool got_data() const { return gotData_; } - - void describe() { impl_->describe(); } - void set_row(row * r) { impl_->set_row(r); } - - template - void exchange_for_rowset(details::into_container const & ic) - { - impl_->exchange_for_rowset(ic); - } - - void exchange_for_rowset(details::into_type_ptr const & i) - { - impl_->exchange_for_rowset(i); - } - - // for diagnostics and advanced users - // (downcast it to expected back-end statement class) - details::statement_backend * get_backend() - { - return impl_->get_backend(); - } - - details::standard_into_type_backend * make_into_type_backend() - { - return impl_->make_into_type_backend(); - } - - details::standard_use_type_backend * make_use_type_backend() - { - return impl_->make_use_type_backend(); - } - - details::vector_into_type_backend * make_vector_into_type_backend() - { - return impl_->make_vector_into_type_backend(); - } - - details::vector_use_type_backend * make_vector_use_type_backend() - { - return impl_->make_vector_use_type_backend(); - } - - std::string rewrite_for_procedure_call(std::string const & query) - { - return impl_->rewrite_for_procedure_call(query); - } - -private: - details::statement_impl * impl_; - bool gotData_; -}; - -namespace details -{ -// exchange_traits for statement - -template <> -struct exchange_traits -{ - typedef basic_type_tag type_family; - enum { x_type = x_statement }; -}; - -// into and use types for Statement (for nested statements and cursors) - -template <> -class into_type : public standard_into_type -{ -public: - into_type(statement & s) : standard_into_type(&s, x_statement) {} - into_type(statement & s, indicator & ind) - : standard_into_type(&s, x_statement, ind) {} -}; - -template <> -class use_type : public standard_use_type -{ -public: - use_type(statement & s, std::string const & name = std::string()) - : standard_use_type(&s, x_statement, false, name) {} - use_type(statement & s, indicator & ind, - std::string const & name = std::string()) - : standard_use_type(&s, x_statement, ind, false, name) {} - - // Note: there is no const version of use for statement, - // because most likely it would not make much sense anyway. -}; - -} // namespace details - -} // namespace soci - -#endif // SOCI_STATEMENT_H_INCLUDED diff --git a/src/soci/include/soci/transaction.h b/src/soci/include/soci/transaction.h deleted file mode 100644 index c55b865f8b..0000000000 --- a/src/soci/include/soci/transaction.h +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_TRANSACTION_H_INCLUDED -#define SOCI_TRANSACTION_H_INCLUDED - -#include "soci/soci-platform.h" -#include "soci/session.h" - -namespace soci -{ - -class SOCI_DECL transaction -{ -public: - explicit transaction(session& sql); - - ~transaction(); - - void commit(); - void rollback(); - -private: - bool handled_; - session& sql_; - - SOCI_NOT_COPYABLE(transaction) -}; - -} // namespace soci - -#endif // SOCI_TRANSACTION_H_INCLUDED diff --git a/src/soci/include/soci/type-conversion-traits.h b/src/soci/include/soci/type-conversion-traits.h deleted file mode 100644 index e334071eaf..0000000000 --- a/src/soci/include/soci/type-conversion-traits.h +++ /dev/null @@ -1,41 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_TYPE_CONVERSION_TRAITS_H_INCLUDED -#define SOCI_TYPE_CONVERSION_TRAITS_H_INCLUDED - -#include "soci/soci-backend.h" - -namespace soci -{ - -// default traits class type_conversion, acts as pass through for row::get() -// when no actual conversion is needed. -template -struct type_conversion -{ - typedef T base_type; - - static void from_base(base_type const & in, indicator ind, T & out) - { - if (ind == i_null) - { - throw soci_error("Null value not allowed for this type"); - } - out = in; - } - - static void to_base(T const & in, base_type & out, indicator & ind) - { - out = in; - ind = i_ok; - } -}; - -} // namespace soci - -#endif // SOCI_TYPE_CONVERSION_TRAITS_H_INCLUDED diff --git a/src/soci/include/soci/type-conversion.h b/src/soci/include/soci/type-conversion.h deleted file mode 100644 index 1dfd891ac9..0000000000 --- a/src/soci/include/soci/type-conversion.h +++ /dev/null @@ -1,507 +0,0 @@ -// -// Copyright (C) 2004-2016 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_TYPE_CONVERSION_H_INCLUDED -#define SOCI_TYPE_CONVERSION_H_INCLUDED - -#include "soci/type-conversion-traits.h" -#include "soci/into-type.h" -#include "soci/use-type.h" -// std -#include -#include -#include - -namespace soci -{ - -namespace details -{ - -// this class is used to ensure correct order of construction -// of into_type and use_type elements that use type_conversion - -template -struct base_value_holder -{ - base_value_holder() - : ownInd_(i_ok) - {} - - typename type_conversion::base_type val_; - indicator ownInd_; -}; - -// Automatically create into_type from a type_conversion - -template -class conversion_into_type - : private base_value_holder, - public into_type::base_type> -{ -public: - typedef typename type_conversion::base_type base_type; - - conversion_into_type(T & value) - : into_type(base_value_holder::val_, base_value_holder::ownInd_) - , value_(value) - , ind_(base_value_holder::ownInd_) - { - } - - conversion_into_type(T & value, indicator & ind) - : into_type(base_value_holder::val_, ind) - , value_(value) - , ind_(ind) - { - } - - -private: - void convert_from_base() SOCI_OVERRIDE - { - type_conversion::from_base( - base_value_holder::val_, ind_, value_); - } - - T & value_; - - // ind_ refers to either ownInd_, or the one provided by the user - // in any case, ind_ refers to some valid indicator - // and can be used by conversion routines - indicator & ind_; - - SOCI_NOT_COPYABLE(conversion_into_type) -}; - -// Automatically create use_type from a type_conversion - -template -class conversion_use_type - : private base_value_holder, - public use_type::base_type> -{ -public: - typedef typename type_conversion::base_type base_type; - - conversion_use_type(T & value, std::string const & name = std::string()) - : use_type(base_value_holder::val_, base_value_holder::ownInd_, name) - , value_(value) - , ind_(base_value_holder::ownInd_) - , readOnly_(false) - { - // TODO: likely to be removed (SHA: c166625a28f7c907318134f625ff5acea7d9a1f8) - //convert_to_base(); - } - - conversion_use_type(T const & value, std::string const & name = std::string()) - : use_type(base_value_holder::val_, base_value_holder::ownInd_, name) - , value_(const_cast(value)) - , ind_(base_value_holder::ownInd_) - , readOnly_(true) - { - // TODO: likely to be removed (SHA: c166625a28f7c907318134f625ff5acea7d9a1f8) - //convert_to_base(); - } - - conversion_use_type(T & value, indicator & ind, - std::string const & name = std::string()) - : use_type(base_value_holder::val_, ind, name) - , value_(value) - , ind_(ind) - , readOnly_(false) - { - // TODO: likely to be removed (SHA: c166625a28f7c907318134f625ff5acea7d9a1f8) - //convert_to_base(); - } - - conversion_use_type(T const & value, indicator & ind, - std::string const & name = std::string()) - : use_type(base_value_holder::val_, ind, name) - , value_(const_cast(value)) - , ind_(ind) - , readOnly_(true) - { - // TODO: likely to be removed (SHA: c166625a28f7c907318134f625ff5acea7d9a1f8) - //convert_to_base(); - } - - void convert_from_base() SOCI_OVERRIDE - { - // NOTE: - // readOnly_ flag indicates that use_type object has been generated - // based on non-const object passed by user as input argument. - // For const objects, this is effectively no-op conversion. - // See standard_use_type::post_use() for more details. - - if (readOnly_ == false) - { - type_conversion::from_base( - base_value_holder::val_, ind_, value_); - } - } - - void convert_to_base() SOCI_OVERRIDE - { - type_conversion::to_base(value_, - base_value_holder::val_, ind_); - } - -private: - T & value_; - - // ind_ refers to either ownInd_, or the one provided by the user - // in any case, ind_ refers to some valid indicator - // and can be used by conversion routines - indicator & ind_; - - bool readOnly_; - - SOCI_NOT_COPYABLE(conversion_use_type) -}; - -// this class is used to ensure correct order of construction -// of vector based into_type and use_type elements that use type_conversion - -template -struct base_vector_holder -{ - base_vector_holder(std::size_t sz = 0) : vec_(sz) {} - mutable std::vector::base_type> vec_; -}; - -// Automatically create a std::vector based into_type from a type_conversion - -template -class conversion_into_type > - : private base_vector_holder, - public into_type::base_type> > -{ -public: - typedef typename std::vector - < - typename type_conversion::base_type - > base_type; - - conversion_into_type(std::vector & value, - std::size_t begin = 0, std::size_t * end = NULL) - : base_vector_holder(value.size()), - into_type( - base_vector_holder::vec_, ownInd_, begin, end), - value_(value), - ownInd_(), - ind_(ownInd_), - begin_(begin), - end_(end) - { - user_ranges_ = end != NULL; - } - - conversion_into_type(std::vector & value, std::vector & ind, - std::size_t begin = 0, std::size_t * end = NULL) - : base_vector_holder(value.size()), - into_type( - base_vector_holder::vec_, ind, begin, end), - value_(value), - ind_(ind), - begin_(begin), - end_(end) - { - user_ranges_ = end != NULL; - } - - std::size_t size() const SOCI_OVERRIDE - { - // the user might have resized his vector in the meantime - // -> synchronize the base-value mirror to have the same size - - std::size_t const userSize = value_.size(); - base_vector_holder::vec_.resize(userSize); - - return into_type::size(); - } - - void resize(std::size_t sz) SOCI_OVERRIDE - { - into_type::resize(sz); - - std::size_t actual_size = base_vector_holder::vec_.size(); - value_.resize(actual_size); - ind_.resize(actual_size); - } - -private: - void convert_from_base() SOCI_OVERRIDE - { - if (user_ranges_) - { - for (std::size_t i = begin_; i != *end_; ++i) - { - type_conversion::from_base( - base_vector_holder::vec_[i], ind_[i], value_[i]); - } - } - else - { - std::size_t const sz = base_vector_holder::vec_.size(); - - for (std::size_t i = 0; i != sz; ++i) - { - type_conversion::from_base( - base_vector_holder::vec_[i], ind_[i], value_[i]); - } - } - } - - std::vector & value_; - - std::vector ownInd_; - - // ind_ refers to either ownInd_, or the one provided by the user - // in any case, ind_ refers to some valid vector of indicators - // and can be used by conversion routines - std::vector & ind_; - - std::size_t begin_; - std::size_t * end_; - bool user_ranges_; - - SOCI_NOT_COPYABLE(conversion_into_type) -}; - - -// Automatically create a std::vector based use_type from a type_conversion - -template -class conversion_use_type > - : private base_vector_holder, - public use_type::base_type> > -{ -public: - typedef typename std::vector - < - typename type_conversion::base_type - > base_type; - - conversion_use_type(std::vector & value, - std::string const & name=std::string()) - : base_vector_holder(value.size()), - use_type( - base_vector_holder::vec_, ownInd_, 0, NULL, name), - value_(value), - ownInd_(), - ind_(ownInd_), - begin_(0), - end_(NULL), - user_ranges_(false) - { - } - - conversion_use_type(std::vector & value, - std::size_t begin, std::size_t * end, - std::string const & name=std::string()) - : base_vector_holder(value.size()), - use_type( - base_vector_holder::vec_, ownInd_, begin, end, name), - value_(value), - ownInd_(), - ind_(ownInd_), - begin_(begin), - end_(end) - { - user_ranges_ = end != NULL; - } - - conversion_use_type(std::vector & value, - std::vector & ind, - std::string const & name = std::string()) - : base_vector_holder(value.size()), - use_type( - base_vector_holder::vec_, ind, 0, NULL, name), - value_(value), - ind_(ind), - begin_(0), - end_(NULL), - user_ranges_(false) - { - } - - conversion_use_type(std::vector & value, - std::vector & ind, - std::size_t begin, std::size_t * end, - std::string const & name = std::string()) - : base_vector_holder(value.size()), - use_type( - base_vector_holder::vec_, ind, begin, end, name), - value_(value), - ind_(ind), - begin_(begin), - end_(end) - { - user_ranges_ = end != NULL; - } - -private: - void convert_from_base() - { - std::size_t const sz = base_vector_holder::vec_.size(); - value_.resize(sz); - ind_.resize(sz); - - if (user_ranges_) - { - for (std::size_t i = begin_; i != *end_; ++i) - { - type_conversion::from_base( - base_vector_holder::vec_[i], value_[i], ind_[i]); - } - } - else - { - for (std::size_t i = 0; i != sz; ++i) - { - type_conversion::from_base( - base_vector_holder::vec_[i], value_[i], ind_[i]); - } - } - } - - void convert_to_base() SOCI_OVERRIDE - { - std::size_t const sz = value_.size(); - base_vector_holder::vec_.resize(sz); - ind_.resize(sz); - - if (user_ranges_) - { - for (std::size_t i = begin_; i != *end_; ++i) - { - type_conversion::to_base(value_[i], - base_vector_holder::vec_[i], ind_[i]); - } - } - else - { - for (std::size_t i = 0; i != sz; ++i) - { - type_conversion::to_base(value_[i], - base_vector_holder::vec_[i], ind_[i]); - } - } - } - - std::vector & value_; - - std::vector ownInd_; - - // ind_ refers to either ownInd_, or the one provided by the user - // in any case, ind_ refers to some valid vector of indicators - // and can be used by conversion routines - std::vector & ind_; - - std::size_t begin_; - std::size_t * end_; - bool user_ranges_; - - SOCI_NOT_COPYABLE(conversion_use_type) -}; - -template -into_type_ptr do_into(T & t, user_type_tag) -{ - return into_type_ptr(new conversion_into_type(t)); -} - -template -into_type_ptr do_into(T & t, indicator & ind, user_type_tag) -{ - return into_type_ptr(new conversion_into_type(t, ind)); -} - -template -into_type_ptr do_into(std::vector & t, - std::size_t begin, size_t * end, user_type_tag) -{ - return into_type_ptr( - new conversion_into_type >(t, begin, end)); -} - -template -into_type_ptr do_into(std::vector & t, std::vector & ind, - std::size_t begin, size_t * end, user_type_tag) -{ - return into_type_ptr( - new conversion_into_type >(t, ind, begin, end)); -} - -template -use_type_ptr do_use(T & t, std::string const & name, user_type_tag) -{ - return use_type_ptr(new conversion_use_type(t, name)); -} - -template -use_type_ptr do_use(T const & t, std::string const & name, user_type_tag) -{ - return use_type_ptr(new conversion_use_type(t, name)); -} - -template -use_type_ptr do_use(T & t, indicator & ind, - std::string const & name, user_type_tag) -{ - return use_type_ptr(new conversion_use_type(t, ind, name)); -} - -template -use_type_ptr do_use(T const & t, indicator & ind, - std::string const & name, user_type_tag) -{ - return use_type_ptr(new conversion_use_type(t, ind, name)); -} - -template -use_type_ptr do_use(std::vector & t, - std::size_t begin, size_t * end, - std::string const & name, user_type_tag) -{ - return use_type_ptr( - new conversion_use_type >(t, begin, end, name)); -} - -template -use_type_ptr do_use(const std::vector & t, - std::size_t begin, size_t * end, - std::string const & name, user_type_tag) -{ - return use_type_ptr( - new conversion_use_type >(t, begin, end, name)); -} - -template -use_type_ptr do_use(std::vector & t, std::vector & ind, - std::size_t begin, size_t * end, - std::string const & name, user_type_tag) -{ - return use_type_ptr( - new conversion_use_type >(t, ind, begin, end, name)); -} - -template -use_type_ptr do_use(const std::vector & t, std::vector & ind, - std::size_t begin, size_t * end, - std::string const & name, user_type_tag) -{ - return use_type_ptr( - new conversion_use_type >(t, ind, begin, end, name)); -} - -} // namespace details - -} // namespace soci - -#endif // SOCI_TYPE_CONVERSION_H_INCLUDED diff --git a/src/soci/include/soci/type-holder.h b/src/soci/include/soci/type-holder.h deleted file mode 100644 index 61c9613bc0..0000000000 --- a/src/soci/include/soci/type-holder.h +++ /dev/null @@ -1,70 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_TYPE_HOLDER_H_INCLUDED -#define SOCI_TYPE_HOLDER_H_INCLUDED - -#include "soci/soci-platform.h" -// std -#include - -namespace soci -{ - -namespace details -{ - -// Base class holder + derived class type_holder for storing type data -// instances in a container of holder objects -template -class type_holder; - -class holder -{ -public: - holder() {} - virtual ~holder() {} - - template - T get() - { - type_holder* p = dynamic_cast *>(this); - if (p) - { - return p->template value(); - } - else - { - throw std::bad_cast(); - } - } - -private: - - template - T value(); -}; - -template -class type_holder : public holder -{ -public: - type_holder(T * t) : t_(t) {} - ~type_holder() SOCI_OVERRIDE { delete t_; } - - template - TypeValue value() const { return *t_; } - -private: - T * t_; -}; - -} // namespace details - -} // namespace soci - -#endif // SOCI_TYPE_HOLDER_H_INCLUDED diff --git a/src/soci/include/soci/type-ptr.h b/src/soci/include/soci/type-ptr.h deleted file mode 100644 index 492362f82b..0000000000 --- a/src/soci/include/soci/type-ptr.h +++ /dev/null @@ -1,30 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_TYPE_PTR_H_INCLUDED -#define SOCI_TYPE_PTR_H_INCLUDED - -namespace soci { namespace details { - -template -class type_ptr -{ -public: - type_ptr(T * p) : p_(p) {} - ~type_ptr() { delete p_; } - - T * get() const { return p_; } - void release() const { p_ = 0; } - -private: - mutable T * p_; -}; - -} // namespace details -} // namespace soci - -#endif // SOCI_TYPE_PTR_H_INCLUDED diff --git a/src/soci/include/soci/type-wrappers.h b/src/soci/include/soci/type-wrappers.h deleted file mode 100644 index 04a5a2f2fb..0000000000 --- a/src/soci/include/soci/type-wrappers.h +++ /dev/null @@ -1,33 +0,0 @@ -// -// Copyright (C) 2016 Maciej Sobczak -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_TYPE_WRAPPERS_H_INCLUDED -#define SOCI_TYPE_WRAPPERS_H_INCLUDED - -namespace soci -{ - -// These wrapper types can be used by the application -// with 'into' and 'use' elements in order to guide the library -// in selecting specialized methods for binding and transferring data; -// if the target database does not provide any such specialized methods, -// it is expected to handle these wrappers as equivalent -// to their contained field types. - -struct xml_type -{ - std::string value; -}; - -struct long_string -{ - std::string value; -}; - -} // namespace soci - -#endif // SOCI_TYPE_WRAPPERS_H_INCLUDED diff --git a/src/soci/include/soci/unsigned-types.h b/src/soci/include/soci/unsigned-types.h deleted file mode 100644 index 7a08bc9d39..0000000000 --- a/src/soci/include/soci/unsigned-types.h +++ /dev/null @@ -1,114 +0,0 @@ -// -// Copyright (C) 2010 Maciej Sobczak -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_UNSIGNED_TYPES_H_INCLUDED -#define SOCI_UNSIGNED_TYPES_H_INCLUDED - -#include "soci/type-conversion-traits.h" -#include - -namespace soci -{ - -// simple fall-back for unsigned types - -template <> -struct type_conversion -{ - typedef long long base_type; - - static void from_base(base_type const & in, indicator ind, - unsigned char & out) - { - if (ind == i_null) - { - throw soci_error("Null value not allowed for this type."); - } - - const base_type max = (std::numeric_limits::max)(); - const base_type min = (std::numeric_limits::min)(); - if (in < min || in > max) - { - /* throw soci_error("Value outside of allowed range."); */ - } - - out = static_cast(in); - } - - static void to_base(unsigned char const & in, - base_type & out, indicator & ind) - { - out = static_cast(in); - ind = i_ok; - } -}; - -template <> -struct type_conversion -{ - typedef long long base_type; - - static void from_base(base_type const & in, indicator ind, - unsigned short & out) - { - if (ind == i_null) - { - throw soci_error("Null value not allowed for this type."); - } - - const long long max = (std::numeric_limits::max)(); - const long long min = (std::numeric_limits::min)(); - if (in < min || in > max) - { - /* throw soci_error("Value outside of allowed range."); */ - } - - out = static_cast(in); - } - - static void to_base(unsigned short const & in, - base_type & out, indicator & ind) - { - out = static_cast(in); - ind = i_ok; - } -}; - -template <> -struct type_conversion -{ - typedef long long base_type; - - static void from_base(base_type const & in, indicator ind, - unsigned int & out) - { - if (ind == i_null) - { - throw soci_error("Null value not allowed for this type."); - } - - const long long max = (std::numeric_limits::max)(); - const long long min = (std::numeric_limits::min)(); - if (in < min || in > max) - { - /* throw soci_error("Value outside of allowed range."); */ - } - - out = static_cast(in); - } - - static void to_base(unsigned int const & in, - base_type & out, indicator & ind) - { - out = static_cast(in); - ind = i_ok; - } -}; - -} // namespace soci - -#endif // SOCI_UNSIGNED_TYPES_H_INCLUDED diff --git a/src/soci/include/soci/use-type.h b/src/soci/include/soci/use-type.h deleted file mode 100644 index 3a431d0975..0000000000 --- a/src/soci/include/soci/use-type.h +++ /dev/null @@ -1,340 +0,0 @@ -// -// Copyright (C) 2004-2016 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_USE_TYPE_H_INCLUDED -#define SOCI_USE_TYPE_H_INCLUDED - -#include "soci/soci-platform.h" -#include "soci/soci-backend.h" -#include "soci/type-ptr.h" -#include "soci/exchange-traits.h" -// std -#include -#include -#include -#include - -namespace soci { namespace details { - -class statement_impl; - -// this is intended to be a base class for all classes that deal with -// binding input data (and OUT PL/SQL variables) -class SOCI_DECL use_type_base -{ -public: - virtual ~use_type_base() {} - - virtual void bind(statement_impl & st, int & position) = 0; - virtual std::string get_name() const = 0; - virtual void dump_value(std::ostream& os) const = 0; - virtual void pre_exec(int num) = 0; - virtual void pre_use() = 0; - virtual void post_use(bool gotData) = 0; - virtual void clean_up() = 0; - - virtual std::size_t size() const = 0; // returns the number of elements -}; - -typedef type_ptr use_type_ptr; - -class SOCI_DECL standard_use_type : public use_type_base -{ -public: - standard_use_type(void* data, exchange_type type, - bool readOnly, std::string const& name = std::string()) - : data_(data) - , type_(type) - , ind_(NULL) - , readOnly_(readOnly) - , name_(name) - , backEnd_(NULL) - { - // FIXME: This was added with Ilia's patch - // https://github.com/SOCI/soci/commit/c166625a28f7c907318134f625ff5acea7d9a1f8 - // but it seems to be a troublemaker, causing duplicated conversions - //convert_to_base(); - } - - standard_use_type(void* data, exchange_type type, indicator& ind, - bool readOnly, std::string const& name = std::string()) - : data_(data) - , type_(type) - , ind_(&ind) - , readOnly_(readOnly) - , name_(name) - , backEnd_(NULL) - { - // FIXME - //convert_to_base(); - } - - ~standard_use_type() SOCI_OVERRIDE; - void bind(statement_impl & st, int & position) SOCI_OVERRIDE; - std::string get_name() const SOCI_OVERRIDE { return name_; } - void dump_value(std::ostream& os) const SOCI_OVERRIDE; - virtual void * get_data() { return data_; } - - // conversion hook (from arbitrary user type to base type) - virtual void convert_to_base() {} - virtual void convert_from_base() {} - -protected: - void pre_use() SOCI_OVERRIDE; - -private: - void pre_exec(int num) SOCI_OVERRIDE; - void post_use(bool gotData) SOCI_OVERRIDE; - void clean_up() SOCI_OVERRIDE; - std::size_t size() const SOCI_OVERRIDE { return 1; } - - void* data_; - exchange_type type_; - indicator* ind_; - bool readOnly_; - std::string name_; - - standard_use_type_backend* backEnd_; -}; - -class SOCI_DECL vector_use_type : public use_type_base -{ -public: - vector_use_type(void* data, exchange_type type, - std::string const& name = std::string()) - : data_(data) - , type_(type) - , ind_(NULL) - , begin_(0) - , end_(NULL) - , name_(name) - , backEnd_(NULL) - {} - - vector_use_type(void* data, exchange_type type, - std::size_t begin, std::size_t * end, - std::string const& name = std::string()) - : data_(data) - , type_(type) - , ind_(NULL) - , begin_(begin) - , end_(end) - , name_(name) - , backEnd_(NULL) - {} - - vector_use_type(void* data, exchange_type type, - std::vector const& ind, - std::string const& name = std::string()) - : data_(data) - , type_(type) - , ind_(&ind) - , begin_(0) - , end_(NULL) - , name_(name) - , backEnd_(NULL) - {} - - vector_use_type(void* data, exchange_type type, - std::vector const& ind, - std::size_t begin, std::size_t * end, - std::string const& name = std::string()) - : data_(data) - , type_(type) - , ind_(&ind) - , begin_(begin) - , end_(end) - , name_(name) - , backEnd_(NULL) - {} - - ~vector_use_type() SOCI_OVERRIDE; - -private: - void bind(statement_impl& st, int & position) SOCI_OVERRIDE; - std::string get_name() const SOCI_OVERRIDE { return name_; } - void dump_value(std::ostream& os) const SOCI_OVERRIDE; - void pre_exec(int num) SOCI_OVERRIDE; - void pre_use() SOCI_OVERRIDE; - void post_use(bool) SOCI_OVERRIDE { /* nothing to do */ } - void clean_up() SOCI_OVERRIDE; - std::size_t size() const SOCI_OVERRIDE; - - void* data_; - exchange_type type_; - std::vector const* ind_; - std::size_t begin_; - std::size_t * end_; - std::string name_; - - vector_use_type_backend * backEnd_; - - virtual void convert_to_base() {} -}; - -// implementation for the basic types (those which are supported by the library -// out of the box without user-provided conversions) - -template -class use_type : public standard_use_type -{ -public: - use_type(T& t, std::string const& name = std::string()) - : standard_use_type(&t, - static_cast(exchange_traits::x_type), false, name) - {} - - use_type(T const& t, std::string const& name = std::string()) - : standard_use_type(const_cast(&t), - static_cast(exchange_traits::x_type), true, name) - {} - - use_type(T& t, indicator& ind, std::string const& name = std::string()) - : standard_use_type(&t, - static_cast(exchange_traits::x_type), ind, false, name) - {} - - use_type(T const& t, indicator& ind, std::string const& name = std::string()) - : standard_use_type(const_cast(&t), - static_cast(exchange_traits::x_type), ind, false, name) - {} -}; - -template -class use_type > : public vector_use_type -{ -public: - use_type(std::vector& v, std::string const& name = std::string()) - : vector_use_type(&v, - static_cast(exchange_traits::x_type), name) - {} - - use_type(std::vector& v, std::size_t begin, std::size_t * end, - std::string const& name = std::string()) - : vector_use_type(&v, - static_cast(exchange_traits::x_type), begin, end, name) - {} - - use_type(std::vector const& v, std::string const& name = std::string()) - : vector_use_type(const_cast*>(&v), - static_cast(exchange_traits::x_type), name) - {} - - use_type(std::vector const& v, std::size_t begin, std::size_t * end, - std::string const& name = std::string()) - : vector_use_type(const_cast*>(&v), - static_cast(exchange_traits::x_type), begin, end, name) - {} - - use_type(std::vector& v, std::vector const& ind, - std::string const& name = std::string()) - : vector_use_type(&v, - static_cast(exchange_traits::x_type), ind, name) - {} - - use_type(std::vector& v, std::vector const& ind, - std::size_t begin, std::size_t * end, std::string const& name = std::string()) - : vector_use_type(&v, - static_cast(exchange_traits::x_type), ind, begin, end, name) - {} - - use_type(std::vector const& v, std::vector const& ind, - std::string const& name = std::string()) - : vector_use_type(const_cast *>(&v), - static_cast(exchange_traits::x_type), ind, name) - {} - - use_type(std::vector const& v, std::vector const& ind, - std::size_t begin, std::size_t * end, std::string const& name = std::string()) - : vector_use_type(const_cast *>(&v), - static_cast(exchange_traits::x_type), ind, begin, end, name) - {} -}; - -// helper dispatchers for basic types - -template -use_type_ptr do_use(T & t, std::string const & name, basic_type_tag) -{ - return use_type_ptr(new use_type(t, name)); -} - -template -use_type_ptr do_use(T const & t, std::string const & name, basic_type_tag) -{ - return use_type_ptr(new use_type(t, name)); -} - -template -use_type_ptr do_use(T & t, indicator & ind, - std::string const & name, basic_type_tag) -{ - return use_type_ptr(new use_type(t, ind, name)); -} - -template -use_type_ptr do_use(T const & t, indicator & ind, - std::string const & name, basic_type_tag) -{ - return use_type_ptr(new use_type(t, ind, name)); -} - -template -use_type_ptr do_use(T & t, std::vector & ind, - std::string const & name, basic_type_tag) -{ - return use_type_ptr(new use_type(t, ind, name)); -} - -template -use_type_ptr do_use(T const & t, std::vector & ind, - std::string const & name, basic_type_tag) -{ - return use_type_ptr(new use_type(t, ind, name)); -} - -template -use_type_ptr do_use(std::vector & t, - std::size_t begin, std::size_t * end, - std::string const & name, basic_type_tag) -{ - return use_type_ptr( - new use_type >(t, begin, end, name)); -} - -template -use_type_ptr do_use(const std::vector & t, - std::size_t begin, std::size_t * end, - std::string const & name, basic_type_tag) -{ - return use_type_ptr( - new use_type >(t, begin, end, name)); -} - -template -use_type_ptr do_use(std::vector & t, std::vector & ind, - std::size_t begin, std::size_t * end, - std::string const & name, basic_type_tag) -{ - return use_type_ptr( - new use_type >(t, ind, begin, end, name)); -} - -template -use_type_ptr do_use(const std::vector & t, std::vector & ind, - std::size_t begin, std::size_t * end, - std::string const & name, basic_type_tag) -{ - return use_type_ptr( - new use_type >(t, ind, begin, end, name)); -} - -} // namespace details - -} // namesapce soci - -#endif // SOCI_USE_TYPE_H_INCLUDED diff --git a/src/soci/include/soci/use.h b/src/soci/include/soci/use.h deleted file mode 100644 index cf8c32a9e7..0000000000 --- a/src/soci/include/soci/use.h +++ /dev/null @@ -1,116 +0,0 @@ -// -// Copyright (C) 2004-2016 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_USE_H_INCLUDED -#define SOCI_USE_H_INCLUDED - -#include "soci/use-type.h" -#include "soci/exchange-traits.h" -#include "soci/type-conversion.h" -#include "soci/soci-backend.h" - -namespace soci -{ - -namespace details -{ -template -struct use_container -{ - use_container(T &_t, Indicator &_ind, const std::string &_name) - : t(_t), ind(_ind), name(_name) {} - - T &t; - Indicator &ind; - const std::string &name; -private: - SOCI_NOT_ASSIGNABLE(use_container) -}; - -typedef void no_indicator; -template -struct use_container -{ - use_container(T &_t, const std::string &_name) - : t(_t), name(_name) {} - - T &t; - const std::string &name; -private: - SOCI_NOT_ASSIGNABLE(use_container) -}; - -} // namespace details - -template -details::use_container use(T &t, const std::string &name = std::string()) -{ return details::use_container(t, name); } - -template -details::use_container use(T const &t, const std::string &name = std::string()) -{ return details::use_container(t, name); } - -template -details::use_container use(T &t, indicator & ind, std::string const &name = std::string()) -{ return details::use_container(t, ind, name); } - -template -details::use_container use(T const &t, indicator & ind, std::string const &name = std::string()) -{ return details::use_container(t, ind, name); } - -// vector containers -template -details::use_container > - use(T &t, std::vector & ind, const std::string &name = std::string()) -{ return details::use_container >(t, ind, name); } - -template -details::use_container, details::no_indicator > - use(std::vector &t, const std::string &name = std::string()) -{ return details::use_container, details::no_indicator>(t, name); } - -// vectors with index ranges - -template -details::use_type_ptr use(std::vector & t, - std::size_t begin, std::size_t & end, - const std::string &name = std::string()) -{ - return details::do_use(t, begin, &end, name, - typename details::exchange_traits >::type_family()); -} - -template -details::use_type_ptr use(const std::vector & t, - std::size_t begin, std::size_t & end, - const std::string &name = std::string()) -{ - return details::do_use(t, begin, &end, name, - typename details::exchange_traits >::type_family()); -} - -template -details::use_type_ptr use(std::vector & t, std::vector & ind, - std::size_t begin, std::size_t & end, - const std::string &name = std::string()) -{ - return details::do_use(t, ind, begin, &end, name, - typename details::exchange_traits >::type_family()); -} - -template -details::use_type_ptr use(const std::vector & t, std::vector & ind, - std::size_t begin, std::size_t & end, - const std::string &name = std::string()) -{ - return details::do_use(t, ind, begin, &end, name, - typename details::exchange_traits >::type_family()); -} - -} // namespace soci - -#endif // SOCI_USE_H_INCLUDED diff --git a/src/soci/include/soci/values-exchange.h b/src/soci/include/soci/values-exchange.h deleted file mode 100644 index d7caeb5323..0000000000 --- a/src/soci/include/soci/values-exchange.h +++ /dev/null @@ -1,150 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_VALUES_EXCHANGE_H_INCLUDED -#define SOCI_VALUES_EXCHANGE_H_INCLUDED - -#include "soci/values.h" -#include "soci/into-type.h" -#include "soci/use-type.h" -#include "soci/row-exchange.h" -// std -#include -#include -#include -#include - -namespace soci -{ - -namespace details -{ - -template <> -struct exchange_traits -{ - typedef basic_type_tag type_family; - - // dummy value to satisfy the template engine, never used - enum { x_type = 0 }; -}; - -template <> -class use_type : public use_type_base -{ -public: - use_type(values & v, std::string const & /*name*/ = std::string()) - : v_(v) - {} - - // we ignore the possibility to have the whole values as NULL - use_type(values & v, indicator /*ind*/, std::string const & /*name*/ = std::string()) - : v_(v) - {} - - void bind(details::statement_impl & st, int & /*position*/) SOCI_OVERRIDE - { - v_.uppercase_column_names(st.session_.get_uppercase_column_names()); - - convert_to_base(); - st.bind(v_); - } - - std::string get_name() const SOCI_OVERRIDE - { - std::ostringstream oss; - - oss << "("; - - std::size_t const num_columns = v_.get_number_of_columns(); - for (std::size_t n = 0; n < num_columns; ++n) - { - if (n != 0) - oss << ", "; - - oss << v_.get_properties(n).get_name(); - } - - oss << ")"; - - return oss.str(); - } - - void dump_value(std::ostream& os) const SOCI_OVERRIDE - { - // TODO: Dump all columns. - os << ""; - } - - void pre_exec(int /* num */) SOCI_OVERRIDE {} - - void post_use(bool /*gotData*/) SOCI_OVERRIDE - { - v_.reset_get_counter(); - convert_from_base(); - } - - void pre_use() SOCI_OVERRIDE {convert_to_base();} - void clean_up() SOCI_OVERRIDE {v_.clean_up();} - std::size_t size() const SOCI_OVERRIDE { return 1; } - - // these are used only to re-dispatch to derived class - // (the derived class might be generated automatically by - // user conversions) - virtual void convert_to_base() {} - virtual void convert_from_base() {} - -private: - values & v_; - - SOCI_NOT_COPYABLE(use_type) -}; - -// this is not supposed to be used - no support for bulk ORM -template <> -class use_type > -{ -private: - use_type(); -}; - -template <> -class into_type : public into_type -{ -public: - into_type(values & v) - : into_type(v.get_row()), v_(v) - {} - - into_type(values & v, indicator & ind) - : into_type(v.get_row(), ind), v_(v) - {} - - void clean_up() SOCI_OVERRIDE - { - v_.clean_up(); - } - -private: - values & v_; - - SOCI_NOT_COPYABLE(into_type) -}; - -// this is not supposed to be used - no support for bulk ORM -template <> -class into_type > -{ -private: - into_type(); -}; - -} // namespace details - -} // namespace soci - -#endif // SOCI_VALUES_EXCHANGE_H_INCLUDED diff --git a/src/soci/include/soci/values.h b/src/soci/include/soci/values.h deleted file mode 100644 index f2868574c8..0000000000 --- a/src/soci/include/soci/values.h +++ /dev/null @@ -1,354 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_VALUES_H_INCLUDED -#define SOCI_VALUES_H_INCLUDED - -#include "soci/statement.h" -#include "soci/into-type.h" -#include "soci/use-type.h" -// std -#include -#include -#include -#include -#include -#include - -namespace soci -{ - -namespace details -{ - -class copy_base -{ -public: - virtual ~copy_base() {} -}; - -template -struct copy_holder : public copy_base -{ - copy_holder(T const & v) : value_(v) {} - - T value_; -}; - -} // namespace details - -class SOCI_DECL values -{ - friend class details::statement_impl; - friend class details::into_type; - friend class details::use_type; - -public: - - values() : row_(NULL), currentPos_(0), uppercaseColumnNames_(false) {} - - indicator get_indicator(std::size_t pos) const; - indicator get_indicator(std::string const & name) const; - - template - T get(std::size_t pos) const - { - if (row_ != NULL) - { - return row_->get(pos); - } - else if (*indicators_[pos] != i_null) - { - return get_from_uses(pos); - } - else - { - std::ostringstream msg; - msg << "Column at position " - << static_cast(pos) - << " contains NULL value and no default was provided"; - throw soci_error(msg.str()); - } - } - - template - T get(std::size_t pos, T const & nullValue) const - { - if (row_ != NULL) - { - return row_->get(pos, nullValue); - } - else if (*indicators_[pos] == i_null) - { - return nullValue; - } - else - { - return get_from_uses(pos); - } - } - - template - T get(std::string const & name) const - { - return row_ != NULL ? row_->get(name) : get_from_uses(name); - } - - template - T get(std::string const & name, T const & nullValue) const - { - return row_ != NULL - ? row_->get(name, nullValue) - : get_from_uses(name, nullValue); - } - - template - values const & operator>>(T & value) const - { - if (row_ != NULL) - { - // row maintains its own position counter - // which is automatically reset when needed - - *row_ >> value; - } - else if (*indicators_[currentPos_] != i_null) - { - // if there is no row object, then the data can be - // extracted from the locally stored use elements, - // but for this the position counter has to be maintained - // as well - - value = get_from_uses(currentPos_); - ++currentPos_; - } - else - { - std::ostringstream msg; - msg << "Column at position " - << static_cast(currentPos_) - << " contains NULL value and no default was provided"; - throw soci_error(msg.str()); - } - - return *this; - } - - void skip(std::size_t num = 1) const - { - if (row_ != NULL) - { - row_->skip(num); - } - else - { - currentPos_ += num; - } - } - - void reset_get_counter() const - { - if (row_ != NULL) - { - row_->reset_get_counter(); - } - else - { - currentPos_ = 0; - } - } - - template - void set(std::string const & name, T const & value, indicator indic = i_ok) - { - typedef typename type_conversion::base_type base_type; - if(index_.find(name) == index_.end()) - { - index_.insert(std::make_pair(name, uses_.size())); - - indicator * pind = new indicator(indic); - indicators_.push_back(pind); - - base_type baseValue; - if (indic == i_ok) - { - type_conversion::to_base(value, baseValue, *pind); - } - - details::copy_holder * pcopy = - new details::copy_holder(baseValue); - deepCopies_.push_back(pcopy); - - uses_.push_back(new details::use_type( - pcopy->value_, *pind, name)); - } - else - { - size_t index = index_.find(name)->second; - *indicators_[index] = indic; - if (indic == i_ok) - { - type_conversion::to_base( - value, - static_cast*>(deepCopies_[index])->value_, - *indicators_[index]); - } - } - } - - template - void set(const T & value, indicator indic = i_ok) - { - indicator * pind = new indicator(indic); - indicators_.push_back(pind); - - typedef typename type_conversion::base_type base_type; - base_type baseValue; - type_conversion::to_base(value, baseValue, *pind); - - details::copy_holder * pcopy = - new details::copy_holder(baseValue); - deepCopies_.push_back(pcopy); - - uses_.push_back(new details::use_type( - pcopy->value_, *pind)); - } - - template - values & operator<<(T const & value) - { - set(value); - return *this; - } - - void uppercase_column_names(bool forceToUpper) - { - uppercaseColumnNames_ = forceToUpper; - } - - std::size_t get_number_of_columns() const - { - return row_ ? row_->size() : 0; - } - - column_properties const& get_properties(std::size_t pos) const; - column_properties const& get_properties(std::string const &name) const; - -private: - - //TODO To make values generally usable outside of type_conversion's, - // these should be reference counted smart pointers - row * row_; - std::vector uses_; - std::map unused_; - std::vector indicators_; - std::map index_; - std::vector deepCopies_; - - mutable std::size_t currentPos_; - - bool uppercaseColumnNames_; - - // When type_conversion::to() is called, a values object is created - // without an underlying row object. In that case, get_from_uses() - // returns the underlying field values - template - T get_from_uses(std::string const & name, T const & nullValue) const - { - std::map::const_iterator pos = index_.find(name); - if (pos != index_.end()) - { - if (*indicators_[pos->second] == i_null) - { - return nullValue; - } - - return get_from_uses(pos->second); - } - throw soci_error("Value named " + name + " not found."); - } - - template - T get_from_uses(std::string const & name) const - { - std::map::const_iterator pos = index_.find(name); - if (pos != index_.end()) - { - return get_from_uses(pos->second); - } - throw soci_error("Value named " + name + " not found."); - } - - template - T get_from_uses(std::size_t pos) const - { - details::standard_use_type* u = uses_[pos]; - - typedef typename type_conversion::base_type base_type; - - if (dynamic_cast *>(u)) - { - base_type const & baseValue = *static_cast(u->get_data()); - - T val; - indicator ind = *indicators_[pos]; - type_conversion::from_base(baseValue, ind, val); - return val; - } - else - { - std::ostringstream msg; - msg << "Value at position " - << static_cast(pos) - << " was set using a different type" - " than the one passed to get()"; - throw soci_error(msg.str()); - } - } - - row& get_row() - { - row_ = new row(); - row_->uppercase_column_names(uppercaseColumnNames_); - - return * row_; - } - - // this is called by Statement::bind(values) - void add_unused(details::use_type_base * u, indicator * i) - { - static_cast(u)->convert_to_base(); - unused_.insert(std::make_pair(u, i)); - } - - // this is called by details::into_type::clean_up() - // and use_type::clean_up() - void clean_up() - { - delete row_; - row_ = NULL; - - // delete any uses and indicators which were created by set() but - // were not bound by the Statement - // (bound uses and indicators are deleted in Statement::clean_up()) - for (std::map::iterator pos = - unused_.begin(); pos != unused_.end(); ++pos) - { - delete pos->first; - delete pos->second; - } - - for (std::size_t i = 0; i != deepCopies_.size(); ++i) - { - delete deepCopies_[i]; - } - } -}; - -} // namespace soci - -#endif // SOCI_VALUES_H_INCLUDED diff --git a/src/soci/include/soci/version.h b/src/soci/include/soci/version.h deleted file mode 100644 index 2de32c7ad3..0000000000 --- a/src/soci/include/soci/version.h +++ /dev/null @@ -1,34 +0,0 @@ -// SOCI version.hpp configuration header file - -// -// Copyright (C) 2011 Mateusz Loskot -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_VERSION_HPP -#define SOCI_VERSION_HPP - -// When updating the version here, don't forget to update it in CMakeLists.txt! - -// -// Caution, this is the only SOCI header that is guarenteed -// to change with every SOCI release, including this header -// will cause a recompile every time a new SOCI version is -// released. -// -// SOCI_VERSION % 100 is the patch level -// SOCI_VERSION / 100 % 1000 is the minor version -// SOCI_VERSION / 100000 is the major version - -#define SOCI_VERSION 400000 - -// -// SOCI_LIB_VERSION must be defined to be the same as SOCI_VERSION -// but as a *string* in the form "x_y[_z]" where x is the major version -// number, y is the minor version number, and z is the patch level if not 0. - -#define SOCI_LIB_VERSION "4_0_0" - -#endif // SOCI_VERSION_HPP diff --git a/src/soci/languages/ada/postgresql_client.gpr b/src/soci/languages/ada/postgresql_client.gpr deleted file mode 100644 index f29b3498b4..0000000000 --- a/src/soci/languages/ada/postgresql_client.gpr +++ /dev/null @@ -1,8 +0,0 @@ -project PostgreSQL_Client is - for Externally_Built use "true"; - for Source_Dirs use (); - for Library_Dir use "/usr/local/lib"; - for Library_Name use "pq"; - for Library_Kind use "static"; -end PostgreSQL_Client; - diff --git a/src/soci/languages/ada/soci-mysql.ads b/src/soci/languages/ada/soci-mysql.ads deleted file mode 100644 index 10156fbc61..0000000000 --- a/src/soci/languages/ada/soci-mysql.ads +++ /dev/null @@ -1,16 +0,0 @@ --- Copyright (C) 2008-2011 Maciej Sobczak --- Distributed under the Boost Software License, Version 1.0. --- (See accompanying file LICENSE_1_0.txt or copy at --- http://www.boost.org/LICENSE_1_0.txt) - -package SOCI.MySQL is - - -- - -- Registers the MySQL backend so that it is ready for use - -- by the dynamic backend loader. - -- - procedure Register_Factory_MySQL; - pragma Import (C, Register_Factory_MySQL, - "register_factory_mysql"); - -end SOCI.MySQL; diff --git a/src/soci/languages/ada/soci-oracle.ads b/src/soci/languages/ada/soci-oracle.ads deleted file mode 100644 index ed8bc6672b..0000000000 --- a/src/soci/languages/ada/soci-oracle.ads +++ /dev/null @@ -1,16 +0,0 @@ --- Copyright (C) 2008-2011 Maciej Sobczak --- Distributed under the Boost Software License, Version 1.0. --- (See accompanying file LICENSE_1_0.txt or copy at --- http://www.boost.org/LICENSE_1_0.txt) - -package SOCI.Oracle is - - -- - -- Registers the Oracle backend so that it is ready for use - -- by the dynamic backend loader. - -- - procedure Register_Factory_Oracle; - pragma Import (C, Register_Factory_Oracle, - "register_factory_oracle"); - -end SOCI.Oracle; diff --git a/src/soci/languages/ada/soci-postgresql.ads b/src/soci/languages/ada/soci-postgresql.ads deleted file mode 100644 index fc750b2572..0000000000 --- a/src/soci/languages/ada/soci-postgresql.ads +++ /dev/null @@ -1,16 +0,0 @@ --- Copyright (C) 2008-2011 Maciej Sobczak --- Distributed under the Boost Software License, Version 1.0. --- (See accompanying file LICENSE_1_0.txt or copy at --- http://www.boost.org/LICENSE_1_0.txt) - -package SOCI.PostgreSQL is - - -- - -- Registers the PostgreSQL backend so that it is ready for use - -- by the dynamic backend loader. - -- - procedure Register_Factory_PostgreSQL; - pragma Import (C, Register_Factory_PostgreSQL, - "register_factory_postgresql"); - -end SOCI.PostgreSQL; diff --git a/src/soci/languages/ada/soci.adb b/src/soci/languages/ada/soci.adb deleted file mode 100644 index 7f72f1bbf6..0000000000 --- a/src/soci/languages/ada/soci.adb +++ /dev/null @@ -1,1465 +0,0 @@ --- Copyright (C) 2008-2011 Maciej Sobczak --- Distributed under the Boost Software License, Version 1.0. --- (See accompanying file LICENSE_1_0.txt or copy at --- http://www.boost.org/LICENSE_1_0.txt) - -with Ada.Strings.Fixed; -with Interfaces.C.Strings; - -package body SOCI is - - procedure Check_Session_State (Handle : in Session_Handle) is - - function Soci_Session_State (S : in Session_Handle) return Interfaces.C.int; - - pragma Import (C, Soci_Session_State, "soci_session_state"); - - function Soci_Session_Error_Message - (S : in Session_Handle) - return Interfaces.C.Strings.chars_ptr; - pragma Import (C, Soci_Session_Error_Message, "soci_session_error_message"); - - State : constant Interfaces.C.int := Soci_Session_State (Handle); - Bad_State : constant Interfaces.C.int := 0; - - use type Interfaces.C.int; - - begin - if State = Bad_State then - declare - Message : constant String := - Interfaces.C.Strings.Value (Soci_Session_Error_Message (Handle)); - begin - raise Database_Error with Message; - end; - end if; - end Check_Session_State; - - function Make_Session_Handle (Connection_String : in String) return Session_Handle is - - function Soci_Create_Session (C : in Interfaces.C.char_array) return Session_Handle; - pragma Import (C, Soci_Create_Session, "soci_create_session"); - - Connection_String_C : constant Interfaces.C.char_array := - Interfaces.C.To_C (Connection_String); - - Handle : constant Session_Handle := - Soci_Create_Session (Connection_String_C); - - begin - if Handle = Null_Session_Handle then - raise Database_Error with "Cannot create session object."; - else - return Handle; - end if; - end Make_Session_Handle; - - function Data_State_To_Int (State : in Data_State) return Interfaces.C.int is - begin - if State = Data_Not_Null then - return 1; - else - return 0; - end if; - end Data_State_To_Int; - - function Int_To_Data_State (State : in Interfaces.C.int) return Data_State is - use type Interfaces.C.int; - begin - if State /= 0 then - return Data_Not_Null; - else - return Data_Null; - end if; - end Int_To_Data_State; - - procedure Check_Is_Open (This : in Session'Class) is - begin - if not This.Initialized then - raise Database_Error with "Session is not initialized."; - end if; - end Check_Is_Open; - - procedure Check_Statement_State (Handle : in Statement_Handle) is - - function Soci_Statement_State (S : in Statement_Handle) return Interfaces.C.int; - pragma Import (C, Soci_Statement_State, "soci_statement_state"); - - function Soci_Statement_Error_Message - (S : in Statement_Handle) - return Interfaces.C.Strings.chars_ptr; - pragma Import (C, Soci_Statement_Error_Message, "soci_statement_error_message"); - - State : constant Interfaces.C.int := Soci_Statement_State (Handle); - Bad_State : constant Interfaces.C.int := 0; - - use type Interfaces.C.int; - - begin - if State = Bad_State then - declare - Message : constant String := - Interfaces.C.Strings.Value (Soci_Statement_Error_Message (Handle)); - begin - raise Database_Error with Message; - end; - end if; - end Check_Statement_State; - - function String_To_Time (Source : in String) return Ada.Calendar.Time is - - Year_N : Natural; - Month_N : Natural; - Day_N : Natural; - Hour_N : Natural; - Minute_N : Natural; - Second_N : Natural; - - procedure Get_Next_Number - (Source : in String; - Position : in out Natural; - Result : out Natural) is - - I : Natural; - begin - I := Ada.Strings.Fixed.Index (Source => Source, - Pattern => " ", - From => Position); - - if I /= 0 then - Result := Natural'Value (Source (Position .. I)); - Position := I + 1; - else - Result := Natural'Value (Source (Position .. Source'Last)); - Position := 0; - end if; - end Get_Next_Number; - - Pos : Natural := 1; - - begin - - Get_Next_Number (Source => Source, Position => Pos, Result => Year_N); - Get_Next_Number (Source => Source, Position => Pos, Result => Month_N); - Get_Next_Number (Source => Source, Position => Pos, Result => Day_N); - Get_Next_Number (Source => Source, Position => Pos, Result => Hour_N); - Get_Next_Number (Source => Source, Position => Pos, Result => Minute_N); - Get_Next_Number (Source => Source, Position => Pos, Result => Second_N); - - return Ada.Calendar.Time_Of (Year_N, Month_N, Day_N, - Duration (Hour_N * 3_600 + Minute_N * 60 + Second_N)); - - end String_To_Time; - - function Time_To_String (Date : in Ada.Calendar.Time) return String is - - Year : Ada.Calendar.Year_Number; - Month : Ada.Calendar.Month_Number; - Day : Ada.Calendar.Day_Number; - Seconds : Ada.Calendar.Day_Duration; - - Hour : Natural; - Minute : Natural; - Seconds_N : Natural; - - begin - Ada.Calendar.Split (Date, Year, Month, Day, Seconds); - Seconds_N := Natural (Seconds); - - Hour := Seconds_N / 3_600; - Minute := (Seconds_N - Natural (Hour) * 3_600) / 60; - Seconds_N := Seconds_N - Natural (Hour) * 3_600 - Natural (Minute) * 60; - return Ada.Calendar.Year_Number'Image (Year) & " " & - Ada.Calendar.Month_Number'Image (Month) & " " & - Ada.Calendar.Day_Number'Image (Day) & " " & - Natural'Image (Hour) & " " & - Natural'Image (Minute) & " " & - Natural'Image (Seconds_N); - end Time_To_String; - - - function Make_Session (Connection_String : in String) return Session is - begin - return S : Session do - S.Handle := Make_Session_Handle (Connection_String); - S.Initialized := True; - Check_Session_State (S.Handle); - end return; - end Make_Session; - - procedure Open (This : in out Session; Connection_String : in String) is - begin - if This.Initialized then - raise Database_Error with "Session is already initialized."; - else - declare - Handle : constant Session_Handle := - Make_Session_Handle (Connection_String); - begin - Check_Session_State (Handle); - - This.Handle := Handle; - This.Initialized := True; - end; - end if; - end Open; - - procedure Close (This : in out Session) is - - procedure Soci_Destroy_Session (S : in Session_Handle); - pragma Import (C, Soci_Destroy_Session, "soci_destroy_session"); - - begin - if This.Initialized then - if This.Belongs_To_Pool then - raise Database_Error with "Cannot close session - not an owner (session in pool)."; - else - Soci_Destroy_Session (This.Handle); - This.Initialized := False; - end if; - end if; - end Close; - - function Is_Open (This : in Session) return Boolean is - begin - return This.Initialized; - end Is_Open; - - procedure Finalize (This : in out Session) is - begin - if This.Initialized then - if This.Belongs_To_Pool then - This.Pool.all.Give_Back (This.Position_In_Pool); - This.Initialized := False; - else - This.Close; - end if; - end if; - end Finalize; - - procedure Start (This : in Session) is - - procedure Soci_Begin (S : in Session_Handle); - pragma Import (C, Soci_Begin, "soci_begin"); - - begin - Check_Is_Open (This); - Soci_Begin (This.Handle); - Check_Session_State (This.Handle); - end Start; - - procedure Commit (This : in Session) is - - procedure Soci_Commit (S : in Session_Handle); - pragma Import (C, Soci_Commit, "soci_commit"); - - begin - Check_Is_Open (This); - Soci_Commit (This.Handle); - Check_Session_State (This.Handle); - end Commit; - - procedure Rollback (This : in Session) is - - procedure Soci_Rollback (S : in Session_Handle); - pragma Import (C, Soci_Rollback, "soci_rollback"); - - begin - Check_Is_Open (This); - Soci_Rollback (This.Handle); - Check_Session_State (This.Handle); - end Rollback; - - procedure Execute (This : in Session; Query : in String) is - S : Statement := Make_Statement (This); - begin - S.Prepare (Query); - S.Execute; - end Execute; - - protected body Connection_Pool_PS is - - procedure Open (Position : in Positive; Connection_String : in String) is - begin - if Position > Size then - raise Database_Error with "Index out of range."; - end if; - - Connections (Position).Open (Connection_String); - end Open; - - procedure Close (Position : in Positive) is - begin - if Position > Size then - raise Database_Error with "Index out of range."; - end if; - - if Is_Used (Position) then - raise Database_Error with "Cannot close connection that is currently in use."; - end if; - - Connections (Position).Close; - end Close; - - entry Lease (S : in out Session'Class) when Available is - Found : Boolean := False; - begin - if S.Initialized then - raise Database_Error with "This session is already initialized."; - end if; - - -- Find some connection in the pool that is not currently used. - for I in 1 .. Size loop - if not Is_Used (I) then - Check_Is_Open (Connections (I)); - - S.Handle := Connections (I).Handle; - S.Initialized := True; - S.Belongs_To_Pool := True; - S.Position_In_Pool := I; - - -- WORKAROUND: - -- The S.Pool component is set in the Lease procedure - -- of the Connection_Pool type, because here the access - -- to the protected object could not be taken (compiler bug). - - Is_Used (I) := True; - Found := True; - exit; - end if; - end loop; - - if not Found then - raise Database_Error with "Internal error."; - end if; - - -- Update the Available flag. - Found := False; - for I in 1 .. Size loop - if not Is_Used (I) then - Found := True; - exit; - end if; - end loop; - Available := Found; - - end Lease; - - procedure Give_Back (Position : in Positive) is - begin - if Position > Size then - raise Database_Error with "Index out of range."; - end if; - - if not Is_Used (Position) then - raise Database_Error with "Cannot give back connection that is not in use."; - end if; - - Is_Used (Position) := False; - Available := True; - end Give_Back; - - end Connection_Pool_PS; - - procedure Open - (This : in out Connection_Pool; - Position : in Positive; - Connection_String : in String) is - begin - This.Pool.Open (Position, Connection_String); - end Open; - - procedure Close (This : in out Connection_Pool; Position : in Positive) is - begin - This.Pool.Close (Position); - end Close; - - procedure Lease (This : in out Connection_Pool; S : in out Session'Class) is - begin - This.Pool.Lease (S); - - -- WORKAROUND: - -- The S.Pool component is set here because the access - -- to protected object cannot be taken in protected body (compiler bug.) - - -- JUSTIFICATION: - -- The Unchecked_Access is taken here to enable the session to properly - -- "unregister" from the pool in Session's Finalize. - -- An alternative would be to rely on the user to explicitly unlock - -- the appropriate entry in the pool, which is too error prone. - -- It is assumed that connection pool always has wider lifetime - -- than that of the session which is temporarily leased from the pool - -- - this guarantees that S.Pool always points to a valid pool object. - - S.Pool := This.Pool'Unchecked_Access; - end Lease; - - function Make_Statement (Sess : in Session'Class) return Statement is - - function Soci_Create_Statement (Sess : in Session_Handle) return Statement_Handle; - pragma Import (C, Soci_Create_Statement, "soci_create_statement"); - - begin - Check_Is_Open (Sess); - - declare - Handle : constant Statement_Handle := - Soci_Create_Statement (Sess.Handle); - begin - - return S : Statement do - S.Handle := Handle; - S.Initialized := True; - Check_Statement_State (S.Handle); - end return; - end; - end Make_Statement; - - procedure Finalize (This : in out Statement) is - - procedure Soci_Destroy_Statement (S : in Statement_Handle); - pragma Import (C, Soci_Destroy_Statement, "soci_destroy_statement"); - - begin - if This.Initialized then - Soci_Destroy_Statement (This.Handle); - This.Initialized := False; - end if; - end Finalize; - - procedure Prepare (This : in Statement; Query : in String) is - - procedure Soci_Prepare (St : in Statement_Handle; Q : in Interfaces.C.char_array); - pragma Import (C, Soci_Prepare, "soci_prepare"); - - Query_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Query); - - begin - Soci_Prepare (This.Handle, Query_C); - Check_Statement_State (This.Handle); - end Prepare; - - procedure Execute (This : in Statement; With_Data_Exchange : in Boolean := False) is - Result : constant Boolean := This.Execute (With_Data_Exchange); - begin - null; - end Execute; - - function Execute - (This : in Statement; - With_Data_Exchange : in Boolean := False) - return Boolean is - - function Soci_Execute - (St : in Statement_Handle; - WDE : in Interfaces.C.int) - return Interfaces.C.int; - pragma Import (C, Soci_Execute, "soci_execute"); - - WDE_C : Interfaces.C.int; - Result : Interfaces.C.int; - - use type Interfaces.C.int; - - begin - if With_Data_Exchange then - WDE_C := 1; - else - WDE_C := 0; - end if; - - Result := Soci_Execute (This.Handle, WDE_C); - Check_Statement_State (This.Handle); - - return Result /= 0; - end Execute; - - function Fetch (This : in Statement) return Boolean is - - function Soci_Fetch (St : in Statement_Handle) return Interfaces.C.int; - pragma Import (C, Soci_Fetch, "soci_fetch"); - - Result : constant Interfaces.C.int := Soci_Fetch (This.Handle); - - use type Interfaces.C.int; - - begin - Check_Statement_State (This.Handle); - return Result /= 0; - end Fetch; - - function Got_Data (This : in Statement) return Boolean is - - function Soci_Got_Data (St : in Statement_Handle) return Interfaces.C.int; - pragma Import (C, Soci_Got_Data, "soci_got_data"); - - Result : constant Interfaces.C.int := Soci_Got_Data (This.Handle); - - use type Interfaces.C.int; - - begin - Check_Statement_State (This.Handle); - return Result /= 0; - end Got_Data; - - function Into_String (This : in Statement) return Into_Position is - - function Soci_Into_String (St : in Statement_Handle) return Interfaces.C.int; - pragma Import (C, Soci_Into_String, "soci_into_string"); - - Result : constant Interfaces.C.int := Soci_Into_String (This.Handle); - - begin - Check_Statement_State (This.Handle); - return Into_Position (Result); - end Into_String; - - function Into_Integer (This : in Statement) return Into_Position is - - function Soci_Into_Int (St : in Statement_Handle) return Interfaces.C.int; - pragma Import (C, Soci_Into_Int, "soci_into_int"); - - Result : constant Interfaces.C.int := Soci_Into_Int (This.Handle); - - begin - Check_Statement_State (This.Handle); - return Into_Position (Result); - end Into_Integer; - - function Into_Long_Long_Integer (This : in Statement) return Into_Position is - - function Soci_Into_Long_Long (St : in Statement_Handle) return Interfaces.C.int; - pragma Import (C, Soci_Into_Long_Long, "soci_into_long_long"); - - Result : constant Interfaces.C.int := Soci_Into_Long_Long (This.Handle); - - begin - Check_Statement_State (This.Handle); - return Into_Position (Result); - end Into_Long_Long_Integer; - - function Into_Long_Float (This : in Statement) return Into_Position is - - function Soci_Into_Double (St : in Statement_Handle) return Interfaces.C.int; - pragma Import (C, Soci_Into_Double, "soci_into_double"); - - Result : constant Interfaces.C.int := Soci_Into_Double (This.Handle); - - begin - Check_Statement_State (This.Handle); - return Into_Position (Result); - end Into_Long_Float; - - function Into_Time (This : in Statement) return Into_Position is - - function Soci_Into_Date (St : in Statement_Handle) return Interfaces.C.int; - pragma Import (C, Soci_Into_Date, "soci_into_date"); - - Result : constant Interfaces.C.int := Soci_Into_Date (This.Handle); - - begin - Check_Statement_State (This.Handle); - return Into_Position (Result); - end Into_Time; - - function Into_Vector_String (This : in Statement) return Into_Position is - - function Soci_Into_String_V (St : in Statement_Handle) return Interfaces.C.int; - pragma Import (C, Soci_Into_String_V, "soci_into_string_v"); - - Result : constant Interfaces.C.int := Soci_Into_String_V (This.Handle); - - begin - Check_Statement_State (This.Handle); - return Into_Position (Result); - end Into_Vector_String; - - function Into_Vector_Integer (This : in Statement) return Into_Position is - - function Soci_Into_Int_V (St : in Statement_Handle) return Interfaces.C.int; - pragma Import (C, Soci_Into_Int_V, "soci_into_int_v"); - - Result : constant Interfaces.C.int := Soci_Into_Int_V (This.Handle); - - begin - Check_Statement_State (This.Handle); - return Into_Position (Result); - end Into_Vector_Integer; - - function Into_Vector_Long_Long_Integer (This : in Statement) return Into_Position is - - function Soci_Into_Long_Long_V (St : in Statement_Handle) return Interfaces.C.int; - pragma Import (C, Soci_Into_Long_Long_V, "soci_into_long_long_v"); - - Result : constant Interfaces.C.int := Soci_Into_Long_Long_V (This.Handle); - - begin - Check_Statement_State (This.Handle); - return Into_Position (Result); - end Into_Vector_Long_Long_Integer; - - function Into_Vector_Long_Float (This : in Statement) return Into_Position is - - function Soci_Into_Double_V (St : in Statement_Handle) return Interfaces.C.int; - pragma Import (C, Soci_Into_Double_V, "soci_into_double_v"); - - Result : constant Interfaces.C.int := Soci_Into_Double_V (This.Handle); - - begin - Check_Statement_State (This.Handle); - return Into_Position (Result); - end Into_Vector_Long_Float; - - function Into_Vector_Time (This : in Statement) return Into_Position is - - function Soci_Into_Date_V (St : in Statement_Handle) return Interfaces.C.int; - pragma Import (C, Soci_Into_Date_V, "soci_into_date_v"); - - Result : constant Interfaces.C.int := Soci_Into_Date_V (This.Handle); - - begin - Check_Statement_State (This.Handle); - return Into_Position (Result); - end Into_Vector_Time; - - function Get_Into_State - (This : in Statement; - Position : in Into_Position) - return Data_State is - - function Soci_Get_Into_State - (St : in Statement_Handle; - P : in Interfaces.C.int) - return Interfaces.C.int; - pragma Import (C, Soci_Get_Into_State, "soci_get_into_state"); - - Result : constant Interfaces.C.int := - Soci_Get_Into_State (This.Handle, Interfaces.C.int (Position)); - - use type Interfaces.C.int; - - begin - Check_Statement_State (This.Handle); - return Int_To_Data_State (Result); - end Get_Into_State; - - function Get_Into_String - (This : in Statement; - Position : in Into_Position) - return String is - - function Soci_Get_Into_String - (St : in Statement_Handle; - P : in Interfaces.C.int) - return Interfaces.C.Strings.chars_ptr; - pragma Import (C, Soci_Get_Into_String, "soci_get_into_string"); - - Result : constant Interfaces.C.Strings.chars_ptr := - Soci_Get_Into_String (This.Handle, Interfaces.C.int (Position)); - - begin - Check_Statement_State (This.Handle); - return Interfaces.C.Strings.Value (Result); - end Get_Into_String; - - function Get_Into_Integer - (This : in Statement; - Position : in Into_Position) - return DB_Integer is - - function Soci_Get_Into_Int - (St : in Statement_Handle; - P : in Interfaces.C.int) - return Interfaces.C.int; - pragma Import (C, Soci_Get_Into_Int, "soci_get_into_int"); - - Result : constant Interfaces.C.int := - Soci_Get_Into_Int (This.Handle, Interfaces.C.int (Position)); - - begin - Check_Statement_State (This.Handle); - return DB_Integer (Result); - end Get_Into_Integer; - - function Get_Into_Long_Long_Integer - (This : in Statement; - Position : in Into_Position) - return DB_Long_Long_Integer is - - function Soci_Get_Into_Long_Long - (St : in Statement_Handle; - P : in Interfaces.C.int) - return Interfaces.Integer_64; - pragma Import (C, Soci_Get_Into_Long_Long, "soci_get_into_long_long"); - - Result : constant Interfaces.Integer_64 := - Soci_Get_Into_Long_Long (This.Handle, Interfaces.C.int (Position)); - - begin - Check_Statement_State (This.Handle); - return DB_Long_Long_Integer (Result); - end Get_Into_Long_Long_Integer; - - function Get_Into_Long_Float - (This : in Statement; - Position : in Into_Position) - return DB_Long_Float is - - function Soci_Get_Into_Double - (St : in Statement_Handle; - P : in Interfaces.C.int) - return Interfaces.C.double; - pragma Import (C, Soci_Get_Into_Double, "soci_get_into_double"); - - Result : constant Interfaces.C.double := - Soci_Get_Into_Double (This.Handle, Interfaces.C.int (Position)); - - begin - Check_Statement_State (This.Handle); - return DB_Long_Float (Result); - end Get_Into_Long_Float; - - function Get_Into_Time - (This : in Statement; - Position : in Into_Position) - return Ada.Calendar.Time is - - function Soci_Get_Into_Date - (St : in Statement_Handle; - P : in Interfaces.C.int) - return Interfaces.C.Strings.chars_ptr; - pragma Import (C, Soci_Get_Into_Date, "soci_get_into_date"); - - Result_C : constant Interfaces.C.Strings.chars_ptr := - Soci_Get_Into_Date (This.Handle, Interfaces.C.int (Position)); - Result : constant String := Interfaces.C.Strings.Value (Result_C); - - begin - Check_Statement_State (This.Handle); - return String_To_Time (Result); - end Get_Into_Time; - - function Get_Into_Vectors_Size (This : in Statement) return Natural is - - function Soci_Into_Get_Size_V - (St : in Statement_Handle) - return Interfaces.C.int; - pragma Import (C, Soci_Into_Get_Size_V, "soci_into_get_size_v"); - - Result_C : constant Interfaces.C.int := Soci_Into_Get_Size_V (This.Handle); - - begin - Check_Statement_State (This.Handle); - return Natural (Result_C); - end Get_Into_Vectors_Size; - - function Into_Vectors_First_Index (This : in Statement) return Vector_Index is - begin - return 0; - end Into_Vectors_First_Index; - - function Into_Vectors_Last_Index (This : in Statement) return Vector_Index is - begin - return Vector_Index (This.Get_Into_Vectors_Size - 1); - end Into_Vectors_Last_Index; - - procedure Into_Vectors_Resize (This : in Statement; New_Size : in Natural) is - - procedure Soci_Into_Resize_V - (St : in Statement_Handle; - New_Size : in Interfaces.C.int); - pragma Import (C, Soci_Into_Resize_V, "soci_into_resize_v"); - - begin - Soci_Into_Resize_V (This.Handle, Interfaces.C.int (New_Size)); - Check_Statement_State (This.Handle); - end Into_Vectors_Resize; - - function Get_Into_Vector_State - (This : in Statement; - Position : in Into_Position; - Index : in Vector_Index) - return Data_State is - - function Soci_Get_Into_State_V - (St : in Statement_Handle; - P : in Interfaces.C.int; - I : in Interfaces.C.int) - return Interfaces.C.int; - pragma Import (C, Soci_Get_Into_State_V, "soci_get_into_state_v"); - - Result : constant Interfaces.C.int := - Soci_Get_Into_State_V - (This.Handle, - Interfaces.C.int (Position), - Interfaces.C.int (Index)); - - use type Interfaces.C.int; - - begin - Check_Statement_State (This.Handle); - return Int_To_Data_State (Result); - end Get_Into_Vector_State; - - function Get_Into_Vector_String - (This : in Statement; - Position : in Into_Position; - Index : in Vector_Index) return String is - - function Soci_Get_Into_String_V - (St : in Statement_Handle; - P : in Interfaces.C.int; - I : in Interfaces.C.int) - return Interfaces.C.Strings.chars_ptr; - pragma Import (C, Soci_Get_Into_String_V, "soci_get_into_string_v"); - - Result : constant Interfaces.C.Strings.chars_ptr := - Soci_Get_Into_String_V (This.Handle, - Interfaces.C.int (Position), - Interfaces.C.int (Index)); - - begin - Check_Statement_State (This.Handle); - return Interfaces.C.Strings.Value (Result); - end Get_Into_Vector_String; - - function Get_Into_Vector_Integer - (This : in Statement; - Position : in Into_Position; - Index : in Vector_Index) - return DB_Integer is - - function Soci_Get_Into_Int_V - (St : in Statement_Handle; - P : in Interfaces.C.int; - I : in Interfaces.C.int) - return Interfaces.C.int; - pragma Import (C, Soci_Get_Into_Int_V, "soci_get_into_int_v"); - - Result : constant Interfaces.C.int := - Soci_Get_Into_Int_V (This.Handle, - Interfaces.C.int (Position), - Interfaces.C.int (Index)); - - begin - Check_Statement_State (This.Handle); - return DB_Integer (Result); - end Get_Into_Vector_Integer; - - function Get_Into_Vector_Long_Long_Integer - (This : in Statement; - Position : in Into_Position; - Index : in Vector_Index) - return DB_Long_Long_Integer is - - function Soci_Get_Into_Long_Long_V - (St : in Statement_Handle; - P : in Interfaces.C.int; - I : in Interfaces.C.int) - return Interfaces.Integer_64; - pragma Import (C, Soci_Get_Into_Long_Long_V, "soci_get_into_long_long_v"); - - Result : constant Interfaces.Integer_64 := - Soci_Get_Into_Long_Long_V (This.Handle, - Interfaces.C.int (Position), - Interfaces.C.int (Index)); - - begin - Check_Statement_State (This.Handle); - return DB_Long_Long_Integer (Result); - end Get_Into_Vector_Long_Long_Integer; - - function Get_Into_Vector_Long_Float - (This : in Statement; - Position : in Into_Position; - Index : in Vector_Index) - return DB_Long_Float is - - function Soci_Get_Into_Double_V - (St : in Statement_Handle; - P : in Interfaces.C.int; - I : in Interfaces.C.int) - return Interfaces.C.double; - pragma Import (C, Soci_Get_Into_Double_V, "soci_get_into_double_v"); - - Result : constant Interfaces.C.double := - Soci_Get_Into_Double_V (This.Handle, - Interfaces.C.int (Position), - Interfaces.C.int (Index)); - - begin - Check_Statement_State (This.Handle); - return DB_Long_Float (Result); - end Get_Into_Vector_Long_Float; - - function Get_Into_Vector_Time - (This : in Statement; - Position : in Into_Position; - Index : in Vector_Index) - return Ada.Calendar.Time is - - function Soci_Get_Into_Date_V - (St : in Statement_Handle; - P : in Interfaces.C.int; - I : in Interfaces.C.int) - return Interfaces.C.Strings.chars_ptr; - pragma Import (C, Soci_Get_Into_Date_V, "soci_get_into_date_v"); - - Result_C : constant Interfaces.C.Strings.chars_ptr := - Soci_Get_Into_Date_V (This.Handle, - Interfaces.C.int (Position), - Interfaces.C.int (Index)); - Result : constant String := Interfaces.C.Strings.Value (Result_C); - - begin - Check_Statement_State (This.Handle); - return String_To_Time (Result); - end Get_Into_Vector_Time; - - procedure Use_String (This : in Statement; Name : in String) is - - procedure Soci_Use_String - (St : in Statement_Handle; - Name : in Interfaces.C.char_array); - pragma Import (C, Soci_Use_String, "soci_use_string"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - - begin - Soci_Use_String (This.Handle, Name_C); - Check_Statement_State (This.Handle); - end Use_String; - - procedure Use_Integer (This : in Statement; Name : in String) is - - procedure Soci_Use_Int - (St : in Statement_Handle; - Name : in Interfaces.C.char_array); - pragma Import (C, Soci_Use_Int, "soci_use_int"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - - begin - Soci_Use_Int (This.Handle, Name_C); - Check_Statement_State (This.Handle); - end Use_Integer; - - procedure Use_Long_Long_Integer (This : in Statement; Name : in String) is - - procedure Soci_Use_Long_Long - (St : in Statement_Handle; - Name : in Interfaces.C.char_array); - pragma Import (C, Soci_Use_Long_Long, "soci_use_long_long"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - - begin - Soci_Use_Long_Long (This.Handle, Name_C); - Check_Statement_State (This.Handle); - end Use_Long_Long_Integer; - - procedure Use_Long_Float (This : in Statement; Name : in String) is - - procedure Soci_Use_Double - (St : in Statement_Handle; - Name : in Interfaces.C.char_array); - pragma Import (C, Soci_Use_Double, "soci_use_double"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - - begin - Soci_Use_Double (This.Handle, Name_C); - Check_Statement_State (This.Handle); - end Use_Long_Float; - - procedure Use_Time (This : in Statement; Name : in String) is - - procedure Soci_Use_Date - (St : in Statement_Handle; - Name : in Interfaces.C.char_array); - pragma Import (C, Soci_Use_Date, "soci_use_date"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - - begin - Soci_Use_Date (This.Handle, Name_C); - Check_Statement_State (This.Handle); - end Use_Time; - - procedure Use_Vector_String (This : in Statement; Name : in String) is - - procedure Soci_Use_String_V - (St : in Statement_Handle; - Name : in Interfaces.C.char_array); - pragma Import (C, Soci_Use_String_V, "soci_use_string_v"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - - begin - Soci_Use_String_V (This.Handle, Name_C); - Check_Statement_State (This.Handle); - end Use_Vector_String; - - procedure Use_Vector_Integer (This : in Statement; Name : in String) is - - procedure Soci_Use_Int_V - (St : in Statement_Handle; - Name : in Interfaces.C.char_array); - pragma Import (C, Soci_Use_Int_V, "soci_use_int_v"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - - begin - Soci_Use_Int_V (This.Handle, Name_C); - Check_Statement_State (This.Handle); - end Use_Vector_Integer; - - procedure Use_Vector_Long_Long_Integer (This : in Statement; Name : in String) is - - procedure Soci_Use_Long_Long_V - (St : in Statement_Handle; - Name : in Interfaces.C.char_array); - pragma Import (C, Soci_Use_Long_Long_V, "soci_use_long_long_v"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - - begin - Soci_Use_Long_Long_V (This.Handle, Name_C); - Check_Statement_State (This.Handle); - end Use_Vector_Long_Long_Integer; - - procedure Use_Vector_Long_Float (This : in Statement; Name : in String) is - - procedure Soci_Use_Double_V - (St : in Statement_Handle; - Name : in Interfaces.C.char_array); - pragma Import (C, Soci_Use_Double_V, "soci_use_double_v"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - - begin - Soci_Use_Double_V (This.Handle, Name_C); - Check_Statement_State (This.Handle); - end Use_Vector_Long_Float; - - procedure Use_Vector_Time (This : in Statement; Name : in String) is - - procedure Soci_Use_Date_V - (St : in Statement_Handle; - Name : in Interfaces.C.char_array); - pragma Import (C, Soci_Use_Date_V, "soci_use_date_v"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - - begin - Soci_Use_Date_V (This.Handle, Name_C); - Check_Statement_State (This.Handle); - end Use_Vector_Time; - - procedure Set_Use_State - (This : in Statement; - Name : in String; - State : in Data_State) is - - procedure Soci_Set_Use_State - (St : in Statement_Handle; - Name : in Interfaces.C.char_array; - State : in Interfaces.C.int); - pragma Import (C, Soci_Set_Use_State, "soci_set_use_state"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - State_C : constant Interfaces.C.int := Data_State_To_Int (State); - - begin - Soci_Set_Use_State (This.Handle, Name_C, State_C); - Check_Statement_State (This.Handle); - end Set_Use_State; - - procedure Set_Use_String - (This : in Statement; - Name : in String; - Value : in String) is - - procedure Soci_Set_Use_String - (St : in Statement_Handle; - Name : in Interfaces.C.char_array; - Value : in Interfaces.C.char_array); - pragma Import (C, Soci_Set_Use_String, "soci_set_use_string"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - Value_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Value); - - begin - Soci_Set_Use_String (This.Handle, Name_C, Value_C); - Check_Statement_State (This.Handle); - end Set_Use_String; - - procedure Set_Use_Integer - (This : in Statement; - Name : in String; - Value : in DB_Integer) is - - procedure Soci_Set_Use_Int - (St : in Statement_Handle; - Name : in Interfaces.C.char_array; - Value : in Interfaces.C.int); - pragma Import (C, Soci_Set_Use_Int, "soci_set_use_int"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - Value_C : constant Interfaces.C.int := Interfaces.C.int (Value); - - begin - Soci_Set_Use_Int (This.Handle, Name_C, Value_C); - Check_Statement_State (This.Handle); - end Set_Use_Integer; - - procedure Set_Use_Long_Long_Integer - (This : in Statement; - Name : in String; - Value : in DB_Long_Long_Integer) is - - procedure Soci_Set_Use_Long_Long - (St : in Statement_Handle; - Name : in Interfaces.C.char_array; - Value : in Interfaces.Integer_64); - pragma Import (C, Soci_Set_Use_Long_Long, "soci_set_use_long_long"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - Value_C : constant Interfaces.Integer_64 := Interfaces.Integer_64 (Value); - - begin - Soci_Set_Use_Long_Long (This.Handle, Name_C, Value_C); - Check_Statement_State (This.Handle); - end Set_Use_Long_Long_Integer; - - procedure Set_Use_Long_Float - (This : in Statement; - Name : in String; - Value : in DB_Long_Float) is - - procedure Soci_Set_Use_Double - (St : in Statement_Handle; - Name : in Interfaces.C.char_array; - Value : in Interfaces.C.double); - pragma Import (C, Soci_Set_Use_Double, "soci_set_use_double"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - Value_C : constant Interfaces.C.double := Interfaces.C.double (Value); - - begin - Soci_Set_Use_Double (This.Handle, Name_C, Value_C); - Check_Statement_State (This.Handle); - end Set_Use_Long_Float; - - procedure Set_Use_Time - (This : in Statement; - Name : in String; - Value : in Ada.Calendar.Time) is - - procedure Soci_Set_Use_Date - (St : in Statement_Handle; - Name : in Interfaces.C.char_array; - Value : in Interfaces.C.char_array); - pragma Import (C, Soci_Set_Use_Date, "soci_set_use_date"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - Value_C : constant Interfaces.C.char_array := - Interfaces.C.To_C (Time_To_String (Value)); - - begin - Soci_Set_Use_Date (This.Handle, Name_C, Value_C); - Check_Statement_State (This.Handle); - end Set_Use_Time; - - function Get_Use_Vectors_Size (This : in Statement) return Natural is - - function Soci_Use_Get_Size_V - (St : in Statement_Handle) - return Interfaces.C.int; - pragma Import (C, Soci_Use_Get_Size_V, "soci_use_get_size_v"); - - Result_C : constant Interfaces.C.int := Soci_Use_Get_Size_V (This.Handle); - - begin - Check_Statement_State (This.Handle); - return Natural (Result_C); - end Get_Use_Vectors_Size; - - function Use_Vectors_First_Index (This : in Statement) return Vector_Index is - begin - return 0; - end Use_Vectors_First_Index; - - function Use_Vectors_Last_Index (This : in Statement) return Vector_Index is - begin - return Vector_Index (This.Get_Use_Vectors_Size - 1); - end Use_Vectors_Last_Index; - - procedure Use_Vectors_Resize (This : in Statement; New_Size : in Natural) is - - procedure Soci_Use_Resize_V - (St : in Statement_Handle; - New_Size : in Interfaces.C.int); - pragma Import (C, Soci_Use_Resize_V, "soci_use_resize_v"); - - begin - Soci_Use_Resize_V (This.Handle, Interfaces.C.int (New_Size)); - Check_Statement_State (This.Handle); - end Use_Vectors_Resize; - - procedure Set_Use_Vector_State - (This : in Statement; - Name : in String; - Index : in Vector_Index; - State : in Data_State) is - - procedure Soci_Set_Use_State_V - (St : in Statement_Handle; - Name : in Interfaces.C.char_array; - Index : in Interfaces.C.int; - State : in Interfaces.C.int); - pragma Import (C, Soci_Set_Use_State_V, "soci_set_use_state_v"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - Index_C : constant Interfaces.C.int := Interfaces.C.int (Index); - State_C : constant Interfaces.C.int := Data_State_To_Int (State); - - begin - Soci_Set_Use_State_V (This.Handle, Name_C, Index_C, State_C); - Check_Statement_State (This.Handle); - end Set_Use_Vector_State; - - procedure Set_Use_Vector_String - (This : in Statement; - Name : in String; - Index : in Vector_Index; - Value : in String) is - - procedure Soci_Set_Use_String_V - (St : in Statement_Handle; - Name : in Interfaces.C.char_array; - Index : in Interfaces.C.int; - Value : in Interfaces.C.char_array); - pragma Import (C, Soci_Set_Use_String_V, "soci_set_use_string_v"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - Index_C : constant Interfaces.C.int := Interfaces.C.int (Index); - Value_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Value); - - begin - Soci_Set_Use_String_V (This.Handle, Name_C, Index_C, Value_C); - Check_Statement_State (This.Handle); - end Set_Use_Vector_String; - - procedure Set_Use_Vector_Integer - (This : in Statement; - Name : in String; - Index : in Vector_Index; - Value : in DB_Integer) is - - procedure Soci_Set_Use_Int_V - (St : in Statement_Handle; - Name : in Interfaces.C.char_array; - Index : in Interfaces.C.int; - Value : in Interfaces.C.int); - pragma Import (C, Soci_Set_Use_Int_V, "soci_set_use_int_v"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - Index_C : constant Interfaces.C.int := Interfaces.C.int (Index); - Value_C : constant Interfaces.C.int := Interfaces.C.int (Value); - - begin - Soci_Set_Use_Int_V (This.Handle, Name_C, Index_C, Value_C); - Check_Statement_State (This.Handle); - end Set_Use_Vector_Integer; - - procedure Set_Use_Vector_Long_Long_Integer - (This : in Statement; - Name : in String; - Index : in Vector_Index; - Value : in DB_Long_Long_Integer) is - - procedure Soci_Set_Use_Long_Long_V - (St : in Statement_Handle; - Name : in Interfaces.C.char_array; - Index : in Interfaces.C.int; - Value : in Interfaces.Integer_64); - pragma Import (C, Soci_Set_Use_Long_Long_V, "soci_set_use_long_long_v"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - Index_C : constant Interfaces.C.int := Interfaces.C.int (Index); - Value_C : constant Interfaces.Integer_64 := Interfaces.Integer_64 (Value); - - begin - Soci_Set_Use_Long_Long_V (This.Handle, Name_C, Index_C, Value_C); - Check_Statement_State (This.Handle); - end Set_Use_Vector_Long_Long_Integer; - - procedure Set_Use_Vector_Long_Float - (This : in Statement; - Name : in String; - Index : in Vector_Index; - Value : in DB_Long_Float) is - - procedure Soci_Set_Use_Double_V - (St : in Statement_Handle; - Name : in Interfaces.C.char_array; - Index : in Interfaces.C.int; - Value : in Interfaces.C.double); - pragma Import (C, Soci_Set_Use_Double_V, "soci_set_use_double_v"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - Index_C : constant Interfaces.C.int := Interfaces.C.int (Index); - Value_C : constant Interfaces.C.double := Interfaces.C.double (Value); - - begin - Soci_Set_Use_Double_V (This.Handle, Name_C, Index_C, Value_C); - Check_Statement_State (This.Handle); - end Set_Use_Vector_Long_Float; - - procedure Set_Use_Vector_Time - (This : in Statement; - Name : in String; - Index : in Vector_Index; - Value : in Ada.Calendar.Time) is - - procedure Soci_Set_Use_Date_V - (St : in Statement_Handle; - Name : in Interfaces.C.char_array; - Index : in Interfaces.C.int; - Value : in Interfaces.C.char_array); - pragma Import (C, Soci_Set_Use_Date_V, "soci_set_use_date_v"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - Index_C : constant Interfaces.C.int := Interfaces.C.int (Index); - Value_C : constant Interfaces.C.char_array := - Interfaces.C.To_C (Time_To_String (Value)); - - begin - Soci_Set_Use_Date_V (This.Handle, Name_C, Index_C, Value_C); - Check_Statement_State (This.Handle); - end Set_Use_Vector_Time; - - function Get_Use_State - (This : in Statement; - Name : in String) return Data_State is - - function Soci_Get_Use_State - (St : in Statement_Handle; - Name : in Interfaces.C.char_array) - return Interfaces.C.int; - pragma Import (C, Soci_Get_Use_State, "soci_get_use_state"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - Result : constant Interfaces.C.int := - Soci_Get_Use_State (This.Handle, Name_C); - - use type Interfaces.C.int; - - begin - Check_Statement_State (This.Handle); - return Int_To_Data_State (Result); - end Get_Use_State; - - function Get_Use_String - (This : in Statement; - Name : in String) - return String is - - function Soci_Get_Use_String - (St : in Statement_Handle; - Name : in Interfaces.C.char_array) - return Interfaces.C.Strings.chars_ptr; - pragma Import (C, Soci_Get_Use_String, "soci_get_use_string"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - Result : constant Interfaces.C.Strings.chars_ptr := - Soci_Get_Use_String (This.Handle, Name_C); - - begin - Check_Statement_State (This.Handle); - return Interfaces.C.Strings.Value (Result); - end Get_Use_String; - - function Get_Use_Integer - (This : in Statement; - Name : in String) - return DB_Integer is - - function Soci_Get_Use_Int - (St : in Statement_Handle; - Name : in Interfaces.C.char_array) - return Interfaces.C.int; - pragma Import (C, Soci_Get_Use_Int, "soci_get_use_int"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - Result : constant Interfaces.C.int := - Soci_Get_Use_Int (This.Handle, Name_C); - - begin - Check_Statement_State (This.Handle); - return DB_Integer (Result); - end Get_Use_Integer; - - function Get_Use_Long_Long_Integer - (This : in Statement; - Name : in String) - return DB_Long_Long_Integer is - - function Soci_Get_Use_Long_Long - (St : in Statement_Handle; - Name : in Interfaces.C.char_array) - return Interfaces.Integer_64; - pragma Import (C, Soci_Get_Use_Long_Long, "soci_get_use_long_long"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - Result : constant Interfaces.Integer_64 := - Soci_Get_Use_Long_Long (This.Handle, Name_C); - - begin - Check_Statement_State (This.Handle); - return DB_Long_Long_Integer (Result); - end Get_Use_Long_Long_Integer; - - function Get_Use_Long_Float - (This : in Statement; - Name : in String) - return DB_Long_Float is - - function Soci_Get_Use_Double - (St : in Statement_Handle; - Name : in Interfaces.C.char_array) - return Interfaces.C.double; - pragma Import (C, Soci_Get_Use_Double, "soci_get_use_double"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - Result : constant Interfaces.C.double := - Soci_Get_Use_Double (This.Handle, Name_C); - - begin - Check_Statement_State (This.Handle); - return DB_Long_Float (Result); - end Get_Use_Long_Float; - - function Get_Use_Time - (This : in Statement; - Name : in String) - return Ada.Calendar.Time is - - function Soci_Get_Use_Date - (St : in Statement_Handle; - Name : in Interfaces.C.char_array) - return Interfaces.C.Strings.chars_ptr; - pragma Import (C, Soci_Get_Use_Date, "soci_get_use_date"); - - Name_C : constant Interfaces.C.char_array := Interfaces.C.To_C (Name); - Result_C : constant Interfaces.C.Strings.chars_ptr := - Soci_Get_Use_Date (This.Handle, Name_C); - Result : constant String := Interfaces.C.Strings.Value (Result_C); - - begin - Check_Statement_State (This.Handle); - return String_To_Time (Result); - end Get_Use_Time; - -end SOCI; diff --git a/src/soci/languages/ada/soci.ads b/src/soci/languages/ada/soci.ads deleted file mode 100644 index 93b59678d6..0000000000 --- a/src/soci/languages/ada/soci.ads +++ /dev/null @@ -1,486 +0,0 @@ --- --- Thin wrapper for the simple interface of the SOCI database access library. --- --- Copyright (C) 2008-2011 Maciej Sobczak --- Distributed under the Boost Software License, Version 1.0. --- (See accompanying file LICENSE_1_0.txt or copy at --- http://www.boost.org/LICENSE_1_0.txt) - -with Ada.Calendar; -with Interfaces.C; - -private with System; -private with Ada.Finalization; - -package SOCI is - - -- - -- General exception related to database and library usage. - -- - - Database_Error : exception; - - -- - -- Session. - -- - - type Session is tagged limited private; - - not overriding - function Make_Session (Connection_String : in String) return Session; - - not overriding - procedure Open (This : in out Session; Connection_String : in String); - - not overriding - procedure Close (This : in out Session); - - not overriding - function Is_Open (This : in Session) return Boolean; - - -- Transaction management. - - not overriding - procedure Start (This : in Session); - - not overriding - procedure Commit (This : in Session); - - not overriding - procedure Rollback (This : in Session); - - -- Immediate query execution. - not overriding - procedure Execute (This : in Session; Query : in String); - - -- - -- Connection pool management. - -- - - type Connection_Pool (Size : Positive) is tagged limited private; - - not overriding - procedure Open - (This : in out Connection_Pool; - Position : in Positive; - Connection_String : in String); - - not overriding - procedure Close (This : in out Connection_Pool; Position : in Positive); - - not overriding - procedure Lease (This : in out Connection_Pool; S : in out Session'Class); - - -- - -- Statement. - -- - - type Statement (<>) is tagged limited private; - - type Data_State is (Data_Null, Data_Not_Null); - - type Into_Position is private; - - type Vector_Index is new Natural; - - not overriding - function Make_Statement (Sess : in Session'Class) return Statement; - - -- Statement preparation and execution. - - not overriding - procedure Prepare (This : in Statement; Query : in String); - - not overriding - procedure Execute - (This : in Statement; - With_Data_Exchange : in Boolean := False); - - not overriding - function Execute - (This : in Statement; - With_Data_Exchange : in Boolean := False) return Boolean; - - not overriding - function Fetch (This : in Statement) return Boolean; - - not overriding - function Got_Data (This : in Statement) return Boolean; - - -- - -- Data items handling. - -- - - -- Database-specific types. - -- These types are most likely identical to standard Integer, - -- Long_Long_Integer and Long_Float, but are defined distinctly - -- to avoid interfacing problems with other compilers. - - type DB_Integer is new Interfaces.C.int; - type DB_Long_Long_Integer is new Interfaces.Integer_64; - type DB_Long_Float is new Interfaces.C.double; - - -- Creation of single into elements. - - not overriding - function Into_String (This : in Statement) return Into_Position; - - not overriding - function Into_Integer (This : in Statement) return Into_Position; - - not overriding - function Into_Long_Long_Integer (This : in Statement) return Into_Position; - - not overriding - function Into_Long_Float (This : in Statement) return Into_Position; - - not overriding - function Into_Time (This : in Statement) return Into_Position; - - -- Creation of vector into elements. - - not overriding - function Into_Vector_String (This : in Statement) return Into_Position; - - not overriding - function Into_Vector_Integer (This : in Statement) return Into_Position; - - not overriding - function Into_Vector_Long_Long_Integer (This : in Statement) return Into_Position; - - not overriding - function Into_Vector_Long_Float (This : in Statement) return Into_Position; - - not overriding - function Into_Vector_Time (This : in Statement) return Into_Position; - - -- Inspection of single into elements. - - not overriding - function Get_Into_State - (This : in Statement; - Position : in Into_Position) - return Data_State; - - not overriding - function Get_Into_String - (This : in Statement; - Position : in Into_Position) - return String; - - not overriding - function Get_Into_Integer - (This : in Statement; - Position : in Into_Position) - return DB_Integer; - - not overriding - function Get_Into_Long_Long_Integer - (This : in Statement; - Position : in Into_Position) - return DB_Long_Long_Integer; - - not overriding - function Get_Into_Long_Float - (This : in Statement; - Position : in Into_Position) - return DB_Long_Float; - - not overriding - function Get_Into_Time - (This : in Statement; - Position : in Into_Position) - return Ada.Calendar.Time; - - -- Inspection of vector into elements. - - not overriding - function Get_Into_Vectors_Size (This : in Statement) return Natural; - - not overriding - function Into_Vectors_First_Index (This : in Statement) return Vector_Index; - - not overriding - function Into_Vectors_Last_Index (This : in Statement) return Vector_Index; - - not overriding - procedure Into_Vectors_Resize (This : in Statement; New_Size : in Natural); - - not overriding - function Get_Into_Vector_State - (This : in Statement; - Position : in Into_Position; - Index : in Vector_Index) - return Data_State; - - not overriding - function Get_Into_Vector_String - (This : in Statement; - Position : in Into_Position; - Index : in Vector_Index) - return String; - - not overriding - function Get_Into_Vector_Integer - (This : in Statement; - Position : in Into_Position; - Index : in Vector_Index) - return DB_Integer; - - not overriding - function Get_Into_Vector_Long_Long_Integer - (This : in Statement; - Position : in Into_Position; - Index : in Vector_Index) - return DB_Long_Long_Integer; - - not overriding - function Get_Into_Vector_Long_Float - (This : in Statement; - Position : in Into_Position; - Index : in Vector_Index) - return DB_Long_Float; - - not overriding - function Get_Into_Vector_Time - (This : in Statement; - Position : in Into_Position; - Index : in Vector_Index) - return Ada.Calendar.Time; - - -- Creation of single use elements. - - not overriding - procedure Use_String (This : in Statement; Name : in String); - - not overriding - procedure Use_Integer (This : in Statement; Name : in String); - - not overriding - procedure Use_Long_Long_Integer (This : in Statement; Name : in String); - - not overriding - procedure Use_Long_Float (This : in Statement; Name : in String); - - not overriding - procedure Use_Time (This : in Statement; Name : in String); - - -- Creation of vector use elements. - - not overriding - procedure Use_Vector_String (This : in Statement; Name : in String); - - not overriding - procedure Use_Vector_Integer (This : in Statement; Name : in String); - - not overriding - procedure Use_Vector_Long_Long_Integer (This : in Statement; Name : in String); - - not overriding - procedure Use_Vector_Long_Float (This : in Statement; Name : in String); - - not overriding - procedure Use_Vector_Time (This : in Statement; Name : in String); - - -- Modifiers for single use elements. - - not overriding - procedure Set_Use_State - (This : in Statement; - Name : in String; - State : in Data_State); - - not overriding - procedure Set_Use_String - (This : in Statement; - Name : in String; - Value : in String); - - not overriding - procedure Set_Use_Integer - (This : in Statement; - Name : in String; - Value : in DB_Integer); - - not overriding - procedure Set_Use_Long_Long_Integer - (This : in Statement; - Name : in String; - Value : in DB_Long_Long_Integer); - - not overriding - procedure Set_Use_Long_Float - (This : in Statement; - Name : in String; - Value : in DB_Long_Float); - - not overriding - procedure Set_Use_Time - (This : in Statement; - Name : in String; - Value : in Ada.Calendar.Time); - - -- Modifiers for vector use elements. - - not overriding - function Get_Use_Vectors_Size (This : in Statement) return Natural; - - not overriding - function Use_Vectors_First_Index (This : in Statement) return Vector_Index; - - not overriding - function Use_Vectors_Last_Index (This : in Statement) return Vector_Index; - - not overriding - procedure Use_Vectors_Resize (This : in Statement; New_Size : in Natural); - - not overriding - procedure Set_Use_Vector_State - (This : in Statement; - Name : in String; - Index : in Vector_Index; - State : in Data_State); - - not overriding - procedure Set_Use_Vector_String - (This : in Statement; - Name : in String; - Index : in Vector_Index; - Value : in String); - - not overriding - procedure Set_Use_Vector_Integer - (This : in Statement; - Name : in String; - Index : in Vector_Index; - Value : in DB_Integer); - - not overriding - procedure Set_Use_Vector_Long_Long_Integer - (This : in Statement; - Name : in String; - Index : in Vector_Index; - Value : in DB_Long_Long_Integer); - - not overriding - procedure Set_Use_Vector_Long_Float - (This : in Statement; - Name : in String; - Index : in Vector_Index; - Value : in DB_Long_Float); - - not overriding - procedure Set_Use_Vector_Time - (This : in Statement; - Name : in String; - Index : in Vector_Index; - Value : in Ada.Calendar.Time); - - -- Inspection of single use elements. - -- - -- Note: Use elements can be modified by the database if they - -- are bound to out and inout parameters of stored procedures - -- (although this is not supported by all database backends). - -- This feature is available only for single use elements. - - not overriding - function Get_Use_State - (This : in Statement; - Name : in String) - return Data_State; - - not overriding - function Get_Use_String - (This : in Statement; - Name : in String) - return String; - - not overriding - function Get_Use_Integer - (This : in Statement; - Name : in String) - return DB_Integer; - - not overriding - function Get_Use_Long_Long_Integer - (This : in Statement; - Name : in String) - return DB_Long_Long_Integer; - - not overriding - function Get_Use_Long_Float - (This : in Statement; - Name : in String) - return DB_Long_Float; - - not overriding - function Get_Use_Time - (This : in Statement; - Name : in String) - return Ada.Calendar.Time; - -private - - -- Connection pool and supporting types. - - type Connection_Array is array (Positive range <>) of Session; - type Used_Array is array (Positive range <>) of Boolean; - - -- Protected state for the connection pool. - protected type Connection_Pool_PS (Size : Positive) is - - procedure Open (Position : in Positive; Connection_String : in String); - procedure Close (Position : in Positive); - - entry Lease (S : in out Session'Class); - procedure Give_Back (Position : in Positive); - - private - - Connections : Connection_Array (1 .. Size); - Is_Used : Used_Array (1 .. Size) := (others => False); - Available : Boolean := True; - - end Connection_Pool_PS; - type Connection_Pool_PS_Ptr is access all Connection_Pool_PS; - - type Connection_Pool (Size : Positive) is tagged limited record - Pool : aliased Connection_Pool_PS (Size); - end record; - - -- Session and supporting types. - - type Session_Handle is new System.Address; - - Null_Session_Handle : constant Session_Handle := - Session_Handle (System.Null_Address); - - type Session is new Ada.Finalization.Limited_Controlled with record - Handle : Session_Handle; - Initialized : Boolean := False; - Belongs_To_Pool : Boolean := False; - Pool : Connection_Pool_PS_Ptr; - Position_In_Pool : Positive; - end record; - - overriding - procedure Finalize (This : in out Session); - - -- Statement and supporting types. - - type Statement_Handle is new System.Address; - - Null_Statement_Handle : constant Statement_Handle := - Statement_Handle (System.Null_Address); - - type Statement is new Ada.Finalization.Limited_Controlled with record - Handle : Statement_Handle; - Initialized : Boolean := False; - end record; - - overriding - procedure Finalize (This : in out Statement); - - type Into_Position is new Natural; - -end SOCI; diff --git a/src/soci/languages/ada/soci_ada.gpr b/src/soci/languages/ada/soci_ada.gpr deleted file mode 100644 index fe783c8d5f..0000000000 --- a/src/soci/languages/ada/soci_ada.gpr +++ /dev/null @@ -1,14 +0,0 @@ -with "std_cpp.gpr"; -with "soci_core.gpr"; - -project SOCI_Ada is - for Source_Dirs use ("."); - for Object_Dir use "."; - for Library_Name use "soci_ada"; - for Library_Dir use "lib"; - for Library_Kind use "static"; - - package Compiler is - for Default_Switches ("Ada") use ("-gnat05", "-O2"); - end Compiler; -end SOCI_Ada; diff --git a/src/soci/languages/ada/soci_core.gpr b/src/soci/languages/ada/soci_core.gpr deleted file mode 100644 index 0283780714..0000000000 --- a/src/soci/languages/ada/soci_core.gpr +++ /dev/null @@ -1,7 +0,0 @@ -project SOCI_Core is - for Externally_Built use "true"; - for Source_Dirs use (); - for Library_Dir use "../../core"; - for Library_Name use "soci_core"; - for Library_Kind use "static"; -end SOCI_Core; diff --git a/src/soci/languages/ada/soci_postgresql.gpr b/src/soci/languages/ada/soci_postgresql.gpr deleted file mode 100644 index 3ce31dbeff..0000000000 --- a/src/soci/languages/ada/soci_postgresql.gpr +++ /dev/null @@ -1,8 +0,0 @@ -project SOCI_PostgreSQL is - for Externally_Built use "true"; - for Source_Dirs use (); - for Library_Dir use "../../backends/postgresql"; - for Library_Name use "soci_postgresql"; - for Library_Kind use "static"; -end SOCI_PostgreSQL; - diff --git a/src/soci/languages/ada/std_cpp.gpr b/src/soci/languages/ada/std_cpp.gpr deleted file mode 100644 index 699a5adc2c..0000000000 --- a/src/soci/languages/ada/std_cpp.gpr +++ /dev/null @@ -1,7 +0,0 @@ -project Std_Cpp is - for Externally_Built use "true"; - for Source_Dirs use (); - for Library_Dir use "."; - for Library_Name use "stdc++"; - for Library_Kind use "static"; -end Std_Cpp; diff --git a/src/soci/languages/ada/test/postgresql_test.adb b/src/soci/languages/ada/test/postgresql_test.adb deleted file mode 100644 index 0d671a4822..0000000000 --- a/src/soci/languages/ada/test/postgresql_test.adb +++ /dev/null @@ -1,609 +0,0 @@ -with SOCI; -with SOCI.PostgreSQL; -with Ada.Text_IO; -with Ada.Calendar; -with Ada.Exceptions; -with Ada.Numerics.Discrete_Random; -with Ada.Command_Line; - -procedure PostgreSQL_Test is - - procedure Test_1 (Connection_String : in String) is - begin - Ada.Text_IO.Put_Line ("testing basic constructor function"); - - declare - S : SOCI.Session := SOCI.Make_Session (Connection_String); - begin - null; - end; - exception - when E : SOCI.Database_Error => - Ada.Text_IO.Put_Line ("Database_Error: "); - Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E)); - end Test_1; - - procedure Test_2 (Connection_String : in String) is - S : SOCI.Session; - begin - Ada.Text_IO.Put_Line ("testing open/close"); - - S.Close; - S.Open (Connection_String); - S.Close; - end Test_2; - - procedure Test_3 (Connection_String : in String) is - begin - Ada.Text_IO.Put_Line ("testing empty start/commit"); - - declare - S : SOCI.Session := SOCI.Make_Session (Connection_String); - begin - S.Start; - S.Commit; - end; - end Test_3; - - procedure Test_4 (Connection_String : in String) is - begin - Ada.Text_IO.Put_Line ("testing simple statements"); - - declare - SQL : SOCI.Session := SOCI.Make_Session (Connection_String); - begin - SQL.Execute ("create table ada_test ( i integer )"); - SQL.Execute ("drop table ada_test"); - end; - end Test_4; - - procedure Test_5 (Connection_String : in String) is - begin - Ada.Text_IO.Put_Line ("testing independent statements"); - - declare - SQL : SOCI.Session := SOCI.Make_Session (Connection_String); - St_1 : SOCI.Statement := SOCI.Make_Statement (SQL); - St_2 : SOCI.Statement := SOCI.Make_Statement (SQL); - begin - St_1.Prepare ("create table ada_test ( i integer )"); - St_2.Prepare ("drop table ada_test"); - St_1.Execute; - St_2.Execute; - end; - end Test_5; - - procedure Test_6 (Connection_String : in String) is - begin - Ada.Text_IO.Put_Line ("testing data types and into elements"); - - declare - SQL : SOCI.Session := SOCI.Make_Session (Connection_String); - begin - declare - St : SOCI.Statement := SOCI.Make_Statement (SQL); - Pos : SOCI.Into_Position; - begin - Pos := St.Into_String; - St.Prepare ("select 'Hello'"); - St.Execute (True); - pragma Assert (St.Get_Into_String (Pos) = "Hello"); - end; - declare - St : SOCI.Statement := SOCI.Make_Statement (SQL); - Pos : SOCI.Into_Position; - Value : SOCI.DB_Integer; - use type SOCI.DB_Integer; - begin - Pos := St.Into_Integer; - St.Prepare ("select 123"); - St.Execute (True); - Value := St.Get_Into_Integer (Pos); - pragma Assert (Value = 123); - end; - declare - St : SOCI.Statement := SOCI.Make_Statement (SQL); - Pos : SOCI.Into_Position; - Value : SOCI.DB_Long_Long_Integer; - use type SOCI.DB_Long_Long_Integer; - begin - Pos := St.Into_Long_Long_Integer; - St.Prepare ("select 10000000000"); - St.Execute (True); - Value := St.Get_Into_Long_Long_Integer (Pos); - pragma Assert (Value = 10_000_000_000); - end; - declare - St : SOCI.Statement := SOCI.Make_Statement (SQL); - Pos : SOCI.Into_Position; - Value : SOCI.DB_Long_Float; - use type SOCI.DB_Long_Float; - begin - Pos := St.Into_Long_Float; - St.Prepare ("select 3.625"); - St.Execute (True); - Value := St.Get_Into_Long_Float (Pos); - pragma Assert (Value = SOCI.DB_Long_Float (3.625)); - end; - declare - St : SOCI.Statement := SOCI.Make_Statement (SQL); - Pos : SOCI.Into_Position; - Value : Ada.Calendar.Time; - begin - Pos := St.Into_Time; - St.Prepare ("select timestamp '2008-06-30 21:01:02'"); - St.Execute (True); - Value := St.Get_Into_Time (Pos); - pragma Assert (Ada.Calendar.Year (Value) = 2008); - pragma Assert (Ada.Calendar.Month (Value) = 6); - pragma Assert (Ada.Calendar.Day (Value) = 30); - pragma Assert - (Ada.Calendar.Seconds (Value) = - Ada.Calendar.Day_Duration (21 * 3_600 + 1 * 60 + 2)); - end; - end; - end Test_6; - - procedure Test_7 (Connection_String : in String) is - begin - Ada.Text_IO.Put_Line ("testing types with into vectors"); - - declare - SQL : SOCI.Session := SOCI.Make_Session (Connection_String); - St : SOCI.Statement := SOCI.Make_Statement (SQL); - Pos_Id : SOCI.Into_Position; - Pos_Str : SOCI.Into_Position; - Pos_LL : SOCI.Into_Position; - Pos_LF : SOCI.Into_Position; - Pos_TM : SOCI.Into_Position; - - use type SOCI.Data_State; - use type Ada.Calendar.Time; - use type SOCI.DB_Integer; - use type SOCI.DB_Long_Long_Integer; - use type SOCI.DB_Long_Float; - - begin - SQL.Execute ("create table soci_test (" & - " id integer," & - " str varchar (20)," & - " ll bigint," & - " lf double precision," & - " tm timestamp" & - ")"); - SQL.Execute ("insert into soci_test (id, str, ll, lf, tm)" & - " values (1, 'abc', 10000000000, 3.0, timestamp '2008-06-30 21:01:02')"); - SQL.Execute ("insert into soci_test (id, str, ll, lf, tm)" & - " values (2, 'xyz', -10000000001, -3.125, timestamp '2008-07-01 21:01:03')"); - SQL.Execute ("insert into soci_test (id, str, ll, lf, tm)" & - " values (3, null, null, null, null)"); - - Pos_Id := St.Into_Vector_Integer; - Pos_Str := St.Into_Vector_String; - Pos_LL := St.Into_Vector_Long_Long_Integer; - Pos_LF := St.Into_Vector_Long_Float; - Pos_TM := St.Into_Vector_Time; - - St.Into_Vectors_Resize (10); -- arbitrary batch size - - St.Prepare ("select id, str, ll, lf, tm from soci_test order by id"); - St.Execute (True); - - pragma Assert (St.Get_Into_Vectors_Size = 3); - - pragma Assert (St.Get_Into_Vector_Integer (Pos_Id, 0) = 1); - pragma Assert (St.Get_Into_Vector_State (Pos_Str, 0) = SOCI.Data_Not_Null); - pragma Assert (St.Get_Into_Vector_String (Pos_Str, 0) = "abc"); - pragma Assert (St.Get_Into_Vector_Long_Long_Integer (Pos_LL, 0) = 10_000_000_000); - pragma Assert (St.Get_Into_Vector_Long_Float (Pos_LF, 0) = SOCI.DB_Long_Float (3.0)); - pragma Assert (St.Get_Into_Vector_Time (Pos_TM, 0) = - Ada.Calendar.Time_Of (2008, 6, 30, - Duration (21 * 3_600 + 1 * 60 + 2))); - - pragma Assert (St.Get_Into_Vector_Integer (Pos_Id, 1) = 2); - pragma Assert (St.Get_Into_Vector_State (Pos_Str, 1) = SOCI.Data_Not_Null); - pragma Assert (St.Get_Into_Vector_String (Pos_Str, 1) = "xyz"); - pragma Assert (St.Get_Into_Vector_Long_Long_Integer (Pos_LL, 1) = -10_000_000_001); - pragma Assert (St.Get_Into_Vector_Long_Float (Pos_LF, 1) = SOCI.DB_Long_Float (-3.125)); - pragma Assert (St.Get_Into_Vector_Time (Pos_TM, 1) = - Ada.Calendar.Time_Of (2008, 7, 1, - Duration (21 * 3_600 + 1 * 60 + 3))); - - pragma Assert (St.Get_Into_Vector_Integer (Pos_Id, 2) = 3); - pragma Assert (St.Get_Into_Vector_State (Pos_Str, 2) = SOCI.Data_Null); - pragma Assert (St.Get_Into_Vector_State (Pos_LL, 2) = SOCI.Data_Null); - pragma Assert (St.Get_Into_Vector_State (Pos_LF, 2) = SOCI.Data_Null); - pragma Assert (St.Get_Into_Vector_State (Pos_TM, 2) = SOCI.Data_Null); - - SQL.Execute ("drop table soci_test"); - end; - end Test_7; - - procedure Test_8 (Connection_String : in String) is - begin - Ada.Text_IO.Put_Line ("testing multi-batch operation with into vectors"); - - declare - SQL : SOCI.Session := SOCI.Make_Session (Connection_String); - St : SOCI.Statement := SOCI.Make_Statement (SQL); - Pos_Id : SOCI.Into_Position; - Got_Data : Boolean; - - use type SOCI.DB_Integer; - begin - SQL.Execute ("create table soci_test (" & - " id integer" & - ")"); - SQL.Execute ("insert into soci_test (id) values (1)"); - SQL.Execute ("insert into soci_test (id) values (2)"); - SQL.Execute ("insert into soci_test (id) values (3)"); - SQL.Execute ("insert into soci_test (id) values (4)"); - SQL.Execute ("insert into soci_test (id) values (5)"); - SQL.Execute ("insert into soci_test (id) values (6)"); - SQL.Execute ("insert into soci_test (id) values (7)"); - SQL.Execute ("insert into soci_test (id) values (8)"); - SQL.Execute ("insert into soci_test (id) values (9)"); - SQL.Execute ("insert into soci_test (id) values (10)"); - - Pos_Id := St.Into_Vector_Integer; - St.Into_Vectors_Resize (4); -- batch of 4 elements - - St.Prepare ("select id from soci_test order by id"); - St.Execute; - - Got_Data := St.Fetch; - pragma Assert (Got_Data); - pragma Assert (St.Get_Into_Vectors_Size = 4); - pragma Assert (St.Get_Into_Vector_Integer (Pos_Id, 0) = 1); - pragma Assert (St.Get_Into_Vector_Integer (Pos_Id, 1) = 2); - pragma Assert (St.Get_Into_Vector_Integer (Pos_Id, 2) = 3); - pragma Assert (St.Get_Into_Vector_Integer (Pos_Id, 3) = 4); - - Got_Data := St.Fetch; - pragma Assert (Got_Data); - pragma Assert (St.Get_Into_Vectors_Size = 4); - pragma Assert (St.Get_Into_Vector_Integer (Pos_Id, 0) = 5); - pragma Assert (St.Get_Into_Vector_Integer (Pos_Id, 1) = 6); - pragma Assert (St.Get_Into_Vector_Integer (Pos_Id, 2) = 7); - pragma Assert (St.Get_Into_Vector_Integer (Pos_Id, 3) = 8); - - Got_Data := St.Fetch; - pragma Assert (Got_Data); - pragma Assert (St.Get_Into_Vectors_Size = 2); - pragma Assert (St.Get_Into_Vector_Integer (Pos_Id, 0) = 9); - pragma Assert (St.Get_Into_Vector_Integer (Pos_Id, 1) = 10); - - Got_Data := St.Fetch; - pragma Assert (not Got_Data); - pragma Assert (St.Get_Into_Vectors_Size = 0); - - SQL.Execute ("drop table soci_test"); - end; - end Test_8; - - procedure Test_9 (Connection_String : in String) is - begin - Ada.Text_IO.Put_Line ("testing data types and use elements"); - - declare - SQL : SOCI.Session := SOCI.Make_Session (Connection_String); - - use type SOCI.DB_Integer; - use type SOCI.DB_Long_Long_Integer; - use type SOCI.DB_Long_Float; - begin - declare - St : SOCI.Statement := SOCI.Make_Statement (SQL); - Pos : SOCI.Into_Position; - begin - St.Use_String ("value"); - St.Set_Use_String ("value", "123"); - Pos := St.Into_Integer; - St.Prepare ("select cast(:value as integer)"); - St.Execute (True); - pragma Assert (St.Get_Into_Integer (Pos) = 123); - end; - declare - St : SOCI.Statement := SOCI.Make_Statement (SQL); - Pos : SOCI.Into_Position; - begin - St.Use_Integer ("value"); - St.Set_Use_Integer ("value", 123); - Pos := St.Into_String; - St.Prepare ("select cast(:value as text)"); - St.Execute (True); - pragma Assert (St.Get_Into_String (Pos) = "123"); - end; - declare - St : SOCI.Statement := SOCI.Make_Statement (SQL); - Pos : SOCI.Into_Position; - begin - St.Use_Long_Long_Integer ("value"); - St.Set_Use_Long_Long_Integer ("value", 10_000_000_000); - Pos := St.Into_String; - St.Prepare ("select cast(:value as text)"); - St.Execute (True); - pragma Assert (St.Get_Into_String (Pos) = "10000000000"); - end; - declare - St : SOCI.Statement := SOCI.Make_Statement (SQL); - Pos : SOCI.Into_Position; - begin - St.Use_Long_Float ("value"); - St.Set_Use_Long_Float ("value", SOCI.DB_Long_Float (5.625)); - Pos := St.Into_String; - St.Prepare ("select cast(:value as text)"); - St.Execute (True); - pragma Assert (St.Get_Into_String (Pos) = "5.625"); - end; - declare - St : SOCI.Statement := SOCI.Make_Statement (SQL); - Pos : SOCI.Into_Position; - begin - St.Use_Time ("value"); - St.Set_Use_Time ("value", Ada.Calendar.Time_Of - (2008, 7, 1, Ada.Calendar.Day_Duration (3723))); - Pos := St.Into_String; - St.Prepare ("select cast(:value as text)"); - St.Execute (True); - pragma Assert (St.Get_Into_String (Pos) = "2008-07-01 01:02:03"); - end; - declare - St : SOCI.Statement := SOCI.Make_Statement (SQL); - Pos : SOCI.Into_Position; - use type SOCI.Data_State; - begin - St.Use_Integer ("value"); - St.Set_Use_State ("value", SOCI.Data_Null); - Pos := St.Into_Integer; - St.Prepare ("select cast(:value as integer)"); - St.Execute (True); - pragma Assert (St.Get_Into_State (Pos) = SOCI.Data_Null); - end; - end; - end Test_9; - - procedure Test_10 (Connection_String : in String) is - begin - Ada.Text_IO.Put_Line ("testing vector use elements and row traversal with single into elements"); - - declare - SQL : SOCI.Session := SOCI.Make_Session (Connection_String); - - Time_1 : constant Ada.Calendar.Time := Ada.Calendar.Time_Of - (2008, 7, 1, Ada.Calendar.Day_Duration (1)); - Time_2 : constant Ada.Calendar.Time := Ada.Calendar.Time_Of - (2008, 7, 2, Ada.Calendar.Day_Duration (2)); - Time_3 : constant Ada.Calendar.Time := Ada.Calendar.Time_Of - (2008, 7, 3, Ada.Calendar.Day_Duration (3)); - Time_4 : constant Ada.Calendar.Time := Ada.Calendar.Time_Of - (2008, 7, 4, Ada.Calendar.Day_Duration (4)); - Time_5 : constant Ada.Calendar.Time := Ada.Calendar.Time_Of - (2008, 7, 5, Ada.Calendar.Day_Duration (5)); - - begin - SQL.Execute ("create table soci_test (" & - " id integer," & - " str varchar (20)," & - " ll bigint," & - " lf double precision," & - " tm timestamp" & - ")"); - - declare - St : SOCI.Statement := SOCI.Make_Statement (SQL); - begin - St.Use_Vector_Integer ("id"); - St.Use_Vector_String ("str"); - St.Use_Vector_Long_Long_Integer ("ll"); - St.Use_Vector_Long_Float ("lf"); - St.Use_Vector_Time ("tm"); - - St.Use_Vectors_Resize (6); - St.Set_Use_Vector_Integer ("id", 0, 1); - St.Set_Use_Vector_Integer ("id", 1, 2); - St.Set_Use_Vector_Integer ("id", 2, 3); - St.Set_Use_Vector_Integer ("id", 3, 4); - St.Set_Use_Vector_Integer ("id", 4, 5); - St.Set_Use_Vector_Integer ("id", 5, 6); - St.Set_Use_Vector_String ("str", 0, "abc"); - St.Set_Use_Vector_String ("str", 1, "def"); - St.Set_Use_Vector_String ("str", 2, "ghi"); - St.Set_Use_Vector_String ("str", 3, "jklm"); - St.Set_Use_Vector_String ("str", 4, "no"); - St.Set_Use_Vector_State ("str", 5, SOCI.Data_Null); - St.Set_Use_Vector_Long_Long_Integer ("ll", 0, 10_000_000_000); - St.Set_Use_Vector_Long_Long_Integer ("ll", 1, 10_000_000_001); - St.Set_Use_Vector_Long_Long_Integer ("ll", 2, 10_000_000_002); - St.Set_Use_Vector_Long_Long_Integer ("ll", 3, 10_000_000_003); - St.Set_Use_Vector_Long_Long_Integer ("ll", 4, 10_000_000_004); - St.Set_Use_Vector_State ("ll", 5, SOCI.Data_Null); - St.Set_Use_Vector_Long_Float ("lf", 0, SOCI.DB_Long_Float (0.0)); - St.Set_Use_Vector_Long_Float ("lf", 1, SOCI.DB_Long_Float (0.125)); - St.Set_Use_Vector_Long_Float ("lf", 2, SOCI.DB_Long_Float (0.25)); - St.Set_Use_Vector_Long_Float ("lf", 3, SOCI.DB_Long_Float (0.5)); - St.Set_Use_Vector_Long_Float ("lf", 4, SOCI.DB_Long_Float (0.625)); - St.Set_Use_Vector_State ("lf", 5, SOCI.Data_Null); - St.Set_Use_Vector_Time ("tm", 0, Time_1); - St.Set_Use_Vector_Time ("tm", 1, Time_2); - St.Set_Use_Vector_Time ("tm", 2, Time_3); - St.Set_Use_Vector_Time ("tm", 3, Time_4); - St.Set_Use_Vector_Time ("tm", 4, Time_5); - St.Set_Use_Vector_State ("tm", 5, SOCI.Data_Null); - - St.Prepare ("insert into soci_test (id, str, ll, lf, tm)" & - " values (:id, :str, :ll, :lf, :tm)"); - St.Execute (True); - end; - declare - St : SOCI.Statement := SOCI.Make_Statement (SQL); - Pos_Id : SOCI.Into_Position; - Pos_Str : SOCI.Into_Position; - Pos_LL : SOCI.Into_Position; - Pos_LF : SOCI.Into_Position; - Pos_TM : SOCI.Into_Position; - Got_Data : Boolean; - - use type Ada.Calendar.Time; - use type SOCI.Data_State; - use type SOCI.DB_Integer; - use type SOCI.DB_Long_Long_Integer; - use type SOCI.DB_Long_Float; - - begin - Pos_Id := St.Into_Integer; - Pos_Str := St.Into_String; - Pos_LL := St.Into_Long_Long_Integer; - Pos_LF := St.Into_Long_Float; - Pos_TM := St.Into_Time; - - St.Prepare ("select id, str, ll, lf, tm from soci_test order by id"); - St.Execute; - - Got_Data := St.Fetch; - pragma Assert (Got_Data); - pragma Assert (St.Get_Into_Integer (Pos_Id) = 1); - pragma Assert (St.Get_Into_String (Pos_Str) = "abc"); - pragma Assert (St.Get_Into_Long_Long_Integer (Pos_LL) = 10_000_000_000); - pragma Assert (St.Get_Into_Long_Float (Pos_LF) = SOCI.DB_Long_Float (0.0)); - pragma Assert (St.Get_Into_Time (Pos_TM) = Time_1); - - Got_Data := St.Fetch; - pragma Assert (Got_Data); - pragma Assert (St.Get_Into_Integer (Pos_Id) = 2); - pragma Assert (St.Get_Into_String (Pos_Str) = "def"); - pragma Assert (St.Get_Into_Long_Long_Integer (Pos_LL) = 10_000_000_001); - pragma Assert (St.Get_Into_Long_Float (Pos_LF) = SOCI.DB_Long_Float (0.125)); - pragma Assert (St.Get_Into_Time (Pos_TM) = Time_2); - - Got_Data := St.Fetch; - pragma Assert (Got_Data); - pragma Assert (St.Get_Into_Integer (Pos_Id) = 3); - pragma Assert (St.Get_Into_String (Pos_Str) = "ghi"); - pragma Assert (St.Get_Into_Long_Long_Integer (Pos_LL) = 10_000_000_002); - pragma Assert (St.Get_Into_Long_Float (Pos_LF) = SOCI.DB_Long_Float (0.25)); - pragma Assert (St.Get_Into_Time (Pos_TM) = Time_3); - - Got_Data := St.Fetch; - pragma Assert (Got_Data); - pragma Assert (St.Get_Into_Integer (Pos_Id) = 4); - pragma Assert (St.Get_Into_String (Pos_Str) = "jklm"); - pragma Assert (St.Get_Into_Long_Long_Integer (Pos_LL) = 10_000_000_003); - pragma Assert (St.Get_Into_Long_Float (Pos_LF) = SOCI.DB_Long_Float (0.5)); - pragma Assert (St.Get_Into_Time (Pos_TM) = Time_4); - - Got_Data := St.Fetch; - pragma Assert (Got_Data); - pragma Assert (St.Get_Into_Integer (Pos_Id) = 5); - pragma Assert (St.Get_Into_String (Pos_Str) = "no"); - pragma Assert (St.Get_Into_Long_Long_Integer (Pos_LL) = 10_000_000_004); - pragma Assert (St.Get_Into_Long_Float (Pos_LF) = SOCI.DB_Long_Float (0.625)); - pragma Assert (St.Get_Into_Time (Pos_TM) = Time_5); - - Got_Data := St.Fetch; - pragma Assert (Got_Data); - pragma Assert (St.Get_Into_State (Pos_Id) = SOCI.Data_Not_Null); - pragma Assert (St.Get_Into_Integer (Pos_Id) = 6); - pragma Assert (St.Get_Into_State (Pos_Str) = SOCI.Data_Null); - pragma Assert (St.Get_Into_State (Pos_LL) = SOCI.Data_Null); - pragma Assert (St.Get_Into_State (Pos_LF) = SOCI.Data_Null); - pragma Assert (St.Get_Into_State (Pos_TM) = SOCI.Data_Null); - - Got_Data := St.Fetch; - pragma Assert (not Got_Data); - end; - - SQL.Execute ("drop table soci_test"); - end; - end Test_10; - - procedure Test_11 (Connection_String : in String) is - - -- test parameters: - Pool_Size : constant := 3; - Number_Of_Tasks : constant := 10; - Iterations_Per_Task : constant := 1000; - - type Small_Integer is mod 20; - package My_Random is new Ada.Numerics.Discrete_Random (Small_Integer); - Rand : My_Random.Generator; - - Pool : SOCI.Connection_Pool (Pool_Size); - - begin - Ada.Text_IO.Put_Line ("testing connection pool"); - - My_Random.Reset (Rand); - - for I in 1 .. Pool_Size loop - Pool.Open (I, Connection_String); - end loop; - - declare - SQL : SOCI.Session := SOCI.Make_Session (Connection_String); - begin - SQL.Execute ("create table soci_test ( id integer )"); - end; - - declare - - task type Worker; - task body Worker is - begin - - for I in 1 .. Iterations_Per_Task loop - declare - SQL : SOCI.Session; - V : Small_Integer; - begin - Pool.Lease (SQL); - - V := My_Random.Random (Rand); - SQL.Execute ("insert into soci_test (id) values (" & - Small_Integer'Image (V) & ")"); - end; - end loop; - exception - when others => - Ada.Text_IO.Put_Line ("An exception occured in the worker task."); - end Worker; - - W : array (1 .. Number_Of_Tasks) of Worker; - - begin - Ada.Text_IO.Put_Line ("--> waiting for the tasks to complete (might take a while)"); - end; - - declare - SQL : SOCI.Session := SOCI.Make_Session (Connection_String); - begin - SQL.Execute ("drop table soci_test"); - end; - end Test_11; - -begin - if Ada.Command_Line.Argument_Count /= 1 then - Ada.Text_IO.Put_Line ("Expecting one argument: connection string"); - return; - end if; - - declare - Connection_String : String := Ada.Command_Line.Argument (1); - begin - Ada.Text_IO.Put_Line ("testing with " & Connection_String); - - SOCI.PostgreSQL.Register_Factory_PostgreSQL; - - Test_1 (Connection_String); - Test_2 (Connection_String); - Test_3 (Connection_String); - Test_4 (Connection_String); - Test_5 (Connection_String); - Test_6 (Connection_String); - Test_7 (Connection_String); - Test_8 (Connection_String); - Test_9 (Connection_String); - Test_10 (Connection_String); - Test_11 (Connection_String); - end; -end PostgreSQL_Test; diff --git a/src/soci/languages/ada/test/postgresql_test.gpr b/src/soci/languages/ada/test/postgresql_test.gpr deleted file mode 100644 index 1af59d3267..0000000000 --- a/src/soci/languages/ada/test/postgresql_test.gpr +++ /dev/null @@ -1,12 +0,0 @@ -with "../soci_ada.gpr"; -with "../soci_postgresql.gpr"; -with "../postgresql_client.gpr"; - -project PostgreSQL_Test is - for Main use ("postgresql_test"); - - package Compiler is - for Default_Switches ("Ada") use ("-gnat05", "-gnata"); - end Compiler; -end PostgreSQL_Test; - diff --git a/src/soci/mkdocs.yml b/src/soci/mkdocs.yml deleted file mode 100644 index 92ea50528e..0000000000 --- a/src/soci/mkdocs.yml +++ /dev/null @@ -1,51 +0,0 @@ -site_name: SOCI 4.0.0 -site_description: SOCI - The C++ Database Access Library -repo_url: https://github.com/SOCI/soci/ -copyright: Copyright © 2017 Maciej Sobczak and SOCI Team. - -pages: - - Home: index.md - - Overview: - - Getting Started: quickstart.md - - Installation: installation.md - - Library Structure: structure.md - - License: license.md - - FAQ: faq.md - - User Guide: - - Connections: connections.md - - Queries: queries.md - - Data Binding: binding.md - - Data Indicators: indicators.md - - Data Types: types.md - - LOBs: lobs.md - - Statemets: statements.md - - Transactions: transactions.md - - Procedures: procedures.md - - Errors: errors.md - - Logging: logging.md - - Interfaces: interfaces.md - - Backends: - - Features: backends/index.md - - DB2: backends/db2.md - - Firebird: backends/firebird.md - - MySQL: backends/mysql.md - - ODBC: backends/odbc.md - - Oracle: backends/oracle.md - - PostgreSQL: backends/postgresql.md - - SQLite3: backends/sqlite3.md - - Miscellaneous: - - Beyond SQL: beyond.md - - Multi-threading: multithreading.md - - Boost: boost.md - - Utilities: utilities.md - - Vagrant: vagrant.md - - API: - - Client API: api/client.md - - Backend API: api/backend.md - - Ada: - - languages/ada/index.md - - languages/ada/concepts.md - - languages/ada/idioms.md - - languages/ada/reference.md - -#theme: readthedocs diff --git a/src/soci/scripts/build.bat b/src/soci/scripts/build.bat deleted file mode 100644 index 2ba3fe43ca..0000000000 --- a/src/soci/scripts/build.bat +++ /dev/null @@ -1,79 +0,0 @@ -@echo off -rem Runs CMake to configure SOCI for Visual Studio 2017. -rem Runs MSBuild to build the generated solution. -rem -rem Usage: -rem 1. Copy build.bat to build.locale.bat (git ignored file) -rem 2. Make your adjustments in the CONFIGURATION section below -rem 3. Run build.local.bat 32|64 -rem 4. Optionally, run devenv.exe SOCI{32|64}.sln from command line - -rem ### CONFIGURATION ##################################### -rem ### Connection strings for tests (alternatively, use command line-c option) -rem ### For example, SQL Server LocalDB instance, MySQL and PostgreSQL on the Vagrant VM. -set TEST_CONNSTR_MSSQL="" -set TEST_CONNSTR_MYSQL="" -set TEST_CONNSTR_PGSQL="" -setlocal -set BOOST_ROOT=C:/local/boost_1_59_0 -rem ####################################################### - -set U="" -if /I "%2"=="U" set U=U -if [%1]==[32] goto :32 -if [%1]==[64] goto :64 -goto :Usage - -:32 -set P=32 -set MSBUILDP=Win32 -set GENERATOR="Visual Studio 15 2017" -goto :Build - -:64 -set P=64 -set MSBUILDP=x64 -set GENERATOR="Visual Studio 15 2017 Win64" -goto :Build - -:Build -set BUILDDIR=_build%P%%U% -mkdir %BUILDDIR% -pushd %BUILDDIR% -cmake.exe ^ - -G %GENERATOR% ^ - -DWITH_BOOST=ON ^ - -DWITH_DB2=ON ^ - -DWITH_FIREBIRD=ON ^ - -DWITH_MYSQL=ON ^ - -DWITH_ODBC=ON ^ - -DWITH_ORACLE=ON ^ - -DWITH_POSTGRESQL=ON ^ - -DWITH_SQLITE3=ON ^ - -DSOCI_EMPTY=ON ^ - -DSOCI_EMPTY_TEST_CONNSTR="" ^ - -DSOCI_DB2=ON ^ - -DSOCI_DB2_TEST_CONNSTR="" ^ - -DSOCI_FIREBIRD=ON ^ - -DSOCI_FIREBIRD_TEST_CONNSTR="" ^ - -DSOCI_MYSQL=ON ^ - -DSOCI_MYSQL_TEST_CONNSTR="" ^ - -DSOCI_ODBC=ON ^ - -DSOCI_ODBC_TEST_MYSQL_CONNSTR="" ^ - -DSOCI_ODBC_TEST_POSTGRESQL_CONNSTR="" ^ - -DSOCI_ORACLE=ON ^ - -DSOCI_ORACLE_TEST_CONNSTR="" ^ - -DSOCI_POSTGRESQL=ON ^ - -DSOCI_POSTGRESQL_TEST_CONNSTR="" ^ - -DSOCI_SQLITE3=ON ^ - -DSOCI_SQLITE3_TEST_CONNSTR="" ^ - .. -move SOCI.sln SOCI%P%%U%.sln -rem msbuild.exe SOCI%P%%U%.sln /p:Configuration=Release /p:Platform=%MSBUILDP% -popd -goto :EOF - -:Usage -@echo build.bat -@echo Usage: build.bat [32 or 64] -exit /B 1 diff --git a/src/soci/scripts/changelog.sh b/src/soci/scripts/changelog.sh deleted file mode 100644 index 3eac2a54f3..0000000000 --- a/src/soci/scripts/changelog.sh +++ /dev/null @@ -1,24 +0,0 @@ -#!/bin/bash -e -# Generates CHANGELOG.md for SOCI project. -# -# Runs github-changelog-generator to automatically generate changelog -# from your tags, closed issues and merged pull requests. -# -# Requirements: -# - https://github.com/skywinder/github-changelog-generator -# -# Copyright (c) 2017 Mateusz Loskot -# -if [[ -z "$CHANGELOG_GITHUB_TOKEN" ]]; then - echo "Environment variable CHANGELOG_GITHUB_TOKEN not found!" >&2 - echo "GitHub API token is required to avoid hitting limit of requests per hour." >&2 - exit 1 -fi - -if ! type "github_changelog_generator" > /dev/null; then - echo "github_changelog_generator not found." >&2 - echo "Go to https://github.com/skywinder/github-changelog-generator" - exit 1 -fi - -github_changelog_generator --verbose --date-format "%Y-%m-%d" diff --git a/src/soci/scripts/travis/before_install.sh b/src/soci/scripts/travis/before_install.sh deleted file mode 100755 index 719a70d7ac..0000000000 --- a/src/soci/scripts/travis/before_install.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/bash -# Run before_install actions for SOCI build at travis-ci.org -# -# Copyright (c) 2013 Mateusz Loskot -# -source ${TRAVIS_BUILD_DIR}/scripts/travis/common.sh - -sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 16126D3A3E5C1192 -sudo add-apt-repository -y ppa:apt-fast/stable - -sudo apt-get update -qq -y -sudo apt-get install -qq -y apt-fast -sudo apt-fast update -qq -y -sudo apt-fast install -qq -y libboost-dev libboost-date-time-dev valgrind - -before_install="${TRAVIS_BUILD_DIR}/scripts/travis/before_install_${SOCI_TRAVIS_BACKEND}.sh" -if [ -x ${before_install} ]; then - echo "Running ${before_install}" - ${before_install} -fi diff --git a/src/soci/scripts/travis/before_install_db2.sh b/src/soci/scripts/travis/before_install_db2.sh deleted file mode 100755 index e4a0e7a76e..0000000000 --- a/src/soci/scripts/travis/before_install_db2.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/bash -e -# Installs DB2 for SOCI build at travis-ci.org -# -# Copyright (c) 2013 Brian R. Toonen -# Copyright (c) 2013 Mateusz Loskot -# -sudo bash -c 'echo "deb http://archive.canonical.com/ubuntu precise partner" >> /etc/apt/sources.list' -sudo apt-get update -qq -y -sudo apt-get install -qq -y db2exc - -echo "Running db2profile and db2rmln" -sudo /bin/sh -c '. ~db2inst1/sqllib/db2profile ; $DB2DIR/cfg/db2rmln' - -echo "Setting up db2 users" -echo -e "db2inst1\ndb2inst1" | sudo passwd db2inst1 -echo -e "db2fenc1\ndb2fenc1" | sudo passwd db2fenc1 -echo -e "dasusr1\ndasusr1" | sudo passwd dasusr1 - -echo "Configuring DB2 ODBC driver" -if test `getconf LONG_BIT` = "64" ; then - if test -f /home/db2inst1/sqllib/lib64/libdb2o.so ; then - DB2_ODBC_DRIVER=/home/db2inst1/sqllib/lib64/libdb2o.so - else - echo "ERROR: can't find the 64-bit DB2 ODBC library" - exit 1 - fi -else - if test -f /home/db2inst1/sqllib/lib32/libdb2.so ; then - DB2_ODBC_DRIVER=/home/db2inst1/sqllib/lib32/libdb2.so - elif test -f /home/db2inst1/sqllib/lib/libdb2.so ; then - DB2_ODBC_DRIVER=/home/db2inst1/sqllib/lib/libdb2.so - else - echo "ERROR: can't find the 32-bit DB2 ODBC library" - exit 1 - fi -fi -echo "DB2 ODBC driver set to $DB2_ODBC_DRIVER" diff --git a/src/soci/scripts/travis/before_install_firebird.sh b/src/soci/scripts/travis/before_install_firebird.sh deleted file mode 100755 index fc56f82420..0000000000 --- a/src/soci/scripts/travis/before_install_firebird.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash -e -# Install Firebird server for SOCI at travis-ci.org -# -# Copyright (c) 2013 Mateusz Loskot -# -source ${TRAVIS_BUILD_DIR}/scripts/travis/common.sh - -sudo apt-get install -qq firebird2.5-super firebird2.5-dev - -# Configure Firebird server -# See: Non-interactive setup for travis-ci.org -# http://tech.groups.yahoo.com/group/firebird-support/message/120883 -#sudo dpkg-reconfigure -f noninteractive firebird2.5-super -sudo sed /ENABLE_FIREBIRD_SERVER=/s/no/yes/ -i /etc/default/firebird2.5 -cat /etc/default/firebird2.5 | grep ENABLE_FIREBIRD_SERVER -sudo service firebird2.5-super start diff --git a/src/soci/scripts/travis/before_install_odbc.sh b/src/soci/scripts/travis/before_install_odbc.sh deleted file mode 100755 index 605e5544fe..0000000000 --- a/src/soci/scripts/travis/before_install_odbc.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/bash -e -# Install ODBC libraries for SOCI at travis-ci.org -# -# Copyright (c) 2013 Mateusz Loskot -# -source ${TRAVIS_BUILD_DIR}/scripts/travis/common.sh - -sudo apt-get install -qq \ - tar bzip2 \ - unixodbc-dev \ - libmyodbc odbc-postgresql - -sudo odbcinst -i -d -f /usr/share/libmyodbc/odbcinst.ini diff --git a/src/soci/scripts/travis/before_install_oracle.sh b/src/soci/scripts/travis/before_install_oracle.sh deleted file mode 100755 index 8ad956112f..0000000000 --- a/src/soci/scripts/travis/before_install_oracle.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/bash -# Script performs non-interactive installation of Oracle XE on Linux -# -# Uses Oracle downloader and installer from https://github.com/cbandy/travis-oracle -# -# set -ex -source ${TRAVIS_BUILD_DIR}/scripts/travis/oracle.sh - -# Install Oracle and travis-oracle requirements -sudo apt-get install -y libaio1 rpm - -curl -s -o $HOME/.nvm/nvm.sh https://raw.githubusercontent.com/creationix/nvm/v0.31.0/nvm.sh -source $HOME/.nvm/nvm.sh -nvm install stable -node --version - -# Install travis-oracle -wget 'https://github.com/cbandy/travis-oracle/archive/v2.0.3.tar.gz' -mkdir -p .travis/oracle -tar x -C .travis/oracle --strip-components=1 -f v2.0.3.tar.gz - -# Download Oracle (do not use Travis CI secure environment!) -export ORACLE_LOGIN_pass="T$(echo $ORACLE_LOGIN_userid | rev)#2017" -bash .travis/oracle/download.sh - -# Install Oracle -bash .travis/oracle/install.sh diff --git a/src/soci/scripts/travis/before_script.sh b/src/soci/scripts/travis/before_script.sh deleted file mode 100755 index 4c1ae2147b..0000000000 --- a/src/soci/scripts/travis/before_script.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash -# Run before_script actions for SOCI build at travis-ci.org -# -# Copyright (c) 2013 Mateusz Loskot -# -source ${TRAVIS_BUILD_DIR}/scripts/travis/common.sh - -before_script="${TRAVIS_BUILD_DIR}/scripts/travis/before_script_${SOCI_TRAVIS_BACKEND}.sh" -if [ -x ${before_script} ]; then - echo "Running ${before_script}" - ${before_script} -fi diff --git a/src/soci/scripts/travis/before_script_db2.sh b/src/soci/scripts/travis/before_script_db2.sh deleted file mode 100755 index 29b5dd02ce..0000000000 --- a/src/soci/scripts/travis/before_script_db2.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash -e -# Sets up environment for SOCI backend DB2 at travis-ci.org -# -# Copyright (c) 2013 Brian R. Toonen -# Copyright (c) 2013 Mateusz Loskot -# -source ${TRAVIS_BUILD_DIR}/scripts/travis/common.sh - -sudo -u db2inst1 -i db2 "CREATE DATABASE SOCITEST" -sudo -u db2inst1 -i db2 "ACTIVATE DATABASE SOCITEST" diff --git a/src/soci/scripts/travis/before_script_firebird.sh b/src/soci/scripts/travis/before_script_firebird.sh deleted file mode 100755 index f940b234d1..0000000000 --- a/src/soci/scripts/travis/before_script_firebird.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/bash -e -# Configure Firebird database for SOCI build at travis-ci.org -# -# Mateusz Loskot , http://github.com/SOCI -# -source ${TRAVIS_BUILD_DIR}/scripts/travis/common.sh - -isql-fb -z -q -i /dev/null # --version -echo 'CREATE DATABASE "LOCALHOST:/tmp/soci_test.fdb" PAGE_SIZE = 16384;' > /tmp/create_soci_test.sql -isql-fb -u SYSDBA -p masterkey -i /tmp/create_soci_test.sql -q -cat /tmp/create_soci_test.sql diff --git a/src/soci/scripts/travis/before_script_mysql.sh b/src/soci/scripts/travis/before_script_mysql.sh deleted file mode 100755 index 52076703c4..0000000000 --- a/src/soci/scripts/travis/before_script_mysql.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/bash -e -# Sets up environment for SOCI backend MySQL at travis-ci.org -# -# Mateusz Loskot , http://github.com/SOCI -# -source ${TRAVIS_BUILD_DIR}/scripts/travis/common.sh - -mysql --version -mysql -e 'create database soci_test;' diff --git a/src/soci/scripts/travis/before_script_odbc.sh b/src/soci/scripts/travis/before_script_odbc.sh deleted file mode 100755 index 9494732ed0..0000000000 --- a/src/soci/scripts/travis/before_script_odbc.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/bash -e -# Sets up environment for SOCI backend ODBC at travis-ci.org -# -# Mateusz Loskot , http://github.com/SOCI -# -source ${TRAVIS_BUILD_DIR}/scripts/travis/common.sh - -mysql --version -mysql -e 'create database soci_test;' -psql --version -psql -c 'create database soci_test;' -U postgres diff --git a/src/soci/scripts/travis/before_script_oracle.sh b/src/soci/scripts/travis/before_script_oracle.sh deleted file mode 100755 index a63958ed48..0000000000 --- a/src/soci/scripts/travis/before_script_oracle.sh +++ /dev/null @@ -1,41 +0,0 @@ -#!/bin/bash -# Sets up environment for p6psy backend Oracle at travis-ci.org -# -# Copyright (c) 2013 Peter Butkovic -# -# Modified by Mateusz Loskot -# Changes: -# - Check connection as user for testing -# -source ${TRAVIS_BUILD_DIR}/scripts/travis/oracle.sh -echo "ORACLE_HOME=${ORACLE_HOME}" -echo "ORACLE_SID=${ORACLE_SID}" - -# travis-oracle installer created travis user w/o password -echo "ALTER USER travis IDENTIFIED BY travis;" | \ -$ORACLE_HOME/bin/sqlplus -S -L sys/admin AS SYSDBA - -echo "grant connect, resource to travis;" | \ -$ORACLE_HOME/bin/sqlplus -S -L sys/admin AS SYSDBA - -echo "grant create session, alter any procedure to travis;" | \ -$ORACLE_HOME/bin/sqlplus -S -L sys/admin AS SYSDBA - -# to enable xa recovery, see: https://community.oracle.com/thread/378954 -echo "grant select on sys.dba_pending_transactions to travis;" | \ -$ORACLE_HOME/bin/sqlplus -S -L sys/admin AS SYSDBA -echo "grant select on sys.pending_trans$ to travis;" | \ -$ORACLE_HOME/bin/sqlplus -S -L sys/admin AS SYSDBA -echo "grant select on sys.dba_2pc_pending to travis;" | \ -$ORACLE_HOME/bin/sqlplus -S -L sys/admin AS SYSDBA -echo "grant execute on sys.dbms_system to travis;" | \ -$ORACLE_HOME/bin/sqlplus -S -L sys/admin AS SYSDBA - -# increase default=40 value of processes to prevent ORA-12520 failures while testing -echo "alter system set processes=100 scope=spfile;" | \ -$ORACLE_HOME/bin/sqlplus -S -L sys/admin AS SYSDBA - -# check connection as user for testing -echo "Connecting using travis/travis@XE" -echo "SELECT * FROM product_component_version;" | \ -$ORACLE_HOME/bin/sqlplus -S -L travis/travis@XE diff --git a/src/soci/scripts/travis/before_script_postgresql.sh b/src/soci/scripts/travis/before_script_postgresql.sh deleted file mode 100755 index 54272cb750..0000000000 --- a/src/soci/scripts/travis/before_script_postgresql.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/bash -e -# Sets up environment for SOCI backend PostgreSQL at travis-ci.org -# -# Mateusz Loskot , http://github.com/SOCI -# -source ${TRAVIS_BUILD_DIR}/scripts/travis/common.sh - -psql --version -psql -c 'create database soci_test;' -U postgres diff --git a/src/soci/scripts/travis/before_script_valgrind.sh b/src/soci/scripts/travis/before_script_valgrind.sh deleted file mode 100755 index daa72e6f39..0000000000 --- a/src/soci/scripts/travis/before_script_valgrind.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash -e -# Sets up environment for SOCI backend at travis-ci.org -# -# Copyright (c) 2013 Mateusz Loskot -# Copyright (c) 2015 Sergei Nikulov -# -source ${TRAVIS_BUILD_DIR}/scripts/travis/common.sh - -mysql --version -mysql -e 'create database soci_test;' -psql --version -psql -c 'create database soci_test;' -U postgres diff --git a/src/soci/scripts/travis/common.sh b/src/soci/scripts/travis/common.sh deleted file mode 100755 index 3f43bfea8f..0000000000 --- a/src/soci/scripts/travis/common.sh +++ /dev/null @@ -1,39 +0,0 @@ -#!/bin/bash -e -# Common definitions used by SOCI build scripts at travis-ci.org -# -# Copyright (c) 2013 Mateusz Loskot -# -if [[ "$TRAVIS" != "true" ]] ; then - echo "Running this script makes no sense outside of travis-ci.org" - exit 1 -fi -# -# Environment -# -TCI_NUMTHREADS=2 -if [[ -f /sys/devices/system/cpu/online ]]; then - # Calculates 1.5 times physical threads - TCI_NUMTHREADS=$(( ( $(cut -f 2 -d '-' /sys/devices/system/cpu/online) + 1 ) * 15 / 10 )) -fi -# -# Functions -# -tmstamp() -{ - echo -n "[$(date '+%H:%M:%S')]" ; -} - -run_make() -{ - [ $TCI_NUMTHREADS -gt 0 ] && make -j $TCI_NUMTHREADS || make -} - -run_test() -{ - ctest -V --output-on-failure "$@" . -} - -run_test_memcheck() -{ - valgrind --leak-check=full --suppressions=${TRAVIS_BUILD_DIR}/valgrind.suppress --error-exitcode=1 --trace-children=yes ctest -V --output-on-failure "$@" . -} diff --git a/src/soci/scripts/travis/oracle.sh b/src/soci/scripts/travis/oracle.sh deleted file mode 100755 index a9acece9bb..0000000000 --- a/src/soci/scripts/travis/oracle.sh +++ /dev/null @@ -1,12 +0,0 @@ -# Definitions used by SOCI when building Oracle backend at travis-ci.org -# -# Copyright (c) 2015 Vadim Zeitlin -# -# Notice that this file is not executable, it is supposed to be sourced from -# the other files. - -# Oracle environment required by https://github.com/cbandy/travis-oracle -export ORACLE_COOKIE=sqldev -export ORACLE_FILE=oracle11g/xe/oracle-xe-11.2.0-1.0.x86_64.rpm.zip -export ORACLE_HOME=/u01/app/oracle/product/11.2.0/xe -export ORACLE_SID=XE diff --git a/src/soci/scripts/travis/script.sh b/src/soci/scripts/travis/script.sh deleted file mode 100755 index 018c0e2dcc..0000000000 --- a/src/soci/scripts/travis/script.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash -# Run test script actions for SOCI build at travis-ci.org -# -# Copyright (c) 2013 Mateusz Loskot -# -source ${TRAVIS_BUILD_DIR}/scripts/travis/common.sh - -# prepare build directory -builddir="${TRAVIS_BUILD_DIR}/_build" -mkdir -p ${builddir} -cd ${builddir} - -# build and run tests -SCRIPT=${TRAVIS_BUILD_DIR}/scripts/travis/script_${SOCI_TRAVIS_BACKEND}.sh -echo "Running ${SCRIPT}" -${SCRIPT} diff --git a/src/soci/scripts/travis/script_db2.sh b/src/soci/scripts/travis/script_db2.sh deleted file mode 100755 index 41f6ff0847..0000000000 --- a/src/soci/scripts/travis/script_db2.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/bash -e -# Builds and tests SOCI backend DB2 at travis-ci.org -# -# Copyright (c) 2013 Brian R. Toonen -# Copyright (c) 2013 Mateusz Loskot -# -source ${TRAVIS_BUILD_DIR}/scripts/travis/common.sh - -cmake \ - -DCMAKE_BUILD_TYPE=Debug \ - -DSOCI_ASAN=ON \ - -DCMAKE_VERBOSE_MAKEFILE=ON \ - -DSOCI_TESTS=ON \ - -DSOCI_STATIC=OFF \ - -DSOCI_DB2=ON \ - -DSOCI_EMPTY=OFF \ - -DSOCI_FIREBIRD=OFF \ - -DSOCI_MYSQL=OFF \ - -DSOCI_ODBC=OFF \ - -DSOCI_ORACLE=OFF \ - -DSOCI_POSTGRESQL=OFF \ - -DSOCI_SQLITE3=OFF \ - -DSOCI_DB2_TEST_CONNSTR:STRING="DSN=SOCITEST\;Uid=db2inst1\;Pwd=db2inst1" \ - .. - -run_make -run_test diff --git a/src/soci/scripts/travis/script_empty.sh b/src/soci/scripts/travis/script_empty.sh deleted file mode 100755 index 1dcd1aed9b..0000000000 --- a/src/soci/scripts/travis/script_empty.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/bash -e -# Builds and tests SOCI backend empty at travis-ci.org -# -# Copyright (c) 2013 Mateusz Loskot -# -source ${TRAVIS_BUILD_DIR}/scripts/travis/common.sh - -cmake \ - -DCMAKE_BUILD_TYPE=Debug \ - -DSOCI_ASAN=ON \ - -DCMAKE_VERBOSE_MAKEFILE=ON \ - -DSOCI_TESTS=ON \ - -DSOCI_STATIC=OFF \ - -DSOCI_DB2=OFF \ - -DSOCI_EMPTY=ON \ - -DSOCI_FIREBIRD=OFF \ - -DSOCI_MYSQL=OFF \ - -DSOCI_ODBC=OFF \ - -DSOCI_ORACLE=OFF \ - -DSOCI_POSTGRESQL=OFF \ - -DSOCI_SQLITE3=OFF \ - .. - -run_make -run_test diff --git a/src/soci/scripts/travis/script_firebird.sh b/src/soci/scripts/travis/script_firebird.sh deleted file mode 100755 index 356c3ac657..0000000000 --- a/src/soci/scripts/travis/script_firebird.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/bin/bash -e -# Builds and tests SOCI backend Firebird at travis-ci.org -# -# Copyright (c) 2013 Mateusz Loskot -# -source ${TRAVIS_BUILD_DIR}/scripts/travis/common.sh - -cmake \ - -DCMAKE_BUILD_TYPE=Debug \ - -DSOCI_ASAN=ON \ - -DCMAKE_VERBOSE_MAKEFILE=ON \ - -DSOCI_TESTS=ON \ - -DSOCI_STATIC=OFF \ - -DSOCI_DB2=OFF \ - -DSOCI_EMPTY=OFF \ - -DSOCI_FIREBIRD=ON \ - -DSOCI_MYSQL=OFF \ - -DSOCI_ODBC=OFF \ - -DSOCI_ORACLE=OFF \ - -DSOCI_POSTGRESQL=OFF \ - -DSOCI_SQLITE3=OFF \ - -DSOCI_FIREBIRD_TEST_CONNSTR:STRING="service=LOCALHOST:/tmp/soci_test.fdb user=SYSDBA password=masterkey" \ - .. - -run_make -run_test diff --git a/src/soci/scripts/travis/script_mysql.sh b/src/soci/scripts/travis/script_mysql.sh deleted file mode 100755 index 0c86831131..0000000000 --- a/src/soci/scripts/travis/script_mysql.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/bin/bash -e -# Builds and tests SOCI backend SQLite3 at travis-ci.org -# -# Copyright (c) 2013 Mateusz Loskot -# -source ${TRAVIS_BUILD_DIR}/scripts/travis/common.sh - -cmake \ - -DCMAKE_BUILD_TYPE=Debug \ - -DSOCI_ASAN=ON \ - -DCMAKE_VERBOSE_MAKEFILE=ON \ - -DSOCI_TESTS=ON \ - -DSOCI_STATIC=OFF \ - -DSOCI_DB2=OFF \ - -DSOCI_EMPTY=OFF \ - -DSOCI_FIREBIRD=OFF \ - -DSOCI_MYSQL=ON \ - -DSOCI_ODBC=OFF \ - -DSOCI_ORACLE=OFF \ - -DSOCI_POSTGRESQL=OFF \ - -DSOCI_SQLITE3=OFF \ - -DSOCI_MYSQL_TEST_CONNSTR:STRING="db=soci_test" \ - .. - -run_make -run_test diff --git a/src/soci/scripts/travis/script_odbc.sh b/src/soci/scripts/travis/script_odbc.sh deleted file mode 100755 index a9b7a8135d..0000000000 --- a/src/soci/scripts/travis/script_odbc.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/bin/bash -e -# Builds and tests SOCI backend ODBC at travis-ci.org -# -# Copyright (c) 2013 Mateusz Loskot -# -source ${TRAVIS_BUILD_DIR}/scripts/travis/common.sh - -ODBC_TEST=${PWD}/../tests/odbc -if test ! -d ${ODBC_TEST}; then - echo "ERROR: '${ODBC_TEST}' directory not found" - exit 1 -fi - -cmake \ - -DCMAKE_BUILD_TYPE=Debug \ - -DSOCI_ASAN=ON \ - -DCMAKE_VERBOSE_MAKEFILE=ON \ - -DSOCI_TESTS=ON \ - -DSOCI_STATIC=OFF \ - -DSOCI_DB2=OFF \ - -DSOCI_EMPTY=OFF \ - -DSOCI_FIREBIRD=OFF \ - -DSOCI_MYSQL=OFF \ - -DSOCI_ODBC=ON \ - -DSOCI_ORACLE=OFF \ - -DSOCI_POSTGRESQL=OFF \ - -DSOCI_SQLITE3=OFF \ - .. - -run_make - -# Exclude the test which can't be run as there is no MS SQL server available. -run_test -E soci_odbc_test_mssql diff --git a/src/soci/scripts/travis/script_oracle.sh b/src/soci/scripts/travis/script_oracle.sh deleted file mode 100755 index c1c92eab51..0000000000 --- a/src/soci/scripts/travis/script_oracle.sh +++ /dev/null @@ -1,28 +0,0 @@ -#!/bin/bash -e -# Builds and tests SOCI backend Oracle at travis-ci.org -# -# Copyright (c) 2013 Mateusz Loskot -# -source ${TRAVIS_BUILD_DIR}/scripts/travis/common.sh -source ${TRAVIS_BUILD_DIR}/scripts/travis/oracle.sh - -cmake \ - -DCMAKE_BUILD_TYPE=Debug \ - -DSOCI_ASAN=ON \ - -DCMAKE_VERBOSE_MAKEFILE=ON \ - -DWITH_BOOST=OFF \ - -DSOCI_TESTS=ON \ - -DSOCI_STATIC=OFF \ - -DSOCI_DB2=OFF \ - -DSOCI_EMPTY=OFF \ - -DSOCI_FIREBIRD=OFF \ - -DSOCI_MYSQL=OFF \ - -DSOCI_ODBC=OFF \ - -DSOCI_ORACLE=ON \ - -DSOCI_POSTGRESQL=OFF \ - -DSOCI_SQLITE3=OFF \ - -DSOCI_ORACLE_TEST_CONNSTR:STRING="service=XE user=travis password=travis" \ - .. - -run_make -run_test diff --git a/src/soci/scripts/travis/script_postgresql.sh b/src/soci/scripts/travis/script_postgresql.sh deleted file mode 100755 index 515705a726..0000000000 --- a/src/soci/scripts/travis/script_postgresql.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/bin/bash -e -# Builds and tests SOCI backend SQLite3 at travis-ci.org -# -# Copyright (c) 2013 Mateusz Loskot -# -source ${TRAVIS_BUILD_DIR}/scripts/travis/common.sh - -cmake \ - -DCMAKE_BUILD_TYPE=Debug \ - -DSOCI_ASAN=ON \ - -DCMAKE_VERBOSE_MAKEFILE=ON \ - -DSOCI_TESTS=ON \ - -DSOCI_STATIC=OFF \ - -DSOCI_DB2=OFF \ - -DSOCI_EMPTY=OFF \ - -DSOCI_FIREBIRD=OFF \ - -DSOCI_MYSQL=OFF \ - -DSOCI_ODBC=OFF \ - -DSOCI_ORACLE=OFF \ - -DSOCI_POSTGRESQL=ON \ - -DSOCI_SQLITE3=OFF \ - -DSOCI_POSTGRESQL_TEST_CONNSTR:STRING="dbname=soci_test user=postgres" \ - .. - -run_make -run_test diff --git a/src/soci/scripts/travis/script_sqlite3.sh b/src/soci/scripts/travis/script_sqlite3.sh deleted file mode 100755 index 105a9d3f90..0000000000 --- a/src/soci/scripts/travis/script_sqlite3.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/bin/bash -e -# Builds and tests SOCI backend SQLite3 at travis-ci.org -# -# Copyright (c) 2013 Mateusz Loskot -# -source ${TRAVIS_BUILD_DIR}/scripts/travis/common.sh - -cmake \ - -DCMAKE_BUILD_TYPE=Debug \ - -DSOCI_ASAN=ON \ - -DCMAKE_VERBOSE_MAKEFILE=ON \ - -DSOCI_TESTS=ON \ - -DSOCI_STATIC=OFF \ - -DSOCI_DB2=OFF \ - -DSOCI_EMPTY=OFF \ - -DSOCI_FIREBIRD=OFF \ - -DSOCI_MYSQL=OFF \ - -DSOCI_ODBC=OFF \ - -DSOCI_ORACLE=OFF \ - -DSOCI_POSTGRESQL=OFF \ - -DSOCI_SQLITE3=ON \ - -DSOCI_SQLITE3_TEST_CONNSTR:STRING="soci_test.db" \ - .. - -run_make -run_test diff --git a/src/soci/scripts/travis/script_valgrind.sh b/src/soci/scripts/travis/script_valgrind.sh deleted file mode 100755 index 070f21652a..0000000000 --- a/src/soci/scripts/travis/script_valgrind.sh +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/bash -e -# Builds and tests SOCI at travis-ci.org -# -# Copyright (c) 2013 Mateusz Loskot -# Copyright (c) 2015 Sergei Nikulov -# -source ${TRAVIS_BUILD_DIR}/scripts/travis/common.sh - -cmake \ - -DCMAKE_VERBOSE_MAKEFILE=ON \ - -DSOCI_TESTS=ON \ - -DSOCI_STATIC=OFF \ - -DCMAKE_BUILD_TYPE=Debug \ - .. - -run_make -run_test_memcheck diff --git a/src/soci/scripts/vagrant/bootstrap.sh b/src/soci/scripts/vagrant/bootstrap.sh deleted file mode 100755 index 61e03c07ac..0000000000 --- a/src/soci/scripts/vagrant/bootstrap.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env bash -# Part of Vagrant virtual development environments for SOCI - -# Pre-installation -echo "Bootstrap: setting common environment in /etc/profile.d/vagrant-soci.sh" -sudo sh -c "cat /vagrant/scripts/vagrant/common.env > /etc/profile.d/vagrant-soci.sh" -export DEBIAN_FRONTEND="noninteractive" -# Installation -# TODO: Switch to apt-fast when it is avaiable for Trusty -sudo apt-get update -y -q -sudo apt-get -o Dpkg::Options::='--force-confnew' -y -q install \ - build-essential \ - avahi-daemon \ - zip -# Post-installation -## Configure Avahi to enable .local hostnames used to connect between VMs. -echo "Bootstrap: updating /etc/nsswitch.conf to configure Avahi/MDNS for .local lookup" -sudo sed -i 's/hosts:.*/hosts: files mdns4_minimal [NOTFOUND=return] dns myhostname/g' /etc/nsswitch.conf diff --git a/src/soci/scripts/vagrant/build.sh b/src/soci/scripts/vagrant/build.sh deleted file mode 100755 index 98794deaa7..0000000000 --- a/src/soci/scripts/vagrant/build.sh +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env bash -# Part of Vagrant virtual development environments for SOCI - -# Builds and tests SOCI from git master branch -source /vagrant/scripts/vagrant/common.env - -# Build SOCI in /home/vagrant on Linux filesystem, -# outside /vagrant which is VM shared directory. -# Otherwise, CMake will fail: -# CMake Error: cmake_symlink_library: System Error: Protocol error -# Explanation from https://github.com/mitchellh/vagrant/issues/713 -# The VirtualBox shared folder filesystem doesn't allow symlinks, unfortunately. -# Your only option is to deploy outside of the shared folders. -if [[ ! -d "${SOCI_BUILD}" ]] ; then - mkdir -p ${SOCI_BUILD} -fi - -echo "Build: building SOCI from sources in ${SOCI_HOME} to build in ${SOCI_BUILD}" -cd ${SOCI_BUILD} && \ -cmake \ - -DSOCI_CXX_C11=ON \ - -DSOCI_TESTS=ON \ - -DSOCI_STATIC=OFF \ - -DSOCI_DB2=ON \ - -DSOCI_ODBC=OFF \ - -DSOCI_ORACLE=OFF \ - -DSOCI_EMPTY=ON \ - -DSOCI_FIREBIRD=ON \ - -DSOCI_MYSQL=ON \ - -DSOCI_POSTGRESQL=ON \ - -DSOCI_SQLITE3=ON \ - -DSOCI_DB2_TEST_CONNSTR:STRING="DATABASE=${SOCI_USER}\\;hostname=${SOCI_DB2_HOST}\\;UID=${SOCI_DB2_USER}\\;PWD=${SOCI_DB2_PASS}\\;ServiceName=50000\\;Protocol=TCPIP\\;" \ - -DSOCI_FIREBIRD_TEST_CONNSTR:STRING="service=LOCALHOST:/tmp/soci.fdb user=${SOCI_USER} password=${SOCI_PASS}" \ - -DSOCI_MYSQL_TEST_CONNSTR:STRING="host=localhost db=${SOCI_USER} user=${SOCI_USER} password=${SOCI_PASS}" \ - -DSOCI_POSTGRESQL_TEST_CONNSTR:STRING="host=localhost port=5432 dbname=${SOCI_USER} user=${SOCI_USER} password=${SOCI_PASS}" \ - ${SOCI_HOME} && \ -make -echo "Build: building DONE" - -# Do not run tests during provisioning, thay may fail terribly, so just build -# and let to run them manually after developer vagrant ssh'ed to the VM. -echo "Build: ready to test SOCI by running: cd ${SOCI_BUILD}; ctest -V --output-on-failure ." diff --git a/src/soci/scripts/vagrant/common.env b/src/soci/scripts/vagrant/common.env deleted file mode 100644 index 7f9740590b..0000000000 --- a/src/soci/scripts/vagrant/common.env +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env bash -# Part of Vagrant virtual development environments for SOCI -export SOCI_HOME=/vagrant -export SOCI_BUILD=/home/vagrant/soci-build -export SOCI_HOST=vmsoci.local -# SOCI_USER has two purposes: database user name, database name -export SOCI_USER=soci -export SOCI_PASS=soci -export SOCI_DB2_HOST=vmdb2.local -export SOCI_DB2_USER=db2inst1 -export SOCI_DB2_PASS=db2inst1 diff --git a/src/soci/scripts/vagrant/db2.sh b/src/soci/scripts/vagrant/db2.sh deleted file mode 100755 index eda1eaa89f..0000000000 --- a/src/soci/scripts/vagrant/db2.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/env bash -# Part of Vagrant virtual development environments for SOCI - -# Installs DB2 Express-C 9.7 -# Pre-installation -source /vagrant/scripts/vagrant/common.env -export DEBIAN_FRONTEND="noninteractive" -# Installation -/vagrant/scripts/travis/before_install_db2.sh -# Post-installation -## Let's be gentle to DB2 and try to not to recreate existing databases -echo "db2: checking if ${SOCI_USER} database exists" -# First time guest machine is created, there is no database, hence test for: -# SQL1031N The database directory cannot be found on the indicated file system. -sudo -u db2inst1 -i db2 "LIST DATABASE DIRECTORY" | grep SQL1031N -NODB=$? -sudo -u db2inst1 -i db2 "LIST DATABASE DIRECTORY" | grep -i ${SOCI_USER} -HASSOCI=$? -if [[ $NODB -eq 0 || $HASSOCI -ne 0 ]]; then - echo "db2: creating database ${SOCI_USER}" - sudo -u db2inst1 -i db2 "CREATE DATABASE ${SOCI_USER}" - sudo -u db2inst1 -i db2 "ACTIVATE DATABASE ${SOCI_USER}" -else - echo "db2: database ${SOCI_USER} (may) exists, skipping" -fi diff --git a/src/soci/scripts/vagrant/db2cli.sh b/src/soci/scripts/vagrant/db2cli.sh deleted file mode 100755 index 99102cfec6..0000000000 --- a/src/soci/scripts/vagrant/db2cli.sh +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env bash -# Part of Vagrant virtual development environments for SOCI - -# Installs DB2 CLI Driver 10.5 (64-bit and 32-bit) from -# IBM Data Server Driver Package (DS Driver) - -# Prerequisities (manual download if wget fails): -# 1. Go to http://www-01.ibm.com/support/docview.wss?uid=swg21385217 -# 2. Go to "IBM Data Server Driver Package (DS Driver)" -# 3. Download "IBM Data Server Driver Package (Linux AMD64 and Intel EM64T)" -# 4. Copy the package to '{SOCI SOURCE TREE ROOT}/tmp' directory. -DSPKG="ibm_data_server_driver_package_linuxx64_v10.5.tar.gz" -DSPREFIX=/opt/ibm -DSDRIVER=${DSPREFIX}/dsdriver -SOCITMP=/vagrant/tmp - -# Try to download from known location -echo "DB2CLI: downloading ${DSPKG} from github.com/rorymckinley/gold_importer" -wget -q https://raw.githubusercontent.com/rorymckinley/gold_importer/master/3rdparty/ibm_data_server_driver_package_linuxx64_v10.5.tar.gz - -# Check if driver package is available -if [[ ! -f ${DSPKG} && ! -f ${SOCITMP}/${DSPKG} ]]; then - echo "DB2CLI: missing ${SOCITMP}/${DSPKG}" - echo "DB2CLI: try manual download, then provision VM to install" - echo "DB2CLI: meanwhile, skipping driver installation" - exit 0 -fi - -if [ -f ${SOCITMP}/${DSPKG} ]; then - DSPKG=${SOCITMP}/${DSPKG} -fi - -# If the drivers is already installed, skip re-installation -# because installDSDriver script does not support it -if [[ -d "${DSDRIVER}" && -f ${DSDRIVER}/db2profile ]]; then - echo "DB2CLI: ${DSDRIVER} already installed, skipping" - echo "DB2CLI: if necessary, upgrade manually running: ${DSDRIVER}/installDSDriver -upgrade ${DSDRIVER}" - exit 0 -fi - -# Korn shell required by installDSDriver script -sudo apt-get -o Dpkg::Options::='--force-confnew' -y -q install \ - ksh - -echo "DB2CLI: unpacking ${DSPKG} to ${DSPREFIX}" -sudo mkdir -p ${DSPREFIX} -sudo tar -zxf ${DSPKG} -C ${DSPREFIX} -echo "DB2CLI: running ${DSDRIVER}/installDSDriver script" -sudo ${DSDRIVER}/installDSDriver -echo "DB2CLI: cat ${DSDRIVER}/installDSDriver.log" -cat ${DSDRIVER}/installDSDriver.log -echo -echo "DB2CLI: installing ${DSDRIVER}/db2profile in /etc/profile.d/db2profile.sh for 64-bit env" -sudo cp ${DSDRIVER}/db2profile /etc/profile.d/db2profile.sh -echo "DB2CLI: For 32-bit, manually source ${DSDRIVER}/db2profile32 to overwrite 64-bit env" diff --git a/src/soci/scripts/vagrant/devel.sh b/src/soci/scripts/vagrant/devel.sh deleted file mode 100755 index 67ce137e0f..0000000000 --- a/src/soci/scripts/vagrant/devel.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env bash -# Part of Vagrant virtual development environments for SOCI - -# Installs essentials and core dependencies -# Pre-installation -source /vagrant/scripts/vagrant/common.env -export DEBIAN_FRONTEND="noninteractive" -# Trusty has CMake 2.8, we need CMake 3 -sudo apt-get install software-properties-common -sudo add-apt-repository ppa:george-edison55/cmake-3.x -sudo apt-get update -y -q -# Installation -sudo apt-get -o Dpkg::Options::='--force-confnew' -y -q install \ - build-essential \ - cmake \ - firebird2.5-dev \ - git \ - libboost-dev \ - libboost-date-time-dev \ - libmyodbc \ - libmysqlclient-dev \ - libpq-dev \ - libsqlite3-dev \ - odbc-postgresql \ - unixodbc-dev \ - valgrind -# Post-installation diff --git a/src/soci/scripts/vagrant/firebird.sh b/src/soci/scripts/vagrant/firebird.sh deleted file mode 100755 index e7e785859c..0000000000 --- a/src/soci/scripts/vagrant/firebird.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env bash -# Part of Vagrant virtual development environments for SOCI - -# Installs PostgreSQL with 'soci' user and database -# Pre-installation -source /vagrant/scripts/vagrant/common.env -export DEBIAN_FRONTEND="noninteractive" -# FIXME: these debconf lines should automate the Firebird config but do/may not :( -# However, keep them enabled to allow smooth(er) apt-get/dpkg operations. -# Othwerise, installation of firebird packages may fail, randomly. -# We work around this bug with Expect script below used to update SYSDBA password. -sudo debconf-set-selections <<< "firebird2.5-super shared/firebird/enabled boolean true" -sudo debconf-set-selections <<< "firebird2.5-super shared/firebird/sysdba_password/first_install password masterkey" -# Installation -sudo apt-get -o Dpkg::Options::='--force-confnew' -y -q install \ - expect \ - firebird2.5-super -# Post-installation -FB_ORIGINAL_PASS=`sudo cat /etc/firebird/2.5/SYSDBA.password \ - | grep ISC_PASSWORD | sed -e 's/ISC_PASSWORD="\([^"]*\)".*/\1/'` -echo "Firebird: dpkg-reconfigure resetting sysdba password from ${FB_ORIGINAL_PASS} to ${SOCI_PASS}" -export DEBIAN_FRONTEND="readline" -# Expect script feeding dpkg-reconfigure prompts -sudo /usr/bin/expect - << ENDMARK > /dev/null -spawn dpkg-reconfigure firebird2.5-super -freadline -expect "Enable Firebird server?" -send "Y\r" - -expect "Password for SYSDBA:" -send "${SOCI_PASS}\r" - -# done -expect eof -ENDMARK -# End of Expect script -export DEBIAN_FRONTEND="noninteractive" -echo "Firebird: cat /etc/firebird/2.5/SYSDBA.password" -sudo cat /etc/firebird/2.5/SYSDBA.password | grep ISC_ -echo -echo "Firebird: creating user ${SOCI_USER}" -sudo gsec -user sysdba -pass ${SOCI_PASS} -delete ${SOCI_USER} -sudo gsec -user sysdba -pass ${SOCI_PASS} -add ${SOCI_USER} -pw ${SOCI_PASS} -admin yes -echo "Firebird: creating database /tmp/${SOCI_USER}.fdb" -sudo rm -f /tmp/${SOCI_USER}.fdb -echo "CREATE DATABASE \"LOCALHOST:/tmp/${SOCI_USER}.fdb\";" \ - | isql-fb -q -u ${SOCI_USER} -p ${SOCI_PASS} -echo "Firebird: restarting" -sudo service firebird2.5-super restart -echo "Firebird: DONE" diff --git a/src/soci/scripts/vagrant/mysql.sh b/src/soci/scripts/vagrant/mysql.sh deleted file mode 100755 index 89eb3bf515..0000000000 --- a/src/soci/scripts/vagrant/mysql.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env bash -# Part of Vagrant virtual development environments for SOCI - -# Installs MySQL with 'soci' user and database -# Pre-installation -source /vagrant/scripts/vagrant/common.env -export DEBIAN_FRONTEND="noninteractive" -sudo debconf-set-selections <<< "mysql-server mysql-server/root_password password ${SOCI_PASS}" -sudo debconf-set-selections <<< "mysql-server mysql-server/root_password_again password ${SOCI_PASS}" -# Installation -sudo apt-get -o Dpkg::Options::='--force-confnew' -y -q install \ - mysql-server -# Post-installation -echo "MySQL: updating /etc/mysql/my.cnf" -sudo sed -i "s/bind-address.*/bind-address = 0.0.0.0/" /etc/mysql/my.cnf -echo "MySQL: setting root password to ${SOCI_PASS}" -mysql -uroot -p${SOCI_PASS} -e \ - "GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '${SOCI_PASS}' WITH GRANT OPTION; FLUSH PRIVILEGES;" -echo "MySQL: creating user ${SOCI_USER}" -mysql -uroot -p${SOCI_PASS} -e \ - "GRANT ALL PRIVILEGES ON ${SOCI_USER}.* TO '${SOCI_USER}'@'%' IDENTIFIED BY '${SOCI_PASS}' WITH GRANT OPTION" -mysql -uroot -p${SOCI_PASS} -e "DROP DATABASE IF EXISTS ${SOCI_USER}" -echo "MySQL: creating database ${SOCI_USER}" -mysql -uroot -p${SOCI_PASS} -e "CREATE DATABASE ${SOCI_USER}" -echo "MySQL: restarting" -sudo service mysql restart -echo "MySQL: DONE" diff --git a/src/soci/scripts/vagrant/postgresql.sh b/src/soci/scripts/vagrant/postgresql.sh deleted file mode 100755 index 21f0d135f8..0000000000 --- a/src/soci/scripts/vagrant/postgresql.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env bash -# Part of Vagrant virtual development environments for SOCI - -# Installs PostgreSQL with 'soci' user and database -# Pre-installation -source /vagrant/scripts/vagrant/common.env -export DEBIAN_FRONTEND="noninteractive" -# Installation -sudo apt-get -o Dpkg::Options::='--force-confnew' -y -q install \ - postgresql \ - postgresql-contrib -# Post-installation -echo "PostgreSQL: updating /etc/postgresql/9.3/main/postgresql.conf" -sudo sed -i "s/#listen_address.*/listen_addresses '*'/" /etc/postgresql/9.3/main/postgresql.conf -echo "PostgreSQL: updating /etc/postgresql/9.3/main/pg_hba.conf" -sudo cat >> /etc/postgresql/9.3/main/pg_hba.conf < -# Changes: -# - Add fake swap support (backup /usr/bin/free manually anyway!) -# -set -ex - -# -# Utilities -# -function free_backup() -{ - # Multiple copies to be on safe side - cp /usr/bin/free /root - mv /usr/bin/free /usr/bin/free.original -} - -function free_restore() -{ - cp /usr/bin/free.original /usr/bin/free -} - -# Install fake free -# http://www.axelog.de/2010/02/7-oracle-ee-refused-to-install-into-openvz/ -free_backup -cat <> /usr/bin/free -#!/bin/sh -cat <<__eof - total used free shared buffers cached -Mem: 1048576 327264 721312 0 0 0 --/+ buffers/cache: 327264 721312 -Swap: 2000000 0 2000000 -__eof -exit -EOF -chmod 755 /usr/bin/free - -# Enable HTTPS for APT repositories. -apt-get -q update -apt-get -qy install apt-transport-https - -# Register the Oracle repository. -echo "deb https://oss.oracle.com/debian/ unstable main non-free" >/etc/apt/sources.list.d/oracle.list -wget -q https://oss.oracle.com/el4/RPM-GPG-KEY-oracle -O- | apt-key add - -apt-get -q update - -# Install the Oracle 10g Express Edition. -apt-get -qy install oracle-xe - -# Clean APT cache. -apt-get clean - -# Fix the problem when the configuration script eats the last -# character of the password if it is 'n': replace IFS="\n" with IFS=$'\n'. -sed -i -e s/IFS=\"\\\\n\"/IFS=\$\'\\\\n\'/ /etc/init.d/oracle-xe - -# Configure the server; provide the answers for the following questions: -# The HTTP port for Oracle Application Express: 8080 -# A port for the database listener: 1521 -# The password for the SYS and SYSTEM database accounts: admin -# Start the server on boot: yes -/etc/init.d/oracle-xe configure <>/root/.bashrc - -. /usr/lib/oracle/xe/app/oracle/product/10.2.0/server/bin/oracle_env.sh -END - -free_restore - diff --git a/src/soci/scripts/windows/Get-ODBCList.ps1 b/src/soci/scripts/windows/Get-ODBCList.ps1 deleted file mode 100644 index 16eb8882ee..0000000000 --- a/src/soci/scripts/windows/Get-ODBCList.ps1 +++ /dev/null @@ -1,105 +0,0 @@ -Function Get-ODBCList -{ - <# - .SYNOPSIS - Get ODBC list. - - .DESCRIPTION - The Get-ODBCList cmdlet to Get ODBC connectors list on specific machine. - - .PARAMETER ComputerName - Specifies a computer name. - - .EXAMPLE - PS C:\> Get-ODBCList -ComputerName "g1","g2","g3" - - ODBC ComputerName - ---- ------------ - SQL Server g1 - Microsoft Access Driver (*.mdb, *.accdb) g1 - Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb) g1 - Microsoft Access dBASE Driver (*.dbf, *.ndx, *.mdx) g1 - Microsoft Access Text Driver (*.txt, *.csv) g1 - SQL Server Native Client 10.0 g1 - SQL Native Client g1 - SQL Server g2 - SQL Server g3 - - .NOTES - Author: Michal Gajda - Blog : http://commandlinegeeks.com/ - #> - [CmdletBinding( - SupportsShouldProcess=$True, - ConfirmImpact="Low" - )] - Param - ( - [parameter(ValueFromPipeline=$true, - ValueFromPipelineByPropertyName=$true)] - [String[]]$ComputerName = $env:COMPUTERNAME - ) - - Begin - { - $Key = "SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers" - $KeyWow64 = "SOFTWARE\Wow6432Node\ODBC\ODBCINST.INI\ODBC Drivers" - $Type = [Microsoft.Win32.RegistryHive]::LocalMachine - } #End Begin - - Process - { - Foreach($Computer in $ComputerName) - { - If(Test-Connection $Computer -Quiet) - { - Try - { - $regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($Type, $Computer) - $regSubKey = $regKey.OpenSubKey($Key) - $regSubKeyWow64 = $regKey.OpenSubKey($KeyWow64) - } - Catch - { - Write-Error $_.Exception.Message -ErrorAction Stop - } - - if($regSubKey -and $regSubKeyWow64) - { - $Bits = 64 - } #End if $regSubKey -and $regSubKeyWow64 - else - { - $Bits = 32 - } #End Else $regSubKey -and $regSubKeyWow64 - - Foreach($val in $regSubKey.GetValueNames()) - { - $log = New-Object PSObject -Property @{ - ComputerName = $Computer - ODBC = $val - Bits = $Bits - } #End New-Object PSObject - - $log - } #End ForEach $val in $regSubKey.GetValueNames() - - if($Bits -eq 64) - { - Foreach($val in $regSubKeyWow64.GetValueNames()) - { - $log = New-Object PSObject -Property @{ - ComputerName = $Computer - ODBC = $val - Bits = 32 - } #End New-Object PSObject - - $log - } #End ForEach $val in $regSubKeyWow64.GetValueNames() - } #End If $Bits -eq 64 - } #End If Test-Connection $Computer -Quiet - } #End Foreach $Computer in $ComputerName - } #End Process - - End{} -} #In The End :) \ No newline at end of file diff --git a/src/soci/scripts/windows/mssql_db_create.sql b/src/soci/scripts/windows/mssql_db_create.sql deleted file mode 100644 index c5a0b6795f..0000000000 --- a/src/soci/scripts/windows/mssql_db_create.sql +++ /dev/null @@ -1 +0,0 @@ -IF db_id('soci_test') IS NULL BEGIN CREATE DATABASE [soci_test] END; diff --git a/src/soci/src/.gitignore b/src/soci/src/.gitignore deleted file mode 100644 index 4746d47534..0000000000 --- a/src/soci/src/.gitignore +++ /dev/null @@ -1,20 +0,0 @@ -*~ -*.kdev[0-9] -*.swp -aclocal.m4 -autom4te.cache -confdefs.h -config.guess -config.log -config.status -config.sub -configure -depcomp -install-sh -libtool -ltmain.sh -m4 -missing -Makefile -Makefile.in -tmp diff --git a/src/soci/src/CMakeLists.txt b/src/soci/src/CMakeLists.txt deleted file mode 100644 index 472ae864c3..0000000000 --- a/src/soci/src/CMakeLists.txt +++ /dev/null @@ -1,14 +0,0 @@ -############################################################################### -# -# This file is part of CMake configuration for SOCI library -# -# Copyright (C) 2013 Mateusz Loskot -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -# -############################################################################### -include_directories(${SOCI_SOURCE_DIR}/include/private) - -add_subdirectory(core) -add_subdirectory(backends) diff --git a/src/soci/src/backends/.gitignore b/src/soci/src/backends/.gitignore deleted file mode 100644 index 64ec3b6829..0000000000 --- a/src/soci/src/backends/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -*.o -*.la -*.lo -.deps -.libs diff --git a/src/soci/src/backends/CMakeLists.txt b/src/soci/src/backends/CMakeLists.txt deleted file mode 100644 index 871e151ef4..0000000000 --- a/src/soci/src/backends/CMakeLists.txt +++ /dev/null @@ -1,50 +0,0 @@ -############################################################################### -# -# This file is part of CMake configuration for SOCI library -# -# Copyright (C) 2010 Mateusz Loskot -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -# -############################################################################### -colormsg(_HIBLUE_ "Configuring SOCI backend libraries:") - -# First, we'll investigate what can be found from database engines -foreach(dep ${SOCI_BACKENDS_DB_DEPENDENCIES}) - string(TOUPPER ${dep} depUP) - if (WITH_${depUP}) - find_package(${dep}) - endif() - if(${dep}_FOUND OR ${depUP}_FOUND) - set(${depUP}_FOUND ON) - else() - set(${depUP}_FOUND OFF) - endif() - set(SOCI_HAVE_${depUP} OFF CACHE INTERNAL "${depUP} backend") -endforeach() - -# get all files in backends -file(GLOB backend_dirs RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *) - -# empty backend always on by default -option(SOCI_EMPTY "Build empty backend" ON) -if(SOCI_EMPTY) - set(WITH_EMPTY ON) - set(EMPTY_FOUND ON) -endif() - -# enable only found backends -foreach(dir ${backend_dirs}) - if(IS_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/${dir}) - if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${dir}/CMakeLists.txt) - string(TOUPPER ${dir} dirUP) - if(${dirUP}_FOUND AND WITH_${dirUP}) - add_subdirectory(${dir}) - set(SOCI_HAVE_${dirUP} ON CACHE INTERNAL "${dirUP} backend") - endif() - endif() - endif() -endforeach() - -message(STATUS "") diff --git a/src/soci/src/backends/db2/CMakeLists.txt b/src/soci/src/backends/db2/CMakeLists.txt deleted file mode 100644 index 7913d7920f..0000000000 --- a/src/soci/src/backends/db2/CMakeLists.txt +++ /dev/null @@ -1,14 +0,0 @@ -############################################################################### -# -# This file is part of CMake configuration for SOCI library -# -# Copyright (C) 2011 Denis Chapligin -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -# -############################################################################### -soci_backend(DB2 - DEPENDS DB2 - DESCRIPTION "SOCI backend for DB2" AUTHORS "Denis Chapligin" - MAINTAINERS "Denis Chapligin") diff --git a/src/soci/src/backends/db2/blob.cpp b/src/soci/src/backends/db2/blob.cpp deleted file mode 100644 index 6c3fcb0d21..0000000000 --- a/src/soci/src/backends/db2/blob.cpp +++ /dev/null @@ -1,62 +0,0 @@ -// -// Copyright (C) 2011-2013 Denis Chapligin -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_DB2_SOURCE -#include "soci/db2/soci-db2.h" - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; - - -db2_blob_backend::db2_blob_backend(db2_session_backend &session) - : session_(session) -{ - // ... -} - -db2_blob_backend::~db2_blob_backend() -{ - // ... -} - -std::size_t db2_blob_backend::get_len() -{ - // ... - return 0; -} - -std::size_t db2_blob_backend::read( - std::size_t /* offset */, char * /* buf */, std::size_t /* toRead */) -{ - // ... - return 0; -} - -std::size_t db2_blob_backend::write( - std::size_t /* offset */, char const * /* buf */, - std::size_t /* toWrite */) -{ - // ... - return 0; -} - -std::size_t db2_blob_backend::append( - char const * /* buf */, std::size_t /* toWrite */) -{ - // ... - return 0; -} - -void db2_blob_backend::trim(std::size_t /* newLen */) -{ - // ... -} diff --git a/src/soci/src/backends/db2/common.h b/src/soci/src/backends/db2/common.h deleted file mode 100644 index 25a6619d1e..0000000000 --- a/src/soci/src/backends/db2/common.h +++ /dev/null @@ -1,21 +0,0 @@ -// -// Copyright (C) 2013 Mateusz Loskot -// Copyright (C) 2011-2013 Denis Chapligin -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_DB2_COMMON_H_INCLUDED -#define SOCI_DB2_COMMON_H_INCLUDED - -#include - -namespace soci { namespace details { namespace db2 { - -const std::size_t cli_max_buffer = 1024 * 1024 * 1024; //CLI limit is about 3 GB, but 1GB should be enough - -}}} // namespace soci::details::db2 - -#endif // SOCI_DB2_COMMON_H_INCLUDED diff --git a/src/soci/src/backends/db2/factory.cpp b/src/soci/src/backends/db2/factory.cpp deleted file mode 100644 index 03e12d6a20..0000000000 --- a/src/soci/src/backends/db2/factory.cpp +++ /dev/null @@ -1,40 +0,0 @@ -// -// Copyright (C) 2011-2013 Denis Chapligin -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_DB2_SOURCE -#include "soci/db2/soci-db2.h" -#include "soci/backend-loader.h" - -using namespace soci; -using namespace soci::details; - - -// concrete factory for ODBC concrete strategies -db2_session_backend * db2_backend_factory::make_session( - connection_parameters const & parameters) const -{ - return new db2_session_backend(parameters); -} - -db2_backend_factory const soci::db2; - -extern "C" -{ - -// for dynamic backend loading -SOCI_DB2_DECL backend_factory const * factory_db2() -{ - return &soci::db2; -} - -SOCI_DB2_DECL void register_factory_db2() -{ - soci::dynamic_backends::register_backend("db2", soci::db2); -} - -} // extern "C" diff --git a/src/soci/src/backends/db2/row-id.cpp b/src/soci/src/backends/db2/row-id.cpp deleted file mode 100644 index 4e51503bdf..0000000000 --- a/src/soci/src/backends/db2/row-id.cpp +++ /dev/null @@ -1,28 +0,0 @@ -// -// Copyright (C) 2011-2013 Denis Chapligin -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_DB2_SOURCE -#include "soci/db2/soci-db2.h" - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; - - -db2_rowid_backend::db2_rowid_backend(db2_session_backend & /* session */) -{ - // ... -} - -db2_rowid_backend::~db2_rowid_backend() -{ - // ... -} diff --git a/src/soci/src/backends/db2/session.cpp b/src/soci/src/backends/db2/session.cpp deleted file mode 100644 index 1d63d9a339..0000000000 --- a/src/soci/src/backends/db2/session.cpp +++ /dev/null @@ -1,248 +0,0 @@ -// -// Copyright (C) 2011-2013 Denis Chapligin -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_DB2_SOURCE -#include "soci/db2/soci-db2.h" -#include "soci/connection-parameters.h" - -#include - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; - -const char* soci::db2_option_driver_complete = "db2.driver_complete"; - -const std::string db2_soci_error::sqlState(std::string const & msg,const SQLSMALLINT htype,const SQLHANDLE hndl) { - std::ostringstream ss(msg, std::ostringstream::app); - - - SQLCHAR message[SQL_MAX_MESSAGE_LENGTH + 1]; - SQLCHAR sqlstate[SQL_SQLSTATE_SIZE + 1]; - SQLINTEGER sqlcode; - SQLSMALLINT length; - - if ( SQLGetDiagRec(htype, - hndl, - 1, - sqlstate, - &sqlcode, - message, - SQL_MAX_MESSAGE_LENGTH + 1, - &length) == SQL_SUCCESS ) { - ss<<" SQLMESSAGE: "; - ss<autocommit=true; //Default value - if (!key.compare("autocommit")) { - if (!value.compare("off")) { - this->autocommit=false; - } - } -} - -/* DSN=SAMPLE;Uid=db2inst1;Pwd=db2inst1;AutoCommit=off */ -/* DATABASE=SAMPLE;hostname=server.com;UID=db2inst1;PWD=db2inst1;ServiceName=50000;Protocol=TCPIP; */ -void db2_session_backend::parseConnectString(std::string const & connectString) { - std::string processingString(connectString); - size_t delimiter=processingString.find_first_of(";"); - while(delimiter!=std::string::npos) { - std::string keyVal=processingString.substr(0,delimiter); - parseKeyVal(keyVal); - processingString=processingString.erase(0,delimiter+1); - delimiter=processingString.find_first_of(";"); - } - if (!processingString.empty()) { - parseKeyVal(processingString); - } -} - -db2_session_backend::db2_session_backend( - connection_parameters const & parameters) : - in_transaction(false) -{ - std::string const& connectString = parameters.get_connect_string(); - parseConnectString(connectString); - - SQLRETURN cliRC = SQL_ERROR; - - /* Prepare handles */ - cliRC = SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&hEnv); - if (cliRC != SQL_SUCCESS) { - throw db2_soci_error("Error while allocating the enironment handle",cliRC); - } - - cliRC = SQLAllocHandle(SQL_HANDLE_DBC, hEnv, &hDbc); - if (cliRC != SQL_SUCCESS) { - std::string msg=db2_soci_error::sqlState("Error while allocating the connection handle",SQL_HANDLE_ENV,hEnv); - SQLFreeHandle(SQL_HANDLE_ENV,hEnv); - throw db2_soci_error(msg,cliRC); - } - - /* Set autocommit */ - if(this->autocommit) { - cliRC = SQLSetConnectAttr(hDbc,SQL_ATTR_AUTOCOMMIT, (SQLPOINTER)SQL_AUTOCOMMIT_ON, SQL_NTS); - } else { - cliRC = SQLSetConnectAttr(hDbc,SQL_ATTR_AUTOCOMMIT, (SQLPOINTER)SQL_AUTOCOMMIT_OFF, SQL_NTS); - } - if (cliRC != SQL_SUCCESS) { - std::string msg=db2_soci_error::sqlState("Error while setting autocommit attribute",SQL_HANDLE_DBC,hDbc); - SQLFreeHandle(SQL_HANDLE_DBC,hDbc); - SQLFreeHandle(SQL_HANDLE_ENV,hEnv); - throw db2_soci_error(msg,cliRC); - } - - /* Connect to database */ - // NOTE: SQLDriverConnect preparation steps below copied from ODBC backend. - SQLCHAR outConnString[1024]; - SQLSMALLINT strLength; - - // Prompt the user for any missing information (typically UID/PWD) in the - // connection string by default but allow overriding this using "prompt" - // option. - SQLHWND hwnd_for_prompt = NULL; - unsigned completion = SQL_DRIVER_COMPLETE; - std::string completionString; - if (parameters.get_option(db2_option_driver_complete, completionString)) - { - // The value of the option is supposed to be just the integer value of - // one of SQL_DRIVER_XXX constants but don't check for the exact value in - // case more of them are added in the future, the ODBC driver will return - // an error if we pass it an invalid value anyhow. - if (std::sscanf(completionString.c_str(), "%u", &completion) != 1) - { - throw soci_error("Invalid non-numeric driver completion option value \"" + - completionString + "\"."); - } - } - - #ifdef _WIN32 - if (completion != SQL_DRIVER_NOPROMPT) - hwnd_for_prompt = ::GetDesktopWindow(); - #endif // _WIN32 - - cliRC = SQLDriverConnect(hDbc, hwnd_for_prompt, - reinterpret_cast(const_cast(connectString.c_str())), - (SQLSMALLINT)connectString.size(), - outConnString, 1024, &strLength, - static_cast(completion)); - - if (cliRC != SQL_SUCCESS) { - std::string msg=db2_soci_error::sqlState("Error connecting to database",SQL_HANDLE_DBC,hDbc); - SQLFreeHandle(SQL_HANDLE_DBC,hDbc); - SQLFreeHandle(SQL_HANDLE_ENV,hEnv); - throw db2_soci_error(msg,cliRC); - } - - connection_string_.assign((const char*)outConnString, strLength); -} - -db2_session_backend::~db2_session_backend() -{ - clean_up(); -} - -void db2_session_backend::begin() -{ - // In DB2, transations begin implicitly; however, autocommit must be disabled for the duration of the transaction - if(autocommit) - { - SQLRETURN cliRC = SQLSetConnectAttr(hDbc, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER) SQL_AUTOCOMMIT_OFF, SQL_NTS); - if (cliRC != SQL_SUCCESS && cliRC != SQL_SUCCESS_WITH_INFO) - { - std::string msg=db2_soci_error::sqlState("Clearing the autocommit attribute failed", SQL_HANDLE_DBC, hDbc); - SQLFreeHandle(SQL_HANDLE_DBC,hDbc); - SQLFreeHandle(SQL_HANDLE_ENV,hEnv); - throw db2_soci_error(msg,cliRC); - } - } - - in_transaction = true; -} - -void db2_session_backend::commit() -{ - if (!autocommit || in_transaction) { - in_transaction = false; - SQLRETURN cliRC = SQLEndTran(SQL_HANDLE_DBC,hDbc,SQL_COMMIT); - if(autocommit) - { - SQLRETURN cliRC2 = SQLSetConnectAttr(hDbc, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER) SQL_AUTOCOMMIT_ON, SQL_NTS); - if ((cliRC == SQL_SUCCESS || cliRC == SQL_SUCCESS_WITH_INFO) && - cliRC2 != SQL_SUCCESS && cliRC2 != SQL_SUCCESS_WITH_INFO) - { - std::string msg=db2_soci_error::sqlState("Setting the autocommit attribute failed", SQL_HANDLE_DBC, hDbc); - SQLFreeHandle(SQL_HANDLE_DBC,hDbc); - SQLFreeHandle(SQL_HANDLE_ENV,hEnv); - throw db2_soci_error(msg,cliRC); - } - } - if (cliRC != SQL_SUCCESS && cliRC != SQL_SUCCESS_WITH_INFO) { - throw db2_soci_error("Commit failed",cliRC); - } - } -} - -void db2_session_backend::rollback() -{ - if (!autocommit || in_transaction) { - in_transaction = false; - SQLRETURN cliRC = SQLEndTran(SQL_HANDLE_DBC,hDbc,SQL_ROLLBACK); - if(autocommit) - { - SQLRETURN cliRC2 = SQLSetConnectAttr(hDbc, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER) SQL_AUTOCOMMIT_ON, SQL_NTS); - if ((cliRC == SQL_SUCCESS || cliRC == SQL_SUCCESS_WITH_INFO) && - cliRC2 != SQL_SUCCESS && cliRC2 != SQL_SUCCESS_WITH_INFO) - { - std::string msg=db2_soci_error::sqlState("Setting the autocommit attribute failed", SQL_HANDLE_DBC, hDbc); - SQLFreeHandle(SQL_HANDLE_DBC,hDbc); - SQLFreeHandle(SQL_HANDLE_ENV,hEnv); - throw db2_soci_error(msg,cliRC); - } - } - if (cliRC != SQL_SUCCESS && cliRC != SQL_SUCCESS_WITH_INFO) { - throw db2_soci_error("Rollback failed",cliRC); - } - } -} - -void db2_session_backend::clean_up() -{ - // if a transaction is in progress, it will automatically be rolled back upon when the connection is disconnected/freed - in_transaction = false; - - SQLDisconnect(hDbc); - SQLFreeHandle(SQL_HANDLE_DBC,hDbc); - SQLFreeHandle(SQL_HANDLE_ENV,hEnv); -} - -db2_statement_backend * db2_session_backend::make_statement_backend() -{ - return new db2_statement_backend(*this); -} - -db2_rowid_backend * db2_session_backend::make_rowid_backend() -{ - return new db2_rowid_backend(*this); -} - -db2_blob_backend * db2_session_backend::make_blob_backend() -{ - return new db2_blob_backend(*this); -} diff --git a/src/soci/src/backends/db2/standard-into-type.cpp b/src/soci/src/backends/db2/standard-into-type.cpp deleted file mode 100644 index 97e6db6ea8..0000000000 --- a/src/soci/src/backends/db2/standard-into-type.cpp +++ /dev/null @@ -1,163 +0,0 @@ -// -// Copyright (C) 2011-2013 Denis Chapligin -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_DB2_SOURCE -#include "soci/db2/soci-db2.h" -#include "soci-exchange-cast.h" -#include "soci-mktime.h" -#include "common.h" -#include - -using namespace soci; -using namespace soci::details; - - -void db2_standard_into_type_backend::define_by_pos( - int & position, void * data, exchange_type type) -{ - this->data = data; - this->type = type; - this->position = position; - position++; - - SQLUINTEGER size = 0; - - switch (type) - { - case x_char: - cType = SQL_C_CHAR; - size = sizeof(char) + 1; - buf = new char[size]; - data = buf; - break; - case x_stdstring: - cType = SQL_C_CHAR; - // Patch: set to min between column size and 100MB (used ot be 32769) - // Column size for text data type can be too large for buffer allocation - size = static_cast(statement_.column_size(this->position)); - size = size > details::db2::cli_max_buffer ? details::db2::cli_max_buffer : size; - size++; - buf = new char[size]; - data = buf; - break; - case x_short: - cType = SQL_C_SSHORT; - size = sizeof(short); - break; - case x_integer: - cType = SQL_C_SLONG; - size = sizeof(SQLINTEGER); - break; - case x_long_long: - cType = SQL_C_SBIGINT; - size = sizeof(long long); - break; - case x_unsigned_long_long: - cType = SQL_C_UBIGINT; - size = sizeof(unsigned long long); - break; - case x_double: - cType = SQL_C_DOUBLE; - size = sizeof(double); - break; - case x_stdtm: - cType = SQL_C_TYPE_TIMESTAMP; - size = sizeof(TIMESTAMP_STRUCT); - buf = new char[size]; - data = buf; - break; - case x_rowid: - cType = SQL_C_UBIGINT; - size = sizeof(unsigned long long); - break; - default: - throw soci_error("Into element used with non-supported type."); - } - - valueLen = 0; - - SQLRETURN cliRC = SQLBindCol(statement_.hStmt, static_cast(this->position), - static_cast(cType), data, size, &valueLen); - if (cliRC != SQL_SUCCESS) - { - throw db2_soci_error("Error while pre-fething into type",cliRC); - } -} - -void db2_standard_into_type_backend::pre_fetch() -{ - //... -} - -void db2_standard_into_type_backend::post_fetch( - bool gotData, bool calledFromFetch, indicator * ind) -{ - if (calledFromFetch == true && gotData == false) - { - // this is a normal end-of-rowset condition, - // no need to do anything (fetch() will return false) - return; - } - - if (gotData) - { - // first, deal with indicators - if (SQL_NULL_DATA == valueLen) - { - if (ind == NULL) - { - throw soci_error( - "Null value fetched and no indicator defined."); - } - - *ind = i_null; - return; - } - else - { - if (ind != NULL) - { - *ind = i_ok; - } - } - - // only std::string and std::tm need special handling - if (type == x_char) - { - exchange_type_cast(data) = buf[0]; - } - if (type == x_stdstring) - { - std::string& s = exchange_type_cast(data); - s = buf; - if (s.size() >= (details::db2::cli_max_buffer - 1)) - { - throw soci_error("Buffer size overflow; maybe got too large string"); - } - } - else if (type == x_stdtm) - { - std::tm& t = exchange_type_cast(data); - - TIMESTAMP_STRUCT * ts = reinterpret_cast(buf); - - details::mktime_from_ymdhms(t, - ts->year, ts->month, ts->day, - ts->hour, ts->minute, ts->second); - } - } -} - -void db2_standard_into_type_backend::clean_up() -{ - if (buf) - { - delete [] buf; - buf = 0; - } -} diff --git a/src/soci/src/backends/db2/standard-use-type.cpp b/src/soci/src/backends/db2/standard-use-type.cpp deleted file mode 100644 index 6c935fa022..0000000000 --- a/src/soci/src/backends/db2/standard-use-type.cpp +++ /dev/null @@ -1,204 +0,0 @@ -// -// Copyright (C) 2011-2013 Denis Chapligin -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#define SOCI_DB2_SOURCE -#include "soci/soci-platform.h" -#include "soci/db2/soci-db2.h" -#include "soci-exchange-cast.h" -#include -#include -#include -#include -#include - -using namespace soci; -using namespace soci::details; - -void *db2_standard_use_type_backend::prepare_for_bind( - void *data, SQLLEN &size, SQLSMALLINT &sqlType, SQLSMALLINT &cType) -{ - switch (type) - { - // simple cases - case x_short: - sqlType = SQL_SMALLINT; - cType = SQL_C_SSHORT; - size = sizeof(short); - break; - case x_integer: - sqlType = SQL_INTEGER; - cType = SQL_C_SLONG; - size = sizeof(int); - break; - case x_long_long: - sqlType = SQL_BIGINT; - cType = SQL_C_SBIGINT; - size = sizeof(long long); - break; - case x_unsigned_long_long: - sqlType = SQL_BIGINT; - cType = SQL_C_UBIGINT; - size = sizeof(unsigned long long); - break; - case x_double: - sqlType = SQL_DOUBLE; - cType = SQL_C_DOUBLE; - size = sizeof(double); - break; - - // cases that require adjustments and buffer management - case x_char: - { - sqlType = SQL_CHAR; - cType = SQL_C_CHAR; - size = sizeof(char) + 1; - buf = new char[size]; - buf[0] = exchange_type_cast(data); - buf[1] = '\0'; - ind = SQL_NTS; - } - break; - case x_stdstring: - { - // TODO: No textual value is assigned here! - - std::string const& s = exchange_type_cast(data); - sqlType = SQL_LONGVARCHAR; - cType = SQL_C_CHAR; - size = static_cast(s.size()) + 1; - buf = new char[size]; - strncpy(buf, s.c_str(), size); - ind = SQL_NTS; - } - break; - case x_stdtm: - { - sqlType = SQL_TIMESTAMP; - cType = SQL_C_TIMESTAMP; - buf = new char[sizeof(TIMESTAMP_STRUCT)]; - std::tm const& t = exchange_type_cast(data); - data = buf; - size = 19; // This number is not the size in bytes, but the number - // of characters in the date if it was written out - // yyyy-mm-dd hh:mm:ss - - TIMESTAMP_STRUCT * ts = reinterpret_cast(buf); - - ts->year = static_cast(t.tm_year + 1900); - ts->month = static_cast(t.tm_mon + 1); - ts->day = static_cast(t.tm_mday); - ts->hour = static_cast(t.tm_hour); - ts->minute = static_cast(t.tm_min); - ts->second = static_cast(t.tm_sec); - ts->fraction = 0; - } - break; - - case x_blob: - case x_xmltype: - case x_longstring: - break; - case x_statement: - case x_rowid: - break; - } - - // Return either the pointer to C++ data itself or the buffer that we - // allocated, if any. - return buf ? buf : data; -} - -void db2_standard_use_type_backend::bind_by_pos( - int &position, void *data, exchange_type type, bool /* readOnly */) -{ - if (statement_.use_binding_method_ == details::db2::BOUND_BY_NAME) - { - throw soci_error("Binding for use elements must be either by position or by name."); - } - statement_.use_binding_method_ = details::db2::BOUND_BY_POSITION; - - this->data = data; // for future reference - this->type = type; // for future reference - this->position = position++; -} - -void db2_standard_use_type_backend::bind_by_name( - std::string const &name, void *data, exchange_type type, bool /* readOnly */) -{ - if (statement_.use_binding_method_ == details::db2::BOUND_BY_POSITION) - { - throw soci_error("Binding for use elements must be either by position or by name."); - } - statement_.use_binding_method_ = details::db2::BOUND_BY_NAME; - - int position = -1; - int count = 1; - - for (std::vector::iterator it = statement_.names_.begin(); - it != statement_.names_.end(); ++it) - { - if (*it == name) - { - position = count; - break; - } - count++; - } - - if (position != -1) - { - this->data = data; // for future reference - this->type = type; // for future reference - this->position = position; - } - else - { - std::ostringstream ss; - ss << "Unable to find name '" << name << "' to bind to"; - throw soci_error(ss.str().c_str()); - } -} - -void db2_standard_use_type_backend::pre_use(indicator const *ind_ptr) -{ - // first deal with data - SQLSMALLINT sqlType; - SQLSMALLINT cType; - SQLLEN size; - - void *sqlData = prepare_for_bind(data, size, sqlType, cType); - - SQLRETURN cliRC = SQLBindParameter(statement_.hStmt, - static_cast(position), - SQL_PARAM_INPUT, - cType, sqlType, size, 0, sqlData, size, &ind); - - if (cliRC != SQL_SUCCESS) - { - throw db2_soci_error("Error while binding value",cliRC); - } - - // then handle indicators - if (ind_ptr != NULL && *ind_ptr == i_null) - { - ind = SQL_NULL_DATA; // null - } -} - -void db2_standard_use_type_backend::post_use(bool /*gotData*/, indicator* /*ind*/) -{ - -} - -void db2_standard_use_type_backend::clean_up() -{ - if (buf != NULL) - { - delete [] buf; - buf = NULL; - } -} diff --git a/src/soci/src/backends/db2/statement.cpp b/src/soci/src/backends/db2/statement.cpp deleted file mode 100644 index 73b7432bbd..0000000000 --- a/src/soci/src/backends/db2/statement.cpp +++ /dev/null @@ -1,322 +0,0 @@ -// -// Copyright (C) 2011-2013 Denis Chapligin -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_DB2_SOURCE -#include "soci/db2/soci-db2.h" -#include - -using namespace soci; -using namespace soci::details; - -db2_statement_backend::db2_statement_backend(db2_session_backend &session) - : session_(session),hasVectorUseElements(false),use_binding_method_(details::db2::BOUND_BY_NONE) -{ -} - -void db2_statement_backend::alloc() -{ - SQLRETURN cliRC = SQL_SUCCESS; - - cliRC = SQLAllocHandle(SQL_HANDLE_STMT,session_.hDbc,&hStmt); - if (cliRC != SQL_SUCCESS) { - throw db2_soci_error("Error while allocation statement handle",cliRC); - } -} - -void db2_statement_backend::clean_up() -{ - SQLRETURN cliRC = SQL_SUCCESS; - - cliRC=SQLFreeHandle(SQL_HANDLE_STMT,hStmt); - if (cliRC != SQL_SUCCESS) { - throw db2_soci_error(db2_soci_error::sqlState("Statement handle clean-up error",SQL_HANDLE_STMT,hStmt),cliRC); - } -} - -void db2_statement_backend::prepare(std::string const & query , - statement_type /* eType */) -{ - // rewrite the query by transforming all named parameters into - // the markers (:abc -> ?, etc.) - - enum { normal, in_quotes, in_name } state = normal; - - std::string name; - - for (std::string::const_iterator it = query.begin(), end = query.end(); - it != end; ++it) - { - switch (state) - { - case normal: - if (*it == '\'') - { - query_ += *it; - state = in_quotes; - } - else if (*it == ':') - { - // Check whether this is a cast operator (e.g. 23::float) - // and treat it as a special case, not as a named binding - const std::string::const_iterator next_it = it + 1; - if ((next_it != end) && (*next_it == ':')) - { - query_ += "::"; - ++it; - } - else - { - state = in_name; - } - } - else // regular character, stay in the same state - { - query_ += *it; - } - break; - case in_quotes: - if (*it == '\'') - { - query_ += *it; - state = normal; - } - else // regular quoted character - { - query_ += *it; - } - break; - case in_name: - if (std::isalnum(*it) || *it == '_') - { - name += *it; - } - else // end of name - { - names_.push_back(name); - name.clear(); - std::ostringstream ss; - ss << '?'; - query_ += ss.str(); - query_ += *it; - state = normal; - - } - break; - } - } - - if (state == in_name) - { - names_.push_back(name); - std::ostringstream ss; - ss << '?'; - query_ += ss.str(); - } - - SQLRETURN cliRC = SQLPrepare(hStmt, const_cast((const SQLCHAR *) query_.c_str()), SQL_NTS); - if (cliRC!=SQL_SUCCESS) { - throw db2_soci_error("Error while preparing query",cliRC); - } -} - -statement_backend::exec_fetch_result -db2_statement_backend::execute(int number ) -{ - SQLUINTEGER rows_processed = 0; - SQLRETURN cliRC; - - if (hasVectorUseElements) - { - SQLSetStmtAttr(hStmt, SQL_ATTR_PARAMS_PROCESSED_PTR, &rows_processed, 0); - } - - // if we are called twice for the same statement we need to close the open - // cursor or an "invalid cursor state" error will occur on execute - cliRC = SQLFreeStmt(hStmt,SQL_CLOSE); - if (cliRC != SQL_SUCCESS) - { - throw db2_soci_error(db2_soci_error::sqlState("Statement execution error",SQL_HANDLE_STMT,hStmt),cliRC); - } - - cliRC = SQLExecute(hStmt); - if (cliRC != SQL_SUCCESS && cliRC != SQL_SUCCESS_WITH_INFO && cliRC != SQL_NO_DATA) - { - throw db2_soci_error(db2_soci_error::sqlState("Statement execution error",SQL_HANDLE_STMT,hStmt),cliRC); - } - - SQLSMALLINT colCount; - SQLNumResultCols(hStmt, &colCount); - - if (number > 0 && colCount > 0) - { - return fetch(number); - } - - return ef_success; -} - -statement_backend::exec_fetch_result -db2_statement_backend::fetch(int number ) -{ - numRowsFetched = 0; - - SQLSetStmtAttr(hStmt, SQL_ATTR_ROW_BIND_TYPE, SQL_BIND_BY_COLUMN, 0); - SQLSetStmtAttr(hStmt, SQL_ATTR_ROW_ARRAY_SIZE, db2::int_as_ptr(number), 0); - SQLSetStmtAttr(hStmt, SQL_ATTR_ROWS_FETCHED_PTR, &numRowsFetched, 0); - - SQLRETURN cliRC = SQLFetch(hStmt); - - if (SQL_NO_DATA == cliRC) - { - return ef_no_data; - } - - if (cliRC != SQL_SUCCESS && cliRC != SQL_SUCCESS_WITH_INFO) - { - throw db2_soci_error(db2_soci_error::sqlState("Error while fetching data", SQL_HANDLE_STMT, hStmt), cliRC); - } - - return ef_success; -} - -long long db2_statement_backend::get_affected_rows() -{ - SQLLEN rows; - - SQLRETURN cliRC = SQLRowCount(hStmt, &rows); - if (cliRC != SQL_SUCCESS && cliRC != SQL_SUCCESS_WITH_INFO) - { - throw db2_soci_error(db2_soci_error::sqlState("Error while getting affected row count", SQL_HANDLE_STMT, hStmt), cliRC); - } - else if (rows == -1) - { - throw soci_error("Error getting affected row count: statement did not perform an update, insert, delete, or merge"); - } - - return rows; -} - -int db2_statement_backend::get_number_of_rows() -{ - return numRowsFetched; -} - -std::string db2_statement_backend::get_parameter_name(int index) const -{ - return names_.at(index); -} - -std::string db2_statement_backend::rewrite_for_procedure_call( - std::string const &query) -{ - return query; -} - -int db2_statement_backend::prepare_for_describe() -{ - SQLSMALLINT numCols; - SQLNumResultCols(hStmt, &numCols); - return numCols; -} - -void db2_statement_backend::describe_column(int colNum, - data_type & type, std::string & columnName ) -{ -SQLCHAR colNameBuffer[2048]; - SQLSMALLINT colNameBufferOverflow; - SQLSMALLINT dataType; - SQLULEN colSize; - SQLSMALLINT decDigits; - SQLSMALLINT isNullable; - - SQLRETURN cliRC = SQLDescribeCol(hStmt, static_cast(colNum), - colNameBuffer, 2048, - &colNameBufferOverflow, &dataType, - &colSize, &decDigits, &isNullable); - - if (cliRC != SQL_SUCCESS) - { - throw db2_soci_error(db2_soci_error::sqlState("Error while describing column",SQL_HANDLE_STMT,hStmt),cliRC); - } - - char const *name = reinterpret_cast(colNameBuffer); - columnName.assign(name, std::strlen(name)); - - switch (dataType) - { - case SQL_TYPE_DATE: - case SQL_TYPE_TIME: - case SQL_TYPE_TIMESTAMP: - type = dt_date; - break; - case SQL_DOUBLE: - case SQL_DECIMAL: - case SQL_REAL: - case SQL_FLOAT: - case SQL_NUMERIC: - type = dt_double; - break; - case SQL_TINYINT: - case SQL_SMALLINT: - case SQL_INTEGER: - type = dt_integer; - break; - case SQL_BIGINT: - type = dt_long_long; - break; - case SQL_CHAR: - case SQL_VARCHAR: - case SQL_LONGVARCHAR: - default: - type = dt_string; - break; - } -} - -size_t db2_statement_backend::column_size(int col) { - SQLCHAR colNameBuffer[2048]; - SQLSMALLINT colNameBufferOverflow; - SQLSMALLINT dataType; - SQLULEN colSize; - SQLSMALLINT decDigits; - SQLSMALLINT isNullable; - - SQLRETURN cliRC = SQLDescribeCol(hStmt, static_cast(col), - colNameBuffer, 2048, - &colNameBufferOverflow, &dataType, - &colSize, &decDigits, &isNullable); - - if (cliRC != SQL_SUCCESS) - { - throw db2_soci_error(db2_soci_error::sqlState("Error while detecting column size",SQL_HANDLE_STMT,hStmt),cliRC); - } - - return colSize; -} - -db2_standard_into_type_backend * db2_statement_backend::make_into_type_backend() -{ - return new db2_standard_into_type_backend(*this); -} - -db2_standard_use_type_backend * db2_statement_backend::make_use_type_backend() -{ - return new db2_standard_use_type_backend(*this); -} - -db2_vector_into_type_backend * -db2_statement_backend::make_vector_into_type_backend() -{ - return new db2_vector_into_type_backend(*this); -} - -db2_vector_use_type_backend * db2_statement_backend::make_vector_use_type_backend() -{ - hasVectorUseElements = true; - return new db2_vector_use_type_backend(*this); -} diff --git a/src/soci/src/backends/db2/vector-into-type.cpp b/src/soci/src/backends/db2/vector-into-type.cpp deleted file mode 100644 index 2e5932d83a..0000000000 --- a/src/soci/src/backends/db2/vector-into-type.cpp +++ /dev/null @@ -1,427 +0,0 @@ -// -// Copyright (C) 2011-2013 Denis Chapligin -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_DB2_SOURCE -#include "soci/db2/soci-db2.h" -#include "soci-mktime.h" -#include -#include -#include -#include -#include - -using namespace soci; -using namespace soci::details; - -void db2_vector_into_type_backend::prepare_indicators(std::size_t size) -{ - if (size == 0) - { - throw soci_error("Vectors of size 0 are not allowed."); - } - - indVec.resize(size); - indptr = &indVec[0]; -} - -void db2_vector_into_type_backend::define_by_pos( - int &position, void *data, exchange_type type) -{ - this->data = data; // for future reference - this->type = type; // for future reference - - SQLINTEGER size = 0; // also dummy - - switch (type) - { - // simple cases - case x_short: - { - cType = SQL_C_SSHORT; - size = sizeof(short); - std::vector *vp = static_cast *>(data); - std::vector &v(*vp); - prepare_indicators(v.size()); - data = &v[0]; - } - break; - case x_integer: - { - cType = SQL_C_SLONG; - size = sizeof(SQLINTEGER); - std::vector *vp = static_cast *>(data); - std::vector &v(*vp); - prepare_indicators(v.size()); - data = &v[0]; - } - break; - case x_long_long: - { - cType = SQL_C_SBIGINT; - size = sizeof(long long); - std::vector *vp - = static_cast *>(data); - std::vector &v(*vp); - prepare_indicators(v.size()); - data = &v[0]; - } - break; - case x_unsigned_long_long: - { - cType = SQL_C_UBIGINT; - size = sizeof(unsigned long long); - std::vector *vp - = static_cast *>(data); - std::vector &v(*vp); - prepare_indicators(v.size()); - data = &v[0]; - } - break; - case x_double: - { - cType = SQL_C_DOUBLE; - size = sizeof(double); - std::vector *vp = static_cast *>(data); - std::vector &v(*vp); - prepare_indicators(v.size()); - data = &v[0]; - } - break; - - // cases that require adjustments and buffer management - - case x_char: - { - cType = SQL_C_CHAR; - - std::vector *v - = static_cast *>(data); - - prepare_indicators(v->size()); - - size = sizeof(char) * 2; - std::size_t bufSize = size * v->size(); - - colSize = size; - - buf = new char[bufSize]; - data = buf; - } - break; - case x_stdstring: - { - cType = SQL_C_CHAR; - std::vector *v - = static_cast *>(data); - colSize = statement_.column_size(position) + 1; - std::size_t bufSize = colSize * v->size(); - buf = new char[bufSize]; - - prepare_indicators(v->size()); - - size = static_cast(colSize); - data = buf; - } - break; - case x_stdtm: - { - cType = SQL_C_TYPE_TIMESTAMP; - std::vector *v - = static_cast *>(data); - - prepare_indicators(v->size()); - - size = sizeof(TIMESTAMP_STRUCT); - colSize = size; - - std::size_t bufSize = size * v->size(); - - buf = new char[bufSize]; - data = buf; - } - break; - - case x_statement: - case x_rowid: - case x_blob: - case x_xmltype: - case x_longstring: - throw soci_error("Unsupported type for vector into parameter"); - } - - SQLRETURN cliRC = SQLBindCol(statement_.hStmt, static_cast(position++), - cType, data, size, indptr); - if (cliRC != SQL_SUCCESS) - { - throw db2_soci_error("Error while pre-fetching into vector",cliRC); - } -} - -void db2_vector_into_type_backend::pre_fetch() -{ - // nothing to do for the supported types -} - -void db2_vector_into_type_backend::post_fetch(bool gotData, indicator *ind) -{ - if (gotData) - { - // first, deal with data - - // only std::string, std::tm and Statement need special handling - if (type == x_char) - { - std::vector *vp - = static_cast *>(data); - - std::vector &v(*vp); - char *pos = buf; - std::size_t const vsize = v.size(); - for (std::size_t i = 0; i != vsize; ++i) - { - v[i] = *pos; - pos += colSize; - } - } - if (type == x_stdstring) - { - std::vector *vp - = static_cast *>(data); - - std::vector &v(*vp); - - const char *pos = buf; - std::size_t const vsize = v.size(); - for (std::size_t i = 0; i != vsize; ++i, pos += colSize) - { - // See ODBC backend for explanation, this code for determining - // the string length is exactly the same as there. - SQLLEN const len = indVec[i]; - if (len == -1) - { - v[i].clear(); - continue; - } - - const char* end = pos + len; - while (end != pos) - { - if (*--end != ' ') - { - ++end; - break; - } - } - - v[i].assign(pos, end - pos); - } - } - else if (type == x_stdtm) - { - std::vector *vp - = static_cast *>(data); - - std::vector &v(*vp); - char *pos = buf; - std::size_t const vsize = v.size(); - for (std::size_t i = 0; i != vsize; ++i) - { - TIMESTAMP_STRUCT * ts = reinterpret_cast(pos); - details::mktime_from_ymdhms(v[i], - ts->year, ts->month, ts->day, - ts->hour, ts->minute, ts->second); - pos += colSize; - } - } - - // then - deal with indicators - if (ind != NULL) - { - std::size_t const indSize = statement_.get_number_of_rows(); - for (std::size_t i = 0; i != indSize; ++i) - { - if (indVec[i] > 0) - { - ind[i] = i_ok; - } - else if (indVec[i] == SQL_NULL_DATA) - { - ind[i] = i_null; - } - else - { - ind[i] = i_truncated; - } - } - } - else - { - std::size_t const indSize = statement_.get_number_of_rows(); - for (std::size_t i = 0; i != indSize; ++i) - { - if (indVec[i] == SQL_NULL_DATA) - { - // fetched null and no indicator - programming error! - throw soci_error( - "Null value fetched and no indicator defined."); - } - } - } - } - else // gotData == false - { - // nothing to do here, vectors are truncated anyway - } -} - -void db2_vector_into_type_backend::resize(std::size_t sz) -{ - indVec.resize(sz); - switch (type) - { - // simple cases - case x_char: - { - std::vector *v = static_cast *>(data); - v->resize(sz); - } - break; - case x_short: - { - std::vector *v = static_cast *>(data); - v->resize(sz); - } - break; - case x_integer: - { - std::vector *v = static_cast *>(data); - v->resize(sz); - } - break; - case x_long_long: - { - std::vector *v - = static_cast *>(data); - v->resize(sz); - } - break; - case x_unsigned_long_long: - { - std::vector *v - = static_cast *>(data); - v->resize(sz); - } - break; - case x_double: - { - std::vector *v - = static_cast *>(data); - v->resize(sz); - } - break; - case x_stdstring: - { - std::vector *v - = static_cast *>(data); - v->resize(sz); - } - break; - case x_stdtm: - { - std::vector *v - = static_cast *>(data); - v->resize(sz); - } - break; - - case x_statement: break; // not supported - case x_rowid: break; // not supported - case x_blob: break; // not supported - case x_xmltype: break; // not supported - case x_longstring:break; // not supported - } -} - -std::size_t db2_vector_into_type_backend::size() -{ - std::size_t sz = 0; // dummy initialization to please the compiler - switch (type) - { - // simple cases - case x_char: - { - std::vector *v = static_cast *>(data); - sz = v->size(); - } - break; - case x_short: - { - std::vector *v = static_cast *>(data); - sz = v->size(); - } - break; - case x_integer: - { - std::vector *v = static_cast *>(data); - sz = v->size(); - } - break; - case x_long_long: - { - std::vector *v - = static_cast *>(data); - sz = v->size(); - } - break; - case x_unsigned_long_long: - { - std::vector *v - = static_cast *>(data); - sz = v->size(); - } - break; - case x_double: - { - std::vector *v - = static_cast *>(data); - sz = v->size(); - } - break; - case x_stdstring: - { - std::vector *v - = static_cast *>(data); - sz = v->size(); - } - break; - case x_stdtm: - { - std::vector *v - = static_cast *>(data); - sz = v->size(); - } - break; - - case x_statement: break; // not supported - case x_rowid: break; // not supported - case x_blob: break; // not supported - case x_xmltype: break; // not supported - case x_longstring:break; // not supported - } - - return sz; -} - -void db2_vector_into_type_backend::clean_up() -{ - if (buf != NULL) - { - delete [] buf; - buf = NULL; - } -} diff --git a/src/soci/src/backends/db2/vector-use-type.cpp b/src/soci/src/backends/db2/vector-use-type.cpp deleted file mode 100644 index dc1cca9910..0000000000 --- a/src/soci/src/backends/db2/vector-use-type.cpp +++ /dev/null @@ -1,402 +0,0 @@ -// -// Copyright (C) 2011-2013 Denis Chapligin -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_DB2_SOURCE -#include "soci/soci-platform.h" -#include "soci/db2/soci-db2.h" -#include -#include -#include -#include -#include - -#ifdef _MSC_VER -// disables the warning about converting int to void*. This is a 64 bit compatibility -// warning, but odbc requires the value to be converted on this line -// SQLSetStmtAttr(statement_.hstmt_, SQL_ATTR_PARAMSET_SIZE, (SQLPOINTER)arraySize, 0); -#pragma warning(disable:4312) -#endif - - -using namespace soci; -using namespace soci::details; - -void db2_vector_use_type_backend::prepare_indicators(std::size_t size) -{ - if (size == 0) - { - throw soci_error("Vectors of size 0 are not allowed."); - } - - indVec.resize(size); - indptr = &indVec[0]; -} - -void db2_vector_use_type_backend::prepare_for_bind(void *&data, SQLUINTEGER &size, - SQLSMALLINT &sqlType, SQLSMALLINT &cType) -{ - switch (type) - { // simple cases - case x_short: - { - sqlType = SQL_SMALLINT; - cType = SQL_C_SSHORT; - size = sizeof(short); - std::vector *vp = static_cast *>(data); - std::vector &v(*vp); - prepare_indicators(v.size()); - data = &v[0]; - } - break; - case x_integer: - { - sqlType = SQL_INTEGER; - cType = SQL_C_SLONG; - size = sizeof(int); - std::vector *vp = static_cast *>(data); - std::vector &v(*vp); - prepare_indicators(v.size()); - data = &v[0]; - } - break; - case x_long_long: - { - sqlType = SQL_BIGINT; - cType = SQL_C_SBIGINT; - size = sizeof(long long); - std::vector *vp - = static_cast *>(data); - std::vector &v(*vp); - prepare_indicators(v.size()); - data = &v[0]; - } - break; - case x_unsigned_long_long: - { - sqlType = SQL_BIGINT; - cType = SQL_C_UBIGINT; - size = sizeof(unsigned long long); - std::vector *vp - = static_cast *>(data); - std::vector &v(*vp); - prepare_indicators(v.size()); - data = &v[0]; - } - break; - case x_double: - { - sqlType = SQL_DOUBLE; - cType = SQL_C_DOUBLE; - size = sizeof(double); - std::vector *vp = static_cast *>(data); - std::vector &v(*vp); - prepare_indicators(v.size()); - data = &v[0]; - } - break; - - // cases that require adjustments and buffer management - case x_char: - { - std::vector *vp - = static_cast *>(data); - std::size_t const vsize = vp->size(); - - prepare_indicators(vsize); - - size = sizeof(char) * 2; - buf = new char[size * vsize]; - - char *pos = buf; - - for (std::size_t i = 0; i != vsize; ++i) - { - *pos++ = (*vp)[i]; - *pos++ = 0; - } - - sqlType = SQL_CHAR; - cType = SQL_C_CHAR; - data = buf; - } - break; - case x_stdstring: - { - sqlType = SQL_CHAR; - cType = SQL_C_CHAR; - - std::vector *vp - = static_cast *>(data); - std::vector &v(*vp); - - std::size_t maxSize = 0; - std::size_t const vecSize = v.size(); - prepare_indicators(vecSize); - for (std::size_t i = 0; i != vecSize; ++i) - { - std::size_t sz = v[i].length(); - indVec[i] = static_cast(sz); - maxSize = sz > maxSize ? sz : maxSize; - } - - maxSize++; // For terminating nul. - - buf = new char[maxSize * vecSize]; - memset(buf, 0, maxSize * vecSize); - - char *pos = buf; - for (std::size_t i = 0; i != vecSize; ++i) - { - memcpy(pos, v[i].c_str(), v[i].length()); - pos += maxSize; - } - - data = buf; - size = static_cast(maxSize); - } - break; - case x_stdtm: - { - std::vector *vp - = static_cast *>(data); - - prepare_indicators(vp->size()); - - buf = new char[sizeof(TIMESTAMP_STRUCT) * vp->size()]; - - sqlType = SQL_TYPE_TIMESTAMP; - cType = SQL_C_TYPE_TIMESTAMP; - data = buf; - size = 19; // This number is not the size in bytes, but the number - // of characters in the date if it was written out - // yyyy-mm-dd hh:mm:ss - } - break; - - case x_statement: break; // not supported - case x_rowid: break; // not supported - case x_blob: break; // not supported - case x_xmltype: break; // not supported - case x_longstring:break; // not supported - } - - colSize = size; -} - -void db2_vector_use_type_backend::bind_helper(int &position, void *data, details::exchange_type type) -{ - this->data = data; // for future reference - this->type = type; // for future reference - - SQLSMALLINT sqlType; - SQLSMALLINT cType; - SQLUINTEGER size; - - prepare_for_bind(data, size, sqlType, cType); - - SQLINTEGER arraySize = (SQLINTEGER)indVec.size(); - SQLSetStmtAttr(statement_.hStmt, SQL_ATTR_PARAMSET_SIZE, db2::int_as_ptr(arraySize), 0); - - SQLRETURN cliRC = SQLBindParameter(statement_.hStmt, static_cast(position++), - SQL_PARAM_INPUT, cType, sqlType, size, 0, - static_cast(data), size, indptr); - - if ( cliRC != SQL_SUCCESS ) - { - throw db2_soci_error("Error while binding value to column", cliRC); - } -} - -void db2_vector_use_type_backend::bind_by_pos(int &position, - void *data, exchange_type type) -{ - if (statement_.use_binding_method_ == details::db2::BOUND_BY_NAME) - { - throw soci_error("Binding for use elements must be either by position or by name."); - } - statement_.use_binding_method_ = details::db2::BOUND_BY_POSITION; - - bind_helper(position, data, type); -} - -void db2_vector_use_type_backend::bind_by_name( - std::string const &name, void *data, exchange_type type) -{ - int position = -1; - int count = 1; - - if (statement_.use_binding_method_ == details::db2::BOUND_BY_POSITION) - { - throw soci_error("Binding for use elements must be either by position or by name."); - } - statement_.use_binding_method_ = details::db2::BOUND_BY_NAME; - - for (std::vector::iterator it = statement_.names_.begin(); - it != statement_.names_.end(); ++it) - { - if (*it == name) - { - position = count; - break; - } - count++; - } - - if (position != -1) - { - bind_helper(position, data, type); - } - else - { - std::ostringstream ss; - ss << "Unable to find name '" << name << "' to bind to"; - throw soci_error(ss.str().c_str()); - } -} - -void db2_vector_use_type_backend::pre_use(indicator const *ind) -{ - // first deal with data - if (type == x_stdtm) - { - std::vector *vp - = static_cast *>(data); - - std::vector &v(*vp); - - char *pos = buf; - std::size_t const vsize = v.size(); - for (std::size_t i = 0; i != vsize; ++i) - { - std::tm t = v[i]; - TIMESTAMP_STRUCT * ts = reinterpret_cast(pos); - - ts->year = static_cast(t.tm_year + 1900); - ts->month = static_cast(t.tm_mon + 1); - ts->day = static_cast(t.tm_mday); - ts->hour = static_cast(t.tm_hour); - ts->minute = static_cast(t.tm_min); - ts->second = static_cast(t.tm_sec); - ts->fraction = 0; - pos += sizeof(TIMESTAMP_STRUCT); - } - } - - // then handle indicators - if (ind != NULL) - { - std::size_t const vsize = size(); - for (std::size_t i = 0; i != vsize; ++i, ++ind) - { - if (*ind == i_null) - { - indVec[i] = SQL_NULL_DATA; // null - } - else - { - // for strings we have already set the values - if (type != x_stdstring) - { - indVec[i] = SQL_NTS; // value is OK - } - } - } - } - else - { - // no indicators - treat all fields as OK - std::size_t const vsize = size(); - for (std::size_t i = 0; i != vsize; ++i) - { - // for strings we have already set the values - if (type != x_stdstring) - { - indVec[i] = SQL_NTS; // value is OK - } - } - } -} - -std::size_t db2_vector_use_type_backend::size() -{ - std::size_t sz = 0; // dummy initialization to please the compiler - switch (type) - { - // simple cases - case x_char: - { - std::vector *vp = static_cast *>(data); - sz = vp->size(); - } - break; - case x_short: - { - std::vector *vp = static_cast *>(data); - sz = vp->size(); - } - break; - case x_integer: - { - std::vector *vp = static_cast *>(data); - sz = vp->size(); - } - break; - case x_long_long: - { - std::vector *vp - = static_cast *>(data); - sz = vp->size(); - } - break; - case x_unsigned_long_long: - { - std::vector *vp - = static_cast *>(data); - sz = vp->size(); - } - break; - case x_double: - { - std::vector *vp - = static_cast *>(data); - sz = vp->size(); - } - break; - case x_stdstring: - { - std::vector *vp - = static_cast *>(data); - sz = vp->size(); - } - break; - case x_stdtm: - { - std::vector *vp - = static_cast *>(data); - sz = vp->size(); - } - break; - - case x_statement: break; // not supported - case x_rowid: break; // not supported - case x_blob: break; // not supported - case x_xmltype: break; // not supported - case x_longstring:break; // not supported - } - - return sz; -} - -void db2_vector_use_type_backend::clean_up() -{ - if (buf != NULL) - { - delete [] buf; - buf = NULL; - } -} diff --git a/src/soci/src/backends/empty/CMakeLists.txt b/src/soci/src/backends/empty/CMakeLists.txt deleted file mode 100644 index b09185b58b..0000000000 --- a/src/soci/src/backends/empty/CMakeLists.txt +++ /dev/null @@ -1,14 +0,0 @@ -############################################################################### -# -# This file is part of CMake configuration for SOCI library -# -# Copyright (C) 2010 Mateusz Loskot -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -# -############################################################################### -soci_backend(Empty - DESCRIPTION "SOCI backend skeleton for new backends development" - AUTHORS "Maciej Sobczak, Stephen Hutton" - MAINTAINERS "Maciej Sobczak") diff --git a/src/soci/src/backends/empty/Makefile.basic b/src/soci/src/backends/empty/Makefile.basic deleted file mode 100644 index 7fe0f91072..0000000000 --- a/src/soci/src/backends/empty/Makefile.basic +++ /dev/null @@ -1,88 +0,0 @@ -# The following variable is specific to this backend and its correct -# values might depend on your environment - feel free to set it accordingly. - -EMPTYINCLUDEDIR = - -# The rest of the Makefile is indepentent of the target environment. - -COMPILER = g++ -CXXFLAGS = -Wall -pedantic -Wno-long-long -CXXFLAGSSO = ${CXXFLAGS} -fPIC -INCLUDEDIRS = -I../../core ${EMPTYINCLUDEDIR} - - -OBJECTS = blob.o factory.o row-id.o session.o standard-into-type.o \ - standard-use-type.o statement.o vector-into-type.o vector-use-type.o - -OBJECTSSO = blob-s.o factory-s.o row-id-s.o session-s.o \ - standard-into-type-s.o standard-use-type-s.o statement-s.o \ - vector-into-type-s.o vector-use-type-s.o - - -libsoci_empty.a : ${OBJECTS} - ar rv $@ $? - rm *.o - - -blob.o : blob.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -factory.o : factory.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -row-id.o : row-id.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -session.o : session.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -standard-into-type.o : standard-into-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -standard-use-type.o : standard-use-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -statement.o : statement.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -vector-into-type.o : vector-into-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -vector-use-type.o : vector-use-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - - -shared : ${OBJECTSSO} - ${COMPILER} -shared -o libsoci_empty.so ${OBJECTSSO} - rm *.o - -blob-s.o : blob.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -factory-s.o : factory.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -row-id-s.o : row-id.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -session-s.o : session.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -standard-into-type-s.o : standard-into-type.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -standard-use-type-s.o : standard-use-type.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -statement-s.o : statement.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -vector-into-type-s.o : vector-into-type.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -vector-use-type-s.o : vector-use-type.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - - -clean : - rm -f libsoci_empty.a libsoci_empty.so diff --git a/src/soci/src/backends/empty/blob.cpp b/src/soci/src/backends/empty/blob.cpp deleted file mode 100644 index 06639959e5..0000000000 --- a/src/soci/src/backends/empty/blob.cpp +++ /dev/null @@ -1,61 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_EMPTY_SOURCE -#include "soci/empty/soci-empty.h" - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; - - -empty_blob_backend::empty_blob_backend(empty_session_backend &session) - : session_(session) -{ - // ... -} - -empty_blob_backend::~empty_blob_backend() -{ - // ... -} - -std::size_t empty_blob_backend::get_len() -{ - // ... - return 0; -} - -std::size_t empty_blob_backend::read( - std::size_t /* offset */, char * /* buf */, std::size_t /* toRead */) -{ - // ... - return 0; -} - -std::size_t empty_blob_backend::write( - std::size_t /* offset */, char const * /* buf */, - std::size_t /* toWrite */) -{ - // ... - return 0; -} - -std::size_t empty_blob_backend::append( - char const * /* buf */, std::size_t /* toWrite */) -{ - // ... - return 0; -} - -void empty_blob_backend::trim(std::size_t /* newLen */) -{ - // ... -} diff --git a/src/soci/src/backends/empty/factory.cpp b/src/soci/src/backends/empty/factory.cpp deleted file mode 100644 index f932623f35..0000000000 --- a/src/soci/src/backends/empty/factory.cpp +++ /dev/null @@ -1,42 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_EMPTY_SOURCE -#include "soci/empty/soci-empty.h" -#include "soci/backend-loader.h" - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; - -// concrete factory for Empty concrete strategies -empty_session_backend* empty_backend_factory::make_session( - connection_parameters const& parameters) const -{ - return new empty_session_backend(parameters); -} - -empty_backend_factory const soci::empty; - -extern "C" -{ - -// for dynamic backend loading -SOCI_EMPTY_DECL backend_factory const* factory_empty() -{ - return &soci::empty; -} - -SOCI_EMPTY_DECL void register_factory_empty() -{ - soci::dynamic_backends::register_backend("empty", soci::empty); -} - -} // extern "C" diff --git a/src/soci/src/backends/empty/row-id.cpp b/src/soci/src/backends/empty/row-id.cpp deleted file mode 100644 index 637c624fd7..0000000000 --- a/src/soci/src/backends/empty/row-id.cpp +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_EMPTY_SOURCE -#include "soci/empty/soci-empty.h" - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; - - -empty_rowid_backend::empty_rowid_backend(empty_session_backend & /* session */) -{ - // ... -} - -empty_rowid_backend::~empty_rowid_backend() -{ - // ... -} diff --git a/src/soci/src/backends/empty/session.cpp b/src/soci/src/backends/empty/session.cpp deleted file mode 100644 index 48521d5f61..0000000000 --- a/src/soci/src/backends/empty/session.cpp +++ /dev/null @@ -1,63 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_EMPTY_SOURCE -#include "soci/empty/soci-empty.h" - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; - - -empty_session_backend::empty_session_backend( - connection_parameters const & /* parameters */) -{ - // ... -} - -empty_session_backend::~empty_session_backend() -{ - clean_up(); -} - -void empty_session_backend::begin() -{ - // ... -} - -void empty_session_backend::commit() -{ - // ... -} - -void empty_session_backend::rollback() -{ - // ... -} - -void empty_session_backend::clean_up() -{ - // ... -} - -empty_statement_backend * empty_session_backend::make_statement_backend() -{ - return new empty_statement_backend(*this); -} - -empty_rowid_backend * empty_session_backend::make_rowid_backend() -{ - return new empty_rowid_backend(*this); -} - -empty_blob_backend * empty_session_backend::make_blob_backend() -{ - return new empty_blob_backend(*this); -} diff --git a/src/soci/src/backends/empty/standard-into-type.cpp b/src/soci/src/backends/empty/standard-into-type.cpp deleted file mode 100644 index a907f11ee9..0000000000 --- a/src/soci/src/backends/empty/standard-into-type.cpp +++ /dev/null @@ -1,39 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_EMPTY_SOURCE -#include "soci/empty/soci-empty.h" - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; - - -void empty_standard_into_type_backend::define_by_pos( - int & /* position */, void * /* data */, exchange_type /* type */) -{ - // ... -} - -void empty_standard_into_type_backend::pre_fetch() -{ - // ... -} - -void empty_standard_into_type_backend::post_fetch( - bool /* gotData */, bool /* calledFromFetch */, indicator * /* ind */) -{ - // ... -} - -void empty_standard_into_type_backend::clean_up() -{ - // ... -} diff --git a/src/soci/src/backends/empty/standard-use-type.cpp b/src/soci/src/backends/empty/standard-use-type.cpp deleted file mode 100644 index cd93ff9053..0000000000 --- a/src/soci/src/backends/empty/standard-use-type.cpp +++ /dev/null @@ -1,47 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_EMPTY_SOURCE -#include "soci/empty/soci-empty.h" - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; - - -void empty_standard_use_type_backend::bind_by_pos( - int & /* position */, void * /* data */, - exchange_type /* type */, bool /* readOnly */) -{ - // ... -} - -void empty_standard_use_type_backend::bind_by_name( - std::string const & /* name */, void * /* data */, - exchange_type /* type */, bool /* readOnly */) -{ - // ... -} - -void empty_standard_use_type_backend::pre_use(indicator const * /* ind */) -{ - // ... -} - -void empty_standard_use_type_backend::post_use( - bool /* gotData */, indicator * /* ind */) -{ - // ... -} - -void empty_standard_use_type_backend::clean_up() -{ - // ... -} diff --git a/src/soci/src/backends/empty/statement.cpp b/src/soci/src/backends/empty/statement.cpp deleted file mode 100644 index 87f9fda9fc..0000000000 --- a/src/soci/src/backends/empty/statement.cpp +++ /dev/null @@ -1,109 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_EMPTY_SOURCE -#include "soci/empty/soci-empty.h" - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; - - -empty_statement_backend::empty_statement_backend(empty_session_backend &session) - : session_(session) -{ -} - -void empty_statement_backend::alloc() -{ - // ... -} - -void empty_statement_backend::clean_up() -{ - // ... -} - -void empty_statement_backend::prepare(std::string const & /* query */, - statement_type /* eType */) -{ - // ... -} - -statement_backend::exec_fetch_result -empty_statement_backend::execute(int /* number */) -{ - // ... - return ef_success; -} - -statement_backend::exec_fetch_result -empty_statement_backend::fetch(int /* number */) -{ - // ... - return ef_success; -} - -long long empty_statement_backend::get_affected_rows() -{ - // ... - return -1; -} - -int empty_statement_backend::get_number_of_rows() -{ - // ... - return 1; -} - -std::string empty_statement_backend::get_parameter_name(int /* index */) const -{ - // ... - return std::string(); -} - -std::string empty_statement_backend::rewrite_for_procedure_call( - std::string const &query) -{ - return query; -} - -int empty_statement_backend::prepare_for_describe() -{ - // ... - return 0; -} - -void empty_statement_backend::describe_column(int /* colNum */, - data_type & /* type */, std::string & /* columnName */) -{ - // ... -} - -empty_standard_into_type_backend * empty_statement_backend::make_into_type_backend() -{ - return new empty_standard_into_type_backend(*this); -} - -empty_standard_use_type_backend * empty_statement_backend::make_use_type_backend() -{ - return new empty_standard_use_type_backend(*this); -} - -empty_vector_into_type_backend * -empty_statement_backend::make_vector_into_type_backend() -{ - return new empty_vector_into_type_backend(*this); -} - -empty_vector_use_type_backend * empty_statement_backend::make_vector_use_type_backend() -{ - return new empty_vector_use_type_backend(*this); -} diff --git a/src/soci/src/backends/empty/vector-into-type.cpp b/src/soci/src/backends/empty/vector-into-type.cpp deleted file mode 100644 index 45ee98012f..0000000000 --- a/src/soci/src/backends/empty/vector-into-type.cpp +++ /dev/null @@ -1,46 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_EMPTY_SOURCE -#include "soci/empty/soci-empty.h" - -using namespace soci; -using namespace soci::details; - - -void empty_vector_into_type_backend::define_by_pos( - int & /* position */, void * /* data */, exchange_type /* type */) -{ - // ... -} - -void empty_vector_into_type_backend::pre_fetch() -{ - // ... -} - -void empty_vector_into_type_backend::post_fetch( - bool /* gotData */, indicator * /* ind */) -{ - // ... -} - -void empty_vector_into_type_backend::resize(std::size_t /* sz */) -{ - // ... -} - -std::size_t empty_vector_into_type_backend::size() -{ - // ... - return 1; -} - -void empty_vector_into_type_backend::clean_up() -{ - // ... -} diff --git a/src/soci/src/backends/empty/vector-use-type.cpp b/src/soci/src/backends/empty/vector-use-type.cpp deleted file mode 100644 index ab5e558512..0000000000 --- a/src/soci/src/backends/empty/vector-use-type.cpp +++ /dev/null @@ -1,46 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_EMPTY_SOURCE -#include "soci/empty/soci-empty.h" - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; - - -void empty_vector_use_type_backend::bind_by_pos(int & /* position */, - void * /* data */, exchange_type /* type */) -{ - // ... -} - -void empty_vector_use_type_backend::bind_by_name( - std::string const & /* name */, void * /* data */, - exchange_type /* type */) -{ - // ... -} - -void empty_vector_use_type_backend::pre_use(indicator const * /* ind */) -{ - // ... -} - -std::size_t empty_vector_use_type_backend::size() -{ - // ... - return 1; -} - -void empty_vector_use_type_backend::clean_up() -{ - // ... -} diff --git a/src/soci/src/backends/firebird/CMakeLists.txt b/src/soci/src/backends/firebird/CMakeLists.txt deleted file mode 100644 index cbf702813e..0000000000 --- a/src/soci/src/backends/firebird/CMakeLists.txt +++ /dev/null @@ -1,16 +0,0 @@ -############################################################################### -# -# This file is part of CMake configuration for SOCI library -# -# Copyright (C) 2013 Viacheslav Naydenov -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -# -############################################################################### - -soci_backend(Firebird - DEPENDS Firebird - DESCRIPTION "SOCI backend for Firebird" - AUTHORS "RafaÅ‚ Bobrowski" - MAINTAINERS "Viacheslav Naydenov") diff --git a/src/soci/src/backends/firebird/Makefile.basic b/src/soci/src/backends/firebird/Makefile.basic deleted file mode 100644 index 5c0ffd15c7..0000000000 --- a/src/soci/src/backends/firebird/Makefile.basic +++ /dev/null @@ -1,101 +0,0 @@ -# The following variable is specific to this backend and its correct -# values might depend on your environment - feel free to set it accordingly. - -FIREBIRDINCLUDEDIR = -I/usr/local/firebird/include - -# The rest of the Makefile is indepentent of the target environment. - -COMPILER = g++ -CXXFLAGS = -Wall -pedantic -Wno-long-long -CXXFLAGSSO = ${CXXFLAGS} -fPIC -INCLUDEDIRS = -I../../core ${FIREBIRDINCLUDEDIR} - -OBJECTS = blob.o factory.o row-id.o session.o standard-into-type.o \ - standard-use-type.o statement.o vector-into-type.o vector-use-type.o \ - error-firebird.o common.o - -OBJECTSSO = blob-s.o factory-s.o row-id-s.o session-s.o \ - standard-into-type-s.o standard-use-type-s.o statement-s.o \ - vector-into-type-s.o vector-use-type-s.o error-firebird-s.o common-s.o - -FIREBIRDLIBS = -lfbclient -lpthread - -libsoci_firebird.a : ${OBJECTS} - ar rv $@ $? - rm *.o - -soci-firebird.o : soci-firebird.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -blob.o : blob.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -error-firebird.o : error-firebird.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -common.o : common.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -factory.o : factory.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -row-id.o : row-id.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -session.o : session.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -standard-into-type.o : standard-into-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -standard-use-type.o : standard-use-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -statement.o : statement.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -vector-into-type.o : vector-into-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -vector-use-type.o : vector-use-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -shared : ${OBJECTSSO} - ${COMPILER} -shared -o libsoci_firebird.so ${OBJECTSSO} ${FIREBIRDLIBS} - rm *.o - -blob-s.o : blob.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -error-firebird-s.o : error-firebird.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -common-s.o : common.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -factory-s.o : factory.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -row-id-s.o : row-id.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -session-s.o : session.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -standard-into-type-s.o : standard-into-type.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -standard-use-type-s.o : standard-use-type.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -statement-s.o : statement.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -vector-into-type-s.o : vector-into-type.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -vector-use-type-s.o : vector-use-type.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -clean : - rm -f *.o libsoci_firebird.a libsoci_firebird.so diff --git a/src/soci/src/backends/firebird/blob.cpp b/src/soci/src/backends/firebird/blob.cpp deleted file mode 100644 index ea433a3add..0000000000 --- a/src/soci/src/backends/firebird/blob.cpp +++ /dev/null @@ -1,314 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, Rafal Bobrowski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_FIREBIRD_SOURCE -#include "soci/firebird/soci-firebird.h" -#include "firebird/error-firebird.h" - -using namespace soci; -using namespace soci::details::firebird; - -firebird_blob_backend::firebird_blob_backend(firebird_session_backend &session) - : session_(session), bid_(), from_db_(false), bhp_(0), data_(), - loaded_(false), max_seg_size_(0) -{} - -firebird_blob_backend::~firebird_blob_backend() -{ - cleanUp(); -} - -std::size_t firebird_blob_backend::get_len() -{ - if (from_db_ && bhp_ == 0) - { - open(); - } - - return data_.size(); -} - -std::size_t firebird_blob_backend::read( - std::size_t offset, char * buf, std::size_t toRead) -{ - if (from_db_ && (loaded_ == false)) - { - // this is blob fetched from database, but not loaded yet - load(); - } - - std::size_t size = data_.size(); - - if (offset > size) - { - throw soci_error("Can't read past-the-end of BLOB data"); - } - - char * itr = buf; - std::size_t limit = size - offset < toRead ? size - offset : toRead; - std::size_t index = 0; - - while (index < limit) - { - *itr = data_[offset+index]; - ++index; - ++itr; - } - - return limit; -} - -std::size_t firebird_blob_backend::write(std::size_t offset, char const * buf, - std::size_t toWrite) -{ - if (from_db_ && (loaded_ == false)) - { - // this is blob fetched from database, but not loaded yet - load(); - } - - std::size_t size = data_.size(); - - if (offset > size) - { - throw soci_error("Can't write past-the-end of BLOB data"); - } - - // make sure there is enough space in buffer - if (toWrite > (size - offset)) - { - data_.resize(size + (toWrite - (size - offset))); - } - - writeBuffer(offset, buf, toWrite); - - return toWrite; -} - -std::size_t firebird_blob_backend::append( - char const * buf, std::size_t toWrite) -{ - if (from_db_ && (loaded_ == false)) - { - // this is blob fetched from database, but not loaded yet - load(); - } - - std::size_t size = data_.size(); - data_.resize(size + toWrite); - - writeBuffer(size, buf, toWrite); - - return toWrite; -} - -void firebird_blob_backend::trim(std::size_t newLen) -{ - if (from_db_ && (loaded_ == false)) - { - // this is blob fetched from database, but not loaded yet - load(); - } - - data_.resize(newLen); -} - -void firebird_blob_backend::writeBuffer(std::size_t offset, - char const * buf, std::size_t toWrite) -{ - char const * itr = buf; - char const * end_itr = buf + toWrite; - - while (itr!=end_itr) - { - data_[offset++] = *itr++; - } -} - -void firebird_blob_backend::open() -{ - if (bhp_ != 0) - { - // BLOB already opened - return; - } - - ISC_STATUS stat[20]; - - if (isc_open_blob2(stat, &session_.dbhp_, session_.current_transaction(), - &bhp_, &bid_, 0, NULL)) - { - bhp_ = 0L; - throw_iscerror(stat); - } - - // get basic blob info - long blob_size = getBLOBInfo(); - - data_.resize(blob_size); -} - -void firebird_blob_backend::cleanUp() -{ - from_db_ = false; - loaded_ = false; - max_seg_size_ = 0; - data_.resize(0); - - if (bhp_ != 0) - { - // close blob - ISC_STATUS stat[20]; - if (isc_close_blob(stat, &bhp_)) - { - throw_iscerror(stat); - } - bhp_ = 0; - } -} - -// loads blob data into internal buffer -void firebird_blob_backend::load() -{ - if (bhp_ == 0) - { - open(); - } - - ISC_STATUS stat[20]; - unsigned short bytes; - std::vector::size_type total_bytes = 0; - bool keep_reading = false; - - do - { - bytes = 0; - // next segment of data - // data_ is large-enough because we know total size of blob - isc_get_segment(stat, &bhp_, &bytes, static_cast(max_seg_size_), - &data_[total_bytes]); - - total_bytes += bytes; - - if (total_bytes == data_.size()) - { - // we have all BLOB data - keep_reading = false; - } - else if (stat[1] == 0 || stat[1] == isc_segment) - { - // there is more data to read from current segment (0) - // or there is next segment (isc_segment) - keep_reading = true; - } - else if (stat[1] == isc_segstr_eof) - { - // BLOB is shorter then we expected ??? - keep_reading = false; - } - else - { - // an error has occured - throw_iscerror(stat); - } - } - while (keep_reading); - - loaded_ = true; -} - -// this method saves BLOB content to database -// (a new BLOB will be created at this point) -// BLOB will be closed after save. -void firebird_blob_backend::save() -{ - // close old blob if necessary - ISC_STATUS stat[20]; - if (bhp_ != 0) - { - if (isc_close_blob(stat, &bhp_)) - { - throw_iscerror(stat); - } - bhp_ = 0; - } - - // create new blob - if (isc_create_blob(stat, &session_.dbhp_, session_.current_transaction(), - &bhp_, &bid_)) - { - throw_iscerror(stat); - } - - if (data_.size() > 0) - { - // write data - size_t size = data_.size(); - size_t offset = 0; - // Segment Size : Specifying the BLOB segment is throwback to times past, when applications for working - // with BLOB data were written in C(Embedded SQL) with the help of the gpre pre - compiler. - // Nowadays, it is effectively irrelevant.The segment size for BLOB data is determined by the client side and is usually larger than the data page size, - // in any case. - do - { - unsigned short segmentSize = 0xFFFF; //last unsigned short number - if (size - offset < segmentSize) //if content size is less than max segment size or last data segment is about to be written - segmentSize = static_cast(size - offset); - //write segment - if (isc_put_segment(stat, &bhp_, segmentSize, &data_[0]+offset)) - { - throw_iscerror(stat); - } - offset += segmentSize; - } - while (offset < size); - } - cleanUp(); - from_db_ = true; -} - -// retrives number of segments and total length of BLOB -// returns total length of BLOB -long firebird_blob_backend::getBLOBInfo() -{ - char blob_items[] = {isc_info_blob_max_segment, isc_info_blob_total_length}; - char res_buffer[20], *p, item; - short length; - long total_length = 0; - - ISC_STATUS stat[20]; - - if (isc_blob_info(stat, &bhp_, sizeof(blob_items), blob_items, - sizeof(res_buffer), res_buffer)) - { - throw_iscerror(stat); - } - - for (p = res_buffer; *p != isc_info_end ;) - { - item = *p++; - length = static_cast(isc_vax_integer(p, 2)); - p += 2; - switch (item) - { - case isc_info_blob_max_segment: - max_seg_size_ = isc_vax_integer(p, length); - break; - case isc_info_blob_total_length: - total_length = isc_vax_integer(p, length); - break; - case isc_info_truncated: - throw soci_error("Fatal Error: BLOB info truncated!"); - break; - default: - break; - } - p += length; - } - - return total_length; -} diff --git a/src/soci/src/backends/firebird/common.cpp b/src/soci/src/backends/firebird/common.cpp deleted file mode 100644 index a3e777f86d..0000000000 --- a/src/soci/src/backends/firebird/common.cpp +++ /dev/null @@ -1,221 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, Rafal Bobrowski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#include "soci/soci-platform.h" -#include "firebird/common.h" -#include "soci/soci-backend.h" -#include // FireBird -#include -#include -#include -#include -#include -#include - -namespace soci -{ - -namespace details -{ - -namespace firebird -{ - -char * allocBuffer(XSQLVAR* var) -{ - std::size_t size; - int type = var->sqltype & ~1; - if (type == SQL_VARYING) - { - size = var->sqllen + sizeof(short); - } - else if (type == SQL_TIMESTAMP || type == SQL_TYPE_TIME - || type == SQL_TYPE_DATE) - { - size = sizeof(std::tm); - } - else - { - size = var->sqllen; - } - - return new char[size]; -} - -void tmEncode(short type, std::tm * src, void * dst) -{ - switch (type & ~1) - { - // In Interbase v6 DATE represents a date-only data type, - // in InterBase v5 DATE represents a date+time data type. - case SQL_TIMESTAMP: - isc_encode_timestamp(src, static_cast(dst)); - break; - case SQL_TYPE_TIME: - isc_encode_sql_time(src, static_cast(dst)); - break; - case SQL_TYPE_DATE: - isc_encode_sql_date(src, static_cast(dst)); - break; - default: - std::ostringstream msg; - msg << "Unexpected type of date/time field (" << type << ")"; - throw soci_error(msg.str()); - } -} - -void tmDecode(short type, void * src, std::tm * dst) -{ - switch (type & ~1) - { - case SQL_TIMESTAMP: - isc_decode_timestamp(static_cast(src), dst); - break; - case SQL_TYPE_TIME: - isc_decode_sql_time(static_cast(src), dst); - break; - case SQL_TYPE_DATE: - isc_decode_sql_date(static_cast(src), dst); - break; - default: - std::ostringstream msg; - msg << "Unexpected type of date/time field (" << type << ")"; - throw soci_error(msg.str()); - } -} - -void setTextParam(char const * s, std::size_t size, char * buf_, - XSQLVAR * var) -{ - int const sqltype = var->sqltype & ~1; - - if (sqltype == SQL_VARYING || sqltype == SQL_TEXT) - { - if (size > static_cast(var->sqllen)) - { - std::ostringstream msg; - msg << "Value \"" << s << "\" is too long (" - << size << " bytes) to be stored in column of size " - << var->sqllen << " bytes"; - throw soci_error(msg.str()); - } - - short const sz = static_cast(size); - - if (sqltype == SQL_VARYING) - { - std::memcpy(buf_, &sz, sizeof(short)); - std::memcpy(buf_ + sizeof(short), s, sz); - } - else // sqltype == SQL_TEXT - { - std::memcpy(buf_, s, sz); - if (sz < var->sqllen) - { - std::memset(buf_+sz, ' ', var->sqllen - sz); - } - } - } - else if (sqltype == SQL_SHORT) - { - parse_decimal(buf_, var, s); - } - else if (sqltype == SQL_LONG) - { - parse_decimal(buf_, var, s); - } - else if (sqltype == SQL_INT64) - { - parse_decimal(buf_, var, s); - } - else if (sqltype == SQL_TIMESTAMP - || sqltype == SQL_TYPE_DATE) - { - unsigned short year, month, day, hour, min, sec; - if (std::sscanf(s, "%hu-%hu-%hu %hu:%hu:%hu", - &year, &month, &day, &hour, &min, &sec) != 6) - { - if (std::sscanf(s, "%hu-%hu-%huT%hu:%hu:%hu", - &year, &month, &day, &hour, &min, &sec) != 6) - { - hour = min = sec = 0; - if (std::sscanf(s, "%hu-%hu-%hu", &year, &month, &day) != 3) - { - throw soci_error("Could not parse timestamp value."); - } - } - } - std::tm t; - std::memset(&t, 0, sizeof(t)); - t.tm_year = year - 1900; - t.tm_mon = month - 1; - t.tm_mday = day; - t.tm_hour = hour; - t.tm_min = min; - t.tm_sec = sec; - std::memcpy(buf_, &t, sizeof(t)); - tmEncode(var->sqltype, &t, buf_); - } - else if (sqltype == SQL_TYPE_TIME) - { - unsigned short hour, min, sec; - if (std::sscanf(s, "%hu:%hu:%hu", &hour, &min, &sec) != 3) - { - throw soci_error("Could not parse timestamp value."); - } - std::tm t; - std::memset(&t, 0, sizeof(t)); - t.tm_hour = hour; - t.tm_min = min; - t.tm_sec = sec; - std::memcpy(buf_, &t, sizeof(t)); - tmEncode(var->sqltype, &t, buf_); - } - else - { - throw soci_error("Unexpected string type."); - } -} - -std::string getTextParam(XSQLVAR const *var) -{ - //std::cerr << "getTextParam: var->sqltype=" << var->sqltype << std::endl; - short size; - std::size_t offset = 0; - - if ((var->sqltype & ~1) == SQL_VARYING) - { - size = *reinterpret_cast(var->sqldata); - offset = sizeof(short); - } - else if ((var->sqltype & ~1) == SQL_TEXT) - { - size = var->sqllen; - } - else if ((var->sqltype & ~1) == SQL_SHORT) - { - return format_decimal(var->sqldata, var->sqlscale); - } - else if ((var->sqltype & ~1) == SQL_LONG) - { - return format_decimal(var->sqldata, var->sqlscale); - } - else if ((var->sqltype & ~1) == SQL_INT64) - { - return format_decimal(var->sqldata, var->sqlscale); - } - else - throw soci_error("Unexpected string type"); - - return std::string(var->sqldata + offset, size); -} - -} // namespace firebird - -} // namespace details - -} // namespace soci diff --git a/src/soci/src/backends/firebird/error-firebird.cpp b/src/soci/src/backends/firebird/error-firebird.cpp deleted file mode 100644 index 5fa122565e..0000000000 --- a/src/soci/src/backends/firebird/error-firebird.cpp +++ /dev/null @@ -1,87 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, Rafal Bobrowski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_FIREBIRD_SOURCE -#include "soci/firebird/soci-firebird.h" -#include "firebird/error-firebird.h" - -#include -#include - -namespace soci -{ - -firebird_soci_error::firebird_soci_error(std::string const & msg, ISC_STATUS const * status) - : soci_error(msg) -{ - if (status != 0) - { - std::size_t i = 0; - while (i < stat_size && status[i] != 0) - { - status_.push_back(status[i++]); - } - } -} - -namespace details -{ - -namespace firebird -{ - -void get_iscerror_details(ISC_STATUS * status_vector, std::string &msg) -{ - char msg_buffer[SOCI_FIREBIRD_ERRMSG]; - const ISC_STATUS *pvector = status_vector; - - try - { - // fetching first error message - fb_interpret(msg_buffer, SOCI_FIREBIRD_ERRMSG, &pvector); - msg = msg_buffer; - - // fetching next errors - while (fb_interpret(msg_buffer, SOCI_FIREBIRD_ERRMSG, &pvector)) - { - msg += "\n"; - msg += msg_buffer; - } - } - catch (...) - { - throw firebird_soci_error("Exception catched while fetching error information"); - } -} - -bool check_iscerror(ISC_STATUS const * status_vector, long errNum) -{ - std::size_t i=0; - while (status_vector[i] != 0) - { - if (status_vector[i] == 1 && status_vector[i+1] == errNum) - { - return true; - } - ++i; - } - - return false; -} -void throw_iscerror(ISC_STATUS * status_vector) -{ - std::string msg; - - get_iscerror_details(status_vector, msg); - throw firebird_soci_error(msg, status_vector); -} - -} // namespace firebird - -} // namespace details - -} // namespace soci diff --git a/src/soci/src/backends/firebird/factory.cpp b/src/soci/src/backends/firebird/factory.cpp deleted file mode 100644 index a45106a7b8..0000000000 --- a/src/soci/src/backends/firebird/factory.cpp +++ /dev/null @@ -1,36 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, Rafal Bobrowski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_FIREBIRD_SOURCE -#include "soci/firebird/soci-firebird.h" -#include "soci/backend-loader.h" - -using namespace soci; - -firebird_session_backend * firebird_backend_factory::make_session( - connection_parameters const & parameters) const -{ - return new firebird_session_backend(parameters); -} - -firebird_backend_factory const soci::firebird; - -extern "C" -{ - -// for dynamic backend loading -SOCI_FIREBIRD_DECL backend_factory const * factory_firebird() -{ - return &soci::firebird; -} - -SOCI_FIREBIRD_DECL void register_factory_firebird() -{ - soci::dynamic_backends::register_backend("firebird", soci::firebird); -} - -} // extern "C" diff --git a/src/soci/src/backends/firebird/session.cpp b/src/soci/src/backends/firebird/session.cpp deleted file mode 100644 index b83d7f5c9d..0000000000 --- a/src/soci/src/backends/firebird/session.cpp +++ /dev/null @@ -1,369 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, Rafal Bobrowski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_FIREBIRD_SOURCE -#include "soci/firebird/soci-firebird.h" -#include "firebird/error-firebird.h" -#include "soci/session.h" -#include -#include -#include -#include - -using namespace soci; -using namespace soci::details::firebird; - -namespace -{ - -// Helpers of explodeISCConnectString() for reading words from a string. "Word" -// here is defined very loosely as just a sequence of non-space characters. -// -// All these helper functions update the input iterator to point to the first -// character not consumed by them. - -// Advance the input iterator until the first non-space character or end of the -// string. -void skipWhiteSpace(std::string::const_iterator& i, std::string::const_iterator const &end) -{ - std::locale const loc; - for (; i != end; ++i) - { - if (!std::isspace(*i, loc)) - break; - } -} - -// Return the string of all characters until the first space or the specified -// delimiter. -// -// Throws if the first non-space character after the end of the word is not the -// delimiter. However just returns en empty string, without throwing, if -// nothing is left at all in the string except for white space. -std::string -getWordUntil(std::string const &s, std::string::const_iterator &i, char delim) -{ - std::string::const_iterator const end = s.end(); - skipWhiteSpace(i, end); - - // We need to handle this case specially because it's not an error if - // nothing at all remains in the string. But if anything does remain, then - // we must have the delimiter. - if (i == end) - return std::string(); - - // Simply put anything until the delimiter into the word, stopping at the - // first white space character. - std::string word; - std::locale const loc; - for (; i != end; ++i) - { - if (*i == delim) - break; - - if (std::isspace(*i, loc)) - { - skipWhiteSpace(i, end); - if (i == end || *i != delim) - { - std::ostringstream os; - os << "Expected '" << delim << "' at position " - << (i - s.begin() + 1) - << " in Firebird connection string \"" - << s << "\"."; - - throw soci_error(os.str()); - } - - break; - } - - word += *i; - } - - if (i == end) - { - std::ostringstream os; - os << "Expected '" << delim - << "' not found before the end of the string " - << "in Firebird connection string \"" - << s << "\"."; - - throw soci_error(os.str()); - } - - ++i; // Skip the delimiter itself. - - return word; -} - -// Return a possibly quoted word, i.e. either just a sequence of non-space -// characters or everything inside a double-quoted string. -// -// Throws if the word is quoted and the closing quote is not found. However -// doesn't throw, just returns an empty string if there is nothing left. -std::string -getPossiblyQuotedWord(std::string const &s, std::string::const_iterator &i) -{ - std::string::const_iterator const end = s.end(); - skipWhiteSpace(i, end); - - std::string word; - - if (i != end && *i == '"') - { - for (;;) - { - if (++i == end) - { - std::ostringstream os; - os << "Expected '\"' not found before the end of the string " - "in Firebird connection string \"" - << s << "\"."; - - throw soci_error(os.str()); - } - - if (*i == '"') - { - ++i; - break; - } - - word += *i; - } - } - else // Not quoted. - { - std::locale const loc; - for (; i != end; ++i) - { - if (std::isspace(*i, loc)) - break; - - word += *i; - } - } - - return word; -} - -// retrieves parameters from the uniform connect string which is supposed to be -// in the form "key=value[ key2=value2 ...]" and the values may be quoted to -// allow including spaces into them. Notice that currently there is no way to -// include both a space and a double quote in a value. -std::map -explodeISCConnectString(std::string const &connectString) -{ - std::map parameters; - - std::string key, value; - for (std::string::const_iterator i = connectString.begin(); ; ) - { - key = getWordUntil(connectString, i, '='); - if (key.empty()) - break; - - value = getPossiblyQuotedWord(connectString, i); - - parameters.insert(std::pair(key, value)); - } - - return parameters; -} - -// extracts given parameter from map previusly build with explodeISCConnectString -bool getISCConnectParameter(std::map const & m, std::string const & key, - std::string & value) -{ - std::map :: const_iterator i; - value.clear(); - - i = m.find(key); - - if (i != m.end()) - { - value = i->second; - return true; - } - else - { - return false; - } -} - -void setDPBOption(std::string& dpb, int const option, std::string const & value) -{ - - if (dpb.empty()) - { - dpb.append(1, static_cast(isc_dpb_version1)); - } - - // now we are adding new option - dpb.append(1, static_cast(option)); - dpb.append(1, static_cast(value.size())); - dpb.append(value); -} - -} // namespace anonymous - -firebird_session_backend::firebird_session_backend( - connection_parameters const & parameters) : dbhp_(0), trhp_(0) - , decimals_as_strings_(false) -{ - // extract connection parameters - std::map - params(explodeISCConnectString(parameters.get_connect_string())); - - ISC_STATUS stat[stat_size]; - std::string param; - - // preparing connection options - std::string dpb; - if (getISCConnectParameter(params, "user", param)) - { - setDPBOption(dpb, isc_dpb_user_name, param); - } - - if (getISCConnectParameter(params, "password", param)) - { - setDPBOption(dpb, isc_dpb_password, param); - } - - if (getISCConnectParameter(params, "role", param)) - { - setDPBOption(dpb, isc_dpb_sql_role_name, param); - } - - if (getISCConnectParameter(params, "charset", param)) - { - setDPBOption(dpb, isc_dpb_lc_ctype, param); - } - - if (getISCConnectParameter(params, "service", param) == false) - { - throw soci_error("Service name not specified."); - } - - // connecting data base - if (isc_attach_database(stat, static_cast(param.size()), - const_cast(param.c_str()), &dbhp_, - static_cast(dpb.size()), const_cast(dpb.c_str()))) - { - throw_iscerror(stat); - } - - if (getISCConnectParameter(params, "decimals_as_strings", param)) - { - decimals_as_strings_ = param == "1" || param == "Y" || param == "y"; - } -} - - -void firebird_session_backend::begin() -{ - if (trhp_ == 0) - { - ISC_STATUS stat[stat_size]; - if (isc_start_transaction(stat, &trhp_, 1, &dbhp_, 0, NULL)) - { - throw_iscerror(stat); - } - } -} - -firebird_session_backend::~firebird_session_backend() -{ - cleanUp(); -} - -void firebird_session_backend::commit() -{ - ISC_STATUS stat[stat_size]; - - if (trhp_ != 0) - { - if (isc_commit_transaction(stat, &trhp_)) - { - throw_iscerror(stat); - } - - trhp_ = 0; - } -} - -void firebird_session_backend::rollback() -{ - ISC_STATUS stat[stat_size]; - - if (trhp_ != 0) - { - if (isc_rollback_transaction(stat, &trhp_)) - { - throw_iscerror(stat); - } - - trhp_ = 0; - } -} - -isc_tr_handle* firebird_session_backend::current_transaction() -{ - // It will do nothing if we're already inside a transaction. - begin(); - - return &trhp_; -} - -void firebird_session_backend::cleanUp() -{ - ISC_STATUS stat[stat_size]; - - // at the end of session our transaction is finally commited. - if (trhp_ != 0) - { - if (isc_commit_transaction(stat, &trhp_)) - { - throw_iscerror(stat); - } - - trhp_ = 0; - } - - if (isc_detach_database(stat, &dbhp_)) - { - throw_iscerror(stat); - } - - dbhp_ = 0L; -} - -bool firebird_session_backend::get_next_sequence_value( - session & s, std::string const & sequence, long & value) -{ - // We could use isq_execute2() directly but this is even simpler. - s << "select next value for " + sequence + " from rdb$database", - into(value); - - return true; -} - -firebird_statement_backend * firebird_session_backend::make_statement_backend() -{ - return new firebird_statement_backend(*this); -} - -details::rowid_backend* firebird_session_backend::make_rowid_backend() -{ - throw soci_error("RowIDs are not supported"); -} - -firebird_blob_backend * firebird_session_backend::make_blob_backend() -{ - return new firebird_blob_backend(*this); -} diff --git a/src/soci/src/backends/firebird/standard-into-type.cpp b/src/soci/src/backends/firebird/standard-into-type.cpp deleted file mode 100644 index 0025163485..0000000000 --- a/src/soci/src/backends/firebird/standard-into-type.cpp +++ /dev/null @@ -1,167 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, Rafal Bobrowski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_FIREBIRD_SOURCE -#include "soci/firebird/soci-firebird.h" -#include "soci-exchange-cast.h" -#include "firebird/common.h" -#include "soci/soci.h" - -#include - -using namespace soci; -using namespace soci::details; -using namespace soci::details::firebird; - -void firebird_standard_into_type_backend::define_by_pos( - int & position, void * data, exchange_type type) -{ - position_ = position-1; - data_ = data; - type_ = type; - - ++position; - - statement_.intoType_ = eStandard; - statement_.intos_.push_back(static_cast(this)); - - XSQLVAR *var = statement_.sqldap_->sqlvar+position_; - - buf_ = allocBuffer(var); - var->sqldata = buf_; - var->sqlind = &indISCHolder_; -} - -void firebird_standard_into_type_backend::pre_fetch() -{ - // nothing to do -} - -void firebird_standard_into_type_backend::post_fetch( - bool gotData, bool calledFromFetch, indicator * ind) -{ - if (calledFromFetch && (gotData == false)) - { - // this is a normal end-of-rowset condition, - // no need to set anything (fetch() will return false) - return; - } - - if (gotData) - { - if (i_null == statement_.inds_[position_][0] && NULL == ind) - { - throw soci_error("Null value fetched and no indicator defined."); - } - else if (NULL != ind) - { - *ind = statement_.inds_[position_][0]; - } - } -} - - -void firebird_standard_into_type_backend::exchangeData() -{ - XSQLVAR *var = statement_.sqldap_->sqlvar+position_; - - switch (type_) - { - // simple cases - case x_char: - exchange_type_cast(data_) = getTextParam(var)[0]; - break; - case x_short: - exchange_type_cast(data_) = from_isc(var); - break; - case x_integer: - exchange_type_cast(data_) = from_isc(var); - break; - case x_long_long: - exchange_type_cast(data_) = from_isc(var); - break; - case x_double: - exchange_type_cast(data_) = from_isc(var); - break; - - // cases that require adjustments and buffer management - case x_stdstring: - exchange_type_cast(data_) = getTextParam(var); - break; - case x_stdtm: - { - std::tm& t = exchange_type_cast(data_); - tmDecode(var->sqltype, buf_, &t); - - // isc_decode_timestamp() used by tmDecode() incorrectly sets - // tm_isdst to 0 in the struct that it creates, see - // http://tracker.firebirdsql.org/browse/CORE-3877, work around it - // by pretending the DST is actually unknown. - t.tm_isdst = -1; - } - break; - - // cases that require special handling - case x_blob: - { - blob *tmp = reinterpret_cast(data_); - - firebird_blob_backend *blob = - dynamic_cast(tmp->get_backend()); - - if (0 == blob) - { - throw soci_error("Can't get Firebid BLOB BackEnd"); - } - - blob->assign(*reinterpret_cast(buf_)); - } - break; - - case x_longstring: - copy_from_blob(exchange_type_cast(data_).value); - break; - - case x_xmltype: - copy_from_blob(exchange_type_cast(data_).value); - break; - - default: - throw soci_error("Into element used with non-supported type."); - } // switch -} - -void firebird_standard_into_type_backend::copy_from_blob(std::string& out) -{ - firebird_blob_backend blob(statement_.session_); - blob.assign(*reinterpret_cast(buf_)); - - std::size_t const len_total = blob.get_len(); - out.resize(len_total); - - std::size_t const len_read = blob.read(0, &out[0], len_total); - if (len_read != len_total) - { - std::ostringstream os; - os << "Read " << len_read << " bytes instead of expected " - << len_total << " from Firebird text blob object"; - throw soci_error(os.str()); - } -} - -void firebird_standard_into_type_backend::clean_up() -{ - if (buf_ != NULL) - { - delete [] buf_; - buf_ = NULL; - } - std::vector::iterator it = - std::find(statement_.intos_.begin(), statement_.intos_.end(), this); - if (it != statement_.intos_.end()) - statement_.intos_.erase(it); -} diff --git a/src/soci/src/backends/firebird/standard-use-type.cpp b/src/soci/src/backends/firebird/standard-use-type.cpp deleted file mode 100644 index da0d304ef2..0000000000 --- a/src/soci/src/backends/firebird/standard-use-type.cpp +++ /dev/null @@ -1,206 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, Rafal Bobrowski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_FIREBIRD_SOURCE -#include "soci/firebird/soci-firebird.h" -#include "soci-exchange-cast.h" -#include "firebird/common.h" -#include "soci/soci.h" - -using namespace soci; -using namespace soci::details; -using namespace soci::details::firebird; - -void firebird_standard_use_type_backend::bind_by_pos( - int & position, void * data, exchange_type type, bool /* readOnly */) -{ - if (statement_.boundByName_) - { - throw soci_error( - "Binding for use elements must be either by position or by name."); - } - - position_ = position-1; - data_ = data; - type_ = type; - - ++position; - - statement_.useType_ = eStandard; - statement_.uses_.push_back(static_cast(this)); - - XSQLVAR *var = statement_.sqlda2p_->sqlvar+position_; - - buf_ = allocBuffer(var); - var->sqldata = buf_; - var->sqlind = &indISCHolder_; - - statement_.boundByPos_ = true; -} - -void firebird_standard_use_type_backend::bind_by_name( - std::string const & name, void * data, - exchange_type type, bool /* readOnly */) -{ - if (statement_.boundByPos_) - { - throw soci_error( - "Binding for use elements must be either by position or by name."); - } - - std::map :: iterator idx = - statement_.names_.find(name); - - if (idx == statement_.names_.end()) - { - throw soci_error("Missing use element for bind by name (" + name + ")"); - } - - position_ = idx->second; - data_ = data; - type_ = type; - - statement_.useType_ = eStandard; - statement_.uses_.push_back(static_cast(this)); - - XSQLVAR *var = statement_.sqlda2p_->sqlvar+position_; - - buf_ = allocBuffer(var); - var->sqldata = buf_; - var->sqlind = &indISCHolder_; - - statement_.boundByName_ = true; -} - -void firebird_standard_use_type_backend::pre_use(indicator const * ind) -{ - indISCHolder_ = 0; - if (ind) - { - switch (*ind) - { - case i_null: - indISCHolder_ = -1; - break; - case i_ok: - indISCHolder_ = 0; - break; - default: - throw soci_error("Unsupported indicator value."); - } - } -} - -void firebird_standard_use_type_backend::exchangeData() -{ - XSQLVAR *var = statement_.sqlda2p_->sqlvar+position_; - - if (0 != indISCHolder_) - return; - - switch (type_) - { - case x_char: - setTextParam(&exchange_type_cast(data_), 1, buf_, var); - break; - case x_short: - to_isc(data_, var); - break; - case x_integer: - to_isc(data_, var); - break; - case x_long_long: - to_isc(data_, var); - break; - case x_double: - to_isc(data_, var); - break; - - case x_stdstring: - { - std::string const& tmp = exchange_type_cast(data_); - setTextParam(tmp.c_str(), tmp.size(), buf_, var); - } - break; - case x_stdtm: - tmEncode(var->sqltype, &exchange_type_cast(data_), buf_); - break; - - // cases that require special handling - case x_blob: - { - blob *tmp = static_cast(data_); - - firebird_blob_backend* blob = - dynamic_cast(tmp->get_backend()); - - if (NULL == blob) - { - throw soci_error("Can't get Firebid BLOB BackEnd"); - } - - blob->save(); - memcpy(buf_, &blob->bid_, var->sqllen); - } - break; - - case x_longstring: - copy_to_blob(exchange_type_cast(data_).value); - break; - - case x_xmltype: - copy_to_blob(exchange_type_cast(data_).value); - break; - - default: - throw soci_error("Use element used with non-supported type."); - } // switch -} - -void firebird_standard_use_type_backend::copy_to_blob(const std::string& in) -{ - blob_ = new firebird_blob_backend(statement_.session_); - blob_->append(in.c_str(), in.length()); - blob_->save(); - memcpy(buf_, &blob_->bid_, sizeof(blob_->bid_)); -} - -void firebird_standard_use_type_backend::post_use( - bool /* gotData */, indicator * /* ind */) -{ - // TODO: Is it possible to have the bound element being overwritten - // by the database? - // If not, then nothing to do here, please remove this comment. - // If yes, then use the value of the readOnly parameter: - // - true: the given object should not be modified and the backend - // should detect if the modification was performed on the - // isolated buffer and throw an exception if the buffer was modified - // (this indicates logic error, because the user used const object - // and executed a query that attempted to modified it) - // - false: the modification should be propagated to the given object. - // ... -} - -void firebird_standard_use_type_backend::clean_up() -{ - if (buf_ != NULL) - { - delete [] buf_; - buf_ = NULL; - } - - if (blob_) - { - delete blob_; - blob_ = NULL; - } - - std::vector::iterator it = - std::find(statement_.uses_.begin(), statement_.uses_.end(), this); - if (it != statement_.uses_.end()) - statement_.uses_.erase(it); -} diff --git a/src/soci/src/backends/firebird/statement.cpp b/src/soci/src/backends/firebird/statement.cpp deleted file mode 100644 index f7ee8c947a..0000000000 --- a/src/soci/src/backends/firebird/statement.cpp +++ /dev/null @@ -1,738 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, Rafal Bobrowski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_FIREBIRD_SOURCE -#include "soci/firebird/soci-firebird.h" -#include "firebird/error-firebird.h" -#include -#include -#include - -using namespace soci; -using namespace soci::details; -using namespace soci::details::firebird; - -firebird_statement_backend::firebird_statement_backend(firebird_session_backend &session) - : session_(session), stmtp_(0), sqldap_(NULL), sqlda2p_(NULL), - boundByName_(false), boundByPos_(false), rowsFetched_(0), endOfRowSet_(false), rowsAffectedBulk_(-1LL), - intoType_(eStandard), useType_(eStandard), procedure_(false) -{} - -void firebird_statement_backend::prepareSQLDA(XSQLDA ** sqldap, short size) -{ - if (*sqldap != NULL) - { - *sqldap = reinterpret_cast(realloc(*sqldap, XSQLDA_LENGTH(size))); - } - else - { - *sqldap = reinterpret_cast(malloc(XSQLDA_LENGTH(size))); - } - - (*sqldap)->sqln = size; - (*sqldap)->version = 1; -} - -void firebird_statement_backend::alloc() -{ - ISC_STATUS stat[stat_size]; - - if (isc_dsql_allocate_statement(stat, &session_.dbhp_, &stmtp_)) - { - throw_iscerror(stat); - } -} - -void firebird_statement_backend::clean_up() -{ - rowsAffectedBulk_ = -1LL; - - ISC_STATUS stat[stat_size]; - - if (stmtp_ != 0) - { - if (isc_dsql_free_statement(stat, &stmtp_, DSQL_drop)) - { - throw_iscerror(stat); - } - stmtp_ = 0; - } - - if (sqldap_ != NULL) - { - free(sqldap_); - sqldap_ = NULL; - } - - if (sqlda2p_ != NULL) - { - free(sqlda2p_); - sqlda2p_ = NULL; - } -} - -void firebird_statement_backend::rewriteParameters( - std::string const & src, std::vector & dst) -{ - std::vector::iterator dst_it = dst.begin(); - - // rewrite the query by transforming all named parameters into - // the Firebird question marks (:abc -> ?, etc.) - - enum { eNormal, eInQuotes, eInName } state = eNormal; - - std::string name; - int position = 0; - - for (std::string::const_iterator it = src.begin(), end = src.end(); - it != end; ++it) - { - switch (state) - { - case eNormal: - if (*it == '\'') - { - *dst_it++ = *it; - state = eInQuotes; - } - else if (*it == ':') - { - state = eInName; - } - else // regular character, stay in the same state - { - *dst_it++ = *it; - } - break; - case eInQuotes: - if (*it == '\'') - { - *dst_it++ = *it; - state = eNormal; - } - else // regular quoted character - { - *dst_it++ = *it; - } - break; - case eInName: - if (std::isalnum(*it) || *it == '_') - { - name += *it; - } - else // end of name - { - names_.insert(std::pair(name, position++)); - name.clear(); - *dst_it++ = '?'; - *dst_it++ = *it; - state = eNormal; - } - break; - } - } - - if (state == eInName) - { - names_.insert(std::pair(name, position++)); - *dst_it++ = '?'; - } - - *dst_it = '\0'; -} - -namespace -{ - int statementType(isc_stmt_handle stmt) - { - int stype; - int length; - char type_item[] = {isc_info_sql_stmt_type}; - char res_buffer[8]; - - ISC_STATUS stat[stat_size]; - - if (isc_dsql_sql_info(stat, &stmt, sizeof(type_item), - type_item, sizeof(res_buffer), res_buffer)) - { - throw_iscerror(stat); - } - - if (res_buffer[0] == isc_info_sql_stmt_type) - { - length = isc_vax_integer(res_buffer+1, 2); - stype = isc_vax_integer(res_buffer+3, static_cast(length)); - } - else - { - throw soci_error("Can't determine statement type."); - } - - return stype; - } -} - -void firebird_statement_backend::rewriteQuery( - std::string const &query, std::vector &buffer) -{ - // buffer for temporary query - std::vector tmpQuery; - std::vector::iterator qItr; - - // buffer for query with named parameters changed to standard ones - std::vector rewQuery(query.size() + 1); - - // take care of named parameters in original query - rewriteParameters(query, rewQuery); - - std::string const prefix("execute procedure "); - std::string const prefix2("select * from "); - - // for procedures, we are preparing statement to determine - // type of procedure. - if (procedure_) - { - tmpQuery.resize(prefix.size() + rewQuery.size()); - qItr = tmpQuery.begin(); - std::copy(prefix.begin(), prefix.end(), qItr); - qItr += prefix.size(); - } - else - { - tmpQuery.resize(rewQuery.size()); - qItr = tmpQuery.begin(); - } - - // prepare temporary query - std::copy(rewQuery.begin(), rewQuery.end(), qItr); - - // preparing buffers for output parameters - if (sqldap_ == NULL) - { - prepareSQLDA(&sqldap_); - } - - ISC_STATUS stat[stat_size]; - isc_stmt_handle tmpStmtp = 0; - - // allocate temporary statement to determine its type - if (isc_dsql_allocate_statement(stat, &session_.dbhp_, &tmpStmtp)) - { - throw_iscerror(stat); - } - - // prepare temporary statement - if (isc_dsql_prepare(stat, session_.current_transaction(), &tmpStmtp, 0, - &tmpQuery[0], SQL_DIALECT_V6, sqldap_)) - { - throw_iscerror(stat); - } - - // get statement type - int stType = statementType(tmpStmtp); - - // free temporary prepared statement - if (isc_dsql_free_statement(stat, &tmpStmtp, DSQL_drop)) - { - throw_iscerror(stat); - } - - // take care of special cases - if (procedure_) - { - // for procedures that return values, we need to use correct syntax - if (sqldap_->sqld != 0) - { - // this is "select" procedure, so we have to change syntax - buffer.resize(prefix2.size() + rewQuery.size()); - qItr = buffer.begin(); - std::copy(prefix2.begin(), prefix2.end(), qItr); - qItr += prefix2.size(); - std::copy(rewQuery.begin(), rewQuery.end(), qItr); - - // that won't be needed anymore - procedure_ = false; - - return; - } - } - else - { - // this is not procedure, so syntax is ok except for named - // parameters in ddl - if (stType == isc_info_sql_stmt_ddl) - { - // this statement is a DDL - we can't rewrite named parameters - // so, we will use original query - buffer.resize(query.size() + 1); - std::copy(query.begin(), query.end(), buffer.begin()); - - // that won't be needed anymore - procedure_ = false; - - return; - } - } - - // here we know, that temporary query is OK, so we leave it as is - buffer.resize(tmpQuery.size()); - std::copy(tmpQuery.begin(), tmpQuery.end(), buffer.begin()); - - // that won't be needed anymore - procedure_ = false; -} - -void firebird_statement_backend::prepare(std::string const & query, - statement_type /* eType */) -{ - //std::cerr << "prepare: query=" << query << std::endl; - // clear named parametes - names_.clear(); - - std::vector queryBuffer; - - // modify query's syntax and prepare buffer for use with - // firebird's api - rewriteQuery(query, queryBuffer); - - ISC_STATUS stat[stat_size]; - - // prepare real statement - if (isc_dsql_prepare(stat, session_.current_transaction(), &stmtp_, 0, - &queryBuffer[0], SQL_DIALECT_V6, sqldap_)) - { - throw_iscerror(stat); - } - - if (sqldap_->sqln < sqldap_->sqld) - { - // sqlda is too small for all columns. it must be reallocated - prepareSQLDA(&sqldap_, sqldap_->sqld); - - if (isc_dsql_describe(stat, &stmtp_, SQL_DIALECT_V6, sqldap_)) - { - throw_iscerror(stat); - } - } - - // preparing input parameters - if (sqlda2p_ == NULL) - { - prepareSQLDA(&sqlda2p_); - } - - if (isc_dsql_describe_bind(stat, &stmtp_, SQL_DIALECT_V6, sqlda2p_)) - { - throw_iscerror(stat); - } - - if (sqlda2p_->sqln < sqlda2p_->sqld) - { - // sqlda is too small for all columns. it must be reallocated - prepareSQLDA(&sqlda2p_, sqlda2p_->sqld); - - if (isc_dsql_describe_bind(stat, &stmtp_, SQL_DIALECT_V6, sqlda2p_)) - { - throw_iscerror(stat); - } - } - - // prepare buffers for indicators - inds_.clear(); - inds_.resize(sqldap_->sqld); - - // reset types of into buffers - intoType_ = eStandard; - intos_.resize(0); - - // reset types of use buffers - useType_ = eStandard; - uses_.resize(0); -} - - -namespace -{ - void checkSize(std::size_t actual, std::size_t expected, - std::string const & name) - { - if (actual != expected) - { - std::ostringstream msg; - msg << "Incorrect number of " << name << " variables. " - << "Expected " << expected << ", got " << actual; - throw soci_error(msg.str()); - } - } -} - -statement_backend::exec_fetch_result -firebird_statement_backend::execute(int number) -{ - ISC_STATUS stat[stat_size]; - XSQLDA *t = NULL; - - std::size_t usize = uses_.size(); - - // do we have enough into variables ? - checkSize(intos_.size(), sqldap_->sqld, "into"); - // do we have enough use variables ? - checkSize(usize, sqlda2p_->sqld, "use"); - - // do we have parameters ? - if (sqlda2p_->sqld) - { - t = sqlda2p_; - - if (useType_ == eStandard) - { - for (std::size_t col=0; col(uses_[col])->exchangeData(); - } - } - } - - // make sure there is no active cursor - if (isc_dsql_free_statement(stat, &stmtp_, DSQL_close)) - { - // ignore attempt to close already closed cursor - if (check_iscerror(stat, isc_dsql_cursor_close_err) == false) - { - throw_iscerror(stat); - } - } - - if (useType_ == eVector) - { - long long rowsAffectedBulkTemp = 0; - - // Here we have to explicitly loop to achieve the - // effect of inserting or updating with vector use elements. - std::size_t rows = static_cast(uses_[0])->size(); - for (std::size_t row=0; row < rows; ++row) - { - // first we have to prepare input parameters - for (std::size_t col=0; col(uses_[col])->exchangeData(row); - } - - // then execute query - if (isc_dsql_execute(stat, session_.current_transaction(), &stmtp_, SQL_DIALECT_V6, t)) - { - // preserve the number of rows affected so far. - rowsAffectedBulk_ = rowsAffectedBulkTemp; - throw_iscerror(stat); - } - else - { - rowsAffectedBulkTemp += get_affected_rows(); - } - // soci does not allow bulk insert/update and bulk select operations - // in same query. So here, we know that into elements are not - // vectors. So, there is no need to fetch data here. - } - rowsAffectedBulk_ = rowsAffectedBulkTemp; - } - else - { - // use elements aren't vectors - if (isc_dsql_execute(stat, session_.current_transaction(), &stmtp_, SQL_DIALECT_V6, t)) - { - throw_iscerror(stat); - } - } - - // Successfully re-executing the statement must reset the "end of rowset" - // flag, we might be able to fetch data again now. - endOfRowSet_ = false; - - if (sqldap_->sqld) - { - // query may return some data - if (number > 0) - { - // number contains size of input variables, so we may fetch() data here - return fetch(number); - } - else - { - // execute(0) was meant to only perform the query - return ef_success; - } - } - else - { - // query can't return any data - return ef_no_data; - } -} - -statement_backend::exec_fetch_result -firebird_statement_backend::fetch(int number) -{ - if (endOfRowSet_) - return ef_no_data; - - ISC_STATUS stat[stat_size]; - - for (size_t i = 0; i(sqldap_->sqld); ++i) - { - inds_[i].resize(number > 0 ? number : 1); - } - - // Here we have to explicitly loop to achieve the effect of fetching - // vector into elements. After each fetch, we have to exchange data - // with into buffers. - rowsFetched_ = 0; - for (int i = 0; i < number; ++i) - { - ISC_STATUS const - fetch_stat = isc_dsql_fetch(stat, &stmtp_, SQL_DIALECT_V6, sqldap_); - - // there is more data to read - if (fetch_stat == 0) - { - ++rowsFetched_; - exchangeData(true, i); - } - else if (fetch_stat == 100L) - { - endOfRowSet_ = true; - return ef_no_data; - } - else - { - // error - endOfRowSet_ = true; - throw_iscerror(stat); - return ef_no_data; // unreachable, for compiler only - } - } // for - - return ef_success; -} - -// here we put data fetched from database into user buffers -void firebird_statement_backend::exchangeData(bool gotData, int row) -{ - if (gotData) - { - for (size_t i = 0; i < static_cast(sqldap_->sqld); ++i) - { - // first save indicators - if (((sqldap_->sqlvar+i)->sqltype & 1) == 0) - { - // there is no indicator for this column - inds_[i][row] = i_ok; - } - else if (*((sqldap_->sqlvar+i)->sqlind) == 0) - { - inds_[i][row] = i_ok; - } - else if (*((sqldap_->sqlvar+i)->sqlind) == -1) - { - inds_[i][row] = i_null; - } - else - { - throw soci_error("Unknown state in firebird_statement_backend::exchangeData()"); - } - - // then deal with data - if (inds_[i][row] != i_null) - { - if (intoType_ == eVector) - { - static_cast( - intos_[i])->exchangeData(row); - } - else - { - static_cast( - intos_[i])->exchangeData(); - } - } - } - } -} - -long long firebird_statement_backend::get_affected_rows() -{ - if (rowsAffectedBulk_ >= 0) - { - return rowsAffectedBulk_; - } - - ISC_STATUS_ARRAY stat; - char type_item[] = { isc_info_sql_records }; - char res_buffer[256]; - - if (isc_dsql_sql_info(stat, &stmtp_, sizeof(type_item), type_item, - sizeof(res_buffer), res_buffer)) - { - throw_iscerror(stat); - } - - // We must get back a isc_info_sql_records block, that we parse below, - // followed by isc_info_end. - if (res_buffer[0] != isc_info_sql_records) - { - throw soci_error("Can't determine the number of affected rows"); - } - - char* sql_rec_buf = res_buffer + 1; - const int length = isc_vax_integer(sql_rec_buf, 2); - sql_rec_buf += 2; - - if (sql_rec_buf[length] != isc_info_end) - { - throw soci_error("Unexpected isc_info_sql_records return format"); - } - - // Examine the 4 sub-blocks each of which has a header indicating the block - // type, its value length in bytes and the value itself. - long long row_count = 0; - - for ( char* p = sql_rec_buf; !row_count && p < sql_rec_buf + length; ) - { - switch (*p++) - { - case isc_info_req_select_count: - case isc_info_req_insert_count: - case isc_info_req_update_count: - case isc_info_req_delete_count: - { - int len = isc_vax_integer(p, 2); - p += 2; - - row_count += isc_vax_integer(p, static_cast(len)); - p += len; - } - break; - - case isc_info_end: - break; - - default: - throw soci_error("Unknown record counter"); - } - } - - return row_count; -} - -int firebird_statement_backend::get_number_of_rows() -{ - return rowsFetched_; -} - -std::string firebird_statement_backend::get_parameter_name(int index) const -{ - for (std::map::const_iterator i = names_.begin(); - i != names_.end(); - ++i) - { - if (i->second == index) - return i->first; - } - - return std::string(); -} - -std::string firebird_statement_backend::rewrite_for_procedure_call( - std::string const &query) -{ - procedure_ = true; - return query; -} - -int firebird_statement_backend::prepare_for_describe() -{ - return static_cast(sqldap_->sqld); -} - -void firebird_statement_backend::describe_column(int colNum, - data_type & type, std::string & columnName) -{ - XSQLVAR * var = sqldap_->sqlvar+(colNum-1); - - columnName.assign(var->aliasname, var->aliasname_length); - - switch (var->sqltype & ~1) - { - case SQL_TEXT: - case SQL_VARYING: - type = dt_string; - break; - case SQL_TYPE_DATE: - case SQL_TYPE_TIME: - case SQL_TIMESTAMP: - type = dt_date; - break; - case SQL_FLOAT: - case SQL_DOUBLE: - type = dt_double; - break; - case SQL_SHORT: - case SQL_LONG: - if (var->sqlscale < 0) - { - if (session_.get_option_decimals_as_strings()) - type = dt_string; - else - type = dt_double; - } - else - { - type = dt_integer; - } - break; - case SQL_INT64: - if (var->sqlscale < 0) - { - if (session_.get_option_decimals_as_strings()) - type = dt_string; - else - type = dt_double; - } - else - { - type = dt_long_long; - } - break; - /* case SQL_BLOB: - case SQL_ARRAY:*/ - default: - std::ostringstream msg; - msg << "Type of column ["<< colNum << "] \"" << columnName - << "\" is not supported for dynamic queries"; - throw soci_error(msg.str()); - break; - } -} - -firebird_standard_into_type_backend * firebird_statement_backend::make_into_type_backend() -{ - return new firebird_standard_into_type_backend(*this); -} - -firebird_standard_use_type_backend * firebird_statement_backend::make_use_type_backend() -{ - return new firebird_standard_use_type_backend(*this); -} - -firebird_vector_into_type_backend * firebird_statement_backend::make_vector_into_type_backend() -{ - return new firebird_vector_into_type_backend(*this); -} - -firebird_vector_use_type_backend * firebird_statement_backend::make_vector_use_type_backend() -{ - return new firebird_vector_use_type_backend(*this); -} diff --git a/src/soci/src/backends/firebird/vector-into-type.cpp b/src/soci/src/backends/firebird/vector-into-type.cpp deleted file mode 100644 index 6a522f30ba..0000000000 --- a/src/soci/src/backends/firebird/vector-into-type.cpp +++ /dev/null @@ -1,208 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, Rafal Bobrowski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_FIREBIRD_SOURCE -#include "soci/firebird/soci-firebird.h" -#include "firebird/common.h" - -using namespace soci; -using namespace soci::details; -using namespace soci::details::firebird; - -void firebird_vector_into_type_backend::define_by_pos( - int & position, void * data, exchange_type type) -{ - position_ = position-1; - data_ = data; - type_ = type; - - ++position; - - statement_.intoType_ = eVector; - statement_.intos_.push_back(static_cast(this)); - - XSQLVAR *var = statement_.sqldap_->sqlvar+position_; - - buf_ = allocBuffer(var); - var->sqldata = buf_; - var->sqlind = &indISCHolder_; -} - -void firebird_vector_into_type_backend::pre_fetch() -{ - // Nothing to do here. -} - -namespace // anonymous -{ -template -void setIntoVector(void *p, std::size_t indx, T const &val) -{ - std::vector *dest = - static_cast *>(p); - - std::vector &v = *dest; - v[indx] = val; -} - -} // namespace anonymous - -// this will exchange data with vector user buffers -void firebird_vector_into_type_backend::exchangeData(std::size_t row) -{ - XSQLVAR *var = statement_.sqldap_->sqlvar+position_; - - switch (type_) - { - // simple cases - case x_char: - setIntoVector(data_, row, getTextParam(var)[0]); - break; - case x_short: - { - short tmp = from_isc(var); - setIntoVector(data_, row, tmp); - } - break; - case x_integer: - { - int tmp = from_isc(var); - setIntoVector(data_, row, tmp); - } - break; - case x_long_long: - { - long long tmp = from_isc(var); - setIntoVector(data_, row, tmp); - } - break; - case x_double: - { - double tmp = from_isc(var); - setIntoVector(data_, row, tmp); - } - break; - - // cases that require adjustments and buffer management - case x_stdstring: - setIntoVector(data_, row, getTextParam(var)); - break; - case x_stdtm: - { - std::tm data = std::tm(); - tmDecode(var->sqltype, buf_, &data); - setIntoVector(data_, row, data); - } - break; - - default: - throw soci_error("Into vector element used with non-supported type."); - } // switch - -} - -void firebird_vector_into_type_backend::post_fetch( - bool gotData, indicator * ind) -{ - // Here we have to set indicators only. Data was exchanged with user - // buffers during fetch() - if (gotData) - { - std::size_t rows = statement_.rowsFetched_; - - for (std::size_t i = 0; i (data_, sz); - break; - case x_short: - resizeVector (data_, sz); - break; - case x_integer: - resizeVector (data_, sz); - break; - case x_long_long: - resizeVector (data_, sz); - break; - case x_double: - resizeVector (data_, sz); - break; - case x_stdstring: - resizeVector (data_, sz); - break; - case x_stdtm: - resizeVector (data_, sz); - break; - - default: - throw soci_error("Into vector element used with non-supported type."); - } -} - -std::size_t firebird_vector_into_type_backend::size() -{ - std::size_t sz = 0; // dummy initialization to please the compiler - switch (type_) - { - // simple cases - case x_char: - sz = getVectorSize (data_); - break; - case x_short: - sz = getVectorSize (data_); - break; - case x_integer: - sz = getVectorSize (data_); - break; - case x_long_long: - sz = getVectorSize (data_); - break; - case x_double: - sz = getVectorSize (data_); - break; - case x_stdstring: - sz = getVectorSize (data_); - break; - case x_stdtm: - sz = getVectorSize (data_); - break; - - default: - throw soci_error("Into vector element used with non-supported type."); - } - - return sz; -} - -void firebird_vector_into_type_backend::clean_up() -{ - if (buf_ != NULL) - { - delete [] buf_; - buf_ = NULL; - } - std::vector::iterator it = - std::find(statement_.intos_.begin(), statement_.intos_.end(), this); - if (it != statement_.intos_.end()) - statement_.intos_.erase(it); -} diff --git a/src/soci/src/backends/firebird/vector-use-type.cpp b/src/soci/src/backends/firebird/vector-use-type.cpp deleted file mode 100644 index 392c0e5d67..0000000000 --- a/src/soci/src/backends/firebird/vector-use-type.cpp +++ /dev/null @@ -1,207 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, Rafal Bobrowski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_FIREBIRD_SOURCE -#include "soci/firebird/soci-firebird.h" -#include "firebird/common.h" - -using namespace soci; -using namespace soci::details; -using namespace soci::details::firebird; - -void firebird_vector_use_type_backend::bind_by_pos(int & position, - void * data, exchange_type type) -{ - if (statement_.boundByName_) - { - throw soci_error( - "Binding for use elements must be either by position or by name."); - } - - position_ = position-1; - data_ = data; - type_ = type; - - ++position; - - statement_.useType_ = eVector; - statement_.uses_.push_back(static_cast(this)); - - XSQLVAR *var = statement_.sqlda2p_->sqlvar+position_; - - buf_ = allocBuffer(var); - var->sqldata = buf_; - var->sqlind = &indISCHolder_; - - statement_.boundByPos_ = true; -} - -void firebird_vector_use_type_backend::bind_by_name( - std::string const & name, void * data, exchange_type type) -{ - if (statement_.boundByPos_) - { - throw soci_error( - "Binding for use elements must be either by position or by name."); - } - - std::map :: iterator idx = - statement_.names_.find(name); - - if (idx == statement_.names_.end()) - { - throw soci_error("Missing use element for bind by name (" + name + ")"); - } - - position_ = idx->second; - data_ = data; - type_ = type; - - statement_.useType_ = eVector; - statement_.uses_.push_back(static_cast(this)); - - XSQLVAR *var = statement_.sqlda2p_->sqlvar+position_; - - buf_ = allocBuffer(var); - var->sqldata = buf_; - var->sqlind = &indISCHolder_; - - statement_.boundByName_ = true; -} - -void firebird_vector_use_type_backend::pre_use(indicator const * ind) -{ - inds_ = ind; -} - -namespace -{ -template -T* getUseVectorValue(void *v, std::size_t index) -{ - std::vector *src = - static_cast *>(v); - - std::vector &v_ = *src; - return &(v_[index]); -} -} - -void firebird_vector_use_type_backend::exchangeData(std::size_t row) -{ - // first prepare indicators - if (inds_ != NULL) - { - switch (inds_[row]) - { - case i_null: - indISCHolder_ = -1; - break; - case i_ok: - indISCHolder_ = 0; - break; - default: - throw soci_error("Use element used with non-supported indicator type."); - } - } - - XSQLVAR * var = statement_.sqlda2p_->sqlvar+position_; - - // then set parameters for query execution - switch (type_) - { - // simple cases - case x_char: - setTextParam(getUseVectorValue(data_, row), 1, buf_, var); - break; - case x_short: - to_isc( - static_cast(getUseVectorValue(data_, row)), - var); - break; - case x_integer: - to_isc( - static_cast(getUseVectorValue(data_, row)), - var); - break; - case x_long_long: - to_isc( - static_cast(getUseVectorValue(data_, row)), - var); - break; - case x_double: - to_isc( - static_cast(getUseVectorValue(data_, row)), - var); - break; - - // cases that require adjustments and buffer management - case x_stdstring: - { - std::string *tmp = getUseVectorValue(data_, row); - setTextParam(tmp->c_str(), tmp->size(), buf_, var); - } - break; - case x_stdtm: - tmEncode(var->sqltype, - getUseVectorValue(data_, row), buf_); - break; - // Not supported - // case x_cstring: - // case x_blob: - default: - throw soci_error("Use element used with non-supported type."); - } // switch -} - -std::size_t firebird_vector_use_type_backend::size() -{ - std::size_t sz = 0; // dummy initialization to please the compiler - switch (type_) - { - // simple cases - case x_char: - sz = getVectorSize (data_); - break; - case x_short: - sz = getVectorSize (data_); - break; - case x_integer: - sz = getVectorSize (data_); - break; - case x_long_long: - sz = getVectorSize (data_); - break; - case x_double: - sz = getVectorSize (data_); - break; - case x_stdstring: - sz = getVectorSize (data_); - break; - case x_stdtm: - sz = getVectorSize (data_); - break; - - default: - throw soci_error("Use vector element used with non-supported type."); - } - - return sz; -} - -void firebird_vector_use_type_backend::clean_up() -{ - if (buf_ != NULL) - { - delete [] buf_; - buf_ = NULL; - } - std::vector::iterator it = - std::find(statement_.uses_.begin(), statement_.uses_.end(), this); - if (it != statement_.uses_.end()) - statement_.uses_.erase(it); -} diff --git a/src/soci/src/backends/mysql/CMakeLists.txt b/src/soci/src/backends/mysql/CMakeLists.txt deleted file mode 100644 index b2dcc9ceb3..0000000000 --- a/src/soci/src/backends/mysql/CMakeLists.txt +++ /dev/null @@ -1,15 +0,0 @@ -############################################################################### -# -# This file is part of CMake configuration for SOCI library -# -# Copyright (C) 2010 Mateusz Loskot -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -# -############################################################################### -soci_backend(MySQL - DEPENDS MySQL - DESCRIPTION "SOCI backend for MySQL" - AUTHORS "Pawel Aleksander Fedorynski" - MAINTAINERS "Pawel Aleksander Fedorynski") diff --git a/src/soci/src/backends/mysql/Makefile.basic b/src/soci/src/backends/mysql/Makefile.basic deleted file mode 100644 index 0073fadd36..0000000000 --- a/src/soci/src/backends/mysql/Makefile.basic +++ /dev/null @@ -1,97 +0,0 @@ -# The following variables are specific to this backend and their correct -# values might depend on your environment - feel free to set it accordingly. - -MYSQLLIBDIR = -L/usr/lib/mysql -MYSQLLIBS = -lmysqlclient -lz -MYSQLINCLUDEDIR = -I/usr/include/mysql - -# The rest of the Makefile is independent of the target environment. - -COMPILER = g++ -CXXFLAGS = -Wall -pedantic -Wno-long-long -CXXFLAGSSO = ${CXXFLAGS} -fPIC -INCLUDEDIRS = -I../../core ${MYSQLINCLUDEDIR} - - -OBJECTS = blob.o factory.o row-id.o session.o standard-into-type.o \ - standard-use-type.o statement.o vector-into-type.o vector-use-type.o \ - common.o - - -OBJECTSSO = blob-s.o factory-s.o row-id-s.o session-s.o \ - standard-into-type-s.o standard-use-type-s.o statement-s.o \ - vector-into-type-s.o vector-use-type-s.o common-s.o - - -libsoci_mysql.a : ${OBJECTS} - ar rv $@ $? - rm *.o - - -blob.o : blob.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -common.o : common.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -factory.o : factory.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -row-id.o : row-id.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -session.o : session.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -standard-into-type.o : standard-into-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -standard-use-type.o : standard-use-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -statement.o : statement.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -vector-into-type.o : vector-into-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -vector-use-type.o : vector-use-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -shared : ${OBJECTSSO} - ${COMPILER} -shared -o libsoci_mysql.so ${OBJECTSSO} - rm *.o - -blob-s.o : blob.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -common-s.o : common.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -factory-s.o : factory.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -row-id-s.o : row-id.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -session-s.o : session.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -standard-into-type-s.o : standard-into-type.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -standard-use-type-s.o : standard-use-type.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -statement-s.o : statement.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -vector-into-type-s.o : vector-into-type.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -vector-use-type-s.o : vector-use-type.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - - -clean : - rm -f libsoci_mysql.a libsoci_mysql.so diff --git a/src/soci/src/backends/mysql/blob.cpp b/src/soci/src/backends/mysql/blob.cpp deleted file mode 100644 index 127e78a0cd..0000000000 --- a/src/soci/src/backends/mysql/blob.cpp +++ /dev/null @@ -1,62 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// MySQL backend copyright (C) 2006 Pawel Aleksander Fedorynski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_MYSQL_SOURCE -#include "soci/mysql/soci-mysql.h" -#include - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4355 4702) -#endif - -using namespace soci; -using namespace soci::details; - -mysql_blob_backend::mysql_blob_backend(mysql_session_backend &session) - : session_(session) -{ - throw soci_error("BLOBs are not supported."); -} - -mysql_blob_backend::~mysql_blob_backend() -{ -} - -std::size_t mysql_blob_backend::get_len() -{ - throw soci_error("BLOBs are not supported."); -} - -std::size_t mysql_blob_backend::read( - std::size_t /* offset */, char * /* buf */, std::size_t /* toRead */) -{ - throw soci_error("BLOBs are not supported."); -} - -std::size_t mysql_blob_backend::write( - std::size_t /* offset */, char const * /* buf */, - std::size_t /* toWrite */) -{ - throw soci_error("BLOBs are not supported."); -} - -std::size_t mysql_blob_backend::append( - char const * /* buf */, std::size_t /* toWrite */) -{ - throw soci_error("BLOBs are not supported."); -} - -void mysql_blob_backend::trim(std::size_t /* newLen */) -{ - throw soci_error("BLOBs are not supported."); -} - -#ifdef _MSC_VER -#pragma warning(pop) -#endif diff --git a/src/soci/src/backends/mysql/common.cpp b/src/soci/src/backends/mysql/common.cpp deleted file mode 100644 index 7a06e00dcb..0000000000 --- a/src/soci/src/backends/mysql/common.cpp +++ /dev/null @@ -1,23 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#include "common.h" -#include -#include -#include -#include - -char * soci::details::mysql::quote(MYSQL * conn, const char *s, size_t len) -{ - char *retv = new char[2 * len + 3]; - retv[0] = '\''; - int len_esc = mysql_real_escape_string(conn, retv + 1, s, static_cast(len)); - retv[len_esc + 1] = '\''; - retv[len_esc + 2] = '\0'; - - return retv; -} diff --git a/src/soci/src/backends/mysql/common.h b/src/soci/src/backends/mysql/common.h deleted file mode 100644 index 0d822c4b16..0000000000 --- a/src/soci/src/backends/mysql/common.h +++ /dev/null @@ -1,90 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_MYSQL_COMMON_H_INCLUDED -#define SOCI_MYSQL_COMMON_H_INCLUDED - -#include "soci/mysql/soci-mysql.h" -#include "soci-cstrtod.h" -#include "soci-compiler.h" -// std -#include -#include -#include -#include -#include - -namespace soci -{ - -namespace details -{ - -namespace mysql -{ - -// The idea is that infinity - infinity gives NaN, and NaN != NaN is true. -// -// This should work on any IEEE-754-compliant implementation, which is -// another way of saying that it does not always work (in particular, -// according to stackoverflow, it won't work with gcc with the --fast-math -// option), but I know of no better way of testing this portably in C++ prior -// to C++11. When soci moves to C++11 this should be replaced -// with std::isfinite(). -template -bool is_infinity_or_nan(T x) -{ - T y = x - x; - - // We really need exact floating point comparison here. - GCC_WARNING_SUPPRESS(float-equal) - - return (y != y); - - GCC_WARNING_RESTORE(float-equal) -} - -template -void parse_num(char const *buf, T &x) -{ - std::istringstream iss(buf); - iss >> x; - if (iss.fail() || (iss.eof() == false)) - { - throw soci_error("Cannot convert data."); - } -} - -inline -void parse_num(char const *buf, double &x) -{ - x = cstring_to_double(buf); - - if (is_infinity_or_nan(x)) { - throw soci_error(std::string("Cannot convert data: string \"") + buf + - "\" is not a finite number."); - } -} - -// helper for escaping strings -char * quote(MYSQL * conn, const char *s, size_t len); - -// helper for vector operations -template -std::size_t get_vector_size(void *p) -{ - std::vector *v = static_cast *>(p); - return v->size(); -} - -} // namespace mysql - -} // namespace details - -} // namespace soci - -#endif // SOCI_MYSQL_COMMON_H_INCLUDED diff --git a/src/soci/src/backends/mysql/factory.cpp b/src/soci/src/backends/mysql/factory.cpp deleted file mode 100644 index ee41340237..0000000000 --- a/src/soci/src/backends/mysql/factory.cpp +++ /dev/null @@ -1,45 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// MySQL backend copyright (C) 2006 Pawel Aleksander Fedorynski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_MYSQL_SOURCE -#include "soci/mysql/soci-mysql.h" -#include "soci/backend-loader.h" -#include - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; - - -// concrete factory for MySQL concrete strategies -mysql_session_backend * mysql_backend_factory::make_session( - connection_parameters const & parameters) const -{ - return new mysql_session_backend(parameters); -} - -mysql_backend_factory const soci::mysql; - -extern "C" -{ - -// for dynamic backend loading -SOCI_MYSQL_DECL backend_factory const * factory_mysql() -{ - return &soci::mysql; -} - -SOCI_MYSQL_DECL void register_factory_mysql() -{ - soci::dynamic_backends::register_backend("mysql", soci::mysql); -} - -} // extern "C" diff --git a/src/soci/src/backends/mysql/row-id.cpp b/src/soci/src/backends/mysql/row-id.cpp deleted file mode 100644 index 2121327202..0000000000 --- a/src/soci/src/backends/mysql/row-id.cpp +++ /dev/null @@ -1,32 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// MySQL backend copyright (C) 2006 Pawel Aleksander Fedorynski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_MYSQL_SOURCE -#include "soci/mysql/soci-mysql.h" - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4355 4702) -#endif - -using namespace soci; -using namespace soci::details; - -mysql_rowid_backend::mysql_rowid_backend( - mysql_session_backend & /* session */) -{ - throw soci_error("RowIDs are not supported."); -} - -mysql_rowid_backend::~mysql_rowid_backend() -{ -} - -#ifdef _MSC_VER -#pragma warning(pop) -#endif diff --git a/src/soci/src/backends/mysql/session.cpp b/src/soci/src/backends/mysql/session.cpp deleted file mode 100644 index a782418047..0000000000 --- a/src/soci/src/backends/mysql/session.cpp +++ /dev/null @@ -1,422 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// MySQL backend copyright (C) 2006 Pawel Aleksander Fedorynski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_MYSQL_SOURCE -#include "soci/mysql/soci-mysql.h" -#include "soci/connection-parameters.h" -// std -#include -#include -#include -#include -#include -#include -#include - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; -using std::string; - - -namespace -{ // anonymous - -void skip_white(std::string::const_iterator *i, - std::string::const_iterator const & end, bool endok) -{ - for (;;) - { - if (*i == end) - { - if (endok) - { - return; - } - else - { - throw soci_error("Unexpected end of connection string."); - } - } - if (std::isspace(**i)) - { - ++*i; - } - else - { - return; - } - } -} - -std::string param_name(std::string::const_iterator *i, - std::string::const_iterator const & end) -{ - std::string val(""); - for (;;) - { - if (*i == end || (!std::isalpha(**i) && **i != '_')) - { - break; - } - val += **i; - ++*i; - } - return val; -} - -string param_value(string::const_iterator *i, - string::const_iterator const & end) -{ - string err = "Malformed connection string."; - bool quot; - if (**i == '\'') - { - quot = true; - ++*i; - } - else - { - quot = false; - } - string val(""); - for (;;) - { - if (*i == end) - { - if (quot) - { - throw soci_error(err); - } - else - { - break; - } - } - if (**i == '\'') - { - if (quot) - { - ++*i; - break; - } - else - { - throw soci_error(err); - } - } - if (!quot && std::isspace(**i)) - { - break; - } - if (**i == '\\') - { - ++*i; - if (*i == end) - { - throw soci_error(err); - } - } - val += **i; - ++*i; - } - return val; -} - -bool valid_int(const string & s) -{ - char *tail; - const char *cstr = s.c_str(); - errno = 0; - long n = std::strtol(cstr, &tail, 10); - if (errno != 0 || n > INT_MAX || n < INT_MIN) - { - return false; - } - if (*tail != '\0') - { - return false; - } - return true; -} - -void parse_connect_string(const string & connectString, - string *host, bool *host_p, - string *user, bool *user_p, - string *password, bool *password_p, - string *db, bool *db_p, - string *unix_socket, bool *unix_socket_p, - int *port, bool *port_p, string *ssl_ca, bool *ssl_ca_p, - string *ssl_cert, bool *ssl_cert_p, string *ssl_key, bool *ssl_key_p, - int *local_infile, bool *local_infile_p, - string *charset, bool *charset_p) -{ - *host_p = false; - *user_p = false; - *password_p = false; - *db_p = false; - *unix_socket_p = false; - *port_p = false; - *ssl_ca_p = false; - *ssl_cert_p = false; - *ssl_key_p = false; - *local_infile_p = false; - *charset_p = false; - string err = "Malformed connection string."; - string::const_iterator i = connectString.begin(), - end = connectString.end(); - while (i != end) - { - skip_white(&i, end, true); - if (i == end) - { - return; - } - string par = param_name(&i, end); - skip_white(&i, end, false); - if (*i == '=') - { - ++i; - } - else - { - throw soci_error(err); - } - skip_white(&i, end, false); - string val = param_value(&i, end); - if (par == "port" && !*port_p) - { - if (!valid_int(val)) - { - throw soci_error(err); - } - *port = std::atoi(val.c_str()); - if (*port < 0) - { - throw soci_error(err); - } - *port_p = true; - } - else if (par == "host" && !*host_p) - { - *host = val; - *host_p = true; - } - else if (par == "user" && !*user_p) - { - *user = val; - *user_p = true; - } - else if ((par == "pass" || par == "password") && !*password_p) - { - *password = val; - *password_p = true; - } - else if ((par == "db" || par == "dbname" || par == "service") and !*db_p) - { - *db = val; - *db_p = true; - } - else if (par == "unix_socket" && !*unix_socket_p) - { - *unix_socket = val; - *unix_socket_p = true; - } - else if (par == "sslca" && !*ssl_ca_p) - { - *ssl_ca = val; - *ssl_ca_p = true; - } - else if (par == "sslcert" && !*ssl_cert_p) - { - *ssl_cert = val; - *ssl_cert_p = true; - } - else if (par == "sslkey" && !*ssl_key_p) - { - *ssl_key = val; - *ssl_key_p = true; - } - else if (par == "local_infile" && !*local_infile_p) - { - if (!valid_int(val)) - { - throw soci_error(err); - } - *local_infile = std::atoi(val.c_str()); - if (*local_infile != 0 && *local_infile != 1) - { - throw soci_error(err); - } - *local_infile_p = true; - } else if (par == "charset" && !*charset_p) - { - *charset = val; - *charset_p = true; - } - else - { - throw soci_error(err); - } - } -} - -} // namespace anonymous - - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wuninitialized" -#endif - -#if defined(__GNUC__) && ( __GNUC__ > 4 || (__GNUC__ == 4 && (__GNUC_MINOR__ > 6))) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" -#endif - - -mysql_session_backend::mysql_session_backend( - connection_parameters const & parameters) -{ - string host, user, password, db, unix_socket, ssl_ca, ssl_cert, ssl_key, - charset; - int port, local_infile; - bool host_p, user_p, password_p, db_p, unix_socket_p, port_p, - ssl_ca_p, ssl_cert_p, ssl_key_p, local_infile_p, charset_p; - parse_connect_string(parameters.get_connect_string(), &host, &host_p, &user, &user_p, - &password, &password_p, &db, &db_p, - &unix_socket, &unix_socket_p, &port, &port_p, - &ssl_ca, &ssl_ca_p, &ssl_cert, &ssl_cert_p, &ssl_key, &ssl_key_p, - &local_infile, &local_infile_p, &charset, &charset_p); - conn_ = mysql_init(NULL); - if (conn_ == NULL) - { - throw soci_error("mysql_init() failed."); - } - if (charset_p) - { - if (0 != mysql_options(conn_, MYSQL_SET_CHARSET_NAME, charset.c_str())) - { - clean_up(); - throw soci_error("mysql_options(MYSQL_SET_CHARSET_NAME) failed."); - } - } - if (ssl_ca_p) - { - mysql_ssl_set(conn_, ssl_key_p ? ssl_key.c_str() : NULL, - ssl_cert_p ? ssl_cert.c_str() : NULL, - ssl_ca.c_str(), 0, 0); - } - if (local_infile_p && local_infile == 1) - { - if (0 != mysql_options(conn_, MYSQL_OPT_LOCAL_INFILE, NULL)) - { - clean_up(); - throw soci_error( - "mysql_options() failed when trying to set local-infile."); - } - } - if (mysql_real_connect(conn_, - host_p ? host.c_str() : NULL, - user_p ? user.c_str() : NULL, - password_p ? password.c_str() : NULL, - db_p ? db.c_str() : NULL, - port_p ? port : 0, - unix_socket_p ? unix_socket.c_str() : NULL, -#ifdef CLIENT_MULTI_RESULTS - CLIENT_FOUND_ROWS | CLIENT_MULTI_RESULTS) == NULL) -#else - CLIENT_FOUND_ROWS) == NULL) -#endif - { - string errMsg = mysql_error(conn_); - unsigned int errNum = mysql_errno(conn_); - clean_up(); - throw mysql_soci_error(errMsg, errNum); - } -} - -#if defined(__GNUC__) && ( __GNUC__ > 4 || (__GNUC__ == 4 && (__GNUC_MINOR__ > 6))) -#pragma GCC diagnostic pop -#endif - -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - - - -mysql_session_backend::~mysql_session_backend() -{ - clean_up(); -} - -namespace // unnamed -{ - -// helper function for hardcoded queries -void hard_exec(MYSQL *conn, const string & query) -{ - if (0 != mysql_real_query(conn, query.c_str(), - static_cast(query.size()))) - { - throw soci_error(mysql_error(conn)); - } -} - -} // namespace unnamed - -void mysql_session_backend::begin() -{ - hard_exec(conn_, "BEGIN"); -} - -void mysql_session_backend::commit() -{ - hard_exec(conn_, "COMMIT"); -} - -void mysql_session_backend::rollback() -{ - hard_exec(conn_, "ROLLBACK"); -} - -bool mysql_session_backend::get_last_insert_id( - session & /* s */, std::string const & /* table */, long & value) -{ - value = static_cast(mysql_insert_id(conn_)); - - return true; -} - -void mysql_session_backend::clean_up() -{ - if (conn_ != NULL) - { - mysql_close(conn_); - conn_ = NULL; - } -} - -mysql_statement_backend * mysql_session_backend::make_statement_backend() -{ - return new mysql_statement_backend(*this); -} - -mysql_rowid_backend * mysql_session_backend::make_rowid_backend() -{ - return new mysql_rowid_backend(*this); -} - -mysql_blob_backend * mysql_session_backend::make_blob_backend() -{ - return new mysql_blob_backend(*this); -} diff --git a/src/soci/src/backends/mysql/standard-into-type.cpp b/src/soci/src/backends/mysql/standard-into-type.cpp deleted file mode 100644 index 06dfc47cc0..0000000000 --- a/src/soci/src/backends/mysql/standard-into-type.cpp +++ /dev/null @@ -1,120 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// MySQL backend copyright (C) 2006 Pawel Aleksander Fedorynski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_MYSQL_SOURCE -#include "soci/mysql/soci-mysql.h" -#include "soci/soci-platform.h" -#include "common.h" -#include "soci-exchange-cast.h" -#include "soci-mktime.h" -// std -#include -#include -#include -#include -#include - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; -using namespace soci::details::mysql; - - -void mysql_standard_into_type_backend::define_by_pos( - int &position, void *data, exchange_type type) -{ - data_ = data; - type_ = type; - position_ = position++; -} - -void mysql_standard_into_type_backend::pre_fetch() -{ - // nothing to do here -} - -void mysql_standard_into_type_backend::post_fetch( - bool gotData, bool calledFromFetch, indicator *ind) -{ - if (calledFromFetch == true && gotData == false) - { - // this is a normal end-of-rowset condition, - // no need to do anything (fetch() will return false) - return; - } - - if (gotData) - { - int pos = position_ - 1; - //mysql_data_seek(statement_.result_, statement_.currentRow_); - mysql_row_seek(statement_.result_, - statement_.resultRowOffsets_[statement_.currentRow_]); - MYSQL_ROW row = mysql_fetch_row(statement_.result_); - if (row[pos] == NULL) - { - if (ind == NULL) - { - throw soci_error( - "Null value fetched and no indicator defined."); - } - *ind = i_null; - return; - } - else - { - if (ind != NULL) - { - *ind = i_ok; - } - } - const char *buf = row[pos] != NULL ? row[pos] : ""; - switch (type_) - { - case x_char: - exchange_type_cast(data_) = *buf; - break; - case x_stdstring: - { - std::string& dest = exchange_type_cast(data_); - unsigned long * lengths = - mysql_fetch_lengths(statement_.result_); - dest.assign(buf, lengths[pos]); - } - break; - case x_short: - parse_num(buf, exchange_type_cast(data_)); - break; - case x_integer: - parse_num(buf, exchange_type_cast(data_)); - break; - case x_long_long: - parse_num(buf, exchange_type_cast(data_)); - break; - case x_unsigned_long_long: - parse_num(buf, exchange_type_cast(data_)); - break; - case x_double: - parse_num(buf, exchange_type_cast(data_)); - break; - case x_stdtm: - // attempt to parse the string and convert to std::tm - parse_std_tm(buf, exchange_type_cast(data_)); - break; - default: - throw soci_error("Into element used with non-supported type."); - } - } -} - -void mysql_standard_into_type_backend::clean_up() -{ - // nothing to do here -} diff --git a/src/soci/src/backends/mysql/standard-use-type.cpp b/src/soci/src/backends/mysql/standard-use-type.cpp deleted file mode 100644 index 608339a847..0000000000 --- a/src/soci/src/backends/mysql/standard-use-type.cpp +++ /dev/null @@ -1,170 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// MySQL backend copyright (C) 2006 Pawel Aleksander Fedorynski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_MYSQL_SOURCE -#include "soci/mysql/soci-mysql.h" -#include "common.h" -#include "soci/soci-platform.h" -#include "soci-dtocstr.h" -#include "soci-exchange-cast.h" -// std -#include -#include -#include -#include - -using namespace soci; -using namespace soci::details; -using namespace soci::details::mysql; - - -void mysql_standard_use_type_backend::bind_by_pos( - int &position, void *data, exchange_type type, bool /* readOnly */) -{ - data_ = data; - type_ = type; - position_ = position++; -} - -void mysql_standard_use_type_backend::bind_by_name( - std::string const &name, void *data, exchange_type type, bool /* readOnly */) -{ - data_ = data; - type_ = type; - name_ = name; -} - -void mysql_standard_use_type_backend::pre_use(indicator const *ind) -{ - if (ind != NULL && *ind == i_null) - { - buf_ = new char[5]; - std::strcpy(buf_, "NULL"); - } - else - { - // allocate and fill the buffer with text-formatted client data - switch (type_) - { - case x_char: - { - char buf[] = { exchange_type_cast(data_), '\0' }; - buf_ = quote(statement_.session_.conn_, buf, 1); - } - break; - case x_stdstring: - { - std::string const& s = exchange_type_cast(data_); - buf_ = quote(statement_.session_.conn_, - s.c_str(), s.size()); - } - break; - case x_short: - { - std::size_t const bufSize - = std::numeric_limits::digits10 + 3; - buf_ = new char[bufSize]; - snprintf(buf_, bufSize, "%d", - static_cast(exchange_type_cast(data_))); - } - break; - case x_integer: - { - std::size_t const bufSize - = std::numeric_limits::digits10 + 3; - buf_ = new char[bufSize]; - snprintf(buf_, bufSize, "%d", exchange_type_cast(data_)); - } - break; - case x_long_long: - { - std::size_t const bufSize - = std::numeric_limits::digits10 + 3; - buf_ = new char[bufSize]; - snprintf(buf_, bufSize, "%" LL_FMT_FLAGS "d", exchange_type_cast(data_)); - } - break; - case x_unsigned_long_long: - { - std::size_t const bufSize - = std::numeric_limits::digits10 + 3; - buf_ = new char[bufSize]; - snprintf(buf_, bufSize, "%" LL_FMT_FLAGS "u", - exchange_type_cast(data_)); - } - break; - - case x_double: - { - double const d = exchange_type_cast(data_); - if (is_infinity_or_nan(d)) { - throw soci_error( - "Use element used with infinity or NaN, which are " - "not supported by the MySQL server."); - } - - std::string const s = double_to_cstring(d); - - buf_ = new char[s.size() + 1]; - std::strcpy(buf_, s.c_str()); - } - break; - case x_stdtm: - { - std::size_t const bufSize = 22; - buf_ = new char[bufSize]; - - std::tm const& t = exchange_type_cast(data_); - snprintf(buf_, bufSize, - "\'%d-%02d-%02d %02d:%02d:%02d\'", - t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, - t.tm_hour, t.tm_min, t.tm_sec); - } - break; - default: - throw soci_error("Use element used with non-supported type."); - } - } - - if (position_ > 0) - { - // binding by position - statement_.useByPosBuffers_[position_] = &buf_; - } - else - { - // binding by name - statement_.useByNameBuffers_[name_] = &buf_; - } -} - -void mysql_standard_use_type_backend::post_use(bool /*gotData*/, indicator* /*ind*/) -{ - // TODO: Is it possible to have the bound element being overwritten - // by the database? - // If not, then nothing to do here, please remove this comment. - // If yes, then use the value of the readOnly parameter: - // - true: the given object should not be modified and the backend - // should detect if the modification was performed on the - // isolated buffer and throw an exception if the buffer was modified - // (this indicates logic error, because the user used const object - // and executed a query that attempted to modified it) - // - false: the modification should be propagated to the given object. - // ... - - clean_up(); -} - -void mysql_standard_use_type_backend::clean_up() -{ - if (buf_ != NULL) - { - delete [] buf_; - buf_ = NULL; - } -} diff --git a/src/soci/src/backends/mysql/statement.cpp b/src/soci/src/backends/mysql/statement.cpp deleted file mode 100644 index cc70e15816..0000000000 --- a/src/soci/src/backends/mysql/statement.cpp +++ /dev/null @@ -1,484 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// MySQL backend copyright (C) 2006 Pawel Aleksander Fedorynski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_MYSQL_SOURCE -#include "soci/mysql/soci-mysql.h" -#include -#include - -using namespace soci; -using namespace soci::details; -using std::string; - - -mysql_statement_backend::mysql_statement_backend( - mysql_session_backend &session) - : session_(session), result_(NULL), - rowsAffectedBulk_(-1LL), justDescribed_(false), - hasIntoElements_(false), hasVectorIntoElements_(false), - hasUseElements_(false), hasVectorUseElements_(false) -{ -} - -void mysql_statement_backend::alloc() -{ - // nothing to do here. -} - -void mysql_statement_backend::clean_up() -{ - // 'reset' the value for a - // potential new execution. - rowsAffectedBulk_ = -1; - - if (result_ != NULL) - { - mysql_free_result(result_); - result_ = NULL; - } -} - -void mysql_statement_backend::prepare(std::string const & query, - statement_type /* eType */) -{ - queryChunks_.clear(); - enum { eNormal, eInQuotes, eInName } state = eNormal; - - std::string name; - queryChunks_.push_back(""); - - bool escaped = false; - for (std::string::const_iterator it = query.begin(), end = query.end(); - it != end; ++it) - { - switch (state) - { - case eNormal: - if (*it == '\'') - { - queryChunks_.back() += *it; - state = eInQuotes; - } - else if (*it == ':') - { - const std::string::const_iterator next_it = it + 1; - // Check whether this is an assignment (e.g. @x:=y) - // and treat it as a special case, not as a named binding. - if (next_it != end && *next_it == '=') - { - queryChunks_.back() += ":="; - ++it; - } - else - { - state = eInName; - } - } - else // regular character, stay in the same state - { - queryChunks_.back() += *it; - } - break; - case eInQuotes: - if (*it == '\'' && !escaped) - { - queryChunks_.back() += *it; - state = eNormal; - } - else // regular quoted character - { - queryChunks_.back() += *it; - } - escaped = *it == '\\' && !escaped; - break; - case eInName: - if (std::isalnum(*it) || *it == '_') - { - name += *it; - } - else // end of name - { - names_.push_back(name); - name.clear(); - queryChunks_.push_back(""); - queryChunks_.back() += *it; - state = eNormal; - } - break; - } - } - - if (state == eInName) - { - names_.push_back(name); - } -/* - cerr << "Chunks: "; - for (std::vector::iterator i = queryChunks_.begin(); - i != queryChunks_.end(); ++i) - { - cerr << "\"" << *i << "\" "; - } - cerr << "\nNames: "; - for (std::vector::iterator i = names_.begin(); - i != names_.end(); ++i) - { - cerr << "\"" << *i << "\" "; - } - cerr << endl; -*/ -} - -statement_backend::exec_fetch_result -mysql_statement_backend::execute(int number) -{ - if (justDescribed_ == false) - { - clean_up(); - - if (number > 1 && hasIntoElements_) - { - throw soci_error( - "Bulk use with single into elements is not supported."); - } - // number - size of vectors (into/use) - // numberOfExecutions - number of loops to perform - int numberOfExecutions = 1; - if (number > 0) - { - numberOfExecutions = hasUseElements_ ? 1 : number; - } - - std::string query; - if (not useByPosBuffers_.empty() or not useByNameBuffers_.empty()) - { - if (not useByPosBuffers_.empty() and not useByNameBuffers_.empty()) - { - throw soci_error( - "Binding for use elements must be either by position " - "or by name."); - } - long long rowsAffectedBulkTemp = -1; - for (int i = 0; i != numberOfExecutions; ++i) - { - std::vector paramValues; - - if (not useByPosBuffers_.empty()) - { - // use elements bind by position - // the map of use buffers can be traversed - // in its natural order - - for (UseByPosBuffersMap::iterator - it = useByPosBuffers_.begin(), - end = useByPosBuffers_.end(); - it != end; ++it) - { - char **buffers = it->second; - //cerr<<"i: "<::iterator - it = names_.begin(), end = names_.end(); - it != end; ++it) - { - UseByNameBuffersMap::iterator b - = useByNameBuffers_.find(*it); - if (b == useByNameBuffers_.end()) - { - std::string msg( - "Missing use element for bind by name ("); - msg += *it; - msg += ")."; - throw soci_error(msg); - } - char **buffers = b->second; - paramValues.push_back(buffers[i]); - } - } - //cerr << "queryChunks_.size(): "<::const_iterator ci - = queryChunks_.begin(); - for (std::vector::const_iterator - pi = paramValues.begin(), end = paramValues.end(); - pi != end; ++ci, ++pi) - { - query += *ci; - query += *pi; - } - if (ci != queryChunks_.end()) - { - query += *ci; - } - if (numberOfExecutions > 1) - { - // bulk operation - //std::cerr << "bulk operation:\n" << query << std::endl; - if (0 != mysql_real_query(session_.conn_, query.c_str(), - static_cast(query.size()))) - { - // preserve the number of rows affected so far. - rowsAffectedBulk_ = rowsAffectedBulkTemp; - throw mysql_soci_error(mysql_error(session_.conn_), - mysql_errno(session_.conn_)); - } - else - { - if(rowsAffectedBulkTemp == -1) - { - rowsAffectedBulkTemp = 0; - } - rowsAffectedBulkTemp += static_cast(mysql_affected_rows(session_.conn_)); - } - if (mysql_field_count(session_.conn_) != 0) - { - throw soci_error("The query shouldn't have returned" - " any data but it did."); - } - query.clear(); - } - } - rowsAffectedBulk_ = rowsAffectedBulkTemp; - if (numberOfExecutions > 1) - { - // bulk - return ef_no_data; - } - } - else - { - query = queryChunks_.front(); - } - - //std::cerr << query << std::endl; - if (0 != mysql_real_query(session_.conn_, query.c_str(), - static_cast(query.size()))) - { - throw mysql_soci_error(mysql_error(session_.conn_), - mysql_errno(session_.conn_)); - } - result_ = mysql_store_result(session_.conn_); - if (result_ == NULL and mysql_field_count(session_.conn_) != 0) - { - throw mysql_soci_error(mysql_error(session_.conn_), - mysql_errno(session_.conn_)); - } - if (result_ != NULL) - { - // Cache the rows offsets to have random access to the rows later. - // [mysql_data_seek() is O(n) so we don't want to use it]. - int numrows = static_cast(mysql_num_rows(result_)); - resultRowOffsets_.resize(numrows); - for (int i = 0; i < numrows; i++) - { - resultRowOffsets_[i] = mysql_row_tell(result_); - mysql_fetch_row(result_); - } - } - } - else - { - justDescribed_ = false; - } - - if (result_ != NULL) - { - currentRow_ = 0; - rowsToConsume_ = 0; - - numberOfRows_ = static_cast(mysql_num_rows(result_)); - if (numberOfRows_ == 0) - { - return ef_no_data; - } - else - { - if (number > 0) - { - // prepare for the subsequent data consumption - return fetch(number); - } - else - { - // execute(0) was meant to only perform the query - return ef_success; - } - } - } - else - { - // it was not a SELECT - return ef_no_data; - } -} - -statement_backend::exec_fetch_result -mysql_statement_backend::fetch(int number) -{ - // Note: This function does not actually fetch anything from anywhere - // - the data was already retrieved from the server in the execute() - // function, and the actual consumption of this data will take place - // in the postFetch functions, called for each into element. - // Here, we only prepare for this to happen (to emulate "the Oracle way"). - - // forward the "cursor" from the last fetch - currentRow_ += rowsToConsume_; - - if (currentRow_ >= numberOfRows_) - { - // all rows were already consumed - return ef_no_data; - } - else - { - if (currentRow_ + number > numberOfRows_) - { - rowsToConsume_ = numberOfRows_ - currentRow_; - - // this simulates the behaviour of Oracle - // - when EOF is hit, we return ef_no_data even when there are - // actually some rows fetched - return ef_no_data; - } - else - { - rowsToConsume_ = number; - return ef_success; - } - } -} - -long long mysql_statement_backend::get_affected_rows() -{ - if (rowsAffectedBulk_ >= 0) - { - return rowsAffectedBulk_; - } - return static_cast(mysql_affected_rows(session_.conn_)); -} - -int mysql_statement_backend::get_number_of_rows() -{ - return numberOfRows_ - currentRow_; -} - -std::string mysql_statement_backend::get_parameter_name(int index) const -{ - return names_.at(index); -} - -std::string mysql_statement_backend::rewrite_for_procedure_call( - std::string const &query) -{ - std::string newQuery("select "); - newQuery += query; - return newQuery; -} - -int mysql_statement_backend::prepare_for_describe() -{ - execute(1); - justDescribed_ = true; - - int columns = mysql_field_count(session_.conn_); - return columns; -} - -void mysql_statement_backend::describe_column(int colNum, - data_type & type, std::string & columnName) -{ - int pos = colNum - 1; - MYSQL_FIELD *field = mysql_fetch_field_direct(result_, pos); - switch (field->type) - { - case FIELD_TYPE_CHAR: //MYSQL_TYPE_TINY: - case FIELD_TYPE_SHORT: //MYSQL_TYPE_SHORT: - case FIELD_TYPE_INT24: //MYSQL_TYPE_INT24: - type = dt_integer; - break; - case FIELD_TYPE_LONG: //MYSQL_TYPE_LONG: - type = field->flags & UNSIGNED_FLAG ? dt_long_long - : dt_integer; - break; - case FIELD_TYPE_LONGLONG: //MYSQL_TYPE_LONGLONG: - type = field->flags & UNSIGNED_FLAG ? dt_unsigned_long_long : - dt_long_long; - break; - case FIELD_TYPE_FLOAT: //MYSQL_TYPE_FLOAT: - case FIELD_TYPE_DOUBLE: //MYSQL_TYPE_DOUBLE: - case FIELD_TYPE_DECIMAL: //MYSQL_TYPE_DECIMAL: - // Prior to MySQL v. 5.x there was no column type corresponding - // to MYSQL_TYPE_NEWDECIMAL. However, MySQL server 5.x happily - // sends field type number 246, no matter which version of libraries - // the client is using. - case 246: //MYSQL_TYPE_NEWDECIMAL: - type = dt_double; - break; - case FIELD_TYPE_TIMESTAMP: //MYSQL_TYPE_TIMESTAMP: - case FIELD_TYPE_DATE: //MYSQL_TYPE_DATE: - case FIELD_TYPE_TIME: //MYSQL_TYPE_TIME: - case FIELD_TYPE_DATETIME: //MYSQL_TYPE_DATETIME: - case FIELD_TYPE_YEAR: //MYSQL_TYPE_YEAR: - case FIELD_TYPE_NEWDATE: //MYSQL_TYPE_NEWDATE: - type = dt_date; - break; -// case MYSQL_TYPE_VARCHAR: - case FIELD_TYPE_VAR_STRING: //MYSQL_TYPE_VAR_STRING: - case FIELD_TYPE_STRING: //MYSQL_TYPE_STRING: - case FIELD_TYPE_BLOB: // TEXT OR BLOB - case FIELD_TYPE_TINY_BLOB: - case FIELD_TYPE_MEDIUM_BLOB: - case FIELD_TYPE_LONG_BLOB: - type = dt_string; - break; - default: - //std::cerr << "field->type: " << field->type << std::endl; - throw soci_error("Unknown data type."); - } - columnName = field->name; -} - -mysql_standard_into_type_backend * -mysql_statement_backend::make_into_type_backend() -{ - hasIntoElements_ = true; - return new mysql_standard_into_type_backend(*this); -} - -mysql_standard_use_type_backend * -mysql_statement_backend::make_use_type_backend() -{ - hasUseElements_ = true; - return new mysql_standard_use_type_backend(*this); -} - -mysql_vector_into_type_backend * -mysql_statement_backend::make_vector_into_type_backend() -{ - hasVectorIntoElements_ = true; - return new mysql_vector_into_type_backend(*this); -} - -mysql_vector_use_type_backend * -mysql_statement_backend::make_vector_use_type_backend() -{ - hasVectorUseElements_ = true; - return new mysql_vector_use_type_backend(*this); -} diff --git a/src/soci/src/backends/mysql/vector-into-type.cpp b/src/soci/src/backends/mysql/vector-into-type.cpp deleted file mode 100644 index 57b98b4314..0000000000 --- a/src/soci/src/backends/mysql/vector-into-type.cpp +++ /dev/null @@ -1,227 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// MySQL backend copyright (C) 2006 Pawel Aleksander Fedorynski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_MYSQL_SOURCE -#include "soci/mysql/soci-mysql.h" -#include "soci-mktime.h" -#include "common.h" -#include "soci/soci-platform.h" -#include -#include - -using namespace soci; -using namespace soci::details; -using namespace soci::details::mysql; - -void mysql_vector_into_type_backend::define_by_pos( - int &position, void *data, exchange_type type) -{ - data_ = data; - type_ = type; - position_ = position++; -} - -void mysql_vector_into_type_backend::pre_fetch() -{ - // nothing to do here -} - -namespace // anonymous -{ - -template -void set_invector_(void *p, int indx, T const &val) -{ - std::vector *dest = - static_cast *>(p); - - std::vector &v = *dest; - v[indx] = val; -} - -} // namespace anonymous - -void mysql_vector_into_type_backend::post_fetch(bool gotData, indicator *ind) -{ - if (gotData) - { - // Here, rowsToConsume_ in the Statement object designates - // the number of rows that need to be put in the user's buffers. - - // MySQL column positions start at 0 - int pos = position_ - 1; - - int const endRow = statement_.currentRow_ + statement_.rowsToConsume_; - - //mysql_data_seek(statement_.result_, statement_.currentRow_); - mysql_row_seek(statement_.result_, - statement_.resultRowOffsets_[statement_.currentRow_]); - for (int curRow = statement_.currentRow_, i = 0; - curRow != endRow; ++curRow, ++i) - { - MYSQL_ROW row = mysql_fetch_row(statement_.result_); - // first, deal with indicators - if (row[pos] == NULL) - { - if (ind == NULL) - { - throw soci_error( - "Null value fetched and no indicator defined."); - } - - ind[i] = i_null; - - // no need to convert data if it is null, go to next row - continue; - } - else - { - if (ind != NULL) - { - ind[i] = i_ok; - } - } - - // buffer with data retrieved from server, in text format - const char *buf = row[pos] != NULL ? row[pos] : ""; - - switch (type_) - { - case x_char: - set_invector_(data_, i, *buf); - break; - case x_stdstring: - { - unsigned long * lengths = - mysql_fetch_lengths(statement_.result_); - // Not sure if it's necessary, but the code below is used - // instead of - // set_invector_(data_, i, std::string(buf, lengths[pos]); - // to avoid copying the (possibly large) temporary string. - std::vector *dest = - static_cast *>(data_); - (*dest)[i].assign(buf, lengths[pos]); - } - break; - case x_short: - { - short val; - parse_num(buf, val); - set_invector_(data_, i, val); - } - break; - case x_integer: - { - int val; - parse_num(buf, val); - set_invector_(data_, i, val); - } - break; - case x_long_long: - { - long long val; - parse_num(buf, val); - set_invector_(data_, i, val); - } - break; - case x_unsigned_long_long: - { - unsigned long long val; - parse_num(buf, val); - set_invector_(data_, i, val); - } - break; - case x_double: - { - double val; - parse_num(buf, val); - set_invector_(data_, i, val); - } - break; - case x_stdtm: - { - // attempt to parse the string and convert to std::tm - std::tm t = std::tm(); - parse_std_tm(buf, t); - - set_invector_(data_, i, t); - } - break; - - default: - throw soci_error("Into element used with non-supported type."); - } - } - } - else // no data retrieved - { - // nothing to do, into vectors are already truncated - } -} - -namespace // anonymous -{ - -template -void resizevector_(void *p, std::size_t sz) -{ - std::vector *v = static_cast *>(p); - v->resize(sz); -} - -} // namespace anonymous - -void mysql_vector_into_type_backend::resize(std::size_t sz) -{ - switch (type_) - { - // simple cases - case x_char: resizevector_ (data_, sz); break; - case x_short: resizevector_ (data_, sz); break; - case x_integer: resizevector_ (data_, sz); break; - case x_long_long: resizevector_ (data_, sz); break; - case x_unsigned_long_long: - resizevector_(data_, sz); - break; - case x_double: resizevector_ (data_, sz); break; - case x_stdstring: resizevector_ (data_, sz); break; - case x_stdtm: resizevector_ (data_, sz); break; - - default: - throw soci_error("Into vector element used with non-supported type."); - } -} - -std::size_t mysql_vector_into_type_backend::size() -{ - std::size_t sz = 0; // dummy initialization to please the compiler - switch (type_) - { - // simple cases - case x_char: sz = get_vector_size (data_); break; - case x_short: sz = get_vector_size (data_); break; - case x_integer: sz = get_vector_size (data_); break; - case x_long_long: sz = get_vector_size (data_); break; - case x_unsigned_long_long: - sz = get_vector_size(data_); - break; - case x_double: sz = get_vector_size (data_); break; - case x_stdstring: sz = get_vector_size (data_); break; - case x_stdtm: sz = get_vector_size (data_); break; - - default: - throw soci_error("Into vector element used with non-supported type."); - } - - return sz; -} - -void mysql_vector_into_type_backend::clean_up() -{ - // nothing to do here -} diff --git a/src/soci/src/backends/mysql/vector-use-type.cpp b/src/soci/src/backends/mysql/vector-use-type.cpp deleted file mode 100644 index 86c59c5dff..0000000000 --- a/src/soci/src/backends/mysql/vector-use-type.cpp +++ /dev/null @@ -1,217 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// MySQL backend copyright (C) 2006 Pawel Aleksander Fedorynski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_MYSQL_SOURCE -#include "soci/mysql/soci-mysql.h" -#include "common.h" -#include "soci/soci-platform.h" -#include "soci-dtocstr.h" -// std -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace soci; -using namespace soci::details; -using namespace soci::details::mysql; - - -void mysql_vector_use_type_backend::bind_by_pos(int &position, void *data, - exchange_type type) -{ - data_ = data; - type_ = type; - position_ = position++; -} - -void mysql_vector_use_type_backend::bind_by_name( - std::string const &name, void *data, exchange_type type) -{ - data_ = data; - type_ = type; - name_ = name; -} - -void mysql_vector_use_type_backend::pre_use(indicator const *ind) -{ - std::size_t const vsize = size(); - for (size_t i = 0; i != vsize; ++i) - { - char *buf; - - // the data in vector can be either i_ok or i_null - if (ind != NULL && ind[i] == i_null) - { - buf = new char[5]; - std::strcpy(buf, "NULL"); - } - else - { - // allocate and fill the buffer with text-formatted client data - switch (type_) - { - case x_char: - { - std::vector *pv - = static_cast *>(data_); - std::vector &v = *pv; - - char tmp[] = { v[i], '\0' }; - buf = quote(statement_.session_.conn_, tmp, 1); - } - break; - case x_stdstring: - { - std::vector *pv - = static_cast *>(data_); - std::vector &v = *pv; - - buf = quote(statement_.session_.conn_, - v[i].c_str(), v[i].size()); - } - break; - case x_short: - { - std::vector *pv - = static_cast *>(data_); - std::vector &v = *pv; - - std::size_t const bufSize - = std::numeric_limits::digits10 + 3; - buf = new char[bufSize]; - snprintf(buf, bufSize, "%d", static_cast(v[i])); - } - break; - case x_integer: - { - std::vector *pv - = static_cast *>(data_); - std::vector &v = *pv; - - std::size_t const bufSize - = std::numeric_limits::digits10 + 3; - buf = new char[bufSize]; - snprintf(buf, bufSize, "%d", v[i]); - } - break; - case x_long_long: - { - std::vector *pv - = static_cast *>(data_); - std::vector &v = *pv; - - std::size_t const bufSize - = std::numeric_limits::digits10 + 3; - buf = new char[bufSize]; - snprintf(buf, bufSize, "%" LL_FMT_FLAGS "d", v[i]); - } - break; - case x_unsigned_long_long: - { - std::vector *pv - = static_cast *>(data_); - std::vector &v = *pv; - - std::size_t const bufSize - = std::numeric_limits::digits10 + 3; - buf = new char[bufSize]; - snprintf(buf, bufSize, "%" LL_FMT_FLAGS "u", v[i]); - } - break; - case x_double: - { - std::vector *pv - = static_cast *>(data_); - std::vector &v = *pv; - - if (is_infinity_or_nan(v[i])) { - throw soci_error( - "Use element used with infinity or NaN, which are " - "not supported by the MySQL server."); - } - - std::string const s = double_to_cstring(v[i]); - - buf = new char[s.size() + 1]; - std::strcpy(buf, s.c_str()); - } - break; - case x_stdtm: - { - std::vector *pv - = static_cast *>(data_); - std::vector &v = *pv; - - std::size_t const bufSize = 22; - buf = new char[bufSize]; - - snprintf(buf, bufSize, "\'%d-%02d-%02d %02d:%02d:%02d\'", - v[i].tm_year + 1900, v[i].tm_mon + 1, v[i].tm_mday, - v[i].tm_hour, v[i].tm_min, v[i].tm_sec); - } - break; - - default: - throw soci_error( - "Use vector element used with non-supported type."); - } - } - - buffers_.push_back(buf); - } - - if (position_ > 0) - { - // binding by position - statement_.useByPosBuffers_[position_] = &buffers_[0]; - } - else - { - // binding by name - statement_.useByNameBuffers_[name_] = &buffers_[0]; - } -} - -std::size_t mysql_vector_use_type_backend::size() -{ - std::size_t sz = 0; // dummy initialization to please the compiler - switch (type_) - { - // simple cases - case x_char: sz = get_vector_size (data_); break; - case x_short: sz = get_vector_size (data_); break; - case x_integer: sz = get_vector_size (data_); break; - case x_long_long: sz = get_vector_size (data_); break; - case x_unsigned_long_long: - sz = get_vector_size(data_); - break; - case x_double: sz = get_vector_size (data_); break; - case x_stdstring: sz = get_vector_size (data_); break; - case x_stdtm: sz = get_vector_size (data_); break; - - default: - throw soci_error("Use vector element used with non-supported type."); - } - - return sz; -} - -void mysql_vector_use_type_backend::clean_up() -{ - std::size_t const bsize = buffers_.size(); - for (std::size_t i = 0; i != bsize; ++i) - { - delete [] buffers_[i]; - } -} diff --git a/src/soci/src/backends/odbc/CMakeLists.txt b/src/soci/src/backends/odbc/CMakeLists.txt deleted file mode 100644 index ce01953934..0000000000 --- a/src/soci/src/backends/odbc/CMakeLists.txt +++ /dev/null @@ -1,15 +0,0 @@ -############################################################################### -# -# This file is part of CMake configuration for SOCI library -# -# Copyright (C) 2010 Mateusz Loskot -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -# -############################################################################### -soci_backend(ODBC - DEPENDS ODBC - DESCRIPTION "SOCI backend for ODBC" - AUTHORS "Maciej Sobczak, Stephen Hutton, David Courtney" - MAINTAINERS "Vadim Zeitlin, Mateusz Loskot, Maciej Sobczak") diff --git a/src/soci/src/backends/odbc/Makefile.basic b/src/soci/src/backends/odbc/Makefile.basic deleted file mode 100644 index 5082f914f3..0000000000 --- a/src/soci/src/backends/odbc/Makefile.basic +++ /dev/null @@ -1,89 +0,0 @@ -# The following variable is specific to this backend and its correct -# values might depend on your environment - feel free to set it accordingly. - -ODBCINCLUDEDIR = -I/usr/include - -# The rest of the Makefile is indepentent of the target environment. - -COMPILER = g++ -CXXFLAGS = -Wall -pedantic -Wno-long-long -CXXFLAGSSO = ${CXXFLAGS} -fPIC -INCLUDEDIRS = -I../../core ${ODBCINCLUDEDIR} - - -OBJECTS = blob.o factory.o row-id.o session.o standard-into-type.o \ - standard-use-type.o statement.o vector-into-type.o vector-use-type.o - -OBJECTSSO = blob-s.o factory-s.o row-id-s.o session-s.o \ - standard-into-type-s.o standard-use-type-s.o statement-s.o \ - vector-into-type-s.o vector-use-type-s.o - - -libsoci_odbc.a : ${OBJECTS} - ar rv $@ $? - ranlib $@ - rm *.o - - -blob.o : blob.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -factory.o : factory.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -row-id.o : row-id.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -session.o : session.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -standard-into-type.o : standard-into-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -standard-use-type.o : standard-use-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -statement.o : statement.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -vector-into-type.o : vector-into-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -vector-use-type.o : vector-use-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - - -shared : ${OBJECTSSO} - ${COMPILER} -shared -o libsoci_odbc.so ${OBJECTSSO} - rm *.o - -blob-s.o : blob.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -factory-s.o : factory.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -row-id-s.o : row-id.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -session-s.o : session.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -standard-into-type-s.o : standard-into-type.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -standard-use-type-s.o : standard-use-type.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -statement-s.o : statement.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -vector-into-type-s.o : vector-into-type.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -vector-use-type-s.o : vector-use-type.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - - -clean : - rm -f libsoci_odbc.a libsoci_odbc.so diff --git a/src/soci/src/backends/odbc/blob.cpp b/src/soci/src/backends/odbc/blob.cpp deleted file mode 100644 index 851c250667..0000000000 --- a/src/soci/src/backends/odbc/blob.cpp +++ /dev/null @@ -1,57 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_ODBC_SOURCE -#include "soci/odbc/soci-odbc.h" - -using namespace soci; -using namespace soci::details; - - -odbc_blob_backend::odbc_blob_backend(odbc_session_backend &session) - : session_(session) -{ - // ... -} - -odbc_blob_backend::~odbc_blob_backend() -{ - // ... -} - -std::size_t odbc_blob_backend::get_len() -{ - // ... - return 0; -} - -std::size_t odbc_blob_backend::read( - std::size_t /* offset */, char * /* buf */, std::size_t /* toRead */) -{ - // ... - return 0; -} - -std::size_t odbc_blob_backend::write( - std::size_t /* offset */, char const * /* buf */, - std::size_t /* toWrite */) -{ - // ... - return 0; -} - -std::size_t odbc_blob_backend::append( - char const * /* buf */, std::size_t /* toWrite */) -{ - // ... - return 0; -} - -void odbc_blob_backend::trim(std::size_t /* newLen */) -{ - // ... -} diff --git a/src/soci/src/backends/odbc/factory.cpp b/src/soci/src/backends/odbc/factory.cpp deleted file mode 100644 index 60c4e62374..0000000000 --- a/src/soci/src/backends/odbc/factory.cpp +++ /dev/null @@ -1,39 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_ODBC_SOURCE -#include "soci/odbc/soci-odbc.h" -#include "soci/backend-loader.h" - -using namespace soci; -using namespace soci::details; - - -// concrete factory for ODBC concrete strategies -odbc_session_backend * odbc_backend_factory::make_session( - connection_parameters const & parameters) const -{ - return new odbc_session_backend(parameters); -} - -odbc_backend_factory const soci::odbc; - -extern "C" -{ - -// for dynamic backend loading -SOCI_ODBC_DECL backend_factory const * factory_odbc() -{ - return &soci::odbc; -} - -SOCI_ODBC_DECL void register_factory_odbc() -{ - soci::dynamic_backends::register_backend("odbc", soci::odbc); -} - -} // extern "C" diff --git a/src/soci/src/backends/odbc/makefile.msvc b/src/soci/src/backends/odbc/makefile.msvc deleted file mode 100644 index dcc5a96be8..0000000000 --- a/src/soci/src/backends/odbc/makefile.msvc +++ /dev/null @@ -1,48 +0,0 @@ -# The following variable is specific to this backend and its correct -# values might depend on your environment - feel free to set it accordingly. - -ODBCINCLUDEDIR="C:\Program Files\Microsoft Platform SDK\Include" - -# The rest of the Makefile is indepentent of the target environment. - -COMPILER = cl -CXXFLAGS = /nologo /EHsc /D_CRT_SECURE_NO_DEPRECATE -INCLUDEDIRS = /I..\..\core /I$(ODBCINCLUDEDIR) - -OBJECTS = blob.obj factory.obj row-id.obj session.obj standard-into-type.obj \ - standard-use-type.obj statement.obj vector-into-type.obj \ - vector-use-type.obj - -soci-odbc.lib : $(OBJECTS) - lib /NOLOGO /OUT:$@ $? - del *.obj - -blob.obj : blob.cpp - $(COMPILER) /c $? $(CXXFLAGS) $(INCLUDEDIRS) - -factory.obj : factory.cpp - $(COMPILER) /c $? $(CXXFLAGS) $(INCLUDEDIRS) - -row-id.obj : row-id.cpp - $(COMPILER) /c $? $(CXXFLAGS) $(INCLUDEDIRS) - -session.obj : session.cpp - $(COMPILER) /c $? $(CXXFLAGS) $(INCLUDEDIRS) - -standard-into-type.obj : standard-into-type.cpp - $(COMPILER) /c $? $(CXXFLAGS) $(INCLUDEDIRS) - -standard-use-type.obj : standard-use-type.cpp - $(COMPILER) /c $? $(CXXFLAGS) $(INCLUDEDIRS) - -statement.obj : statement.cpp - $(COMPILER) /c $? $(CXXFLAGS) $(INCLUDEDIRS) - -vector-into-type.obj : vector-into-type.cpp - $(COMPILER) /c $? $(CXXFLAGS) $(INCLUDEDIRS) - -vector-use-type.obj : vector-use-type.cpp - $(COMPILER) /c $? $(CXXFLAGS) $(INCLUDEDIRS) - -clean : - del soci-odbc.lib soci-odbc.dll diff --git a/src/soci/src/backends/odbc/row-id.cpp b/src/soci/src/backends/odbc/row-id.cpp deleted file mode 100644 index 62331ddd95..0000000000 --- a/src/soci/src/backends/odbc/row-id.cpp +++ /dev/null @@ -1,23 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_ODBC_SOURCE -#include "soci/odbc/soci-odbc.h" - -using namespace soci; -using namespace soci::details; - - -odbc_rowid_backend::odbc_rowid_backend(odbc_session_backend & /* session */) -{ - // ... -} - -odbc_rowid_backend::~odbc_rowid_backend() -{ - // ... -} diff --git a/src/soci/src/backends/odbc/session.cpp b/src/soci/src/backends/odbc/session.cpp deleted file mode 100644 index fb4c6c13a3..0000000000 --- a/src/soci/src/backends/odbc/session.cpp +++ /dev/null @@ -1,383 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_ODBC_SOURCE -#include "soci/soci-platform.h" -#include "soci/odbc/soci-odbc.h" -#include "soci/session.h" - -#include - -using namespace soci; -using namespace soci::details; - -char const * soci::odbc_option_driver_complete = "odbc.driver_complete"; - -odbc_session_backend::odbc_session_backend( - connection_parameters const & parameters) - : henv_(0), hdbc_(0), product_(prod_uninitialized) -{ - SQLRETURN rc; - - // Allocate environment handle - rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv_); - if (is_odbc_error(rc)) - { - throw soci_error("Unable to get environment handle"); - } - - // Set the ODBC version environment attribute - rc = SQLSetEnvAttr(henv_, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); - if (is_odbc_error(rc)) - { - throw odbc_soci_error(SQL_HANDLE_ENV, henv_, "setting ODBC version 3"); - } - - // Allocate connection handle - rc = SQLAllocHandle(SQL_HANDLE_DBC, henv_, &hdbc_); - if (is_odbc_error(rc)) - { - throw odbc_soci_error(SQL_HANDLE_DBC, hdbc_, - "allocating connection handle"); - } - - SQLCHAR outConnString[1024]; - SQLSMALLINT strLength; - - // Prompt the user for any missing information (typically UID/PWD) in the - // connection string by default but allow overriding this using "prompt" - // option. - SQLHWND hwnd_for_prompt = NULL; - unsigned completion = SQL_DRIVER_COMPLETE; - std::string completionString; - if (parameters.get_option(odbc_option_driver_complete, completionString)) - { - // The value of the option is supposed to be just the integer value of - // one of SQL_DRIVER_XXX constants but don't check for the exact value in - // case more of them are added in the future, the ODBC driver will return - // an error if we pass it an invalid value anyhow. - if (std::sscanf(completionString.c_str(), "%u", &completion) != 1) - { - throw soci_error("Invalid non-numeric driver completion option value \"" + - completionString + "\"."); - } - } - -#ifdef _WIN32 - if (completion != SQL_DRIVER_NOPROMPT) - hwnd_for_prompt = ::GetDesktopWindow(); -#endif // _WIN32 - - std::string const & connectString = parameters.get_connect_string(); - rc = SQLDriverConnect(hdbc_, hwnd_for_prompt, - sqlchar_cast(connectString), - (SQLSMALLINT)connectString.size(), - outConnString, 1024, &strLength, - static_cast(completion)); - - if (is_odbc_error(rc)) - { - throw odbc_soci_error(SQL_HANDLE_DBC, hdbc_, "connecting to database"); - } - - connection_string_.assign((const char*)outConnString, strLength); - - reset_transaction(); - - configure_connection(); -} - -void odbc_session_backend::configure_connection() -{ - if ( get_database_product() == prod_postgresql ) - { - // Increase the number of digits used for floating point values to - // ensure that the conversions to/from text round trip correctly, which - // is not the case with the default value of 0. Use the maximal - // supported value, which was 2 until 9.x and is 3 since it. - - char product_ver[1024]; - SQLSMALLINT len = sizeof(product_ver); - SQLRETURN rc = SQLGetInfo(hdbc_, SQL_DBMS_VER, product_ver, len, &len); - if (is_odbc_error(rc)) - { - throw odbc_soci_error(SQL_HANDLE_DBC, henv_, - "getting PostgreSQL ODBC driver version"); - } - - // The returned string is of the form "##.##.#### ...", but we don't - // need to parse it fully, we just need the major version which, - // conveniently, comes first. - unsigned major_ver = 0; - if (std::sscanf(product_ver, "%u", &major_ver) != 1) - { - throw soci_error("DBMS version \"" + std::string(product_ver) + - "\" in unrecognizable format."); - } - - odbc_statement_backend st(*this); - st.alloc(); - - std::string const q(major_ver >= 9 ? "SET extra_float_digits = 3" - : "SET extra_float_digits = 2"); - rc = SQLExecDirect(st.hstmt_, sqlchar_cast(q), static_cast(q.size())); - - st.clean_up(); - - if (is_odbc_error(rc)) - { - throw odbc_soci_error(SQL_HANDLE_DBC, henv_, - "setting extra_float_digits for PostgreSQL"); - } - - // This is extracted from pgapifunc.h header from psqlODBC driver. - enum - { - SQL_ATTR_PGOPT_UNKNOWNSASLONGVARCHAR = 65544 - }; - - // Also configure the driver to handle unknown types, such as "xml", - // that we use for x_xmltype, as long varchar instead of limiting them - // to 256 characters (by default). - rc = SQLSetConnectAttr(hdbc_, SQL_ATTR_PGOPT_UNKNOWNSASLONGVARCHAR, (SQLPOINTER)1, 0); - - // Ignore the error from this one, failure to set it is not fatal and - // the attribute is only supported in very recent version of the driver - // (>= 9.6.300). Using "UnknownsAsLongVarchar=1" in odbc.ini (or - // setting the corresponding option in the driver dialog box) should - // work with all versions however. - } -} - -odbc_session_backend::~odbc_session_backend() -{ - clean_up(); -} - -void odbc_session_backend::begin() -{ - SQLRETURN rc = SQLSetConnectAttr( hdbc_, SQL_ATTR_AUTOCOMMIT, - (SQLPOINTER)SQL_AUTOCOMMIT_OFF, 0 ); - if (is_odbc_error(rc)) - { - throw odbc_soci_error(SQL_HANDLE_DBC, hdbc_, "beginning transaction"); - } -} - -void odbc_session_backend::commit() -{ - SQLRETURN rc = SQLEndTran(SQL_HANDLE_DBC, hdbc_, SQL_COMMIT); - if (is_odbc_error(rc)) - { - throw odbc_soci_error(SQL_HANDLE_DBC, hdbc_, "committing transaction"); - } - reset_transaction(); -} - -void odbc_session_backend::rollback() -{ - SQLRETURN rc = SQLEndTran(SQL_HANDLE_DBC, hdbc_, SQL_ROLLBACK); - if (is_odbc_error(rc)) - { - throw odbc_soci_error(SQL_HANDLE_DBC, hdbc_, "rolling back transaction"); - } - reset_transaction(); -} - -bool odbc_session_backend::get_next_sequence_value( - session & s, std::string const & sequence, long & value) -{ - std::string query; - - switch ( get_database_product() ) - { - case prod_firebird: - query = "select next value for " + sequence + " from rdb$database"; - break; - - case prod_oracle: - query = "select " + sequence + ".nextval from dual"; - break; - - case prod_postgresql: - query = "select nextval('" + sequence + "')"; - break; - - case prod_mssql: - case prod_mysql: - case prod_sqlite: - // These RDBMS implement get_last_insert_id() instead. - return false; - - case prod_unknown: - // For this one we can't do anything at all. - return false; - - case prod_uninitialized: - // This is not supposed to happen at all but still cover this case - // here to avoid gcc warnings about unhandled enum values in a - // switch. - return false; - } - - s << query, into(value); - - return true; -} - -bool odbc_session_backend::get_last_insert_id( - session & s, std::string const & table, long & value) -{ - std::string query; - - switch ( get_database_product() ) - { - case prod_mssql: - query = "select ident_current('" + table + "')"; - break; - - case prod_mysql: - query = "select last_insert_id()"; - break; - - case prod_sqlite: - query = "select last_insert_rowid()"; - break; - - case prod_firebird: - case prod_oracle: - case prod_postgresql: - // For these RDBMS get_next_sequence_value() should have been used. - return false; - - - case prod_unknown: - // For this one we can't do anything at all. - return false; - - case prod_uninitialized: - // As above, this is not supposed to happen but put it here to - // mollify gcc. - return false; - } - - s << query, into(value); - - return true; -} - -std::string odbc_session_backend::get_dummy_from_table() const -{ - std::string table; - - switch ( get_database_product() ) - { - case prod_firebird: - table = "rdb$database"; - break; - - case prod_oracle: - table = "dual"; - break; - - case prod_mssql: - case prod_mysql: - case prod_sqlite: - case prod_postgresql: - // No special dummy table needed. - break; - - // These cases are here just to make the switch exhaustive, we - // can't really do anything about them anyhow. - case prod_unknown: - case prod_uninitialized: - break; - } - - return table; -} - -void odbc_session_backend::reset_transaction() -{ - SQLRETURN rc = SQLSetConnectAttr( hdbc_, SQL_ATTR_AUTOCOMMIT, - (SQLPOINTER)SQL_AUTOCOMMIT_ON, 0 ); - if (is_odbc_error(rc)) - { - throw odbc_soci_error(SQL_HANDLE_DBC, hdbc_, "enabling auto commit"); - } -} - - -void odbc_session_backend::clean_up() -{ - SQLRETURN rc = SQLDisconnect(hdbc_); - if (is_odbc_error(rc)) - { - throw odbc_soci_error(SQL_HANDLE_DBC, hdbc_, "disconnecting"); - } - - rc = SQLFreeHandle(SQL_HANDLE_DBC, hdbc_); - if (is_odbc_error(rc)) - { - throw odbc_soci_error(SQL_HANDLE_DBC, hdbc_, "freeing connection"); - } - - rc = SQLFreeHandle(SQL_HANDLE_ENV, henv_); - if (is_odbc_error(rc)) - { - throw odbc_soci_error(SQL_HANDLE_ENV, henv_, "freeing environment"); - } -} - -odbc_statement_backend * odbc_session_backend::make_statement_backend() -{ - return new odbc_statement_backend(*this); -} - -odbc_rowid_backend * odbc_session_backend::make_rowid_backend() -{ - return new odbc_rowid_backend(*this); -} - -odbc_blob_backend * odbc_session_backend::make_blob_backend() -{ - return new odbc_blob_backend(*this); -} - -odbc_session_backend::database_product -odbc_session_backend::get_database_product() const -{ - // Cache the product type, it's not going to change during our life time. - if (product_ != prod_uninitialized) - return product_; - - char product_name[1024]; - SQLSMALLINT len = sizeof(product_name); - SQLRETURN rc = SQLGetInfo(hdbc_, SQL_DBMS_NAME, product_name, len, &len); - if (is_odbc_error(rc)) - { - throw odbc_soci_error(SQL_HANDLE_DBC, henv_, - "getting ODBC driver name"); - } - - if (strcmp(product_name, "Firebird") == 0) - product_ = prod_firebird; - else if (strcmp(product_name, "Microsoft SQL Server") == 0) - product_ = prod_mssql; - else if (strcmp(product_name, "MySQL") == 0) - product_ = prod_mysql; - else if (strcmp(product_name, "Oracle") == 0) - product_ = prod_oracle; - else if (strcmp(product_name, "PostgreSQL") == 0) - product_ = prod_postgresql; - else if (strcmp(product_name, "SQLite") == 0) - product_ = prod_sqlite; - else - product_ = prod_unknown; - - return product_; -} diff --git a/src/soci/src/backends/odbc/standard-into-type.cpp b/src/soci/src/backends/odbc/standard-into-type.cpp deleted file mode 100644 index 69b6b3d90e..0000000000 --- a/src/soci/src/backends/odbc/standard-into-type.cpp +++ /dev/null @@ -1,208 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_ODBC_SOURCE -#include "soci/soci-platform.h" -#include "soci/odbc/soci-odbc.h" -#include "soci-exchange-cast.h" -#include "soci-mktime.h" -#include -#include // sscanf() - -using namespace soci; -using namespace soci::details; - -void odbc_standard_into_type_backend::define_by_pos( - int & position, void * data, exchange_type type) -{ - data_ = data; - type_ = type; - position_ = position++; - - SQLUINTEGER size = 0; - switch (type_) - { - case x_char: - odbcType_ = SQL_C_CHAR; - size = sizeof(char) + 1; - buf_ = new char[size]; - data = buf_; - break; - case x_stdstring: - case x_longstring: - case x_xmltype: - odbcType_ = SQL_C_CHAR; - // Patch: set to min between column size and 100MB (used ot be 32769) - // Column size for text data type can be too large for buffer allocation - size = static_cast(statement_.column_size(position_)); - size = (size > odbc_max_buffer_length || size == 0) ? odbc_max_buffer_length : size; - size++; - buf_ = new char[size]; - data = buf_; - break; - case x_short: - odbcType_ = SQL_C_SSHORT; - size = sizeof(short); - break; - case x_integer: - odbcType_ = SQL_C_SLONG; - size = sizeof(int); - break; - case x_long_long: - if (use_string_for_bigint()) - { - odbcType_ = SQL_C_CHAR; - size = max_bigint_length; - buf_ = new char[size]; - data = buf_; - } - else // Normal case, use ODBC support. - { - odbcType_ = SQL_C_SBIGINT; - size = sizeof(long long); - } - break; - case x_unsigned_long_long: - if (use_string_for_bigint()) - { - odbcType_ = SQL_C_CHAR; - size = max_bigint_length; - buf_ = new char[size]; - data = buf_; - } - else // Normal case, use ODBC support. - { - odbcType_ = SQL_C_UBIGINT; - size = sizeof(unsigned long long); - } - break; - case x_double: - odbcType_ = SQL_C_DOUBLE; - size = sizeof(double); - break; - case x_stdtm: - odbcType_ = SQL_C_TYPE_TIMESTAMP; - size = sizeof(TIMESTAMP_STRUCT); - buf_ = new char[size]; - data = buf_; - break; - case x_rowid: - odbcType_ = SQL_C_ULONG; - size = sizeof(unsigned long); - break; - default: - throw soci_error("Into element used with non-supported type."); - } - - valueLen_ = 0; - - SQLRETURN rc = SQLBindCol(statement_.hstmt_, static_cast(position_), - static_cast(odbcType_), data, size, &valueLen_); - if (is_odbc_error(rc)) - { - std::ostringstream ss; - ss << "binding output column #" << position_; - throw odbc_soci_error(SQL_HANDLE_STMT, statement_.hstmt_, ss.str()); - } -} - -void odbc_standard_into_type_backend::pre_fetch() -{ - //... -} - -void odbc_standard_into_type_backend::post_fetch( - bool gotData, bool calledFromFetch, indicator * ind) -{ - if (calledFromFetch == true && gotData == false) - { - // this is a normal end-of-rowset condition, - // no need to do anything (fetch() will return false) - return; - } - - if (gotData) - { - // first, deal with indicators - if (SQL_NULL_DATA == valueLen_) - { - if (ind == NULL) - { - throw soci_error( - "Null value fetched and no indicator defined."); - } - - *ind = i_null; - return; - } - else - { - if (ind != NULL) - { - *ind = i_ok; - } - } - - // only std::string and std::tm need special handling - if (type_ == x_char) - { - exchange_type_cast(data_) = buf_[0]; - } - else if (type_ == x_stdstring) - { - std::string& s = exchange_type_cast(data_); - s = buf_; - if (s.size() >= (odbc_max_buffer_length - 1)) - { - throw soci_error("Buffer size overflow; maybe got too large string"); - } - } - else if (type_ == x_longstring) - { - exchange_type_cast(data_).value = buf_; - } - else if (type_ == x_xmltype) - { - exchange_type_cast(data_).value = buf_; - } - else if (type_ == x_stdtm) - { - std::tm& t = exchange_type_cast(data_); - - TIMESTAMP_STRUCT * ts = reinterpret_cast(buf_); - - details::mktime_from_ymdhms(t, - ts->year, ts->month, ts->day, - ts->hour, ts->minute, ts->second); - } - else if (type_ == x_long_long && use_string_for_bigint()) - { - long long& ll = exchange_type_cast(data_); - if (sscanf(buf_, "%" LL_FMT_FLAGS "d", &ll) != 1) - { - throw soci_error("Failed to parse the returned 64-bit integer value"); - } - } - else if (type_ == x_unsigned_long_long && use_string_for_bigint()) - { - unsigned long long& ll = exchange_type_cast(data_); - if (sscanf(buf_, "%" LL_FMT_FLAGS "u", &ll) != 1) - { - throw soci_error("Failed to parse the returned 64-bit integer value"); - } - } - } -} - -void odbc_standard_into_type_backend::clean_up() -{ - if (buf_) - { - delete [] buf_; - buf_ = 0; - } -} diff --git a/src/soci/src/backends/odbc/standard-use-type.cpp b/src/soci/src/backends/odbc/standard-use-type.cpp deleted file mode 100644 index 0f90617892..0000000000 --- a/src/soci/src/backends/odbc/standard-use-type.cpp +++ /dev/null @@ -1,267 +0,0 @@ -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) - -#define SOCI_ODBC_SOURCE -#include "soci/soci-platform.h" -#include "soci/odbc/soci-odbc.h" -#include "soci-exchange-cast.h" -#include -#include -#include -#include -#include - -using namespace soci; -using namespace soci::details; - -void* odbc_standard_use_type_backend::prepare_for_bind( - SQLLEN &size, SQLSMALLINT &sqlType, SQLSMALLINT &cType) -{ - switch (type_) - { - // simple cases - case x_short: - sqlType = SQL_SMALLINT; - cType = SQL_C_SSHORT; - size = sizeof(short); - break; - case x_integer: - sqlType = SQL_INTEGER; - cType = SQL_C_SLONG; - size = sizeof(int); - break; - case x_long_long: - if (use_string_for_bigint()) - { - sqlType = SQL_NUMERIC; - cType = SQL_C_CHAR; - size = max_bigint_length; - buf_ = new char[size]; - snprintf(buf_, size, "%" LL_FMT_FLAGS "d", - exchange_type_cast(data_)); - indHolder_ = SQL_NTS; - } - else // Normal case, use ODBC support. - { - sqlType = SQL_BIGINT; - cType = SQL_C_SBIGINT; - size = sizeof(long long); - } - break; - case x_unsigned_long_long: - if (use_string_for_bigint()) - { - sqlType = SQL_NUMERIC; - cType = SQL_C_CHAR; - size = max_bigint_length; - buf_ = new char[size]; - snprintf(buf_, size, "%" LL_FMT_FLAGS "u", - exchange_type_cast(data_)); - indHolder_ = SQL_NTS; - } - else // Normal case, use ODBC support. - { - sqlType = SQL_BIGINT; - cType = SQL_C_UBIGINT; - size = sizeof(unsigned long long); - } - break; - case x_double: - sqlType = SQL_DOUBLE; - cType = SQL_C_DOUBLE; - size = sizeof(double); - break; - - case x_char: - sqlType = SQL_CHAR; - cType = SQL_C_CHAR; - size = 2; - buf_ = new char[size]; - buf_[0] = exchange_type_cast(data_); - buf_[1] = '\0'; - indHolder_ = SQL_NTS; - break; - case x_stdstring: - { - std::string const& s = exchange_type_cast(data_); - - copy_from_string(s, size, sqlType, cType); - } - break; - case x_stdtm: - { - std::tm const& t = exchange_type_cast(data_); - - sqlType = SQL_TIMESTAMP; - cType = SQL_C_TIMESTAMP; - buf_ = new char[sizeof(TIMESTAMP_STRUCT)]; - size = 19; // This number is not the size in bytes, but the number - // of characters in the date if it was written out - // yyyy-mm-dd hh:mm:ss - - TIMESTAMP_STRUCT * ts = reinterpret_cast(buf_); - - ts->year = static_cast(t.tm_year + 1900); - ts->month = static_cast(t.tm_mon + 1); - ts->day = static_cast(t.tm_mday); - ts->hour = static_cast(t.tm_hour); - ts->minute = static_cast(t.tm_min); - ts->second = static_cast(t.tm_sec); - ts->fraction = 0; - } - break; - - case x_longstring: - copy_from_string(exchange_type_cast(data_).value, - size, sqlType, cType); - break; - case x_xmltype: - copy_from_string(exchange_type_cast(data_).value, - size, sqlType, cType); - break; - - // unsupported types - default: - throw soci_error("Use element used with non-supported type."); - } - - // Return either the pointer to C++ data itself or the buffer that we - // allocated, if any. - return buf_ ? buf_ : data_; -} - -void odbc_standard_use_type_backend::copy_from_string( - std::string const& s, - SQLLEN& size, - SQLSMALLINT& sqlType, - SQLSMALLINT& cType - ) -{ - sqlType = SQL_VARCHAR; - cType = SQL_C_CHAR; - size = s.size(); - buf_ = new char[size+1]; - memcpy(buf_, s.c_str(), size); - buf_[size++] = '\0'; - indHolder_ = SQL_NTS; -} - -void odbc_standard_use_type_backend::bind_by_pos( - int &position, void *data, exchange_type type, bool /* readOnly */) -{ - if (statement_.boundByName_) - { - throw soci_error( - "Binding for use elements must be either by position or by name."); - } - - position_ = position++; - data_ = data; - type_ = type; - - statement_.boundByPos_ = true; -} - -void odbc_standard_use_type_backend::bind_by_name( - std::string const &name, void *data, exchange_type type, bool /* readOnly */) -{ - if (statement_.boundByPos_) - { - throw soci_error( - "Binding for use elements must be either by position or by name."); - } - - int position = -1; - int count = 1; - - for (std::vector::iterator it = statement_.names_.begin(); - it != statement_.names_.end(); ++it) - { - if (*it == name) - { - position = count; - break; - } - count++; - } - - if (position == -1) - { - std::ostringstream ss; - ss << "Unable to find name '" << name << "' to bind to"; - throw soci_error(ss.str().c_str()); - } - - position_ = position; - data_ = data; - type_ = type; - - statement_.boundByName_ = true; -} - -void odbc_standard_use_type_backend::pre_use(indicator const *ind) -{ - // first deal with data - SQLSMALLINT sqlType(0); - SQLSMALLINT cType(0); - SQLLEN size(0); - SQLLEN bufLen(0); - - void* const sqlData = prepare_for_bind(size, sqlType, cType); - if (size > ODBC_MAX_COL_SIZE) - { - bufLen = size; - size = SQL_SS_LENGTH_UNLIMITED; - } - SQLRETURN rc = SQLBindParameter(statement_.hstmt_, - static_cast(position_), - SQL_PARAM_INPUT, - cType, sqlType, size, 0, - sqlData, bufLen, &indHolder_); - - if (is_odbc_error(rc)) - { - std::ostringstream ss; - ss << "binding input parameter #" << position_; - throw odbc_soci_error(SQL_HANDLE_STMT, statement_.hstmt_, ss.str()); - } - - // then handle indicators - if (ind != NULL && *ind == i_null) - { - indHolder_ = SQL_NULL_DATA; // null - } -} - -void odbc_standard_use_type_backend::post_use(bool gotData, indicator *ind) -{ - if (ind != NULL) - { - if (gotData) - { - if (indHolder_ == 0) - { - *ind = i_ok; - } - else if (indHolder_ == SQL_NULL_DATA) - { - *ind = i_null; - } - else - { - *ind = i_truncated; - } - } - } -} - -void odbc_standard_use_type_backend::clean_up() -{ - if (buf_ != NULL) - { - delete [] buf_; - buf_ = NULL; - } -} diff --git a/src/soci/src/backends/odbc/statement.cpp b/src/soci/src/backends/odbc/statement.cpp deleted file mode 100644 index a83124fbb1..0000000000 --- a/src/soci/src/backends/odbc/statement.cpp +++ /dev/null @@ -1,366 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_ODBC_SOURCE -#include "soci/odbc/soci-odbc.h" -#include -#include -#include - -using namespace soci; -using namespace soci::details; - - -odbc_statement_backend::odbc_statement_backend(odbc_session_backend &session) - : session_(session), hstmt_(0), numRowsFetched_(0), - hasVectorUseElements_(false), boundByName_(false), boundByPos_(false), - rowsAffected_(-1LL) -{ -} - -void odbc_statement_backend::alloc() -{ - SQLRETURN rc; - - // Allocate environment handle - rc = SQLAllocHandle(SQL_HANDLE_STMT, session_.hdbc_, &hstmt_); - if (is_odbc_error(rc)) - { - throw odbc_soci_error(SQL_HANDLE_DBC, session_.hdbc_, - "allocating statement"); - } -} - -void odbc_statement_backend::clean_up() -{ - rowsAffected_ = -1LL; - - SQLFreeHandle(SQL_HANDLE_STMT, hstmt_); -} - - -void odbc_statement_backend::prepare(std::string const & query, - statement_type /* eType */) -{ - // rewrite the query by transforming all named parameters into - // the ODBC numbers ones (:abc -> $1, etc.) - - enum { eNormal, eInQuotes, eInName, eInAccessDate } state = eNormal; - - std::string name; - query_.reserve(query.length()); - - for (std::string::const_iterator it = query.begin(), end = query.end(); - it != end; ++it) - { - switch (state) - { - case eNormal: - if (*it == '\'') - { - query_ += *it; - state = eInQuotes; - } - else if (*it == '#') - { - query_ += *it; - state = eInAccessDate; - } - else if (*it == ':') - { - state = eInName; - } - else // regular character, stay in the same state - { - query_ += *it; - } - break; - case eInQuotes: - if (*it == '\'') - { - query_ += *it; - state = eNormal; - } - else // regular quoted character - { - query_ += *it; - } - break; - case eInName: - if (std::isalnum(*it) || *it == '_') - { - name += *it; - } - else // end of name - { - names_.push_back(name); - name.clear(); - query_ += "?"; - query_ += *it; - state = eNormal; - } - break; - case eInAccessDate: - if (*it == '#') - { - query_ += *it; - state = eNormal; - } - else // regular quoted character - { - query_ += *it; - } - break; - } - } - - if (state == eInName) - { - names_.push_back(name); - query_ += "?"; - } - - SQLRETURN rc = SQLPrepare(hstmt_, sqlchar_cast(query_), (SQLINTEGER)query_.size()); - if (is_odbc_error(rc)) - { - std::ostringstream ss; - ss << "preparing query \"" << query_ << "\""; - throw odbc_soci_error(SQL_HANDLE_STMT, hstmt_, ss.str()); - } -} - -statement_backend::exec_fetch_result -odbc_statement_backend::execute(int number) -{ - // Store the number of rows processed by this call. - SQLULEN rows_processed = 0; - if (hasVectorUseElements_) - { - SQLSetStmtAttr(hstmt_, SQL_ATTR_PARAMS_PROCESSED_PTR, &rows_processed, 0); - } - - // if we are called twice for the same statement we need to close the open - // cursor or an "invalid cursor state" error will occur on execute - SQLCloseCursor(hstmt_); - - SQLRETURN rc = SQLExecute(hstmt_); - if (is_odbc_error(rc)) - { - // Construct the error object immediately, before calling any other - // ODBC functions, in order to not lose the error message. - const odbc_soci_error err(SQL_HANDLE_STMT, hstmt_, "executing statement"); - - // There is no universal way to determine the number of affected rows - // after a failed update. - rowsAffected_ = -1LL; - - // If executing bulk operation a partial - // number of rows affected may be available. - if (hasVectorUseElements_) - { - do - { - SQLLEN res = 0; - // SQLRowCount will return error after a partially executed statement. - // SQL_DIAG_ROW_COUNT returns the same info but must be collected immediatelly after the execution. - rc = SQLGetDiagField(SQL_HANDLE_STMT, hstmt_, 0, SQL_DIAG_ROW_COUNT, &res, 0, NULL); - if (!is_odbc_error(rc) && res != -1) - { - if (rowsAffected_ == -1LL) - rowsAffected_ = res; - else - rowsAffected_ += res; - } - --rows_processed; // Avoid unnecessary calls to SQLGetDiagField - } - // Move forward to the next result while there are rows processed. - while (rows_processed > 0 && SQLMoreResults(hstmt_) == SQL_SUCCESS); - } - throw err; - } - else if (hasVectorUseElements_) - { - // We already have the number of rows, no need to do anything. - rowsAffected_ = rows_processed; - } - else // We need to retrieve the number of rows affected explicitly. - { - SQLLEN res = 0; - rc = SQLRowCount(hstmt_, &res); - if (is_odbc_error(rc)) - { - throw odbc_soci_error(SQL_HANDLE_STMT, hstmt_, - "getting number of affected rows"); - } - - rowsAffected_ = res; - } - SQLSMALLINT colCount; - SQLNumResultCols(hstmt_, &colCount); - - if (number > 0 && colCount > 0) - { - return fetch(number); - } - - return ef_success; -} - -statement_backend::exec_fetch_result -odbc_statement_backend::fetch(int number) -{ - numRowsFetched_ = 0; - SQLULEN const row_array_size = static_cast(number); - - SQLSetStmtAttr(hstmt_, SQL_ATTR_ROW_BIND_TYPE, SQL_BIND_BY_COLUMN, 0); - SQLSetStmtAttr(hstmt_, SQL_ATTR_ROW_ARRAY_SIZE, (SQLPOINTER)row_array_size, 0); - SQLSetStmtAttr(hstmt_, SQL_ATTR_ROWS_FETCHED_PTR, &numRowsFetched_, 0); - - SQLRETURN rc = SQLFetch(hstmt_); - - if (SQL_NO_DATA == rc) - { - return ef_no_data; - } - - if (is_odbc_error(rc)) - { - throw odbc_soci_error(SQL_HANDLE_STMT, hstmt_, "fetching data"); - } - - return ef_success; -} - -long long odbc_statement_backend::get_affected_rows() -{ - return rowsAffected_; -} - -int odbc_statement_backend::get_number_of_rows() -{ - return static_cast(numRowsFetched_); -} - -std::string odbc_statement_backend::get_parameter_name(int index) const -{ - return names_.at(index); -} - -std::string odbc_statement_backend::rewrite_for_procedure_call( - std::string const &query) -{ - return query; -} - -int odbc_statement_backend::prepare_for_describe() -{ - SQLSMALLINT numCols; - SQLNumResultCols(hstmt_, &numCols); - return numCols; -} - -void odbc_statement_backend::describe_column(int colNum, data_type & type, - std::string & columnName) -{ - SQLCHAR colNameBuffer[2048]; - SQLSMALLINT colNameBufferOverflow; - SQLSMALLINT dataType; - SQLULEN colSize; - SQLSMALLINT decDigits; - SQLSMALLINT isNullable; - - SQLRETURN rc = SQLDescribeCol(hstmt_, static_cast(colNum), - colNameBuffer, 2048, - &colNameBufferOverflow, &dataType, - &colSize, &decDigits, &isNullable); - - if (is_odbc_error(rc)) - { - std::ostringstream ss; - ss << "getting description of column at position " << colNum; - throw odbc_soci_error(SQL_HANDLE_STMT, hstmt_, ss.str()); - } - - char const *name = reinterpret_cast(colNameBuffer); - columnName.assign(name, std::strlen(name)); - - switch (dataType) - { - case SQL_TYPE_DATE: - case SQL_TYPE_TIME: - case SQL_TYPE_TIMESTAMP: - type = dt_date; - break; - case SQL_DOUBLE: - case SQL_DECIMAL: - case SQL_REAL: - case SQL_FLOAT: - case SQL_NUMERIC: - type = dt_double; - break; - case SQL_TINYINT: - case SQL_SMALLINT: - case SQL_INTEGER: - type = dt_integer; - break; - case SQL_BIGINT: - type = dt_long_long; - break; - case SQL_CHAR: - case SQL_VARCHAR: - case SQL_LONGVARCHAR: - default: - type = dt_string; - break; - } -} - -std::size_t odbc_statement_backend::column_size(int colNum) -{ - SQLCHAR colNameBuffer[2048]; - SQLSMALLINT colNameBufferOverflow; - SQLSMALLINT dataType; - SQLULEN colSize; - SQLSMALLINT decDigits; - SQLSMALLINT isNullable; - - SQLRETURN rc = SQLDescribeCol(hstmt_, static_cast(colNum), - colNameBuffer, 2048, - &colNameBufferOverflow, &dataType, - &colSize, &decDigits, &isNullable); - - if (is_odbc_error(rc)) - { - std::ostringstream ss; - ss << "getting size of column at position " << colNum; - throw odbc_soci_error(SQL_HANDLE_STMT, hstmt_, ss.str()); - } - - return colSize; -} - -odbc_standard_into_type_backend * odbc_statement_backend::make_into_type_backend() -{ - return new odbc_standard_into_type_backend(*this); -} - -odbc_standard_use_type_backend * odbc_statement_backend::make_use_type_backend() -{ - return new odbc_standard_use_type_backend(*this); -} - -odbc_vector_into_type_backend * -odbc_statement_backend::make_vector_into_type_backend() -{ - return new odbc_vector_into_type_backend(*this); -} - -odbc_vector_use_type_backend * odbc_statement_backend::make_vector_use_type_backend() -{ - hasVectorUseElements_ = true; - return new odbc_vector_use_type_backend(*this); -} diff --git a/src/soci/src/backends/odbc/utility.h b/src/soci/src/backends/odbc/utility.h deleted file mode 100644 index 5633c933ee..0000000000 --- a/src/soci/src/backends/odbc/utility.h +++ /dev/null @@ -1,62 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_UTILITY_H_INCLUDED -#define SOCI_UTILITY_H_INCLUDED - -#include "soci-backend.h" -#include - -namespace soci -{ - -inline void throw_odbc_error(SQLSMALLINT htype, SQLHANDLE hndl, char const * msg) -{ - SQLCHAR message[SQL_MAX_MESSAGE_LENGTH + 1]; - SQLCHAR sqlstate[SQL_SQLSTATE_SIZE + 1]; - SQLINTEGER sqlcode; - SQLSMALLINT length, i; - - std::stringstream ss; - - i = 1; - - /* get multiple field settings of diagnostic record */ - while (SQLGetDiagRecA(htype, - hndl, - i, - sqlstate, - &sqlcode, - message, - SQL_MAX_MESSAGE_LENGTH + 1, - &length) == SQL_SUCCESS) - { - ss << std::endl << "SOCI ODBC Error: " << msg << std::endl - << "SQLSTATE = " << sqlstate << std::endl - << "Native Error Code = " << sqlcode << std::endl - << message << std::endl; - ++i; - } - - throw soci_error(ss.str()); -} - -inline bool is_odbc_error(SQLRETURN rc) -{ - if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) - { - return true; - } - else - { - return false; - } -} - -} - -#endif // SOCI_UTILITY_H_INCLUDED diff --git a/src/soci/src/backends/odbc/vector-into-type.cpp b/src/soci/src/backends/odbc/vector-into-type.cpp deleted file mode 100644 index 5275173a35..0000000000 --- a/src/soci/src/backends/odbc/vector-into-type.cpp +++ /dev/null @@ -1,490 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_ODBC_SOURCE -#include "soci/soci-platform.h" -#include "soci/odbc/soci-odbc.h" -#include "soci-mktime.h" -#include "soci-static-assert.h" -#include -#include -#include -#include -#include -#include // sscanf() - -using namespace soci; -using namespace soci::details; - -void odbc_vector_into_type_backend::prepare_indicators(std::size_t size) -{ - if (size == 0) - { - throw soci_error("Vectors of size 0 are not allowed."); - } - - indHolderVec_.resize(size); - indHolders_ = &indHolderVec_[0]; -} - -void odbc_vector_into_type_backend::define_by_pos( - int &position, void *data, exchange_type type) -{ - data_ = data; // for future reference - type_ = type; // for future reference - - SQLLEN size = 0; // also dummy - - switch (type) - { - // simple cases - case x_short: - { - odbcType_ = SQL_C_SSHORT; - size = sizeof(short); - std::vector *vp = static_cast *>(data); - std::vector &v(*vp); - prepare_indicators(v.size()); - data = &v[0]; - } - break; - case x_integer: - { - odbcType_ = SQL_C_SLONG; - size = sizeof(SQLINTEGER); - SOCI_STATIC_ASSERT(sizeof(SQLINTEGER) == sizeof(int)); - std::vector *vp = static_cast *>(data); - std::vector &v(*vp); - prepare_indicators(v.size()); - data = &v[0]; - } - break; - case x_long_long: - { - std::vector *vp = - static_cast *>(data); - std::vector &v(*vp); - prepare_indicators(v.size()); - if (use_string_for_bigint()) - { - odbcType_ = SQL_C_CHAR; - size = max_bigint_length; - std::size_t bufSize = size * v.size(); - colSize_ = size; - buf_ = new char[bufSize]; - data = buf_; - } - else // Normal case, use ODBC support. - { - odbcType_ = SQL_C_SBIGINT; - size = sizeof(long long); - data = &v[0]; - } - } - break; - case x_unsigned_long_long: - { - std::vector *vp = - static_cast *>(data); - std::vector &v(*vp); - prepare_indicators(v.size()); - if (use_string_for_bigint()) - { - odbcType_ = SQL_C_CHAR; - size = max_bigint_length; - std::size_t bufSize = size * v.size(); - colSize_ = size; - buf_ = new char[bufSize]; - data = buf_; - } - else // Normal case, use ODBC support. - { - odbcType_ = SQL_C_UBIGINT; - size = sizeof(unsigned long long); - data = &v[0]; - } - } - break; - case x_double: - { - odbcType_ = SQL_C_DOUBLE; - size = sizeof(double); - std::vector *vp = static_cast *>(data); - std::vector &v(*vp); - prepare_indicators(v.size()); - data = &v[0]; - } - break; - - // cases that require adjustments and buffer management - - case x_char: - { - odbcType_ = SQL_C_CHAR; - - std::vector *v - = static_cast *>(data); - - prepare_indicators(v->size()); - - size = sizeof(char) * 2; - std::size_t bufSize = size * v->size(); - - colSize_ = size; - - buf_ = new char[bufSize]; - data = buf_; - } - break; - case x_stdstring: - { - odbcType_ = SQL_C_CHAR; - std::vector *v - = static_cast *>(data); - colSize_ = statement_.column_size(position) + 1; - std::size_t bufSize = colSize_ * v->size(); - buf_ = new char[bufSize]; - - prepare_indicators(v->size()); - - size = static_cast(colSize_); - data = buf_; - } - break; - case x_stdtm: - { - odbcType_ = SQL_C_TYPE_TIMESTAMP; - std::vector *v - = static_cast *>(data); - - prepare_indicators(v->size()); - - size = sizeof(TIMESTAMP_STRUCT); - colSize_ = size; - - std::size_t bufSize = size * v->size(); - - buf_ = new char[bufSize]; - data = buf_; - } - break; - - default: - throw soci_error("Into element used with non-supported type."); - } - - SQLRETURN rc - = SQLBindCol(statement_.hstmt_, static_cast(position++), - odbcType_, static_cast(data), size, indHolders_); - if (is_odbc_error(rc)) - { - std::ostringstream ss; - ss << "binding output vector column #" << position; - throw odbc_soci_error(SQL_HANDLE_STMT, statement_.hstmt_, ss.str()); - } -} - -void odbc_vector_into_type_backend::pre_fetch() -{ - // nothing to do for the supported types -} - -void odbc_vector_into_type_backend::post_fetch(bool gotData, indicator *ind) -{ - if (gotData) - { - // first, deal with data - - // only std::string, std::tm and Statement need special handling - if (type_ == x_char) - { - std::vector *vp - = static_cast *>(data_); - - std::vector &v(*vp); - char *pos = buf_; - std::size_t const vsize = v.size(); - for (std::size_t i = 0; i != vsize; ++i) - { - v[i] = *pos; - pos += colSize_; - } - } - if (type_ == x_stdstring) - { - std::vector *vp - = static_cast *>(data_); - - std::vector &v(*vp); - - const char *pos = buf_; - std::size_t const vsize = v.size(); - for (std::size_t i = 0; i != vsize; ++i, pos += colSize_) - { - SQLLEN const len = indHolderVec_[i]; - if (len == -1) - { - // Value is null. - v[i].clear(); - continue; - } - - // Find the actual length of the string: for a VARCHAR(N) - // column, it may be right-padded with spaces up to the length - // of the longest string in the result set. This happens with - // at least MS SQL (and the exact behaviour depends on the - // value of the ANSI_PADDING option) and it seems like some - // other ODBC drivers also have options like "PADVARCHAR", so - // it's probably not the only case when it does. - // - // So deal with this generically by just trimming all the - // spaces from the right hand-side. - const char* end = pos + len; - while (end != pos) - { - // Pre-decrement as "end" is one past the end, as usual. - if (*--end != ' ') - { - // We must count the last non-space character. - ++end; - break; - } - } - - v[i].assign(pos, end - pos); - } - } - else if (type_ == x_stdtm) - { - std::vector *vp - = static_cast *>(data_); - - std::vector &v(*vp); - char *pos = buf_; - std::size_t const vsize = v.size(); - for (std::size_t i = 0; i != vsize; ++i) - { - TIMESTAMP_STRUCT * ts = reinterpret_cast(pos); - details::mktime_from_ymdhms(v[i], - ts->year, ts->month, ts->day, - ts->hour, ts->minute, ts->second); - pos += colSize_; - } - } - else if (type_ == x_long_long && use_string_for_bigint()) - { - std::vector *vp - = static_cast *>(data_); - std::vector &v(*vp); - char *pos = buf_; - std::size_t const vsize = v.size(); - for (std::size_t i = 0; i != vsize; ++i) - { - if (sscanf(pos, "%" LL_FMT_FLAGS "d", &v[i]) != 1) - { - throw soci_error("Failed to parse the returned 64-bit integer value"); - } - pos += colSize_; - } - } - else if (type_ == x_unsigned_long_long && use_string_for_bigint()) - { - std::vector *vp - = static_cast *>(data_); - std::vector &v(*vp); - char *pos = buf_; - std::size_t const vsize = v.size(); - for (std::size_t i = 0; i != vsize; ++i) - { - if (sscanf(pos, "%" LL_FMT_FLAGS "u", &v[i]) != 1) - { - throw soci_error("Failed to parse the returned 64-bit integer value"); - } - pos += colSize_; - } - } - - // then - deal with indicators - if (ind != NULL) - { - std::size_t const indSize = statement_.get_number_of_rows(); - for (std::size_t i = 0; i != indSize; ++i) - { - if (indHolderVec_[i] > 0) - { - ind[i] = i_ok; - } - else if (indHolderVec_[i] == SQL_NULL_DATA) - { - ind[i] = i_null; - } - else - { - ind[i] = i_truncated; - } - } - } - else - { - std::size_t const indSize = statement_.get_number_of_rows(); - for (std::size_t i = 0; i != indSize; ++i) - { - if (indHolderVec_[i] == SQL_NULL_DATA) - { - // fetched null and no indicator - programming error! - throw soci_error( - "Null value fetched and no indicator defined."); - } - } - } - } - else // gotData == false - { - // nothing to do here, vectors are truncated anyway - } -} - -void odbc_vector_into_type_backend::resize(std::size_t sz) -{ - indHolderVec_.resize(sz); - switch (type_) - { - // simple cases - case x_char: - { - std::vector *v = static_cast *>(data_); - v->resize(sz); - } - break; - case x_short: - { - std::vector *v = static_cast *>(data_); - v->resize(sz); - } - break; - case x_integer: - { - std::vector *v = static_cast *>(data_); - v->resize(sz); - } - break; - case x_long_long: - { - std::vector *v = - static_cast *>(data_); - v->resize(sz); - } - break; - case x_unsigned_long_long: - { - std::vector *v = - static_cast *>(data_); - v->resize(sz); - } - break; - case x_double: - { - std::vector *v - = static_cast *>(data_); - v->resize(sz); - } - break; - case x_stdstring: - { - std::vector *v - = static_cast *>(data_); - v->resize(sz); - } - break; - case x_stdtm: - { - std::vector *v - = static_cast *>(data_); - v->resize(sz); - } - break; - - default: - throw soci_error("Into vector element used with non-supported type."); - } -} - -std::size_t odbc_vector_into_type_backend::size() -{ - std::size_t sz = 0; // dummy initialization to please the compiler - switch (type_) - { - // simple cases - case x_char: - { - std::vector *v = static_cast *>(data_); - sz = v->size(); - } - break; - case x_short: - { - std::vector *v = static_cast *>(data_); - sz = v->size(); - } - break; - case x_integer: - { - std::vector *v = static_cast *>(data_); - sz = v->size(); - } - break; - case x_long_long: - { - std::vector *v = - static_cast *>(data_); - sz = v->size(); - } - break; - case x_unsigned_long_long: - { - std::vector *v = - static_cast *>(data_); - sz = v->size(); - } - break; - case x_double: - { - std::vector *v - = static_cast *>(data_); - sz = v->size(); - } - break; - case x_stdstring: - { - std::vector *v - = static_cast *>(data_); - sz = v->size(); - } - break; - case x_stdtm: - { - std::vector *v - = static_cast *>(data_); - sz = v->size(); - } - break; - - default: - throw soci_error("Into vector element used with non-supported type."); - } - - return sz; -} - -void odbc_vector_into_type_backend::clean_up() -{ - if (buf_ != NULL) - { - delete [] buf_; - buf_ = NULL; - } -} diff --git a/src/soci/src/backends/odbc/vector-use-type.cpp b/src/soci/src/backends/odbc/vector-use-type.cpp deleted file mode 100644 index 92b200dfb6..0000000000 --- a/src/soci/src/backends/odbc/vector-use-type.cpp +++ /dev/null @@ -1,495 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_ODBC_SOURCE -#include "soci/soci-platform.h" -#include "soci/odbc/soci-odbc.h" -#include "soci-static-assert.h" -#include -#include -#include -#include -#include - -#ifdef _MSC_VER -// disables the warning about converting int to void*. This is a 64 bit compatibility -// warning, but odbc requires the value to be converted on this line -// SQLSetStmtAttr(statement_.hstmt_, SQL_ATTR_PARAMSET_SIZE, (SQLPOINTER)arraySize, 0); -#pragma warning(disable:4312) -#endif - -using namespace soci; -using namespace soci::details; - -void odbc_vector_use_type_backend::prepare_indicators(std::size_t size) -{ - if (size == 0) - { - throw soci_error("Vectors of size 0 are not allowed."); - } - - indHolderVec_.resize(size); - indHolders_ = &indHolderVec_[0]; -} - -void odbc_vector_use_type_backend::prepare_for_bind(void *&data, SQLUINTEGER &size, - SQLSMALLINT &sqlType, SQLSMALLINT &cType) -{ - switch (type_) - { // simple cases - case x_short: - { - sqlType = SQL_SMALLINT; - cType = SQL_C_SSHORT; - size = sizeof(short); - std::vector *vp = static_cast *>(data); - std::vector &v(*vp); - prepare_indicators(v.size()); - data = &v[0]; - } - break; - case x_integer: - { - sqlType = SQL_INTEGER; - cType = SQL_C_SLONG; - size = sizeof(SQLINTEGER); - SOCI_STATIC_ASSERT(sizeof(SQLINTEGER) == sizeof(int)); - std::vector *vp = static_cast *>(data); - std::vector &v(*vp); - prepare_indicators(v.size()); - data = &v[0]; - } - break; - case x_long_long: - { - std::vector *vp = - static_cast *>(data); - std::vector &v(*vp); - std::size_t const vsize = v.size(); - prepare_indicators(vsize); - - if (use_string_for_bigint()) - { - sqlType = SQL_NUMERIC; - cType = SQL_C_CHAR; - size = max_bigint_length; - buf_ = new char[size * vsize]; - data = buf_; - } - else // Normal case, use ODBC support. - { - sqlType = SQL_BIGINT; - cType = SQL_C_SBIGINT; - size = sizeof(long long); - data = &v[0]; - } - } - break; - case x_unsigned_long_long: - { - std::vector *vp = - static_cast *>(data); - std::vector &v(*vp); - std::size_t const vsize = v.size(); - prepare_indicators(vsize); - - if (use_string_for_bigint()) - { - sqlType = SQL_NUMERIC; - cType = SQL_C_CHAR; - size = max_bigint_length; - buf_ = new char[size * vsize]; - data = buf_; - } - else // Normal case, use ODBC support. - { - sqlType = SQL_BIGINT; - cType = SQL_C_SBIGINT; - size = sizeof(unsigned long long); - data = &v[0]; - } - } - break; - case x_double: - { - sqlType = SQL_DOUBLE; - cType = SQL_C_DOUBLE; - size = sizeof(double); - std::vector *vp = static_cast *>(data); - std::vector &v(*vp); - prepare_indicators(v.size()); - data = &v[0]; - } - break; - - // cases that require adjustments and buffer management - case x_char: - { - std::vector *vp - = static_cast *>(data); - std::size_t const vsize = vp->size(); - - prepare_indicators(vsize); - - size = sizeof(char) * 2; - buf_ = new char[size * vsize]; - - char *pos = buf_; - - for (std::size_t i = 0; i != vsize; ++i) - { - *pos++ = (*vp)[i]; - *pos++ = 0; - } - - sqlType = SQL_CHAR; - cType = SQL_C_CHAR; - data = buf_; - } - break; - case x_stdstring: - { - sqlType = SQL_CHAR; - cType = SQL_C_CHAR; - - std::vector *vp - = static_cast *>(data); - std::vector &v(*vp); - - std::size_t maxSize = 0; - std::size_t const vecSize = v.size(); - prepare_indicators(vecSize); - for (std::size_t i = 0; i != vecSize; ++i) - { - std::size_t sz = v[i].length(); - indHolderVec_[i] = static_cast(sz); - maxSize = sz > maxSize ? sz : maxSize; - } - - maxSize++; // For terminating nul. - - buf_ = new char[maxSize * vecSize]; - memset(buf_, 0, maxSize * vecSize); - - char *pos = buf_; - for (std::size_t i = 0; i != vecSize; ++i) - { - memcpy(pos, v[i].c_str(), v[i].length()); - pos += maxSize; - } - - data = buf_; - size = static_cast(maxSize); - } - break; - case x_stdtm: - { - std::vector *vp - = static_cast *>(data); - - prepare_indicators(vp->size()); - - buf_ = new char[sizeof(TIMESTAMP_STRUCT) * vp->size()]; - - sqlType = SQL_TYPE_TIMESTAMP; - cType = SQL_C_TYPE_TIMESTAMP; - data = buf_; - size = 19; // This number is not the size in bytes, but the number - // of characters in the date if it was written out - // yyyy-mm-dd hh:mm:ss - } - break; - - // not supported - default: - throw soci_error("Use vector element used with non-supported type."); - } - - colSize_ = size; -} - -void odbc_vector_use_type_backend::bind_helper(int &position, void *data, exchange_type type) -{ - data_ = data; // for future reference - type_ = type; // for future reference - - SQLSMALLINT sqlType(0); - SQLSMALLINT cType(0); - SQLUINTEGER size(0); - - prepare_for_bind(data, size, sqlType, cType); - - SQLULEN const arraySize = static_cast(indHolderVec_.size()); - SQLSetStmtAttr(statement_.hstmt_, SQL_ATTR_PARAMSET_SIZE, (SQLPOINTER)arraySize, 0); - - SQLRETURN rc = SQLBindParameter(statement_.hstmt_, static_cast(position++), - SQL_PARAM_INPUT, cType, sqlType, size, 0, - static_cast(data), size, indHolders_); - - if (is_odbc_error(rc)) - { - std::ostringstream ss; - ss << "binding input vector parameter #" << position; - throw odbc_soci_error(SQL_HANDLE_STMT, statement_.hstmt_, ss.str()); - } -} - -void odbc_vector_use_type_backend::bind_by_pos(int &position, - void *data, exchange_type type) -{ - if (statement_.boundByName_) - { - throw soci_error( - "Binding for use elements must be either by position or by name."); - } - - bind_helper(position, data, type); - - statement_.boundByPos_ = true; -} - -void odbc_vector_use_type_backend::bind_by_name( - std::string const &name, void *data, exchange_type type) -{ - if (statement_.boundByPos_) - { - throw soci_error( - "Binding for use elements must be either by position or by name."); - } - - int position = -1; - int count = 1; - - for (std::vector::iterator it = statement_.names_.begin(); - it != statement_.names_.end(); ++it) - { - if (*it == name) - { - position = count; - break; - } - count++; - } - - if (position != -1) - { - bind_helper(position, data, type); - } - else - { - std::ostringstream ss; - ss << "Unable to find name '" << name << "' to bind to"; - throw soci_error(ss.str().c_str()); - } - - statement_.boundByName_ = true; -} - -void odbc_vector_use_type_backend::pre_use(indicator const *ind) -{ - // first deal with data - SQLLEN non_null_indicator = 0; - switch (type_) - { - case x_short: - case x_integer: - case x_double: - // Length of the parameter value is ignored for these types. - break; - - case x_char: - case x_stdstring: - non_null_indicator = SQL_NTS; - break; - - case x_stdtm: - { - std::vector *vp - = static_cast *>(data_); - - std::vector &v(*vp); - - char *pos = buf_; - std::size_t const vsize = v.size(); - for (std::size_t i = 0; i != vsize; ++i) - { - std::tm t = v[i]; - TIMESTAMP_STRUCT * ts = reinterpret_cast(pos); - - ts->year = static_cast(t.tm_year + 1900); - ts->month = static_cast(t.tm_mon + 1); - ts->day = static_cast(t.tm_mday); - ts->hour = static_cast(t.tm_hour); - ts->minute = static_cast(t.tm_min); - ts->second = static_cast(t.tm_sec); - ts->fraction = 0; - pos += sizeof(TIMESTAMP_STRUCT); - } - } - break; - - case x_long_long: - if (use_string_for_bigint()) - { - std::vector *vp - = static_cast *>(data_); - std::vector &v(*vp); - - char *pos = buf_; - std::size_t const vsize = v.size(); - for (std::size_t i = 0; i != vsize; ++i) - { - snprintf(pos, max_bigint_length, "%" LL_FMT_FLAGS "d", v[i]); - pos += max_bigint_length; - } - - non_null_indicator = SQL_NTS; - } - break; - - case x_unsigned_long_long: - if (use_string_for_bigint()) - { - std::vector *vp - = static_cast *>(data_); - std::vector &v(*vp); - - char *pos = buf_; - std::size_t const vsize = v.size(); - for (std::size_t i = 0; i != vsize; ++i) - { - snprintf(pos, max_bigint_length, "%" LL_FMT_FLAGS "u", v[i]); - pos += max_bigint_length; - } - - non_null_indicator = SQL_NTS; - } - break; - - case x_statement: - case x_rowid: - case x_blob: - case x_xmltype: - case x_longstring: - // Those are unreachable, we would have thrown from - // prepare_for_bind() if we we were using one of them, only handle - // them here to avoid compiler warnings about unhandled enum - // elements. - break; - } - - // then handle indicators - if (ind != NULL) - { - std::size_t const vsize = size(); - for (std::size_t i = 0; i != vsize; ++i, ++ind) - { - if (*ind == i_null) - { - indHolderVec_[i] = SQL_NULL_DATA; // null - } - else - { - // for strings we have already set the values - if (type_ != x_stdstring) - { - indHolderVec_[i] = non_null_indicator; - } - } - } - } - else - { - // no indicators - treat all fields as OK - std::size_t const vsize = size(); - for (std::size_t i = 0; i != vsize; ++i, ++ind) - { - // for strings we have already set the values - if (type_ != x_stdstring) - { - indHolderVec_[i] = non_null_indicator; - } - } - } -} - -std::size_t odbc_vector_use_type_backend::size() -{ - std::size_t sz = 0; // dummy initialization to please the compiler - switch (type_) - { - // simple cases - case x_char: - { - std::vector *vp = static_cast *>(data_); - sz = vp->size(); - } - break; - case x_short: - { - std::vector *vp = static_cast *>(data_); - sz = vp->size(); - } - break; - case x_integer: - { - std::vector *vp = static_cast *>(data_); - sz = vp->size(); - } - break; - case x_long_long: - { - std::vector *vp = - static_cast *>(data_); - sz = vp->size(); - } - break; - case x_unsigned_long_long: - { - std::vector *vp = - static_cast *>(data_); - sz = vp->size(); - } - break; - case x_double: - { - std::vector *vp - = static_cast *>(data_); - sz = vp->size(); - } - break; - case x_stdstring: - { - std::vector *vp - = static_cast *>(data_); - sz = vp->size(); - } - break; - case x_stdtm: - { - std::vector *vp - = static_cast *>(data_); - sz = vp->size(); - } - break; - - // not supported - default: - throw soci_error("Use vector element used with non-supported type."); - } - - return sz; -} - -void odbc_vector_use_type_backend::clean_up() -{ - if (buf_ != NULL) - { - delete [] buf_; - buf_ = NULL; - } -} diff --git a/src/soci/src/backends/oracle/CMakeLists.txt b/src/soci/src/backends/oracle/CMakeLists.txt deleted file mode 100644 index 632ca61790..0000000000 --- a/src/soci/src/backends/oracle/CMakeLists.txt +++ /dev/null @@ -1,15 +0,0 @@ -############################################################################### -# -# This file is part of CMake configuration for SOCI library -# -# Copyright (C) 2010 Mateusz Loskot -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -# -############################################################################### -soci_backend(Oracle - DEPENDS Oracle - DESCRIPTION "SOCI backend for Oracle 10+" - AUTHORS "Maciej Sobczak, Stephen Hutton" - MAINTAINERS "Maciej Sobczak") diff --git a/src/soci/src/backends/oracle/Makefile.basic b/src/soci/src/backends/oracle/Makefile.basic deleted file mode 100644 index 31b861f5e4..0000000000 --- a/src/soci/src/backends/oracle/Makefile.basic +++ /dev/null @@ -1,95 +0,0 @@ -# The following variable is specific to this backend and its correct -# values might depend on your environment - feel free to set it accordingly. - -ORACLEINCLUDEDIR = -I${ORACLE_HOME}/rdbms/public - -# The rest of the Makefile is indepentent of the target environment. - -COMPILER = g++ -CXXFLAGS = -Wall -pedantic -Wno-long-long -CXXFLAGSSO = ${CXXFLAGS} -fPIC -INCLUDEDIRS = -I../../../include -I../../../include/private ${ORACLEINCLUDEDIR} - -OBJECTS = blob.o factory.o row-id.o session.o standard-into-type.o \ - standard-use-type.o statement.o vector-into-type.o vector-use-type.o \ - error.o - -OBJECTSSO = blob-s.o factory-s.o row-id-s.o session-s.o \ - standard-into-type-s.o standard-use-type-s.o statement-s.o \ - vector-into-type-s.o vector-use-type-s.o error-s.o - -libsoci_oracle.a : ${OBJECTS} - ar rv $@ $? - rm *.o - -soci-oracle.o : soci-oracle.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -blob.o : blob.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -error.o : error.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -factory.o : factory.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -row-id.o : row-id.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -session.o : session.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -standard-into-type.o : standard-into-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -standard-use-type.o : standard-use-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -statement.o : statement.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -vector-into-type.o : vector-into-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -vector-use-type.o : vector-use-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - - -shared : ${OBJECTSSO} - ${COMPILER} -shared -o libsoci_oracle.so ${OBJECTSSO} - rm *.o - -blob-s.o : blob.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -error-s.o : error.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -factory-s.o : factory.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -row-id-s.o : row-id.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -session-s.o : session.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -standard-into-type-s.o : standard-into-type.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -standard-use-type-s.o : standard-use-type.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -statement-s.o : statement.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -vector-into-type-s.o : vector-into-type.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - -vector-use-type-s.o : vector-use-type.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGSSO} ${INCLUDEDIRS} - - -clean : - rm -f *.o libsoci_oracle.a libsoci_oracle.so diff --git a/src/soci/src/backends/oracle/blob.cpp b/src/soci/src/backends/oracle/blob.cpp deleted file mode 100644 index d9c90fd601..0000000000 --- a/src/soci/src/backends/oracle/blob.cpp +++ /dev/null @@ -1,112 +0,0 @@ -// -// Copyright (C) 2004-2007 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#include "soci/oracle/soci-oracle.h" -#include "error.h" -#include "soci/statement.h" -#include -#include -#include -#include -#include - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; -using namespace soci::details::oracle; - -oracle_blob_backend::oracle_blob_backend(oracle_session_backend &session) - : session_(session) -{ - sword res = OCIDescriptorAlloc(session.envhp_, - reinterpret_cast(&lobp_), OCI_DTYPE_LOB, 0, 0); - if (res != OCI_SUCCESS) - { - throw soci_error("Cannot allocate the LOB locator"); - } -} - -oracle_blob_backend::~oracle_blob_backend() -{ - OCIDescriptorFree(lobp_, OCI_DTYPE_LOB); -} - -std::size_t oracle_blob_backend::get_len() -{ - ub4 len; - - sword res = OCILobGetLength(session_.svchp_, session_.errhp_, - lobp_, &len); - - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, session_.errhp_); - } - - return static_cast(len); -} - -std::size_t oracle_blob_backend::read( - std::size_t offset, char *buf, std::size_t toRead) -{ - ub4 amt = static_cast(toRead); - - sword res = OCILobRead(session_.svchp_, session_.errhp_, lobp_, &amt, - static_cast(offset), reinterpret_cast(buf), - amt, 0, 0, 0, 0); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, session_.errhp_); - } - - return static_cast(amt); -} - -std::size_t oracle_blob_backend::write( - std::size_t offset, char const *buf, std::size_t toWrite) -{ - ub4 amt = static_cast(toWrite); - - sword res = OCILobWrite(session_.svchp_, session_.errhp_, lobp_, &amt, - static_cast(offset), - reinterpret_cast(const_cast(buf)), - amt, OCI_ONE_PIECE, 0, 0, 0, 0); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, session_.errhp_); - } - - return static_cast(amt); -} - -std::size_t oracle_blob_backend::append(char const *buf, std::size_t toWrite) -{ - ub4 amt = static_cast(toWrite); - - sword res = OCILobWriteAppend(session_.svchp_, session_.errhp_, lobp_, - &amt, reinterpret_cast(const_cast(buf)), - amt, OCI_ONE_PIECE, 0, 0, 0, 0); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, session_.errhp_); - } - - return static_cast(amt); -} - -void oracle_blob_backend::trim(std::size_t newLen) -{ - sword res = OCILobTrim(session_.svchp_, session_.errhp_, lobp_, - static_cast(newLen)); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, session_.errhp_); - } -} diff --git a/src/soci/src/backends/oracle/error.cpp b/src/soci/src/backends/oracle/error.cpp deleted file mode 100644 index b7795272c3..0000000000 --- a/src/soci/src/backends/oracle/error.cpp +++ /dev/null @@ -1,82 +0,0 @@ -// -// Copyright (C) 2004-2007 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_ORACLE_SOURCE -#include "soci/oracle/soci-oracle.h" -#include "error.h" -#include -#include - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; -using namespace soci::details::oracle; - -oracle_soci_error::oracle_soci_error(std::string const & msg, int errNum) - : soci_error(msg), err_num_(errNum), cat_(unknown) -{ - if (errNum == 12162 || errNum == 25403) - { - cat_ = connection_error; - } - else if (errNum == 1400) - { - cat_ = constraint_violation; - } - else if (errNum == 1466 || - errNum == 2055 || - errNum == 2067 || - errNum == 2091 || - errNum == 2092 || - errNum == 25401 || - errNum == 25402 || - errNum == 25405 || - errNum == 25408 || - errNum == 25409) - { - cat_ = unknown_transaction_state; - } -} - -void soci::details::oracle::get_error_details(sword res, OCIError *errhp, - std::string &msg, int &errNum) -{ - text errbuf[512]; - sb4 errcode; - errNum = 0; - - switch (res) - { - case OCI_NO_DATA: - msg = "soci error: No data"; - break; - case OCI_ERROR: - case OCI_SUCCESS_WITH_INFO: - OCIErrorGet(errhp, 1, 0, &errcode, - errbuf, sizeof(errbuf), OCI_HTYPE_ERROR); - msg = reinterpret_cast(errbuf); - errNum = static_cast(errcode); - break; - case OCI_INVALID_HANDLE: - msg = "soci error: Invalid handle"; - break; - default: - msg = "soci error: Unknown error code"; - } -} - -void soci::details::oracle::throw_oracle_soci_error(sword res, OCIError *errhp) -{ - std::string msg; - int errNum; - - get_error_details(res, errhp, msg, errNum); - throw oracle_soci_error(msg, errNum); -} diff --git a/src/soci/src/backends/oracle/error.h b/src/soci/src/backends/oracle/error.h deleted file mode 100644 index 57f172554a..0000000000 --- a/src/soci/src/backends/oracle/error.h +++ /dev/null @@ -1,33 +0,0 @@ -// -// Copyright (C) 2004-2007 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_ORACLE_ERROR_H_INCLUDED -#define SOCI_ORACLE_ERROR_H_INCLUDED - -#include "soci/oracle/soci-oracle.h" - -namespace soci -{ - -namespace details -{ - -namespace oracle -{ - -void throw_oracle_soci_error(sword res, OCIError *errhp); - -void get_error_details(sword res, OCIError *errhp, - std::string &msg, int &errNum); - -} // namespace oracle - -} // namespace details - -} // namespace soci - -#endif diff --git a/src/soci/src/backends/oracle/factory.cpp b/src/soci/src/backends/oracle/factory.cpp deleted file mode 100644 index 6b09c044fa..0000000000 --- a/src/soci/src/backends/oracle/factory.cpp +++ /dev/null @@ -1,207 +0,0 @@ -// -// Copyright (C) 2004-2007 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_ORACLE_SOURCE -#include "soci/oracle/soci-oracle.h" -#include "soci/connection-parameters.h" -#include "soci/backend-loader.h" -#include -#include -#include -#include -#include - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; - -// iterates the string pointed by i, searching for pairs of key value. -// it returns the position after the value -std::string::const_iterator get_key_value(std::string::const_iterator & i, - std::string::const_iterator const & end, - std::string & key, - std::string & value) -{ - bool in_value = false; - bool quoted = false; - - key.clear(); - value.clear(); - - while (i != end) - { - if (in_value == false) - { - if (*i == '=') - { - in_value = true; - if (i != end && *(i + 1) == '"') - { - quoted = true; - ++i; // jump over the quote - } - } - else if (!isspace(*i)) - { - key += *i; - } - } - else - { - if ((quoted == true && *i == '"') || (quoted == false && isspace(*i))) - { - return ++i; - } - else - { - value += *i; - } - } - ++i; - } - return i; -} - -// decode charset and ncharset names -int charset_code(const std::string & name) -{ - // Note: unofficial reference for charset ids is: - // http://www.mydul.net/charsets.html - - int code; - - if (name == "utf8") - { - code = 871; - } - else if (name == "utf16") - { - code = OCI_UTF16ID; - } - else if (name == "we8mswin1252" || name == "win1252") - { - code = 178; - } - else - { - // allow explicit number value - - std::istringstream ss(name); - - ss >> code; - if (!ss) - { - throw soci_error("Invalid character set name."); - } - } - - return code; -} - -// retrieves service name, user name and password from the -// uniform connect string -void chop_connect_string(std::string const & connectString, - std::string & serviceName, std::string & userName, - std::string & password, int & mode, bool & decimals_as_strings, - int & charset, int & ncharset) -{ - serviceName.clear(); - userName.clear(); - password.clear(); - mode = OCI_DEFAULT; - decimals_as_strings = false; - charset = 0; - ncharset = 0; - - std::string key, value; - std::string::const_iterator i = connectString.begin(); - while (i != connectString.end()) - { - i = get_key_value(i, connectString.end(), key, value); - if (key == "service") - { - serviceName = value; - } - else if (key == "user") - { - userName = value; - } - else if (key == "password") - { - password = value; - } - else if (key == "mode") - { - if (value == "sysdba") - { - mode = OCI_SYSDBA; - } - else if (value == "sysoper") - { - mode = OCI_SYSOPER; - } - else if (value == "default") - { - mode = OCI_DEFAULT; - } - else - { - throw soci_error("Invalid connection mode."); - } - } - else if (key == "decimals_as_strings") - { - decimals_as_strings = value == "1" || value == "Y" || value == "y"; - } - else if (key == "charset") - { - charset = charset_code(value); - } - else if (key == "ncharset") - { - ncharset = charset_code(value); - } - } -} - -// concrete factory for Empty concrete strategies -oracle_session_backend * oracle_backend_factory::make_session( - connection_parameters const & parameters) const -{ - std::string serviceName, userName, password; - int mode; - bool decimals_as_strings; - int charset; - int ncharset; - - chop_connect_string(parameters.get_connect_string(), serviceName, userName, password, - mode, decimals_as_strings, charset, ncharset); - - return new oracle_session_backend(serviceName, userName, password, - mode, decimals_as_strings, charset, ncharset); -} - -oracle_backend_factory const soci::oracle; - -extern "C" -{ - -// for dynamic backend loading -SOCI_ORACLE_DECL backend_factory const * factory_oracle() -{ - return &soci::oracle; -} - -SOCI_ORACLE_DECL void register_factory_oracle() -{ - soci::dynamic_backends::register_backend("oracle", soci::oracle); -} - -} // extern "C" diff --git a/src/soci/src/backends/oracle/row-id.cpp b/src/soci/src/backends/oracle/row-id.cpp deleted file mode 100644 index f0584b7a62..0000000000 --- a/src/soci/src/backends/oracle/row-id.cpp +++ /dev/null @@ -1,32 +0,0 @@ -// -// Copyright (C) 2013 Mateusz Loskot -// Copyright (C) 2004-2007 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_ORACLE_SOURCE -#include "soci/oracle/soci-oracle.h" - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; - -oracle_rowid_backend::oracle_rowid_backend(oracle_session_backend &session) -{ - sword res = OCIDescriptorAlloc(session.envhp_, - reinterpret_cast(&rowidp_), OCI_DTYPE_ROWID, 0, 0); - if (res != OCI_SUCCESS) - { - throw soci_error("Cannot allocate the ROWID descriptor"); - } -} - -oracle_rowid_backend::~oracle_rowid_backend() -{ - OCIDescriptorFree(rowidp_, OCI_DTYPE_ROWID); -} diff --git a/src/soci/src/backends/oracle/session.cpp b/src/soci/src/backends/oracle/session.cpp deleted file mode 100644 index c502fba316..0000000000 --- a/src/soci/src/backends/oracle/session.cpp +++ /dev/null @@ -1,441 +0,0 @@ -// -// Copyright (C) 2004-2007 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_ORACLE_SOURCE -#include "soci/oracle/soci-oracle.h" -#include "soci/callbacks.h" -#include "error.h" -#include -#include -#include -#include -#include - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; -using namespace soci::details::oracle; - -namespace // unnamed -{ - -sb4 fo_callback(void * /* svchp */, void * /* envhp */, void * fo_ctx, - ub4 /* fo_type */, ub4 fo_event) -{ - oracle_session_backend * backend = - static_cast(fo_ctx); - - failover_callback * callback = backend->failoverCallback_; - - if (callback != NULL) - { - session * sql = backend->session_; - - switch (fo_event) - { - case OCI_FO_BEGIN: - // failover operation was initiated - - try - { - callback->started(); - } - catch (...) - { - // ignore exceptions from user callbacks - } - - break; - - case OCI_FO_END: - // failover was successful - - try - { - callback->finished(*sql); - } - catch (...) - { - // ignore exceptions from user callbacks - } - - break; - - case OCI_FO_ABORT: - // failover was aborted with no possibility to recovery - - try - { - callback->aborted(); - } - catch (...) - { - // ignore exceptions from user callbacks - } - - break; - - case OCI_FO_ERROR: - // failover failed, but can be retried - - try - { - bool retry = false; - std::string newTarget; - callback->failed(retry, newTarget); - - // newTarget is ignored, as the new target - // is selected by Oracle client configuration - - if (retry) - { - return OCI_FO_RETRY; - } - } - catch (...) - { - // ignore exceptions from user callbacks - } - - break; - - case OCI_FO_REAUTH: - // nothing interesting - break; - - default: - // ignore unknown callback types (if any) - break; - } - } - - return 0; -} - -} // unnamed namespace - -oracle_session_backend::oracle_session_backend(std::string const & serviceName, - std::string const & userName, std::string const & password, int mode, - bool decimals_as_strings, int charset, int ncharset) - : envhp_(NULL), srvhp_(NULL), errhp_(NULL), svchp_(NULL), usrhp_(NULL), - decimals_as_strings_(decimals_as_strings) -{ - // assume service/user/password are utf8-compatible already - const int defaultSourceCharSetId = 871; - - // arbitrary length for charset conversion buffer - const size_t nlsBufLen = 100; - - char nlsService[nlsBufLen]; - size_t nlsServiceLen; - char nlsUserName[nlsBufLen]; - size_t nlsUserNameLen; - char nlsPassword[nlsBufLen]; - size_t nlsPasswordLen; - - sword res; - - // create the environment - res = OCIEnvNlsCreate(&envhp_, OCI_THREADED | OCI_ENV_NO_MUTEX, - 0, 0, 0, 0, 0, 0, charset, ncharset); - if (res != OCI_SUCCESS) - { - throw soci_error("Cannot create environment"); - } - - // create the server handle - res = OCIHandleAlloc(envhp_, reinterpret_cast(&srvhp_), - OCI_HTYPE_SERVER, 0, 0); - if (res != OCI_SUCCESS) - { - clean_up(); - throw soci_error("Cannot create server handle"); - } - - // create the error handle - res = OCIHandleAlloc(envhp_, reinterpret_cast(&errhp_), - OCI_HTYPE_ERROR, 0, 0); - if (res != OCI_SUCCESS) - { - clean_up(); - throw soci_error("Cannot create error handle"); - } - - if (charset != 0) - { - // convert service/user/password to the expected charset - - res = OCINlsCharSetConvert(envhp_, errhp_, - charset, nlsService, nlsBufLen, - defaultSourceCharSetId, serviceName.c_str(), serviceName.size(), &nlsServiceLen); - if (res != OCI_SUCCESS) - { - std::string msg; - int errNum; - get_error_details(res, errhp_, msg, errNum); - clean_up(); - throw oracle_soci_error(msg, errNum); - } - - res = OCINlsCharSetConvert(envhp_, errhp_, - charset, nlsUserName, nlsBufLen, - defaultSourceCharSetId, userName.c_str(), userName.size(), &nlsUserNameLen); - if (res != OCI_SUCCESS) - { - std::string msg; - int errNum; - get_error_details(res, errhp_, msg, errNum); - clean_up(); - throw oracle_soci_error(msg, errNum); - } - - res = OCINlsCharSetConvert(envhp_, errhp_, - charset, nlsPassword, nlsBufLen, - defaultSourceCharSetId, password.c_str(), password.size(), &nlsPasswordLen); - if (res != OCI_SUCCESS) - { - std::string msg; - int errNum; - get_error_details(res, errhp_, msg, errNum); - clean_up(); - throw oracle_soci_error(msg, errNum); - } - } - else - { - // do not perform any charset conversions - - nlsServiceLen = serviceName.size(); - if (nlsServiceLen < nlsBufLen) - { - std::strcpy(nlsService, serviceName.c_str()); - } - else - { - throw soci_error("Service name is too long."); - } - - nlsUserNameLen = userName.size(); - if (nlsUserNameLen < nlsBufLen) - { - std::strcpy(nlsUserName, userName.c_str()); - } - else - { - throw soci_error("User name is too long."); - } - - nlsPasswordLen = password.size(); - if (nlsPasswordLen < nlsBufLen) - { - std::strcpy(nlsPassword, password.c_str()); - } - else - { - throw soci_error("Password is too long."); - } - } - - // create the server context - res = OCIServerAttach(srvhp_, errhp_, - reinterpret_cast(nlsService), nlsServiceLen, OCI_DEFAULT); - if (res != OCI_SUCCESS) - { - std::string msg; - int errNum; - get_error_details(res, errhp_, msg, errNum); - clean_up(); - throw oracle_soci_error(msg, errNum); - } - - // register failover callback - OCIFocbkStruct fo; - fo.fo_ctx = this; - fo.callback_function = &fo_callback; - - res = OCIAttrSet(srvhp_, static_cast(OCI_HTYPE_SERVER), - &fo, 0, static_cast(OCI_ATTR_FOCBK), errhp_); - if (res != OCI_SUCCESS) - { - std::string msg; - int errNum; - get_error_details(res, errhp_, msg, errNum); - clean_up(); - throw oracle_soci_error(msg, errNum); - } - - // create service context handle - res = OCIHandleAlloc(envhp_, reinterpret_cast(&svchp_), - OCI_HTYPE_SVCCTX, 0, 0); - if (res != OCI_SUCCESS) - { - clean_up(); - throw soci_error("Cannot create service context"); - } - - // set the server attribute in the context handle - res = OCIAttrSet(svchp_, OCI_HTYPE_SVCCTX, srvhp_, 0, - OCI_ATTR_SERVER, errhp_); - if (res != OCI_SUCCESS) - { - std::string msg; - int errNum; - get_error_details(res, errhp_, msg, errNum); - clean_up(); - throw oracle_soci_error(msg, errNum); - } - - // allocate user session handle - res = OCIHandleAlloc(envhp_, reinterpret_cast(&usrhp_), - OCI_HTYPE_SESSION, 0, 0); - if (res != OCI_SUCCESS) - { - clean_up(); - throw soci_error("Cannot allocate user session handle"); - } - - // select credentials type - use rdbms based credentials by default - // and switch to external credentials if username and - // password are both not specified - ub4 credentialType = OCI_CRED_RDBMS; - if (userName.empty() && password.empty()) - { - credentialType = OCI_CRED_EXT; - } - else - { - // set username attribute in the user session handle - res = OCIAttrSet(usrhp_, OCI_HTYPE_SESSION, - reinterpret_cast(nlsUserName), - nlsUserNameLen, OCI_ATTR_USERNAME, errhp_); - if (res != OCI_SUCCESS) - { - clean_up(); - throw soci_error("Cannot set username"); - } - - // set password attribute - res = OCIAttrSet(usrhp_, OCI_HTYPE_SESSION, - reinterpret_cast(nlsPassword), - nlsPasswordLen, OCI_ATTR_PASSWORD, errhp_); - if (res != OCI_SUCCESS) - { - clean_up(); - throw soci_error("Cannot set password"); - } - } - - // begin the session - res = OCISessionBegin(svchp_, errhp_, usrhp_, - credentialType, mode); - if (res != OCI_SUCCESS && res != OCI_SUCCESS_WITH_INFO) - { - std::string msg; - int errNum; - get_error_details(res, errhp_, msg, errNum); - clean_up(); - throw oracle_soci_error(msg, errNum); - } - - // set the session in the context handle - res = OCIAttrSet(svchp_, OCI_HTYPE_SVCCTX, usrhp_, - 0, OCI_ATTR_SESSION, errhp_); - if (res != OCI_SUCCESS) - { - std::string msg; - int errNum; - get_error_details(res, errhp_, msg, errNum); - clean_up(); - throw oracle_soci_error(msg, errNum); - } -} - -oracle_session_backend::~oracle_session_backend() -{ - clean_up(); -} - -void oracle_session_backend::begin() -{ - // This code is commented out because it causes one of the transaction - // tests in common_tests::test10() to fail with error 'Invalid handle' - // With the code commented out, all tests pass. - // sword res = OCITransStart(svchp_, errhp_, 0, OCI_TRANS_NEW); - // if (res != OCI_SUCCESS) - // { - // throworacle_soci_error(res, errhp_); - // } -} - -void oracle_session_backend::commit() -{ - sword res = OCITransCommit(svchp_, errhp_, OCI_DEFAULT); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, errhp_); - } -} - -void oracle_session_backend::rollback() -{ - sword res = OCITransRollback(svchp_, errhp_, OCI_DEFAULT); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, errhp_); - } -} - -void oracle_session_backend::clean_up() -{ - if (svchp_ != NULL && errhp_ != NULL && usrhp_ != NULL) - { - OCISessionEnd(svchp_, errhp_, usrhp_, OCI_DEFAULT); - } - - if (usrhp_) { OCIHandleFree(usrhp_, OCI_HTYPE_SESSION); } - if (svchp_) { OCIHandleFree(svchp_, OCI_HTYPE_SVCCTX); } - if (srvhp_) - { - OCIServerDetach(srvhp_, errhp_, OCI_DEFAULT); - OCIHandleFree(srvhp_, OCI_HTYPE_SERVER); - } - if (errhp_) { OCIHandleFree(errhp_, OCI_HTYPE_ERROR); } - if (envhp_) { OCIHandleFree(envhp_, OCI_HTYPE_ENV); } -} - -oracle_statement_backend * oracle_session_backend::make_statement_backend() -{ - return new oracle_statement_backend(*this); -} - -oracle_rowid_backend * oracle_session_backend::make_rowid_backend() -{ - return new oracle_rowid_backend(*this); -} - -oracle_blob_backend * oracle_session_backend::make_blob_backend() -{ - return new oracle_blob_backend(*this); -} - -ub2 oracle_session_backend::get_double_sql_type() const -{ - // SQLT_BDOUBLE avoids unnecessary conversions which is better from both - // performance and correctness point of view as it avoids rounding - // problems, however it's only available starting in Oracle 10.1, so - // normally we should do run-time Oracle version detection here, but for - // now just assume that if we use new headers (i.e. have high enough - // compile-time version), then the run-time is at least as high. -#ifdef SQLT_BDOUBLE - return SQLT_BDOUBLE; -#else - return SQLT_FLT; -#endif -} diff --git a/src/soci/src/backends/oracle/standard-into-type.cpp b/src/soci/src/backends/oracle/standard-into-type.cpp deleted file mode 100644 index 1c24f990a1..0000000000 --- a/src/soci/src/backends/oracle/standard-into-type.cpp +++ /dev/null @@ -1,372 +0,0 @@ -// -// Copyright (C) 2004-2007 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_ORACLE_SOURCE -#include "soci/oracle/soci-oracle.h" -#include "soci/blob.h" -#include "error.h" -#include "soci/rowid.h" -#include "soci/statement.h" -#include "soci/soci-platform.h" -#include "soci-exchange-cast.h" -#include "soci-mktime.h" -#include -#include -#include -#include -#include -#include - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; -using namespace soci::details::oracle; - -oracle_standard_into_type_backend * -oracle_statement_backend::make_into_type_backend() -{ - return new oracle_standard_into_type_backend(*this); -} - -oracle_standard_use_type_backend * -oracle_statement_backend::make_use_type_backend() -{ - return new oracle_standard_use_type_backend(*this); -} - -oracle_vector_into_type_backend * -oracle_statement_backend::make_vector_into_type_backend() -{ - return new oracle_vector_into_type_backend(*this); -} - -oracle_vector_use_type_backend * -oracle_statement_backend::make_vector_use_type_backend() -{ - return new oracle_vector_use_type_backend(*this); -} - -void oracle_standard_into_type_backend::define_by_pos( - int &position, void *data, exchange_type type) -{ - data_ = data; // for future reference - type_ = type; // for future reference - - ub2 oracleType = 0; // dummy initialization to please the compiler - sb4 size = 0; // also dummy - - switch (type) - { - // simple cases - case x_char: - oracleType = SQLT_AFC; - size = sizeof(char); - break; - case x_short: - oracleType = SQLT_INT; - size = sizeof(short); - break; - case x_integer: - oracleType = SQLT_INT; - size = sizeof(int); - break; - case x_double: - oracleType = statement_.session_.get_double_sql_type(); - size = sizeof(double); - break; - - // cases that require adjustments and buffer management - case x_long_long: - case x_unsigned_long_long: - oracleType = SQLT_STR; - size = 100; // arbitrary buffer length - buf_ = new char[size]; - data = buf_; - break; - case x_stdstring: - oracleType = SQLT_STR; - size = 32769; // support selecting strings from LONG columns - buf_ = new char[size]; - data = buf_; - break; - case x_stdtm: - oracleType = SQLT_DAT; - size = 7 * sizeof(ub1); - buf_ = new char[size]; - data = buf_; - break; - - // cases that require special handling - case x_statement: - { - oracleType = SQLT_RSET; - - statement *st = static_cast(data); - st->alloc(); - - oracle_statement_backend *stbe - = static_cast(st->get_backend()); - size = 0; - data = &stbe->stmtp_; - } - break; - case x_rowid: - { - oracleType = SQLT_RDD; - - rowid *rid = static_cast(data); - - oracle_rowid_backend *rbe - = static_cast(rid->get_backend()); - - size = 0; - data = &rbe->rowidp_; - } - break; - case x_blob: - { - oracleType = SQLT_BLOB; - - blob *b = static_cast(data); - - oracle_blob_backend *bbe - = static_cast(b->get_backend()); - - size = 0; - data = &bbe->lobp_; - } - break; - - case x_xmltype: - case x_longstring: - { - oracleType = SQLT_CLOB; - - // lazy initialization of the temporary LOB object, - // actual creation of this object is in pre_exec, which - // is called right before statement's execute - - OCILobLocator * lobp = NULL; - - size = sizeof(lobp); - data = &ociData_; - ociData_ = lobp; - } - break; - } - - sword res = OCIDefineByPos(statement_.stmtp_, &defnp_, - statement_.session_.errhp_, - position++, data, size, oracleType, - &indOCIHolder_, 0, &rCode_, OCI_DEFAULT); - - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, statement_.session_.errhp_); - } -} - -void oracle_standard_into_type_backend::pre_exec(int /* num */) -{ - if (type_ == x_xmltype || type_ == x_longstring) - { - // lazy initialization of the temporary LOB object - - OCILobLocator * lobp; - sword res = OCIDescriptorAlloc(statement_.session_.envhp_, - reinterpret_cast(&lobp), OCI_DTYPE_LOB, 0, 0); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, statement_.session_.errhp_); - } - - res = OCILobCreateTemporary(statement_.session_.svchp_, - statement_.session_.errhp_, - lobp, 0, SQLCS_IMPLICIT, - OCI_TEMP_CLOB, OCI_ATTR_NOCACHE, OCI_DURATION_SESSION); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, statement_.session_.errhp_); - } - - ociData_ = lobp; - } -} - -void oracle_standard_into_type_backend::pre_fetch() -{ - // nothing to do except with Statement into objects - - if (type_ == x_statement) - { - statement *st = static_cast(data_); - st->undefine_and_bind(); - } -} - -void oracle_standard_into_type_backend::read_from_lob(OCILobLocator * lobp, std::string & value) -{ - ub4 len; - - sword res = OCILobGetLength(statement_.session_.svchp_, statement_.session_.errhp_, - lobp, &len); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, statement_.session_.errhp_); - } - - std::vector buf(len); - - if (len != 0) - { - ub4 offset = 1; - - res = OCILobRead(statement_.session_.svchp_, statement_.session_.errhp_, - lobp, &len, - offset, reinterpret_cast(&buf[0]), - len, 0, 0, 0, 0); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, statement_.session_.errhp_); - } - } - - value.assign(buf.begin(), buf.end()); -} - -void oracle_standard_into_type_backend::post_fetch( - bool gotData, bool calledFromFetch, indicator *ind) -{ - // first, deal with data - if (gotData) - { - // only std::string, std::tm and Statement need special handling - if (type_ == x_stdstring) - { - if (indOCIHolder_ != -1) - { - exchange_type_cast(data_) = buf_; - } - } - else if (type_ == x_long_long) - { - if (indOCIHolder_ != -1) - { - exchange_type_cast(data_) = std::strtoll(buf_, NULL, 10); - } - } - else if (type_ == x_unsigned_long_long) - { - if (indOCIHolder_ != -1) - { - exchange_type_cast(data_) = std::strtoull(buf_, NULL, 10); - } - } - else if (type_ == x_stdtm) - { - if (indOCIHolder_ != -1) - { - std::tm& t = exchange_type_cast(data_); - - ub1 *pos = reinterpret_cast(buf_); - int year = (*pos++ - 100) * 100; - year += *pos++ - 100; - int const month = *pos++; - int const day = *pos++; - int const hour = *pos++ - 1; - int const minute = *pos++ - 1; - int const second = *pos++ - 1; - - details::mktime_from_ymdhms(t, year, month, day, hour, minute, second); - } - } - else if (type_ == x_statement) - { - statement *st = static_cast(data_); - st->define_and_bind(); - } - else if (type_ == x_xmltype) - { - if (indOCIHolder_ != -1) - { - OCILobLocator * lobp = static_cast(ociData_); - - read_from_lob(lobp, exchange_type_cast(data_).value); - } - } - else if (type_ == x_longstring) - { - if (indOCIHolder_ != -1) - { - OCILobLocator * lobp = static_cast(ociData_); - - read_from_lob(lobp, exchange_type_cast(data_).value); - } - } - } - - // then - deal with indicators - if (calledFromFetch == true && gotData == false) - { - // this is a normal end-of-rowset condition, - // no need to set anything (fetch() will return false) - return; - } - if (ind != NULL) - { - if (gotData) - { - if (indOCIHolder_ == 0) - { - *ind = i_ok; - } - else if (indOCIHolder_ == -1) - { - *ind = i_null; - } - else - { - *ind = i_truncated; - } - } - } - else - { - if (indOCIHolder_ == -1) - { - // fetched null and no indicator - programming error! - throw soci_error("Null value fetched and no indicator defined."); - } - } -} - -void oracle_standard_into_type_backend::clean_up() -{ - if (type_ == x_xmltype || type_ == x_longstring) - { - OCILobLocator * lobp = static_cast(ociData_); - - // ignore errors from this call - (void) OCILobFreeTemporary(statement_.session_.svchp_, statement_.session_.errhp_, - lobp); - } - - if (defnp_ != NULL) - { - OCIHandleFree(defnp_, OCI_HTYPE_DEFINE); - defnp_ = NULL; - } - - if (buf_ != NULL) - { - delete [] buf_; - buf_ = NULL; - } -} diff --git a/src/soci/src/backends/oracle/standard-use-type.cpp b/src/soci/src/backends/oracle/standard-use-type.cpp deleted file mode 100644 index 5e94326626..0000000000 --- a/src/soci/src/backends/oracle/standard-use-type.cpp +++ /dev/null @@ -1,609 +0,0 @@ -// -// Copyright (C) 2004-2007 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define soci_ORACLE_SOURCE -#include "soci/oracle/soci-oracle.h" -#include "soci/blob.h" -#include "error.h" -#include "soci/rowid.h" -#include "soci/statement.h" -#include "soci/type-wrappers.h" -#include "soci/soci-platform.h" - -#include "soci-compiler.h" -#include "soci-exchange-cast.h" -#include "soci-mktime.h" - -#include -#include -#include -#include -#include -#include - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#define snprintf _snprintf -#endif - -using namespace soci; -using namespace soci::details; -using namespace soci::details::oracle; - -void oracle_standard_use_type_backend::prepare_for_bind( - void *&data, sb4 &size, ub2 &oracleType, bool readOnly) -{ - readOnly_ = readOnly; - - switch (type_) - { - // simple cases - case x_char: - oracleType = SQLT_AFC; - size = sizeof(char); - if (readOnly) - { - buf_ = new char[size]; - data = buf_; - } - break; - case x_short: - oracleType = SQLT_INT; - size = sizeof(short); - if (readOnly) - { - buf_ = new char[size]; - data = buf_; - } - break; - case x_integer: - oracleType = SQLT_INT; - size = sizeof(int); - if (readOnly) - { - buf_ = new char[size]; - data = buf_; - } - break; - case x_double: - oracleType = statement_.session_.get_double_sql_type(); - size = sizeof(double); - if (readOnly) - { - buf_ = new char[size]; - data = buf_; - } - break; - - // cases that require adjustments and buffer management - case x_long_long: - case x_unsigned_long_long: - oracleType = SQLT_STR; - size = 100; // arbitrary buffer length - buf_ = new char[size]; - data = buf_; - break; - case x_stdstring: - oracleType = SQLT_STR; - // 4000 is Oracle max VARCHAR2 size; 32768 is max LONG size - size = 32769; - buf_ = new char[size]; - data = buf_; - break; - case x_stdtm: - oracleType = SQLT_DAT; - size = 7 * sizeof(ub1); - buf_ = new char[size]; - data = buf_; - break; - - // cases that require special handling - case x_statement: - { - oracleType = SQLT_RSET; - - statement *st = static_cast(data); - st->alloc(); - - oracle_statement_backend *stbe - = static_cast(st->get_backend()); - size = 0; - data = &stbe->stmtp_; - } - break; - case x_rowid: - { - oracleType = SQLT_RDD; - - rowid *rid = static_cast(data); - - oracle_rowid_backend *rbe - = static_cast(rid->get_backend()); - - size = 0; - data = &rbe->rowidp_; - } - break; - case x_blob: - { - oracleType = SQLT_BLOB; - - blob *b = static_cast(data); - - oracle_blob_backend *bbe - = static_cast(b->get_backend()); - - size = 0; - data = &bbe->lobp_; - } - break; - - case x_xmltype: - case x_longstring: - { - oracleType = SQLT_CLOB; - - // lazy initialization of the temporary LOB object, - // actual creation of this object is in pre_exec, which - // is called right before statement's execute - - OCILobLocator * lobp = NULL; - - size = sizeof(lobp); - data = &ociData_; - ociData_ = lobp; - } - break; - } -} - -void oracle_standard_use_type_backend::bind_by_pos( - int &position, void *data, exchange_type type, bool readOnly) -{ - if (statement_.boundByName_) - { - throw soci_error( - "Binding for use elements must be either by position or by name."); - } - - data_ = data; // for future reference - type_ = type; // for future reference - - ub2 oracleType; - sb4 size; - - prepare_for_bind(data, size, oracleType, readOnly); - - sword res = OCIBindByPos(statement_.stmtp_, &bindp_, - statement_.session_.errhp_, - position++, data, size, oracleType, - &indOCIHolder_, 0, 0, 0, 0, OCI_DEFAULT); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, statement_.session_.errhp_); - } - - statement_.boundByPos_ = true; -} - -void oracle_standard_use_type_backend::bind_by_name( - std::string const &name, void *data, exchange_type type, bool readOnly) -{ - if (statement_.boundByPos_) - { - throw soci_error( - "Binding for use elements must be either by position or by name."); - } - - data_ = data; // for future reference - type_ = type; // for future reference - - ub2 oracleType; - sb4 size; - - prepare_for_bind(data, size, oracleType, readOnly); - - sword res = OCIBindByName(statement_.stmtp_, &bindp_, - statement_.session_.errhp_, - reinterpret_cast(const_cast(name.c_str())), - static_cast(name.size()), - data, size, oracleType, - &indOCIHolder_, 0, 0, 0, 0, OCI_DEFAULT); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, statement_.session_.errhp_); - } - - statement_.boundByName_ = true; -} - -void oracle_standard_use_type_backend::write_to_lob(OCILobLocator * lobp, const std::string & value) -{ - ub4 toWrite = value.size(); - ub4 offset = 1; - sword res; - - if (toWrite != 0) - { - res = OCILobWrite(statement_.session_.svchp_, statement_.session_.errhp_, - lobp, &toWrite, offset, - reinterpret_cast(const_cast(value.data())), - toWrite, OCI_ONE_PIECE, 0, 0, 0, SQLCS_IMPLICIT); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, statement_.session_.errhp_); - } - } - - ub4 len; - - res = OCILobGetLength(statement_.session_.svchp_, statement_.session_.errhp_, - lobp, &len); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, statement_.session_.errhp_); - } - - if (toWrite < len) - { - res = OCILobTrim(statement_.session_.svchp_, statement_.session_.errhp_, - lobp, toWrite); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, statement_.session_.errhp_); - } - } -} - -void oracle_standard_use_type_backend::lazy_temp_lob_init() -{ - OCILobLocator * lobp; - sword res = OCIDescriptorAlloc(statement_.session_.envhp_, - reinterpret_cast(&lobp), OCI_DTYPE_LOB, 0, 0); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, statement_.session_.errhp_); - } - - res = OCILobCreateTemporary(statement_.session_.svchp_, - statement_.session_.errhp_, - lobp, 0, SQLCS_IMPLICIT, - OCI_TEMP_CLOB, OCI_ATTR_NOCACHE, OCI_DURATION_SESSION); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, statement_.session_.errhp_); - } - - ociData_ = lobp; -} - -void oracle_standard_use_type_backend::pre_exec(int /* num */) -{ - switch (type_) - { - case x_xmltype: - { - // lazy initialization of the temporary LOB object - - lazy_temp_lob_init(); - - OCILobLocator * lobp = static_cast(ociData_); - - write_to_lob(lobp, exchange_type_cast(data_).value); - } - break; - case x_longstring: - { - // lazy initialization of the temporary LOB object - - lazy_temp_lob_init(); - - OCILobLocator * lobp = static_cast(ociData_); - - write_to_lob(lobp, exchange_type_cast(data_).value); - } - break; - default: - // nothing to do - break; - } -} - -void oracle_standard_use_type_backend::pre_use(indicator const *ind) -{ - // first deal with data - switch (type_) - { - case x_char: - if (readOnly_) - { - buf_[0] = exchange_type_cast(data_); - } - break; - case x_short: - if (readOnly_) - { - exchange_type_cast(buf_) = exchange_type_cast(data_); - } - break; - case x_integer: - if (readOnly_) - { - exchange_type_cast(buf_) = exchange_type_cast(data_); - } - break; - case x_long_long: - { - size_t const size = 100; // arbitrary, but consistent with prepare_for_bind - snprintf(buf_, size, "%" LL_FMT_FLAGS "d", exchange_type_cast(data_)); - } - break; - case x_unsigned_long_long: - { - size_t const size = 100; // arbitrary, but consistent with prepare_for_bind - snprintf(buf_, size, "%" LL_FMT_FLAGS "u", exchange_type_cast(data_)); - } - break; - case x_double: - if (readOnly_) - { - exchange_type_cast(buf_) = exchange_type_cast(data_); - } - break; - case x_stdstring: - { - std::string const& s = exchange_type_cast(data_); - - // 4000 is Oracle max VARCHAR2 size; 32768 is max LONG size - std::size_t const bufSize = 32769; - std::size_t const sSize = s.size(); - std::size_t const toCopy = - sSize < bufSize -1 ? sSize + 1 : bufSize - 1; - strncpy(buf_, s.c_str(), toCopy); - buf_[toCopy] = '\0'; - } - break; - case x_stdtm: - { - std::tm const& t = exchange_type_cast(data_); - ub1* pos = reinterpret_cast(buf_); - - *pos++ = static_cast(100 + (1900 + t.tm_year) / 100); - *pos++ = static_cast(100 + t.tm_year % 100); - *pos++ = static_cast(t.tm_mon + 1); - *pos++ = static_cast(t.tm_mday); - *pos++ = static_cast(t.tm_hour + 1); - *pos++ = static_cast(t.tm_min + 1); - *pos = static_cast(t.tm_sec + 1); - } - break; - case x_statement: - { - statement *s = static_cast(data_); - - s->undefine_and_bind(); - } - break; - - case x_xmltype: - case x_longstring: - case x_rowid: - case x_blob: - // nothing to do - break; - } - - // then handle indicators - if (ind != NULL && *ind == i_null) - { - indOCIHolder_ = -1; // null - } - else - { - indOCIHolder_ = 0; // value is OK - } -} - -void oracle_standard_use_type_backend::post_use(bool gotData, indicator *ind) -{ - // It is possible to have the bound element being overwritten - // by the database. - // - // With readOnly_ == true the propagation of modification should *not* - // take place and in addition the attempt of modification should be detected and reported. - - // first, deal with data - if (gotData) - { - switch (type_) - { - case x_char: - if (readOnly_) - { - const char original = exchange_type_cast(data_); - const char bound = buf_[0]; - - if (original != bound) - { - throw soci_error("Attempted modification of const use element"); - } - } - break; - case x_short: - if (readOnly_) - { - const short original = exchange_type_cast(data_); - const short bound = exchange_type_cast(buf_); - - if (original != bound) - { - throw soci_error("Attempted modification of const use element"); - } - } - break; - case x_integer: - if (readOnly_) - { - const int original = exchange_type_cast(data_); - const int bound = exchange_type_cast(buf_); - - if (original != bound) - { - throw soci_error("Attempted modification of const use element"); - } - } - break; - case x_long_long: - if (readOnly_) - { - long long const original = exchange_type_cast(data_); - long long const bound = std::strtoll(buf_, NULL, 10); - - if (original != bound) - { - throw soci_error("Attempted modification of const use element"); - } - } - break; - case x_unsigned_long_long: - if (readOnly_) - { - unsigned long long const original = exchange_type_cast(data_); - unsigned long long const bound = std::strtoull(buf_, NULL, 10); - - if (original != bound) - { - throw soci_error("Attempted modification of const use element"); - } - } - break; - case x_double: - if (readOnly_) - { - const double original = exchange_type_cast(data_); - const double bound = exchange_type_cast(buf_); - - // Exact comparison is fine here, they are really supposed to - // be exactly the same. - GCC_WARNING_SUPPRESS(float-equal) - - if (original != bound) - { - throw soci_error("Attempted modification of const use element"); - } - - GCC_WARNING_RESTORE(float-equal) - } - break; - case x_stdstring: - { - std::string& original = exchange_type_cast(data_); - if (original != buf_) - { - if (readOnly_) - { - throw soci_error("Attempted modification of const use element"); - } - else - { - original = buf_; - } - } - } - break; - case x_stdtm: - { - std::tm& original = exchange_type_cast(data_); - - ub1 *pos = reinterpret_cast(buf_); - int year = (*pos++ - 100) * 100; - year += *pos++ - 100; - int const month = *pos++; - int const day = *pos++; - int const hour = *pos++ - 1; - int const minute = *pos++ - 1; - int const second = *pos++ - 1; - - std::tm bound; - details::mktime_from_ymdhms(bound, year, month, day, hour, minute, second); - - if (original.tm_year != bound.tm_year || - original.tm_mon != bound.tm_mon || - original.tm_mday != bound.tm_mday || - original.tm_hour != bound.tm_hour || - original.tm_min != bound.tm_min || - original.tm_sec != bound.tm_sec) - { - if (readOnly_) - { - throw soci_error("Attempted modification of const use element"); - } - else - { - original = bound; - } - } - } - break; - case x_statement: - { - statement *s = static_cast(data_); - s->define_and_bind(); - } - break; - case x_rowid: - case x_blob: - case x_xmltype: - case x_longstring: - // nothing to do here - break; - } - } - - if (ind != NULL) - { - if (gotData) - { - if (indOCIHolder_ == 0) - { - *ind = i_ok; - } - else if (indOCIHolder_ == -1) - { - *ind = i_null; - } - else - { - *ind = i_truncated; - } - } - } -} - -void oracle_standard_use_type_backend::clean_up() -{ - if (type_ == x_xmltype || type_ == x_longstring) - { - OCILobLocator * lobp = static_cast(ociData_); - - // ignore errors from this call - (void) OCILobFreeTemporary(statement_.session_.svchp_, statement_.session_.errhp_, - lobp); - } - - if (bindp_ != NULL) - { - OCIHandleFree(bindp_, OCI_HTYPE_DEFINE); - bindp_ = NULL; - } - - if (buf_ != NULL) - { - delete [] buf_; - buf_ = NULL; - } -} diff --git a/src/soci/src/backends/oracle/statement.cpp b/src/soci/src/backends/oracle/statement.cpp deleted file mode 100644 index ec3ce21093..0000000000 --- a/src/soci/src/backends/oracle/statement.cpp +++ /dev/null @@ -1,352 +0,0 @@ -// -// Copyright (C) 2004-2007 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define soci_ORACLE_SOURCE - -#include "soci/oracle/soci-oracle.h" -#include "error.h" -#include "soci/soci-backend.h" -#include -#include -#include -#include -#include -#include - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; -using namespace soci::details::oracle; - -oracle_statement_backend::oracle_statement_backend(oracle_session_backend &session) - : session_(session), stmtp_(NULL), boundByName_(false), boundByPos_(false), - noData_(false) -{ -} - -void oracle_statement_backend::alloc() -{ - sword res = OCIHandleAlloc(session_.envhp_, - reinterpret_cast(&stmtp_), - OCI_HTYPE_STMT, 0, 0); - if (res != OCI_SUCCESS) - { - throw soci_error("Cannot allocate statement handle"); - } -} - -void oracle_statement_backend::clean_up() -{ - // deallocate statement handle - if (stmtp_ != NULL) - { - OCIHandleFree(stmtp_, OCI_HTYPE_STMT); - stmtp_ = NULL; - } - - boundByName_ = false; - boundByPos_ = false; -} - -void oracle_statement_backend::prepare(std::string const &query, - statement_type /* eType */) -{ - sb4 stmtLen = static_cast(query.size()); - sword res = OCIStmtPrepare(stmtp_, - session_.errhp_, - reinterpret_cast(const_cast(query.c_str())), - stmtLen, OCI_V7_SYNTAX, OCI_DEFAULT); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, session_.errhp_); - } -} - -statement_backend::exec_fetch_result oracle_statement_backend::execute(int number) -{ - sword res = OCIStmtExecute(session_.svchp_, stmtp_, session_.errhp_, - static_cast(number), 0, 0, 0, OCI_DEFAULT); - - if (res == OCI_SUCCESS || res == OCI_SUCCESS_WITH_INFO) - { - noData_ = false; - return ef_success; - } - else if (res == OCI_NO_DATA) - { - noData_ = true; - return ef_no_data; - } - else - { - throw_oracle_soci_error(res, session_.errhp_); - return ef_no_data; // unreachable dummy return to please the compiler - } -} - -statement_backend::exec_fetch_result oracle_statement_backend::fetch(int number) -{ - if (noData_) - { - return ef_no_data; - } - - sword res = OCIStmtFetch(stmtp_, session_.errhp_, - static_cast(number), OCI_FETCH_NEXT, OCI_DEFAULT); - - if (res == OCI_SUCCESS || res == OCI_SUCCESS_WITH_INFO) - { - return ef_success; - } - else if (res == OCI_NO_DATA) - { - noData_ = true; - return ef_no_data; - } - else - { - throw_oracle_soci_error(res, session_.errhp_); - return ef_no_data; // unreachable dummy return to please the compiler - } -} - -long long oracle_statement_backend::get_affected_rows() -{ - ub4 row_count; - sword res = OCIAttrGet(static_cast(stmtp_), - OCI_HTYPE_STMT, &row_count, - 0, OCI_ATTR_ROW_COUNT, session_.errhp_); - - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, session_.errhp_); - } - - return row_count; -} - -int oracle_statement_backend::get_number_of_rows() -{ - int rows; - sword res = OCIAttrGet(static_cast(stmtp_), - OCI_HTYPE_STMT, static_cast(&rows), - 0, OCI_ATTR_ROWS_FETCHED, session_.errhp_); - - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, session_.errhp_); - } - - return rows; -} - -std::string oracle_statement_backend::get_parameter_name(int /* index */) const -{ - // TODO: How to get the parameter names from the query we prepared? - return std::string(); -} - -std::string oracle_statement_backend::rewrite_for_procedure_call( - std::string const &query) -{ - std::string newQuery("begin "); - newQuery += query; - newQuery += "; end;"; - return newQuery; -} - -int oracle_statement_backend::prepare_for_describe() -{ - sword res = OCIStmtExecute(session_.svchp_, stmtp_, session_.errhp_, - 1, 0, 0, 0, OCI_DESCRIBE_ONLY); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, session_.errhp_); - } - - int cols; - res = OCIAttrGet(static_cast(stmtp_), - static_cast(OCI_HTYPE_STMT), static_cast(&cols), - 0, static_cast(OCI_ATTR_PARAM_COUNT), session_.errhp_); - - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, session_.errhp_); - } - - return cols; -} - -void oracle_statement_backend::describe_column(int colNum, data_type &type, - std::string &columnName) -{ - ub2 dbtype; - text* dbname; - ub4 nameLength; - - ub2 dbsize; - sb2 dbprec; - ub1 dbscale; //sb2 in some versions of Oracle? - - // Get the column handle - OCIParam* colhd; - sword res = OCIParamGet(reinterpret_cast(stmtp_), - static_cast(OCI_HTYPE_STMT), - reinterpret_cast(session_.errhp_), - reinterpret_cast(&colhd), - static_cast(colNum)); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, session_.errhp_); - } - - // Get the column name - res = OCIAttrGet(reinterpret_cast(colhd), - static_cast(OCI_DTYPE_PARAM), - reinterpret_cast(&dbname), - reinterpret_cast(&nameLength), - static_cast(OCI_ATTR_NAME), - reinterpret_cast(session_.errhp_)); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, session_.errhp_); - } - - // Get the column type - res = OCIAttrGet(reinterpret_cast(colhd), - static_cast(OCI_DTYPE_PARAM), - reinterpret_cast(&dbtype), - 0, - static_cast(OCI_ATTR_DATA_TYPE), - reinterpret_cast(session_.errhp_)); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, session_.errhp_); - } - - // get the data size - res = OCIAttrGet(reinterpret_cast(colhd), - static_cast(OCI_DTYPE_PARAM), - reinterpret_cast(&dbsize), - 0, - static_cast(OCI_ATTR_DATA_SIZE), - reinterpret_cast(session_.errhp_)); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, session_.errhp_); - } - - // get the precision - res = OCIAttrGet(reinterpret_cast(colhd), - static_cast(OCI_DTYPE_PARAM), - reinterpret_cast(&dbprec), - 0, - static_cast(OCI_ATTR_PRECISION), - reinterpret_cast(session_.errhp_)); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, session_.errhp_); - } - - // get the scale - res = OCIAttrGet(reinterpret_cast(colhd), - static_cast(OCI_DTYPE_PARAM), - reinterpret_cast(&dbscale), - 0, - static_cast(OCI_ATTR_SCALE), - reinterpret_cast(session_.errhp_)); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, session_.errhp_); - } - - columnName.assign(dbname, dbname + nameLength); - - switch (dbtype) - { - case SQLT_CHR: - case SQLT_AFC: - type = dt_string; - break; - case SQLT_NUM: - if (dbscale > 0) - { - if (session_.get_option_decimals_as_strings()) - { - type = dt_string; - } - else - { - type = dt_double; - } - } - else if (dbprec <= std::numeric_limits::digits10) - { - type = dt_integer; - } - else - { - type = dt_long_long; - } - break; - case OCI_TYPECODE_BDOUBLE: - type = dt_double; - break; - case SQLT_DAT: - type = dt_date; - break; - default: - // Unknown oracle types will just be represented by a string - type = dt_string; - } -} - -std::size_t oracle_statement_backend::column_size(int position) -{ - // Note: we may want to optimize so that the OCI_DESCRIBE_ONLY call - // happens only once per statement. - // Possibly use existing statement::describe() / make column prop - // access lazy at same time - - int colSize(0); - - sword res = OCIStmtExecute(session_.svchp_, stmtp_, - session_.errhp_, 1, 0, 0, 0, OCI_DESCRIBE_ONLY); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, session_.errhp_); - } - - // Get The Column Handle - OCIParam* colhd; - res = OCIParamGet(reinterpret_cast(stmtp_), - static_cast(OCI_HTYPE_STMT), - reinterpret_cast(session_.errhp_), - reinterpret_cast(&colhd), - static_cast(position)); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, session_.errhp_); - } - - // Get The Data Size - res = OCIAttrGet(reinterpret_cast(colhd), - static_cast(OCI_DTYPE_PARAM), - reinterpret_cast(&colSize), - 0, - static_cast(OCI_ATTR_DATA_SIZE), - reinterpret_cast(session_.errhp_)); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, session_.errhp_); - } - - return static_cast(colSize); -} diff --git a/src/soci/src/backends/oracle/vector-into-type.cpp b/src/soci/src/backends/oracle/vector-into-type.cpp deleted file mode 100644 index 6bb3ee52e0..0000000000 --- a/src/soci/src/backends/oracle/vector-into-type.cpp +++ /dev/null @@ -1,504 +0,0 @@ -// -// Copyright (C) 2004-2007 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define soci_ORACLE_SOURCE -#include "soci/oracle/soci-oracle.h" -#include "soci/statement.h" -#include "error.h" -#include "soci/soci-platform.h" -#include "soci-mktime.h" -#include -#include -#include -#include -#include -#include - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; -using namespace soci::details::oracle; - -void oracle_vector_into_type_backend::prepare_indicators(std::size_t size) -{ - if (size == 0) - { - throw soci_error("Vectors of size 0 are not allowed."); - } - - indOCIHolderVec_.resize(size); - indOCIHolders_ = &indOCIHolderVec_[0]; - - sizes_.resize(size); - rCodes_.resize(size); -} - -void oracle_vector_into_type_backend::define_by_pos_bulk( - int & position, void * data, exchange_type type, - std::size_t begin, std::size_t * end) -{ - data_ = data; // for future reference - type_ = type; // for future reference - begin_ = begin; - end_ = end; - - end_var_ = full_size(); - - ub2 oracleType = 0; // dummy initialization to please the compiler - sb4 elementSize = 0; // also dummy - void * dataBuf; - - switch (type) - { - // simple cases - case x_char: - { - oracleType = SQLT_AFC; - elementSize = sizeof(char); - std::vector *vp = static_cast *>(data); - std::vector &v(*vp); - prepare_indicators(size()); - dataBuf = &v[begin_]; - } - break; - case x_short: - { - oracleType = SQLT_INT; - elementSize = sizeof(short); - std::vector *vp = static_cast *>(data); - std::vector &v(*vp); - prepare_indicators(size()); - dataBuf = &v[begin_]; - } - break; - case x_integer: - { - oracleType = SQLT_INT; - elementSize = sizeof(int); - std::vector *vp = static_cast *>(data); - std::vector &v(*vp); - prepare_indicators(size()); - dataBuf = &v[begin_]; - } - break; - case x_double: - { - oracleType = statement_.session_.get_double_sql_type(); - elementSize = sizeof(double); - std::vector *vp = static_cast *>(data); - std::vector &v(*vp); - prepare_indicators(size()); - dataBuf = &v[begin_]; - } - break; - - // cases that require adjustments and buffer management - - case x_long_long: - { - oracleType = SQLT_STR; - const std::size_t vecSize = size(); - colSize_ = 100; // arbitrary buffer size for each entry - std::size_t const bufSize = colSize_ * vecSize; - buf_ = new char[bufSize]; - - prepare_indicators(vecSize); - - elementSize = static_cast(colSize_); - dataBuf = buf_; - } - break; - case x_unsigned_long_long: - { - oracleType = SQLT_STR; - const std::size_t vecSize = size(); - colSize_ = 100; // arbitrary buffer size for each entry - std::size_t const bufSize = colSize_ * vecSize; - buf_ = new char[bufSize]; - - prepare_indicators(vecSize); - - elementSize = static_cast(colSize_); - dataBuf = buf_; - } - break; - case x_stdstring: - { - oracleType = SQLT_CHR; - const std::size_t vecSize = size(); - colSize_ = statement_.column_size(position) + 1; - std::size_t bufSize = colSize_ * vecSize; - buf_ = new char[bufSize]; - - prepare_indicators(vecSize); - - elementSize = static_cast(colSize_); - dataBuf = buf_; - } - break; - case x_stdtm: - { - oracleType = SQLT_DAT; - const std::size_t vecSize = size(); - - prepare_indicators(vecSize); - - elementSize = 7; // 7 is the size of SQLT_DAT - std::size_t bufSize = elementSize * vecSize; - - buf_ = new char[bufSize]; - dataBuf = buf_; - } - break; - - case x_xmltype: - case x_longstring: - case x_statement: - case x_rowid: - case x_blob: - throw soci_error("Unsupported type for vector into parameter"); - } - - sword res = OCIDefineByPos(statement_.stmtp_, &defnp_, - statement_.session_.errhp_, - position++, dataBuf, elementSize, oracleType, - indOCIHolders_, &sizes_[0], &rCodes_[0], OCI_DEFAULT); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, statement_.session_.errhp_); - } -} - -void oracle_vector_into_type_backend::pre_fetch() -{ - // nothing to do for the supported types -} - -void oracle_vector_into_type_backend::post_fetch(bool gotData, indicator * ind) -{ - if (gotData) - { - // first, deal with data - - // only std::string, std::tm, long long and Statement need special handling - if (type_ == x_stdstring) - { - std::vector *vp - = static_cast *>(data_); - - std::vector &v(*vp); - - char *pos = buf_; - std::size_t const vecSize = size(); - for (std::size_t i = 0; i != vecSize; ++i) - { - if (indOCIHolderVec_[i] != -1) - { - v[begin_ + i].assign(pos, sizes_[i]); - } - pos += colSize_; - } - } - else if (type_ == x_long_long) - { - std::vector *vp - = static_cast *>(data_); - - std::vector &v(*vp); - - char *pos = buf_; - std::size_t const vecSize = size(); - for (std::size_t i = 0; i != vecSize; ++i) - { - if (indOCIHolderVec_[i] != -1) - { - v[begin_ + i] = std::strtoll(pos, NULL, 10); - } - pos += colSize_; - } - } - else if (type_ == x_unsigned_long_long) - { - std::vector *vp - = static_cast *>(data_); - - std::vector &v(*vp); - - char *pos = buf_; - std::size_t const vecSize = size(); - for (std::size_t i = 0; i != vecSize; ++i) - { - if (indOCIHolderVec_[i] != -1) - { - v[begin_ + i] = std::strtoull(pos, NULL, 10); - } - pos += colSize_; - } - } - else if (type_ == x_stdtm) - { - std::vector *vp - = static_cast *>(data_); - - std::vector &v(*vp); - - ub1 *pos = reinterpret_cast(buf_); - std::size_t const vecSize = size(); - for (std::size_t i = 0; i != vecSize; ++i) - { - if (indOCIHolderVec_[i] == -1) - { - pos += 7; // size of SQLT_DAT - } - else - { - int year = (*pos++ - 100) * 100; - year += *pos++ - 100; - int const month = *pos++; - int const day = *pos++; - int const hour = *pos++ - 1; - int const minute = *pos++ - 1; - int const second = *pos++ - 1; - - details::mktime_from_ymdhms(v[begin_ + i], - year, month, day, hour, minute, second); - } - } - } - else if (type_ == x_statement) - { - statement *st = static_cast(data_); - st->define_and_bind(); - } - - // then - deal with indicators - if (ind != NULL) - { - std::size_t const indSize = statement_.get_number_of_rows(); - for (std::size_t i = 0; i != indSize; ++i) - { - if (indOCIHolderVec_[i] == 0) - { - ind[begin_ + i] = i_ok; - } - else if (indOCIHolderVec_[i] == -1) - { - ind[begin_ + i] = i_null; - } - else - { - ind[begin_ + i] = i_truncated; - } - } - } - else - { - std::size_t const indSize = indOCIHolderVec_.size(); - for (std::size_t i = 0; i != indSize; ++i) - { - if (indOCIHolderVec_[i] == -1) - { - // fetched null and no indicator - programming error! - throw soci_error( - "Null value fetched and no indicator defined."); - } - } - } - } - else // gotData == false - { - // nothing to do here, vectors are truncated anyway - } -} - -void oracle_vector_into_type_backend::resize(std::size_t sz) -{ - if (user_ranges_) - { - // resize only in terms of user-provided ranges (below) - } - else - { - switch (type_) - { - // simple cases - case x_char: - { - std::vector *v = static_cast *>(data_); - v->resize(sz); - } - break; - case x_short: - { - std::vector *v = static_cast *>(data_); - v->resize(sz); - } - break; - case x_integer: - { - std::vector *v = static_cast *>(data_); - v->resize(sz); - } - break; - case x_long_long: - { - std::vector *v - = static_cast *>(data_); - v->resize(sz); - } - break; - case x_unsigned_long_long: - { - std::vector *v - = static_cast *>(data_); - v->resize(sz); - } - break; - case x_double: - { - std::vector *v - = static_cast *>(data_); - v->resize(sz); - } - break; - case x_stdstring: - { - std::vector *v - = static_cast *>(data_); - v->resize(sz); - } - break; - case x_stdtm: - { - std::vector *v - = static_cast *>(data_); - v->resize(sz); - } - break; - - case x_xmltype: break; // not supported - case x_longstring: break; // not supported - case x_statement: break; // not supported - case x_rowid: break; // not supported - case x_blob: break; // not supported - } - - end_var_ = sz; - } - - // resize ranges, either user-provided or internally managed - *end_ = begin_ + sz; -} - -std::size_t oracle_vector_into_type_backend::size() -{ - // as a special error-detection measure, check if the actual vector size - // was changed since the original bind (when it was stored in end_var_): - const std::size_t actual_size = full_size(); - if (actual_size != end_var_) - { - // ... and in that case return the actual size - return actual_size; - } - - if (end_ != NULL && *end_ != 0) - { - return *end_ - begin_; - } - else - { - return end_var_; - } -} - -std::size_t oracle_vector_into_type_backend::full_size() -{ - std::size_t sz = 0; // dummy initialization to please the compiler - switch (type_) - { - // simple cases - case x_char: - { - std::vector *v = static_cast *>(data_); - sz = v->size(); - } - break; - case x_short: - { - std::vector *v = static_cast *>(data_); - sz = v->size(); - } - break; - case x_integer: - { - std::vector *v = static_cast *>(data_); - sz = v->size(); - } - break; - case x_long_long: - { - std::vector *v - = static_cast *>(data_); - sz = v->size(); - } - break; - case x_unsigned_long_long: - { - std::vector *v - = static_cast *>(data_); - sz = v->size(); - } - break; - case x_double: - { - std::vector *v - = static_cast *>(data_); - sz = v->size(); - } - break; - case x_stdstring: - { - std::vector *v - = static_cast *>(data_); - sz = v->size(); - } - break; - case x_stdtm: - { - std::vector *v - = static_cast *>(data_); - sz = v->size(); - } - break; - - case x_xmltype: break; // not supported - case x_longstring: break; // not supported - case x_statement: break; // not supported - case x_rowid: break; // not supported - case x_blob: break; // not supported - } - - return sz; -} - -void oracle_vector_into_type_backend::clean_up() -{ - if (defnp_ != NULL) - { - OCIHandleFree(defnp_, OCI_HTYPE_DEFINE); - defnp_ = NULL; - } - - if (buf_ != NULL) - { - delete [] buf_; - buf_ = NULL; - } -} diff --git a/src/soci/src/backends/oracle/vector-use-type.cpp b/src/soci/src/backends/oracle/vector-use-type.cpp deleted file mode 100644 index 0d2846c567..0000000000 --- a/src/soci/src/backends/oracle/vector-use-type.cpp +++ /dev/null @@ -1,426 +0,0 @@ -// -// Copyright (C) 2004-2007 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define soci_ORACLE_SOURCE -#include "soci/oracle/soci-oracle.h" -#include "error.h" -#include "soci/soci-platform.h" -#include -#include -#include -#include -#include - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#define snprintf _snprintf -#endif - -using namespace soci; -using namespace soci::details; -using namespace soci::details::oracle; - -void oracle_vector_use_type_backend::prepare_indicators(std::size_t size) -{ - if (size == 0) - { - throw soci_error("Vectors of size 0 are not allowed."); - } - - indOCIHolderVec_.resize(size); - indOCIHolders_ = &indOCIHolderVec_[0]; -} - -void oracle_vector_use_type_backend::prepare_for_bind( - void * & data, sb4 & elementSize, ub2 & oracleType) -{ - switch (type_) - { - // simple cases - case x_char: - { - oracleType = SQLT_AFC; - elementSize = sizeof(char); - std::vector *vp = static_cast *>(data_); - std::vector &v(*vp); - prepare_indicators(size()); - data = &v[begin_]; - } - break; - case x_short: - { - oracleType = SQLT_INT; - elementSize = sizeof(short); - std::vector *vp = static_cast *>(data_); - std::vector &v(*vp); - prepare_indicators(size()); - data = &v[begin_]; - } - break; - case x_integer: - { - oracleType = SQLT_INT; - elementSize = sizeof(int); - std::vector *vp = static_cast *>(data_); - std::vector &v(*vp); - prepare_indicators(size()); - data = &v[begin_]; - } - break; - case x_double: - { - oracleType = statement_.session_.get_double_sql_type(); - elementSize = sizeof(double); - std::vector *vp = static_cast *>(data_); - std::vector &v(*vp); - prepare_indicators(size()); - data = &v[begin_]; - } - break; - - // cases that require adjustments and buffer management - - case x_long_long: - { - std::size_t const vecSize = size(); - std::size_t const entrySize = 100; // arbitrary - std::size_t const bufSize = entrySize * vecSize; - buf_ = new char[bufSize]; - - oracleType = SQLT_STR; - data = buf_; - elementSize = entrySize; - - prepare_indicators(vecSize); - } - break; - case x_unsigned_long_long: - { - std::size_t const vecSize = size(); - std::size_t const entrySize = 100; // arbitrary - std::size_t const bufSize = entrySize * vecSize; - buf_ = new char[bufSize]; - - oracleType = SQLT_STR; - data = buf_; - elementSize = entrySize; - - prepare_indicators(vecSize); - } - break; - case x_stdstring: - { - std::vector *vp - = static_cast *>(data_); - std::vector &v(*vp); - - std::size_t maxSize = 0; - std::size_t const vecSize = size(); - prepare_indicators(vecSize); - for (std::size_t i = 0; i != vecSize; ++i) - { - std::size_t sz = v[begin_ + i].length(); - sizes_.push_back(static_cast(sz)); - maxSize = sz > maxSize ? sz : maxSize; - } - - buf_ = new char[maxSize * vecSize]; - char *pos = buf_; - for (std::size_t i = 0; i != vecSize; ++i) - { - strncpy(pos, v[begin_ + i].c_str(), v[begin_ + i].length()); - pos += maxSize; - } - - oracleType = SQLT_CHR; - data = buf_; - elementSize = static_cast(maxSize); - } - break; - case x_stdtm: - { - std::size_t const vecSize = size(); - prepare_indicators(vecSize); - - sb4 const dlen = 7; // size of SQLT_DAT - buf_ = new char[dlen * vecSize]; - - oracleType = SQLT_DAT; - data = buf_; - elementSize = dlen; - } - break; - - case x_xmltype: break; // not supported - case x_longstring: break; // not supported - case x_statement: break; // not supported - case x_rowid: break; // not supported - case x_blob: break; // not supported - } -} - -void oracle_vector_use_type_backend::bind_by_pos_bulk(int & position, - void * data, exchange_type type, - std::size_t begin, std::size_t * end) -{ - data_ = data; // for future reference - type_ = type; // for future reference - begin_ = begin; - end_ = end; - - end_var_ = full_size(); - - ub2 oracleType; - sb4 elementSize; - void * dataBuf; - - prepare_for_bind(dataBuf, elementSize, oracleType); - - ub2 *sizesP = 0; // used only for std::string - if (type == x_stdstring) - { - sizesP = &sizes_[0]; - } - - sword res = OCIBindByPos(statement_.stmtp_, &bindp_, - statement_.session_.errhp_, - position++, dataBuf, elementSize, oracleType, - indOCIHolders_, sizesP, 0, 0, 0, OCI_DEFAULT); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, statement_.session_.errhp_); - } -} - -void oracle_vector_use_type_backend::bind_by_name_bulk( - std::string const &name, void *data, exchange_type type, - std::size_t begin, std::size_t * end) -{ - data_ = data; // for future reference - type_ = type; // for future reference - begin_ = begin; - end_ = end; - - end_var_ = full_size(); - - ub2 oracleType; - sb4 elementSize; - void * dataBuf; - - prepare_for_bind(dataBuf, elementSize, oracleType); - - ub2 *sizesP = 0; // used only for std::string - if (type == x_stdstring) - { - sizesP = &sizes_[0]; - } - - sword res = OCIBindByName(statement_.stmtp_, &bindp_, - statement_.session_.errhp_, - reinterpret_cast(const_cast(name.c_str())), - static_cast(name.size()), - dataBuf, elementSize, oracleType, - indOCIHolders_, sizesP, 0, 0, 0, OCI_DEFAULT); - if (res != OCI_SUCCESS) - { - throw_oracle_soci_error(res, statement_.session_.errhp_); - } -} - -void oracle_vector_use_type_backend::pre_use(indicator const *ind) -{ - // first deal with data - if (type_ == x_stdstring) - { - // nothing to do - it's already done during bind - // (and it's probably impossible to separate them, because - // changes in the string size could not be handled here) - } - else if (type_ == x_long_long) - { - std::vector *vp - = static_cast *>(data_); - std::vector &v(*vp); - - char *pos = buf_; - std::size_t const entrySize = 100; // arbitrary, but consistent - std::size_t const vecSize = size(); - for (std::size_t i = 0; i != vecSize; ++i) - { - snprintf(pos, entrySize, "%" LL_FMT_FLAGS "d", v[begin_ + i]); - pos += entrySize; - } - } - else if (type_ == x_unsigned_long_long) - { - std::vector *vp - = static_cast *>(data_); - std::vector &v(*vp); - - char *pos = buf_; - std::size_t const entrySize = 100; // arbitrary, but consistent - std::size_t const vecSize = size(); - for (std::size_t i = 0; i != vecSize; ++i) - { - snprintf(pos, entrySize, "%" LL_FMT_FLAGS "u", v[begin_ + i]); - pos += entrySize; - } - } - else if (type_ == x_stdtm) - { - std::vector *vp - = static_cast *>(data_); - std::vector &v(*vp); - - ub1* pos = reinterpret_cast(buf_); - std::size_t const vecSize = size(); - for (std::size_t i = 0; i != vecSize; ++i) - { - std::tm & t = v[begin_ + i]; - - *pos++ = static_cast(100 + (1900 + t.tm_year) / 100); - *pos++ = static_cast(100 + t.tm_year % 100); - *pos++ = static_cast(t.tm_mon + 1); - *pos++ = static_cast(t.tm_mday); - *pos++ = static_cast(t.tm_hour + 1); - *pos++ = static_cast(t.tm_min + 1); - *pos++ = static_cast(t.tm_sec + 1); - } - } - - // then handle indicators - if (ind != NULL) - { - std::size_t const vecSize = size(); - for (std::size_t i = 0; i != vecSize; ++i) - { - if (ind[begin_ + i] == i_null) - { - indOCIHolderVec_[i] = -1; // null - } - else - { - indOCIHolderVec_[i] = 0; // value is OK - } - } - } - else - { - // no indicators - treat all fields as OK - std::size_t const vecSize = size(); - for (std::size_t i = 0; i != vecSize; ++i) - { - indOCIHolderVec_[i] = 0; // value is OK - } - } -} - -std::size_t oracle_vector_use_type_backend::size() -{ - // as a special error-detection measure, check if the actual vector size - // was changed since the original bind (when it was stored in end_var_): - const std::size_t actual_size = full_size(); - if (actual_size != end_var_) - { - // ... and in that case return the actual size - return actual_size; - } - - if (end_ != NULL && *end_ != 0) - { - return *end_ - begin_; - } - else - { - return end_var_; - } -} - -std::size_t oracle_vector_use_type_backend::full_size() -{ - std::size_t sz = 0; // dummy initialization to please the compiler - switch (type_) - { - // simple cases - case x_char: - { - std::vector *vp = static_cast *>(data_); - sz = vp->size(); - } - break; - case x_short: - { - std::vector *vp = static_cast *>(data_); - sz = vp->size(); - } - break; - case x_integer: - { - std::vector *vp = static_cast *>(data_); - sz = vp->size(); - } - break; - case x_long_long: - { - std::vector *vp - = static_cast *>(data_); - sz = vp->size(); - } - break; - case x_unsigned_long_long: - { - std::vector *vp - = static_cast *>(data_); - sz = vp->size(); - } - break; - case x_double: - { - std::vector *vp - = static_cast *>(data_); - sz = vp->size(); - } - break; - case x_stdstring: - { - std::vector *vp - = static_cast *>(data_); - sz = vp->size(); - } - break; - case x_stdtm: - { - std::vector *vp - = static_cast *>(data_); - sz = vp->size(); - } - break; - - case x_xmltype: break; // not supported - case x_longstring: break; // not supported - case x_statement: break; // not supported - case x_rowid: break; // not supported - case x_blob: break; // not supported - } - - return sz; -} - -void oracle_vector_use_type_backend::clean_up() -{ - if (buf_ != NULL) - { - delete [] buf_; - buf_ = NULL; - } - - if (bindp_ != NULL) - { - OCIHandleFree(bindp_, OCI_HTYPE_DEFINE); - bindp_ = NULL; - } -} diff --git a/src/soci/src/backends/postgresql/CMakeLists.txt b/src/soci/src/backends/postgresql/CMakeLists.txt deleted file mode 100644 index 09b781abd9..0000000000 --- a/src/soci/src/backends/postgresql/CMakeLists.txt +++ /dev/null @@ -1,59 +0,0 @@ -############################################################################### -# -# This file is part of CMake configuration for SOCI library -# -# Copyright (C) 2010 Mateusz Loskot -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -# -############################################################################### - -include(CMakeDependentOption) - -option(SOCI_POSTGRESQL_NOSINLGEROWMODE - "Do not use single row mode. PostgreSQL <9 portability." - OFF) - -option(SOCI_POSTGRESQL_NOPARAMS - "Do not use input parameters. PostgreSQL 7.x portability." - OFF) - -option(SOCI_POSTGRESQL_NOBINDBYNAME - "Disable query rewriting to native form. PostgreSQL 7.0 portability." - OFF) - -cmake_dependent_option(SOCI_POSTGRESQL_NOPREPARE - "Disable prepared statements. Set ON if SOCI_POSTGRESQL_NOBINDBYNAME is ON. PostgreSQL 7.0 portability." ON - SOCI_POSTGRESQL_NOBINDBYNAME OFF) - -if(SOCI_POSTGRESQL_NOPARAMS) - add_definitions(-DSOCI_POSTGRESQL_NOPARAMS=1) -endif() - -if(SOCI_POSTGRESQL_NOBINDBYNAME) - add_definitions(-DSOCI_POSTGRESQL_NOBINDBYNAME=1) -endif() - -if(SOCI_POSTGRESQL_NOPREPARE) - add_definitions(-DSOCI_POSTGRESQL_NOPREPARE=1) -endif() - -if (POSTGRESQL_VERSION VERSION_LESS "9.0.0") - set(SOCI_POSTGRESQL_NOSINLGEROWMODE ON CACHE BOOL "Use single row mode for PostgreSQL 9+" FORCE) -endif() - -if(SOCI_POSTGRESQL_NOSINLGEROWMODE) - add_definitions(-DSOCI_POSTGRESQL_NOSINLGEROWMODE=1) -endif() - -soci_backend(PostgreSQL - DEPENDS PostgreSQL - DESCRIPTION "SOCI backend for PostgreSQL" - AUTHORS "Maciej Sobczak, Stephen Hutton" - MAINTAINERS "Mateusz Loskot") - -boost_report_value(SOCI_POSTGRESQL_NOPARAMS) -boost_report_value(SOCI_POSTGRESQL_NOBINDBYNAME) -boost_report_value(SOCI_POSTGRESQL_NOPREPARE) -boost_report_value(SOCI_POSTGRESQL_NOSINLGEROWMODE) diff --git a/src/soci/src/backends/postgresql/Makefile.basic b/src/soci/src/backends/postgresql/Makefile.basic deleted file mode 100644 index 473abfffdd..0000000000 --- a/src/soci/src/backends/postgresql/Makefile.basic +++ /dev/null @@ -1,114 +0,0 @@ -# The following variable is specific to this backend and its correct -# values might depend on your environment - feel free to set it accordingly. - -PGSQLINCLUDEDIR = -I/usr/include/postgresql -PGSQLLIBDIR = -L/usr/lib -PGSQLLIBS = -lpq - -# The rest of the Makefile is indepentent of the target environment. - -COMPILER = g++ -CXXFLAGS = -Wall -pedantic -Wno-long-long -SHARED_CXXFLAGS = ${CXXFLAGS} -fPIC -INCLUDEDIRS = -I../../../include -I../../../include/private ${PGSQLINCLUDEDIR} - -SHARED_LIBDIRS = ${PGSQLLIBDIR} -SHARED_LIBS = ${PGSQLLIBS} ../../core/libsoci_core.a - -UNAME = $(shell uname) -ifeq ($(UNAME),Darwin) - SHARED_LINK_FLAGS = -dynamiclib -flat_namespace -undefined suppress -else - SHARED_LINK_FLAGS = -shared -endif - - -OBJECTS = blob.o error.o factory.o row-id.o session.o standard-into-type.o \ - standard-use-type.o statement.o vector-into-type.o vector-use-type.o \ - common.o - -SHARED_OBJECTS = blob-s.o error-s.o factory-s.o row-id-s.o session-s.o \ - standard-into-type-s.o standard-use-type-s.o statement-s.o \ - vector-into-type-s.o vector-use-type-s.o common-s.o - - -libsoci_postgresql.a : ${OBJECTS} - ar rv $@ $? - rm *.o - - -blob.o : blob.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -error.o : error.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -common.o : ../../core/common.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -factory.o : factory.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -row-id.o : row-id.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -session.o : session.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -standard-into-type.o : standard-into-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -standard-use-type.o : standard-use-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -statement.o : statement.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -vector-into-type.o : vector-into-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -vector-use-type.o : vector-use-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - - -shared : ${SHARED_OBJECTS} - ${COMPILER} ${SHARED_LINK_FLAGS} -o libsoci_postgresql.so \ - ${SHARED_OBJECTS} ${SHARED_LIBDIRS} ${SHARED_LIBS} - rm *.o - -blob-s.o : blob.cpp - ${COMPILER} -c -o $@ $? ${SHARED_CXXFLAGS} ${INCLUDEDIRS} - -error-s.o : error.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGS} ${INCLUDEDIRS} - -common-s.o : ../../core/common.cpp - ${COMPILER} -c -o $@ $? ${SHARED_CXXFLAGS} ${INCLUDEDIRS} - -factory-s.o : factory.cpp - ${COMPILER} -c -o $@ $? ${SHARED_CXXFLAGS} ${INCLUDEDIRS} - -row-id-s.o : row-id.cpp - ${COMPILER} -c -o $@ $? ${SHARED_CXXFLAGS} ${INCLUDEDIRS} - -session-s.o : session.cpp - ${COMPILER} -c -o $@ $? ${SHARED_CXXFLAGS} ${INCLUDEDIRS} - -standard-into-type-s.o : standard-into-type.cpp - ${COMPILER} -c -o $@ $? ${SHARED_CXXFLAGS} ${INCLUDEDIRS} - -standard-use-type-s.o : standard-use-type.cpp - ${COMPILER} -c -o $@ $? ${SHARED_CXXFLAGS} ${INCLUDEDIRS} - -statement-s.o : statement.cpp - ${COMPILER} -c -o $@ $? ${SHARED_CXXFLAGS} ${INCLUDEDIRS} - -vector-into-type-s.o : vector-into-type.cpp - ${COMPILER} -c -o $@ $? ${SHARED_CXXFLAGS} ${INCLUDEDIRS} - -vector-use-type-s.o : vector-use-type.cpp - ${COMPILER} -c -o $@ $? ${SHARED_CXXFLAGS} ${INCLUDEDIRS} - - -clean : - rm -f libsoci_postgresql.a libsoci_postgresql.so diff --git a/src/soci/src/backends/postgresql/blob.cpp b/src/soci/src/backends/postgresql/blob.cpp deleted file mode 100644 index 1a4deed53a..0000000000 --- a/src/soci/src/backends/postgresql/blob.cpp +++ /dev/null @@ -1,116 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_POSTGRESQL_SOURCE -#include "soci/postgresql/soci-postgresql.h" -#include // libpq -#include -#include -#include -#include -#include - -#ifdef SOCI_POSTGRESQL_NOPARAMS -#ifndef SOCI_POSTGRESQL_NOBINDBYNAME -#define SOCI_POSTGRESQL_NOBINDBYNAME -#endif // SOCI_POSTGRESQL_NOBINDBYNAME -#endif // SOCI_POSTGRESQL_NOPARAMS - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; - - -postgresql_blob_backend::postgresql_blob_backend( - postgresql_session_backend & session) - : session_(session), fd_(-1) -{ - // nothing to do here, the descriptor is open in the postFetch - // method of the Into element -} - -postgresql_blob_backend::~postgresql_blob_backend() -{ - lo_close(session_.conn_, fd_); -} - -std::size_t postgresql_blob_backend::get_len() -{ - int const pos = lo_lseek(session_.conn_, fd_, 0, SEEK_END); - if (pos == -1) - { - throw soci_error("Cannot retrieve the size of BLOB."); - } - - return static_cast(pos); -} - -std::size_t postgresql_blob_backend::read( - std::size_t offset, char * buf, std::size_t toRead) -{ - int const pos = lo_lseek(session_.conn_, fd_, - static_cast(offset), SEEK_SET); - if (pos == -1) - { - throw soci_error("Cannot seek in BLOB."); - } - - int const readn = lo_read(session_.conn_, fd_, buf, toRead); - if (readn < 0) - { - throw soci_error("Cannot read from BLOB."); - } - - return static_cast(readn); -} - -std::size_t postgresql_blob_backend::write( - std::size_t offset, char const * buf, std::size_t toWrite) -{ - int const pos = lo_lseek(session_.conn_, fd_, - static_cast(offset), SEEK_SET); - if (pos == -1) - { - throw soci_error("Cannot seek in BLOB."); - } - - int const writen = lo_write(session_.conn_, fd_, - const_cast(buf), toWrite); - if (writen < 0) - { - throw soci_error("Cannot write to BLOB."); - } - - return static_cast(writen); -} - -std::size_t postgresql_blob_backend::append( - char const * buf, std::size_t toWrite) -{ - int const pos = lo_lseek(session_.conn_, fd_, 0, SEEK_END); - if (pos == -1) - { - throw soci_error("Cannot seek in BLOB."); - } - - int const writen = lo_write(session_.conn_, fd_, - const_cast(buf), toWrite); - if (writen < 0) - { - throw soci_error("Cannot append to BLOB."); - } - - return static_cast(writen); -} - -void postgresql_blob_backend::trim(std::size_t /* newLen */) -{ - throw soci_error("Trimming BLOBs is not supported."); -} diff --git a/src/soci/src/backends/postgresql/common.h b/src/soci/src/backends/postgresql/common.h deleted file mode 100644 index 4da94fbaa7..0000000000 --- a/src/soci/src/backends/postgresql/common.h +++ /dev/null @@ -1,129 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_POSTGRESQL_COMMON_H_INCLUDED -#define SOCI_POSTGRESQL_COMMON_H_INCLUDED - -#include "soci/postgresql/soci-postgresql.h" -#include -#include -#include -#include -#include - -namespace soci -{ - -namespace details -{ - -namespace postgresql -{ - -// helper function for parsing integers -template -T string_to_integer(char const * buf) -{ - long long t(0); - int n(0); - int const converted = std::sscanf(buf, "%" LL_FMT_FLAGS "d%n", &t, &n); - if (converted == 1 && static_cast(n) == std::strlen(buf)) - { - // successfully converted to long long - // and no other characters were found in the buffer - - const T max = (std::numeric_limits::max)(); - const T min = (std::numeric_limits::min)(); - if (t <= static_cast(max) && - t >= static_cast(min)) - { - return static_cast(t); - } - else - { - // value out of target range - throw soci_error("Cannot convert data."); - } - } - else - { - // try additional conversion from boolean - // (PostgreSQL gives 't' or 'f' for boolean results) - - if (buf[0] == 't' && buf[1] == '\0') - { - return static_cast(1); - } - else if (buf[0] == 'f' && buf[1] == '\0') - { - return static_cast(0); - } - else - { - throw soci_error("Cannot convert data."); - } - } -} - -// helper function for parsing unsigned integers -template -T string_to_unsigned_integer(char const * buf) -{ - unsigned long long t(0); - int n(0); - int const converted = std::sscanf(buf, "%" LL_FMT_FLAGS "u%n", &t, &n); - if (converted == 1 && static_cast(n) == std::strlen(buf)) - { - // successfully converted to unsigned long long - // and no other characters were found in the buffer - - const T max = (std::numeric_limits::max)(); - if (t <= static_cast(max)) - { - return static_cast(t); - } - else - { - // value out of target range - throw soci_error("Cannot convert data."); - } - } - else - { - // try additional conversion from boolean - // (PostgreSQL gives 't' or 'f' for boolean results) - - if (buf[0] == 't' && buf[1] == '\0') - { - return static_cast(1); - } - else if (buf[0] == 'f' && buf[1] == '\0') - { - return static_cast(0); - } - else - { - throw soci_error("Cannot convert data."); - } - } -} - -// helper for vector operations -template -std::size_t get_vector_size(void * p) -{ - std::vector * v = static_cast *>(p); - return v->size(); -} - -} // namespace postgresql - -} // namespace details - -} // namespace soci - -#endif // SOCI_POSTGRESQL_COMMON_H_INCLUDED diff --git a/src/soci/src/backends/postgresql/error.cpp b/src/soci/src/backends/postgresql/error.cpp deleted file mode 100644 index 172eca01c0..0000000000 --- a/src/soci/src/backends/postgresql/error.cpp +++ /dev/null @@ -1,157 +0,0 @@ -// -// Copyright (C) 2011 Gevorg Voskanyan -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_POSTGRESQL_SOURCE -#include "soci/postgresql/soci-postgresql.h" -#include "soci/callbacks.h" -#include "soci/connection-parameters.h" -#include - -using namespace soci; -using namespace soci::details; - -postgresql_soci_error::postgresql_soci_error( - std::string const & msg, char const *sqlst) - : soci_error(msg), cat_(unknown) -{ - std::memcpy(sqlstate_, sqlst, 5); - - if (std::memcmp(sqlst, "08", 2) == 0) - { - cat_ = connection_error; - } - else if (std::memcmp(sqlst, "42501", 5) == 0) - { - cat_ = no_privilege; - } - else if (std::memcmp(sqlst, "42", 2) == 0) - { - cat_ = invalid_statement; - } - else if (std::memcmp(sqlst, "02", 2) == 0) - { - cat_ = no_data; - } - else if (std::memcmp(sqlst, "23", 2) == 0) - { - cat_ = constraint_violation; - } - else if ((std::memcmp(sqlst, "53", 2) == 0) || - (std::memcmp(sqlst, "54", 2) == 0) || - (std::memcmp(sqlst, "58", 2) == 0) || - (std::memcmp(sqlst, "XX", 2) == 0)) - { - cat_ = system_error; - } -} - -std::string postgresql_soci_error::sqlstate() const -{ - return std::string(sqlstate_, 5); -} - -void -details::postgresql_result::check_for_errors(char const* errMsg) const -{ - static_cast(check_for_data(errMsg)); -} - -bool -details::postgresql_result::check_for_data(char const* errMsg) const -{ - std::string msg(errMsg); - - ExecStatusType const status = PQresultStatus(result_); - switch (status) - { - case PGRES_EMPTY_QUERY: - case PGRES_COMMAND_OK: - // No data but don't throw neither. - return false; - - case PGRES_TUPLES_OK: - return true; - - case PGRES_FATAL_ERROR: - msg += " Fatal error."; - - if (PQstatus(sessionBackend_.conn_) == CONNECTION_BAD) - { - msg += " Connection failed."; - - // call the failover callback, if registered - - failover_callback * callback = sessionBackend_.failoverCallback_; - if (callback != NULL) - { - bool reconnected = false; - - try - { - callback->started(); - - bool retry = false; - std::string newTarget; - - callback->failed(retry, newTarget); - - if (retry) - { - connection_parameters parameters("postgresql", newTarget); - - sessionBackend_.clean_up(); - - sessionBackend_.connect(parameters); - - reconnected = true; - } - } - catch (...) - { - // ignore exceptions from user callbacks - } - - if (reconnected == false) - { - try - { - callback->aborted(); - } - catch (...) - { - // ignore exceptions from user callbacks - } - } - } - } - - break; - - default: - // Some of the other status codes are not really errors but we're - // not prepared to handle them right now and shouldn't ever receive - // them so throw nevertheless - - break; - } - - const char* const pqError = PQresultErrorMessage(result_); - if (pqError && *pqError) - { - msg += " "; - msg += pqError; - } - - const char* sqlstate = PQresultErrorField(result_, PG_DIAG_SQLSTATE); - const char* const blank_sql_state = " "; - if (!sqlstate) - { - sqlstate = blank_sql_state; - } - - throw postgresql_soci_error(msg, sqlstate); -} diff --git a/src/soci/src/backends/postgresql/factory.cpp b/src/soci/src/backends/postgresql/factory.cpp deleted file mode 100644 index 7744afa54c..0000000000 --- a/src/soci/src/backends/postgresql/factory.cpp +++ /dev/null @@ -1,142 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_POSTGRESQL_SOURCE -#include "soci/postgresql/soci-postgresql.h" -#include "soci/connection-parameters.h" -#include "soci/backend-loader.h" -#include // libpq - -#ifdef SOCI_POSTGRESQL_NOPARAMS -#ifndef SOCI_POSTGRESQL_NOBINDBYNAME -#define SOCI_POSTGRESQL_NOBINDBYNAME -#endif // SOCI_POSTGRESQL_NOBINDBYNAME -#endif // SOCI_POSTGRESQL_NOPARAMS - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; - -namespace // unnamed -{ - -// iterates the string pointed by i, searching for pairs of key value. -// it returns the position after the value -std::string::const_iterator get_key_value(std::string::const_iterator & i, - std::string::const_iterator const & end, - std::string & key, - std::string & value) -{ - bool in_value = false; - bool quoted = false; - - key.clear(); - value.clear(); - - while (i != end) - { - if (in_value == false) - { - if (*i == '=') - { - in_value = true; - if (i != end && *(i + 1) == '"') - { - quoted = true; - ++i; // jump over the quote - } - } - else if (!isspace(*i)) - { - key += *i; - } - } - else - { - if ((quoted == true && *i == '"') || (quoted == false && isspace(*i))) - { - return ++i; - } - else - { - value += *i; - } - } - ++i; - } - return i; -} - -// retrieves specific parameters from the -// uniform connect string -std::string chop_connect_string(std::string const & connectString, - bool & single_row_mode) -{ - std::string pruned_conn_string; - - single_row_mode = false; - - std::string key, value; - std::string::const_iterator i = connectString.begin(); - while (i != connectString.end()) - { - i = get_key_value(i, connectString.end(), key, value); - if (key == "singlerow" || key == "singlerows") - { - single_row_mode = (value == "true" || value == "yes"); - } - else - { - if (pruned_conn_string.empty() == false) - { - pruned_conn_string += ' '; - } - - pruned_conn_string += key + '=' + value; - } - } - - return pruned_conn_string; -} - -} // unnamed namespace - -// concrete factory for Empty concrete strategies -postgresql_session_backend * postgresql_backend_factory::make_session( - connection_parameters const & parameters) const -{ - bool single_row_mode; - - const std::string pruned_conn_string = - chop_connect_string(parameters.get_connect_string(), single_row_mode); - - connection_parameters pruned_parameters(parameters); - pruned_parameters.set_connect_string(pruned_conn_string); - - return new postgresql_session_backend(pruned_parameters, single_row_mode); -} - -postgresql_backend_factory const soci::postgresql; - -extern "C" -{ - -// for dynamic backend loading -SOCI_POSTGRESQL_DECL backend_factory const * factory_postgresql() -{ - return &soci::postgresql; -} - -SOCI_POSTGRESQL_DECL void register_factory_postgresql() -{ - soci::dynamic_backends::register_backend("postgresql", soci::postgresql); -} - -} // extern "C" diff --git a/src/soci/src/backends/postgresql/row-id.cpp b/src/soci/src/backends/postgresql/row-id.cpp deleted file mode 100644 index 8789969b37..0000000000 --- a/src/soci/src/backends/postgresql/row-id.cpp +++ /dev/null @@ -1,40 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_POSTGRESQL_SOURCE -#include "soci/postgresql/soci-postgresql.h" -#include // libpq -#include -#include -#include -#include -#include - -#ifdef SOCI_POSTGRESQL_NOPARAMS -#ifndef SOCI_POSTGRESQL_NOBINDBYNAME -#define SOCI_POSTGRESQL_NOBINDBYNAME -#endif // SOCI_POSTGRESQL_NOBINDBYNAME -#endif // SOCI_POSTGRESQL_NOPARAMS - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; - - -postgresql_rowid_backend::postgresql_rowid_backend( - postgresql_session_backend & /* session */) - : value_(0) -{ -} - -postgresql_rowid_backend::~postgresql_rowid_backend() -{ - // nothing to do here -} diff --git a/src/soci/src/backends/postgresql/session.cpp b/src/soci/src/backends/postgresql/session.cpp deleted file mode 100644 index 1adab44b1a..0000000000 --- a/src/soci/src/backends/postgresql/session.cpp +++ /dev/null @@ -1,146 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_POSTGRESQL_SOURCE -#include "soci/soci-platform.h" -#include "soci/postgresql/soci-postgresql.h" -#include "soci/session.h" -#include "soci/connection-parameters.h" -#include // libpq -#include -#include -#include -#include -#include - -#ifdef SOCI_POSTGRESQL_NOPARAMS -#ifndef SOCI_POSTGRESQL_NOBINDBYNAME -#define SOCI_POSTGRESQL_NOBINDBYNAME -#endif // SOCI_POSTGRESQL_NOBINDBYNAME -#endif // SOCI_POSTGRESQL_NOPARAMS - -using namespace soci; -using namespace soci::details; - -namespace // unnamed -{ - -// helper function for hardcoded queries -void hard_exec(postgresql_session_backend & session_backend, - PGconn * conn, char const * query, char const * errMsg) -{ - postgresql_result(session_backend, PQexec(conn, query)).check_for_errors(errMsg); -} - -} // namespace unnamed - -postgresql_session_backend::postgresql_session_backend( - connection_parameters const& parameters, bool single_row_mode) - : statementCount_(0) -{ - single_row_mode_ = single_row_mode; - - connect(parameters); -} - -void postgresql_session_backend::connect( - connection_parameters const& parameters) -{ - PGconn* conn = PQconnectdb(parameters.get_connect_string().c_str()); - if (0 == conn || CONNECTION_OK != PQstatus(conn)) - { - std::string msg = "Cannot establish connection to the database."; - if (0 != conn) - { - msg += '\n'; - msg += PQerrorMessage(conn); - PQfinish(conn); - } - - throw soci_error(msg); - } - - // Increase the number of digits used for floating point values to ensure - // that the conversions to/from text round trip correctly, which is not the - // case with the default value of 0. Use the maximal supported value, which - // was 2 until 9.x and is 3 since it. - int const version = PQserverVersion(conn); - hard_exec(*this, conn, - version >= 90000 ? "SET extra_float_digits = 3" - : "SET extra_float_digits = 2", - "Cannot set extra_float_digits parameter"); - - conn_ = conn; -} - -postgresql_session_backend::~postgresql_session_backend() -{ - clean_up(); -} - -void postgresql_session_backend::begin() -{ - hard_exec(*this, conn_, "BEGIN", "Cannot begin transaction."); -} - -void postgresql_session_backend::commit() -{ - hard_exec(*this, conn_, "COMMIT", "Cannot commit transaction."); -} - -void postgresql_session_backend::rollback() -{ - hard_exec(*this, conn_, "ROLLBACK", "Cannot rollback transaction."); -} - -void postgresql_session_backend::deallocate_prepared_statement( - const std::string & statementName) -{ - const std::string & query = "DEALLOCATE " + statementName; - - hard_exec(*this, conn_, query.c_str(), - "Cannot deallocate prepared statement."); -} - -bool postgresql_session_backend::get_next_sequence_value( - session & s, std::string const & sequence, long & value) -{ - s << "select nextval('" + sequence + "')", into(value); - - return true; -} - -void postgresql_session_backend::clean_up() -{ - if (0 != conn_) - { - PQfinish(conn_); - conn_ = 0; - } -} - -std::string postgresql_session_backend::get_next_statement_name() -{ - char nameBuf[20] = { 0 }; // arbitrary length - sprintf(nameBuf, "st_%d", ++statementCount_); - return nameBuf; -} - -postgresql_statement_backend * postgresql_session_backend::make_statement_backend() -{ - return new postgresql_statement_backend(*this, single_row_mode_); -} - -postgresql_rowid_backend * postgresql_session_backend::make_rowid_backend() -{ - return new postgresql_rowid_backend(*this); -} - -postgresql_blob_backend * postgresql_session_backend::make_blob_backend() -{ - return new postgresql_blob_backend(*this); -} diff --git a/src/soci/src/backends/postgresql/standard-into-type.cpp b/src/soci/src/backends/postgresql/standard-into-type.cpp deleted file mode 100644 index 93fc23c1a6..0000000000 --- a/src/soci/src/backends/postgresql/standard-into-type.cpp +++ /dev/null @@ -1,171 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_POSTGRESQL_SOURCE -#include "soci/soci-platform.h" -#include "soci/postgresql/soci-postgresql.h" -#include "soci-cstrtod.h" -#include "soci-mktime.h" -#include "common.h" -#include "soci/rowid.h" -#include "soci/blob.h" -#include "soci/type-wrappers.h" -#include "soci-exchange-cast.h" -#include // libpq -#include -#include -#include -#include -#include -#include - -#ifdef SOCI_POSTGRESQL_NOPARAMS -#ifndef SOCI_POSTGRESQL_NOBINDBYNAME -#define SOCI_POSTGRESQL_NOBINDBYNAME -#endif // SOCI_POSTGRESQL_NOBINDBYNAME -#endif // SOCI_POSTGRESQL_NOPARAMS - -using namespace soci; -using namespace soci::details; -using namespace soci::details::postgresql; - - -void postgresql_standard_into_type_backend::define_by_pos( - int & position, void * data, exchange_type type) -{ - data_ = data; - type_ = type; - position_ = position++; -} - -void postgresql_standard_into_type_backend::pre_fetch() -{ - // nothing to do here -} - -void postgresql_standard_into_type_backend::post_fetch( - bool gotData, bool calledFromFetch, indicator * ind) -{ - if (calledFromFetch == true && gotData == false) - { - // this is a normal end-of-rowset condition, - // no need to do anything (fetch() will return false) - return; - } - - if (gotData) - { - // postgresql_ positions start at 0 - int const pos = position_ - 1; - - // first, deal with indicators - if (PQgetisnull(statement_.result_, statement_.currentRow_, pos) != 0) - { - if (ind == NULL) - { - throw soci_error( - "Null value fetched and no indicator defined."); - } - - *ind = i_null; - - // no need to convert data if it is null - return; - } - else - { - if (ind != NULL) - { - *ind = i_ok; - } - } - - // raw data, in text format - char const * buf = PQgetvalue(statement_.result_, - statement_.currentRow_, pos); - - switch (type_) - { - case x_char: - exchange_type_cast(data_) = *buf; - break; - case x_stdstring: - exchange_type_cast(data_) = buf; - break; - case x_short: - exchange_type_cast(data_) = string_to_integer(buf); - break; - case x_integer: - exchange_type_cast(data_) = string_to_integer(buf); - break; - case x_long_long: - exchange_type_cast(data_) = string_to_integer(buf); - break; - case x_unsigned_long_long: - exchange_type_cast(data_) = string_to_unsigned_integer(buf); - break; - case x_double: - exchange_type_cast(data_) = cstring_to_double(buf); - break; - case x_stdtm: - // attempt to parse the string and convert to std::tm - parse_std_tm(buf, exchange_type_cast(data_)); - break; - case x_rowid: - { - // RowID is internally identical to unsigned long - - rowid * rid = static_cast(data_); - postgresql_rowid_backend * rbe - = static_cast( - rid->get_backend()); - - rbe->value_ = string_to_unsigned_integer(buf); - } - break; - case x_blob: - { - unsigned long oid = - string_to_unsigned_integer(buf); - - int fd = lo_open(statement_.session_.conn_, oid, - INV_READ | INV_WRITE); - if (fd == -1) - { - throw soci_error("Cannot open the blob object."); - } - - blob * b = static_cast(data_); - postgresql_blob_backend * bbe - = static_cast(b->get_backend()); - - if (bbe->fd_ != -1) - { - lo_close(statement_.session_.conn_, bbe->fd_); - } - - bbe->fd_ = fd; - bbe->oid_ = oid; - } - break; - case x_xmltype: - exchange_type_cast(data_).value.assign(buf); - break; - case x_longstring: - exchange_type_cast(data_).value.assign(buf); - break; - - default: - throw soci_error("Into element used with non-supported type."); - } - } -} - -void postgresql_standard_into_type_backend::clean_up() -{ - // nothing to do here -} diff --git a/src/soci/src/backends/postgresql/standard-use-type.cpp b/src/soci/src/backends/postgresql/standard-use-type.cpp deleted file mode 100644 index 177181fc3e..0000000000 --- a/src/soci/src/backends/postgresql/standard-use-type.cpp +++ /dev/null @@ -1,204 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_POSTGRESQL_SOURCE -#include "soci/postgresql/soci-postgresql.h" -#include "soci/blob.h" -#include "soci/rowid.h" -#include "soci/type-wrappers.h" -#include "soci/soci-platform.h" -#include "soci-dtocstr.h" -#include "soci-exchange-cast.h" -#include // libpq -#include -#include -#include -#include -#include -#include - -#ifdef SOCI_POSTGRESQL_NOPARAMS -#ifndef SOCI_POSTGRESQL_NOBINDBYNAME -#define SOCI_POSTGRESQL_NOBINDBYNAME -#endif // SOCI_POSTGRESQL_NOBINDBYNAME -#endif // SOCI_POSTGRESQL_NOPARAMS - -using namespace soci; -using namespace soci::details; - -void postgresql_standard_use_type_backend::bind_by_pos( - int & position, void * data, exchange_type type, bool /* readOnly */) -{ - // readOnly is ignored, because PostgreSQL does not support - // any data to be written back to used (bound) objects. - - data_ = data; - type_ = type; - position_ = position++; -} - -void postgresql_standard_use_type_backend::bind_by_name( - std::string const & name, void * data, exchange_type type, bool /* readOnly */) -{ - // readOnly is ignored, because PostgreSQL does not support - // any data to be written back to used (bound) objects. - - data_ = data; - type_ = type; - name_ = name; -} - -void postgresql_standard_use_type_backend::pre_use(indicator const * ind) -{ - if (ind != NULL && *ind == i_null) - { - // leave the working buffer as NULL - } - else - { - // allocate and fill the buffer with text-formatted client data - switch (type_) - { - case x_char: - { - buf_ = new char[2]; - buf_[0] = exchange_type_cast(data_); - buf_[1] = '\0'; - } - break; - case x_stdstring: - copy_from_string(exchange_type_cast(data_)); - break; - case x_short: - { - std::size_t const bufSize - = std::numeric_limits::digits10 + 3; - buf_ = new char[bufSize]; - snprintf(buf_, bufSize, "%d", - static_cast(exchange_type_cast(data_))); - } - break; - case x_integer: - { - std::size_t const bufSize - = std::numeric_limits::digits10 + 3; - buf_ = new char[bufSize]; - snprintf(buf_, bufSize, "%d", - exchange_type_cast(data_)); - } - break; - case x_long_long: - { - std::size_t const bufSize - = std::numeric_limits::digits10 + 3; - buf_ = new char[bufSize]; - snprintf(buf_, bufSize, "%" LL_FMT_FLAGS "d", - exchange_type_cast(data_)); - } - break; - case x_unsigned_long_long: - { - std::size_t const bufSize - = std::numeric_limits::digits10 + 2; - buf_ = new char[bufSize]; - snprintf(buf_, bufSize, "%" LL_FMT_FLAGS "u", - exchange_type_cast(data_)); - } - break; - case x_double: - copy_from_string(double_to_cstring(exchange_type_cast(data_))); - break; - case x_stdtm: - { - std::size_t const bufSize = 20; - buf_ = new char[bufSize]; - - std::tm const& t = exchange_type_cast(data_); - snprintf(buf_, bufSize, "%d-%02d-%02d %02d:%02d:%02d", - t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, - t.tm_hour, t.tm_min, t.tm_sec); - } - break; - case x_rowid: - { - // RowID is internally identical to unsigned long - - rowid * rid = static_cast(data_); - postgresql_rowid_backend * rbe - = static_cast( - rid->get_backend()); - - std::size_t const bufSize - = std::numeric_limits::digits10 + 2; - buf_ = new char[bufSize]; - - snprintf(buf_, bufSize, "%lu", rbe->value_); - } - break; - case x_blob: - { - blob * b = static_cast(data_); - postgresql_blob_backend * bbe = - static_cast(b->get_backend()); - - std::size_t const bufSize - = std::numeric_limits::digits10 + 2; - buf_ = new char[bufSize]; - snprintf(buf_, bufSize, "%lu", bbe->oid_); - } - break; - case x_xmltype: - copy_from_string(exchange_type_cast(data_).value); - break; - case x_longstring: - copy_from_string(exchange_type_cast(data_).value); - break; - - default: - throw soci_error("Use element used with non-supported type."); - } - } - - if (position_ > 0) - { - // binding by position - statement_.useByPosBuffers_[position_] = &buf_; - } - else - { - // binding by name - statement_.useByNameBuffers_[name_] = &buf_; - } -} - -void postgresql_standard_use_type_backend::post_use( - bool /* gotData */, indicator * /* ind */) -{ - // PostgreSQL does not support any data moving back the same channel, - // so there is nothing to do here. - // In particular, there is nothing to protect, because both const and non-const - // objects will never be modified. - - // clean up the working buffer, it might be allocated anew in - // the next run of preUse - clean_up(); -} - -void postgresql_standard_use_type_backend::clean_up() -{ - if (buf_ != NULL) - { - delete [] buf_; - buf_ = NULL; - } -} - -void postgresql_standard_use_type_backend::copy_from_string(std::string const& s) -{ - buf_ = new char[s.size() + 1]; - std::strcpy(buf_, s.c_str()); -} diff --git a/src/soci/src/backends/postgresql/statement.cpp b/src/soci/src/backends/postgresql/statement.cpp deleted file mode 100644 index 5c0aabe1be..0000000000 --- a/src/soci/src/backends/postgresql/statement.cpp +++ /dev/null @@ -1,898 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_POSTGRESQL_SOURCE -#include "soci/postgresql/soci-postgresql.h" -#include "soci/soci-platform.h" -#include // libpq -#include -#include -#include -#include -#include -#include - -#ifdef SOCI_POSTGRESQL_NOPARAMS -#ifndef SOCI_POSTGRESQL_NOBINDBYNAME -#define SOCI_POSTGRESQL_NOBINDBYNAME -#endif // SOCI_POSTGRESQL_NOBINDBYNAME -#endif // SOCI_POSTGRESQL_NOPARAMS - -using namespace soci; -using namespace soci::details; - -namespace // unnamed -{ - -// used only with asynchronous operations in single-row mode - -void wait_until_operation_complete(postgresql_session_backend & session) -{ - while (true) - { - PGresult * result = PQgetResult(session.conn_); - if (result == NULL) - { - break; - } - else - { - postgresql_result r(session, result); - r.check_for_errors("Cannot execute asynchronous query in single-row mode"); - } - } -} - -void throw_soci_error(PGconn * conn, const char * msg) -{ - std::string description = msg; - description += ": "; - description += PQerrorMessage(conn); - - throw soci_error(description); -} - -} // unnamed namespace - -postgresql_statement_backend::postgresql_statement_backend( - postgresql_session_backend &session, bool single_row_mode) - : session_(session), single_row_mode_(single_row_mode), - result_(session, NULL), - rowsAffectedBulk_(-1LL), justDescribed_(false), - hasIntoElements_(false), hasVectorIntoElements_(false), - hasUseElements_(false), hasVectorUseElements_(false) -{ -#ifndef SOCI_POSTGRESQL_NOSINLGEROWMODE - if (single_row_mode) - { - throw soci_error("Single row mode not supported in this version of the library"); - } -#endif // !SOCI_POSTGRESQL_NOSINLGEROWMODE -} - -postgresql_statement_backend::~postgresql_statement_backend() -{ - if (statementName_.empty() == false) - { - try - { - session_.deallocate_prepared_statement(statementName_); - } - catch (...) - { - // Don't allow exceptions to escape from dtor. Suppressing them is - // not ideal, but terminating the program, as would happen if we're - // already unwinding the stack because of a previous exception, - // would be even worse. - } - } -} - -void postgresql_statement_backend::alloc() -{ - // nothing to do here -} - -void postgresql_statement_backend::clean_up() -{ - // 'reset' the value for a - // potential new execution. - rowsAffectedBulk_ = -1; - - // nothing to do here -} - -void postgresql_statement_backend::prepare(std::string const & query, - statement_type stType) -{ -#ifdef SOCI_POSTGRESQL_NOBINDBYNAME - query_ = query; -#else - // rewrite the query by transforming all named parameters into - // the postgresql_ numbers ones (:abc -> $1, etc.) - - enum { normal, in_quotes, in_name } state = normal; - - std::string name; - int position = 1; - - for (std::string::const_iterator it = query.begin(), end = query.end(); - it != end; ++it) - { - switch (state) - { - case normal: - if (*it == '\'') - { - query_ += *it; - state = in_quotes; - } - else if (*it == ':') - { - // Check whether this is a cast operator (e.g. 23::float) - // and treat it as a special case, not as a named binding - const std::string::const_iterator next_it = it + 1; - if ((next_it != end) && (*next_it == ':')) - { - query_ += "::"; - ++it; - } - // Check whether this is an assignment(e.g. x:=y) - // and treat it as a special case, not as a named binding - else if ((next_it != end) && (*next_it == '=')) - { - query_ += ":="; - ++it; - } - else - { - state = in_name; - } - } - else // regular character, stay in the same state - { - query_ += *it; - } - break; - case in_quotes: - if (*it == '\'') - { - query_ += *it; - state = normal; - } - else // regular quoted character - { - query_ += *it; - } - break; - case in_name: - if (std::isalnum(*it) || *it == '_') - { - name += *it; - } - else // end of name - { - names_.push_back(name); - name.clear(); - std::ostringstream ss; - ss << '$' << position++; - query_ += ss.str(); - query_ += *it; - state = normal; - - // Check whether the named parameter is immediatelly - // followed by a cast operator (e.g. :name::float) - // and handle the additional colon immediately to avoid - // its misinterpretation later on. - if (*it == ':') - { - const std::string::const_iterator next_it = it + 1; - if ((next_it != end) && (*next_it == ':')) - { - query_ += ':'; - ++it; - } - } - } - break; - } - } - - if (state == in_name) - { - names_.push_back(name); - std::ostringstream ss; - ss << '$' << position++; - query_ += ss.str(); - } - -#endif // SOCI_POSTGRESQL_NOBINDBYNAME - -#ifndef SOCI_POSTGRESQL_NOPREPARE - - if (stType == st_repeatable_query) - { - if (!statementName_.empty()) - { - throw soci_error("Shouldn't already have a prepared statement."); - } - - // Holding the name temporarily in this var because - // if it fails to prepare it we can't DEALLOCATE it. - std::string statementName = session_.get_next_statement_name(); - -#ifndef SOCI_POSTGRESQL_NOSINLGEROWMODE - if (single_row_mode_) - { - // prepare for single-row retrieval - - int result = PQsendPrepare(session_.conn_, statementName.c_str(), - query_.c_str(), static_cast(names_.size()), NULL); - if (result != 1) - { - throw_soci_error(session_.conn_, - "Cannot prepare statement in singlerow mode"); - } - - wait_until_operation_complete(session_); - } - else -#endif // !SOCI_POSTGRESQL_NOSINLGEROWMODE - { - // default multi-row query execution - - postgresql_result result(session_, - PQprepare(session_.conn_, statementName.c_str(), - query_.c_str(), static_cast(names_.size()), NULL)); - result.check_for_errors("Cannot prepare statement."); - } - - // Now it's safe to save this info. - statementName_ = statementName; - } - - stType_ = stType; - -#endif // SOCI_POSTGRESQL_NOPREPARE -} - -statement_backend::exec_fetch_result -postgresql_statement_backend::execute(int number) -{ -#ifndef SOCI_POSTGRESQL_NOSINLGEROWMODE - if (single_row_mode_ && (number > 1)) - { - throw soci_error("Bulk operations are not supported with single-row mode."); - } -#endif // !SOCI_POSTGRESQL_NOSINLGEROWMODE - - // If the statement was "just described", then we know that - // it was actually executed with all the use elements - // already bound and pre-used. This means that the result of the - // query is already on the client side, so there is no need - // to re-execute it. - // The optimization based on the existing results - // from the row description can be performed only once. - // If the same statement is re-executed, - // it will be *really* re-executed, without reusing existing data. - - if (justDescribed_ == false) - { - // This object could have been already filled with data before. - clean_up(); - - if ((number > 1) && hasIntoElements_) - { - throw soci_error( - "Bulk use with single into elements is not supported."); - } - - // Since the bulk operations are not natively supported by postgresql_, - // we have to explicitly loop to achieve the bulk operations. - // On the other hand, looping is not needed if there are single - // use elements, even if there is a bulk fetch. - // We know that single use and bulk use elements in the same query are - // not supported anyway, so in the effect the 'number' parameter here - // specifies the size of vectors (into/use), but 'numberOfExecutions' - // specifies the number of loops that need to be performed. - - int numberOfExecutions = 1; - if (number > 0) - { - numberOfExecutions = hasUseElements_ ? 1 : number; - } - - if ((useByPosBuffers_.empty() == false) || - (useByNameBuffers_.empty() == false)) - { - if ((useByPosBuffers_.empty() == false) && - (useByNameBuffers_.empty() == false)) - { - throw soci_error( - "Binding for use elements must be either by position " - "or by name."); - } - long long rowsAffectedBulkTemp = 0; - for (int i = 0; i != numberOfExecutions; ++i) - { - std::vector paramValues; - - if (useByPosBuffers_.empty() == false) - { - // use elements bind by position - // the map of use buffers can be traversed - // in its natural order - - for (UseByPosBuffersMap::iterator - it = useByPosBuffers_.begin(), - end = useByPosBuffers_.end(); - it != end; ++it) - { - char ** buffers = it->second; - paramValues.push_back(buffers[i]); - } - } - else - { - // use elements bind by name - - for (std::vector::iterator - it = names_.begin(), end = names_.end(); - it != end; ++it) - { - UseByNameBuffersMap::iterator b - = useByNameBuffers_.find(*it); - if (b == useByNameBuffers_.end()) - { - std::string msg( - "Missing use element for bind by name ("); - msg += *it; - msg += ")."; - throw soci_error(msg); - } - char ** buffers = b->second; - paramValues.push_back(buffers[i]); - } - } - -#ifdef SOCI_POSTGRESQL_NOPARAMS - - throw soci_error("Queries with parameters are not supported."); - -#else - -#ifdef SOCI_POSTGRESQL_NOPREPARE - -#ifndef SOCI_POSTGRESQL_NOSINLGEROWMODE - if (single_row_mode_) - { - int result = PQsendQueryParams( - session_.conn_, query_.c_str(), - static_cast(paramValues.size()), - NULL, ¶mValues[0], NULL, NULL, 0); - if (result != 1) - { - throw_soci_error(session_.conn_, - "Cannot execute query in single-row mode"); - } - - result = PQsetSingleRowMode(session_.conn_); - if (result != 1) - { - throw_soci_error(session_.conn_, - "cannot set singlerow mode"); - } - } - else -#endif // !SOCI_POSTGRESQL_NOSINLGEROWMODE - { - // default multi-row execution - result_.reset(PQexecParams(session_.conn_, query_.c_str(), - static_cast(paramValues.size()), - NULL, ¶mValues[0], NULL, NULL, 0)); - } -#else - if (stType_ == st_repeatable_query) - { - // this query was separately prepared - -#ifndef SOCI_POSTGRESQL_NOSINLGEROWMODE - if (single_row_mode_) - { - int result = PQsendQueryPrepared(session_.conn_, - statementName_.c_str(), - static_cast(paramValues.size()), - ¶mValues[0], NULL, NULL, 0); - if (result != 1) - { - throw_soci_error(session_.conn_, - "Cannot execute prepared query in single-row mode"); - } - - result = PQsetSingleRowMode(session_.conn_); - if (result != 1) - { - throw_soci_error(session_.conn_, - "Cannot set singlerow mode"); - } - } - else -#endif // !SOCI_POSTGRESQL_NOSINLGEROWMODE - { - // default multi-row execution - - result_.reset(PQexecPrepared(session_.conn_, - statementName_.c_str(), - static_cast(paramValues.size()), - ¶mValues[0], NULL, NULL, 0)); - } - } - else // stType_ == st_one_time_query - { - // this query was not separately prepared and should - // be executed as a one-time query - -#ifndef SOCI_POSTGRESQL_NOSINLGEROWMODE - if (single_row_mode_) - { - int result = PQsendQueryParams(session_.conn_, query_.c_str(), - static_cast(paramValues.size()), - NULL, ¶mValues[0], NULL, NULL, 0); - if (result != 1) - { - throw_soci_error(session_.conn_, - "cannot execute query in single-row mode"); - } - - result = PQsetSingleRowMode(session_.conn_); - if (result != 1) - { - throw_soci_error(session_.conn_, - "Cannot set singlerow mode"); - } - } - else -#endif // !SOCI_POSTGRESQL_NOSINLGEROWMODE - { - // default multi-row execution - - result_.reset(PQexecParams(session_.conn_, query_.c_str(), - static_cast(paramValues.size()), - NULL, ¶mValues[0], NULL, NULL, 0)); - } - } - -#endif // SOCI_POSTGRESQL_NOPREPARE - -#endif // SOCI_POSTGRESQL_NOPARAMS - - if (numberOfExecutions > 1) - { - // there are only bulk use elements (no intos) - - // preserve the number of rows affected so far. - rowsAffectedBulk_ = rowsAffectedBulkTemp; - - result_.check_for_errors("Cannot execute query."); - - rowsAffectedBulkTemp += get_affected_rows(); - } - } - rowsAffectedBulk_ = rowsAffectedBulkTemp; - - if (numberOfExecutions > 1) - { - // it was a bulk operation - result_.reset(); - return ef_no_data; - } - - // otherwise (no bulk), follow the code below - } - else - { - // there are no use elements - // - execute the query without parameter information - -#ifdef SOCI_POSTGRESQL_NOPREPARE - -#ifndef SOCI_POSTGRESQL_NOSINLGEROWMODE - if (single_row_mode_) - { - int result = PQsendQuery(session_.conn_, query_.c_str()); - if (result != 1) - { - throw_soci_error(session_.conn_, - "Cannot execute query in single-row mode"); - } - - result = PQsetSingleRowMode(session_.conn_); - if (result != 1) - { - throw_soci_error(session_.conn_, - "Cannot set single-row mode"); - } - } - else -#endif // !SOCI_POSTGRESQL_NOSINLGEROWMODE - { - // default multi-row execution - - result_.reset(PQexec(session_.conn_, query_.c_str())); - } -#else - if (stType_ == st_repeatable_query) - { - // this query was separately prepared - -#ifndef SOCI_POSTGRESQL_NOSINLGEROWMODE - if (single_row_mode_) - { - int result = PQsendQueryPrepared(session_.conn_, - statementName_.c_str(), 0, NULL, NULL, NULL, 0); - if (result != 1) - { - throw_soci_error(session_.conn_, - "Cannot execute prepared query in single-row mode"); - } - - result = PQsetSingleRowMode(session_.conn_); - if (result != 1) - { - throw_soci_error(session_.conn_, - "Cannot set singlerow mode"); - } - } - else -#endif // !SOCI_POSTGRESQL_NOSINLGEROWMODE - { - // default multi-row execution - - result_.reset(PQexecPrepared(session_.conn_, - statementName_.c_str(), 0, NULL, NULL, NULL, 0)); - } - } - else // stType_ == st_one_time_query - { -#ifndef SOCI_POSTGRESQL_NOSINLGEROWMODE - if (single_row_mode_) - { - int result = PQsendQuery(session_.conn_, query_.c_str()); - if (result != 1) - { - throw_soci_error(session_.conn_, - "Cannot execute query in single-row mode"); - } - - result = PQsetSingleRowMode(session_.conn_); - if (result != 1) - { - throw_soci_error(session_.conn_, - "Cannot set single-row mode"); - } - } - else -#endif // !SOCI_POSTGRESQL_NOSINLGEROWMODE - { - // default multi-row execution - - result_.reset(PQexec(session_.conn_, query_.c_str())); - } - } - -#endif // SOCI_POSTGRESQL_NOPREPARE - } - } - - bool process_result; -#ifndef SOCI_POSTGRESQL_NOSINLGEROWMODE - if (single_row_mode_) - { - if (justDescribed_) - { - // reuse the result_ that was already filled when executing the query - // for the purpose of row describe - } - else - { - PGresult * res = PQgetResult(session_.conn_); - result_.reset(res); - } - - process_result = result_.check_for_data("Cannot execute query."); - } - else -#endif // !SOCI_POSTGRESQL_NOSINLGEROWMODE - { - // default multi-row execution - - process_result = result_.check_for_data("Cannot execute query."); - } - - justDescribed_ = false; - - if (process_result) - { - currentRow_ = 0; - rowsToConsume_ = 0; - - numberOfRows_ = PQntuples(result_); - if (numberOfRows_ == 0) - { - return ef_no_data; - } - else - { - if (number > 0) - { - // prepare for the subsequent data consumption - return fetch(number); - } - else - { - // execute(0) was meant to only perform the query - return ef_success; - } - } - } - else - { - return ef_no_data; - } -} - -statement_backend::exec_fetch_result -postgresql_statement_backend::fetch(int number) -{ -#ifndef SOCI_POSTGRESQL_NOSINLGEROWMODE - if (single_row_mode_ && (number > 1)) - { - throw soci_error("Bulk operations are not supported with single-row mode."); - } -#endif // !SOCI_POSTGRESQL_NOSINLGEROWMODE - - // Note: - // In the multi-row mode this function does not actually fetch anything from anywhere - // - the data was already retrieved from the server in the execute() - // function, and the actual consumption of this data will take place - // in the postFetch functions, called for each into element. - // Here, we only prepare for this to happen (to emulate "the Oracle way"). - // In the single-row mode the fetch of single row of data is performed as expected. - - // forward the "cursor" from the last fetch - currentRow_ += rowsToConsume_; - - if (currentRow_ >= numberOfRows_) - { -#ifndef SOCI_POSTGRESQL_NOSINLGEROWMODE - if (single_row_mode_) - { - PGresult* res = PQgetResult(session_.conn_); - result_.reset(res); - - if (res == NULL) - { - return ef_no_data; - } - - currentRow_ = 0; - rowsToConsume_ = 0; - - numberOfRows_ = PQntuples(result_); - if (numberOfRows_ == 0) - { - return ef_no_data; - } - else - { - rowsToConsume_ = 1; - - return ef_success; - } - } - else -#endif // !SOCI_POSTGRESQL_NOSINLGEROWMODE - { - // default multi-row execution - - // all rows were already consumed - - return ef_no_data; - } - } - else - { - if (currentRow_ + number > numberOfRows_) - { -#ifndef SOCI_POSTGRESQL_NOSINLGEROWMODE - if (single_row_mode_) - { - rowsToConsume_ = 1; - - return ef_success; - } - else -#endif // !SOCI_POSTGRESQL_NOSINLGEROWMODE - { - // default multi-row execution - - rowsToConsume_ = numberOfRows_ - currentRow_; - - // this simulates the behaviour of Oracle - // - when EOF is hit, we return ef_no_data even when there are - // actually some rows fetched - return ef_no_data; - } - } - else - { -#ifndef SOCI_POSTGRESQL_NOSINLGEROWMODE - if (single_row_mode_) - { - rowsToConsume_ = 1; - } - else -#endif // !SOCI_POSTGRESQL_NOSINLGEROWMODE - { - rowsToConsume_ = number; - } - - return ef_success; - } - } -} - -long long postgresql_statement_backend::get_affected_rows() -{ - // PQcmdTuples() doesn't really modify the result but it takes a non-const - // pointer to it, so we can't rely on implicit conversion here. - const char * const resultStr = PQcmdTuples(result_.get_result()); - char * end; - long long result = std::strtoll(resultStr, &end, 0); - if (end != resultStr) - { - return result; - } - else if (rowsAffectedBulk_ >= 0) - { - return rowsAffectedBulk_; - } - else - { - return -1; - } -} - -int postgresql_statement_backend::get_number_of_rows() -{ - return numberOfRows_ - currentRow_; -} - -std::string postgresql_statement_backend::get_parameter_name(int index) const -{ - return names_.at(index); -} - -std::string postgresql_statement_backend::rewrite_for_procedure_call( - std::string const & query) -{ - std::string newQuery("select "); - newQuery += query; - return newQuery; -} - -int postgresql_statement_backend::prepare_for_describe() -{ - execute(1); - justDescribed_ = true; - - int columns = PQnfields(result_); - return columns; -} - -void postgresql_statement_backend::describe_column(int colNum, data_type & type, - std::string & columnName) -{ - // In postgresql_ column numbers start from 0 - int const pos = colNum - 1; - - unsigned long const typeOid = PQftype(result_, pos); - switch (typeOid) - { - // Note: the following list of OIDs was taken from the pg_type table - // we do not claim that this list is exchaustive or even correct. - - // from pg_type: - - case 25: // text - case 1043: // varchar - case 2275: // cstring - case 18: // char - case 1042: // bpchar - case 142: // xml - case 114: // json - case 17: // bytea - case 2950: // uuid - type = dt_string; - break; - - case 702: // abstime - case 703: // reltime - case 1082: // date - case 1083: // time - case 1114: // timestamp - case 1184: // timestamptz - case 1266: // timetz - type = dt_date; - break; - - case 700: // float4 - case 701: // float8 - case 1700: // numeric - type = dt_double; - break; - - case 16: // bool - case 21: // int2 - case 23: // int4 - case 26: // oid - type = dt_integer; - break; - - case 20: // int8 - type = dt_long_long; - break; - - default: - { - int form = PQfformat(result_, pos); - int size = PQfsize(result_, pos); - if (form == 0 && size == -1) - { - type = dt_string; - } - else - { - std::stringstream message; - message << "unknown data type with typelem: " << typeOid - << " for colNum: " << colNum - << " with name: " << PQfname(result_, pos); - throw soci_error(message.str()); - } - } - } - - columnName = PQfname(result_, pos); -} - -postgresql_standard_into_type_backend * -postgresql_statement_backend::make_into_type_backend() -{ - hasIntoElements_ = true; - return new postgresql_standard_into_type_backend(*this); -} - -postgresql_standard_use_type_backend * -postgresql_statement_backend::make_use_type_backend() -{ - hasUseElements_ = true; - return new postgresql_standard_use_type_backend(*this); -} - -postgresql_vector_into_type_backend * -postgresql_statement_backend::make_vector_into_type_backend() -{ - hasVectorIntoElements_ = true; - return new postgresql_vector_into_type_backend(*this); -} - -postgresql_vector_use_type_backend * -postgresql_statement_backend::make_vector_use_type_backend() -{ - hasVectorUseElements_ = true; - return new postgresql_vector_use_type_backend(*this); -} diff --git a/src/soci/src/backends/postgresql/vector-into-type.cpp b/src/soci/src/backends/postgresql/vector-into-type.cpp deleted file mode 100644 index b5b94a086c..0000000000 --- a/src/soci/src/backends/postgresql/vector-into-type.cpp +++ /dev/null @@ -1,313 +0,0 @@ -// -// Copyright (C) 2004-2016 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_POSTGRESQL_SOURCE -#include "soci/soci-platform.h" -#include "soci/postgresql/soci-postgresql.h" -#include "soci-cstrtod.h" -#include "soci-mktime.h" -#include "common.h" -#include "soci/type-wrappers.h" -#include // libpq -#include -#include -#include -#include -#include - -#ifdef SOCI_POSTGRESQL_NOPARAMS -#ifndef SOCI_POSTGRESQL_NOBINDBYNAME -#define SOCI_POSTGRESQL_NOBINDBYNAME -#endif // SOCI_POSTGRESQL_NOBINDBYNAME -#endif // SOCI_POSTGRESQL_NOPARAMS - -using namespace soci; -using namespace soci::details; -using namespace soci::details::postgresql; - - -void postgresql_vector_into_type_backend::define_by_pos_bulk( - int & position, void * data, exchange_type type, - std::size_t begin, std::size_t * end) -{ - data_ = data; - type_ = type; - begin_ = begin; - end_ = end; - position_ = position++; - - end_var_ = full_size(); -} - -void postgresql_vector_into_type_backend::pre_fetch() -{ - // nothing to do here -} - -namespace // anonymous -{ - -template -void set_invector_(void * p, int indx, T const & val) -{ - std::vector * dest = - static_cast *>(p); - - std::vector & v = *dest; - v[indx] = val; -} - -template -void set_invector_wrappers_(void * p, int indx, V const & val) -{ - std::vector * dest = - static_cast *>(p); - - std::vector & v = *dest; - v[indx].value = val; -} - -} // namespace anonymous - -void postgresql_vector_into_type_backend::post_fetch(bool gotData, indicator * ind) -{ - if (gotData) - { - // Here, rowsToConsume_ in the Statement object designates - // the number of rows that need to be put in the user's buffers. - - // postgresql_ column positions start at 0 - int const pos = position_ - 1; - - int const endRow = statement_.currentRow_ + statement_.rowsToConsume_; - - for (int curRow = statement_.currentRow_, i = begin_; - curRow != endRow; ++curRow, ++i) - { - // first, deal with indicators - if (PQgetisnull(statement_.result_, curRow, pos) != 0) - { - if (ind == NULL) - { - throw soci_error( - "Null value fetched and no indicator defined."); - } - - ind[i] = i_null; - - // no need to convert data if it is null, go to next row - continue; - } - else - { - if (ind != NULL) - { - ind[i] = i_ok; - } - } - - // buffer with data retrieved from server, in text format - char * buf = PQgetvalue(statement_.result_, curRow, pos); - - switch (type_) - { - case x_char: - set_invector_(data_, i, *buf); - break; - case x_stdstring: - set_invector_(data_, i, buf); - break; - case x_short: - { - short const val = string_to_integer(buf); - set_invector_(data_, i, val); - } - break; - case x_integer: - { - int const val = string_to_integer(buf); - set_invector_(data_, i, val); - } - break; - case x_long_long: - { - long long const val = string_to_integer(buf); - set_invector_(data_, i, val); - } - break; - case x_unsigned_long_long: - { - unsigned long long const val = - string_to_unsigned_integer(buf); - set_invector_(data_, i, val); - } - break; - case x_double: - { - double const val = cstring_to_double(buf); - set_invector_(data_, i, val); - } - break; - case x_stdtm: - { - // attempt to parse the string and convert to std::tm - std::tm t = std::tm(); - parse_std_tm(buf, t); - - set_invector_(data_, i, t); - } - break; - case x_xmltype: - set_invector_wrappers_(data_, i, buf); - break; - case x_longstring: - set_invector_wrappers_(data_, i, buf); - break; - - default: - throw soci_error("Into element used with non-supported type."); - } - } - } - else // no data retrieved - { - // nothing to do, into vectors are already truncated - } -} - -namespace // anonymous -{ - -template -void resizevector_(void * p, std::size_t sz) -{ - std::vector * v = static_cast *>(p); - v->resize(sz); -} - -} // namespace anonymous - -void postgresql_vector_into_type_backend::resize(std::size_t sz) -{ - if (user_ranges_) - { - // resize only in terms of user-provided ranges (below) - } - else - { - switch (type_) - { - // simple cases - case x_char: - resizevector_(data_, sz); - break; - case x_short: - resizevector_(data_, sz); - break; - case x_integer: - resizevector_(data_, sz); - break; - case x_long_long: - resizevector_(data_, sz); - break; - case x_unsigned_long_long: - resizevector_(data_, sz); - break; - case x_double: - resizevector_(data_, sz); - break; - case x_stdstring: - resizevector_(data_, sz); - break; - case x_stdtm: - resizevector_(data_, sz); - break; - case x_xmltype: - resizevector_(data_, sz); - break; - case x_longstring: - resizevector_(data_, sz); - break; - default: - throw soci_error("Into vector element used with non-supported type."); - } - - end_var_ = sz; - } - - // resize ranges, either user-provided or internally managed - *end_ = begin_ + sz; -} - -std::size_t postgresql_vector_into_type_backend::size() -{ - // as a special error-detection measure, check if the actual vector size - // was changed since the original bind (when it was stored in end_var_): - const std::size_t actual_size = full_size(); - if (actual_size != end_var_) - { - // ... and in that case return the actual size - return actual_size; - } - - if (end_ != NULL && *end_ != 0) - { - return *end_ - begin_; - } - else - { - return end_var_; - } -} - -std::size_t postgresql_vector_into_type_backend::full_size() -{ - std::size_t sz = 0; // dummy initialization to please the compiler - switch (type_) - { - // simple cases - case x_char: - sz = get_vector_size(data_); - break; - case x_short: - sz = get_vector_size(data_); - break; - case x_integer: - sz = get_vector_size(data_); - break; - case x_long_long: - sz = get_vector_size(data_); - break; - case x_unsigned_long_long: - sz = get_vector_size(data_); - break; - case x_double: - sz = get_vector_size(data_); - break; - case x_stdstring: - sz = get_vector_size(data_); - break; - case x_stdtm: - sz = get_vector_size(data_); - break; - case x_xmltype: - sz = get_vector_size(data_); - break; - case x_longstring: - sz = get_vector_size(data_); - break; - default: - throw soci_error("Into vector element used with non-supported type."); - } - - return sz; -} - -void postgresql_vector_into_type_backend::clean_up() -{ - // nothing to do here -} diff --git a/src/soci/src/backends/postgresql/vector-use-type.cpp b/src/soci/src/backends/postgresql/vector-use-type.cpp deleted file mode 100644 index 5d0cb15715..0000000000 --- a/src/soci/src/backends/postgresql/vector-use-type.cpp +++ /dev/null @@ -1,295 +0,0 @@ -// -// Copyright (C) 2004-2016 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_POSTGRESQL_SOURCE -#include "soci/soci-platform.h" -#include "soci/postgresql/soci-postgresql.h" -#include "soci-dtocstr.h" -#include "common.h" -#include "soci/type-wrappers.h" -#include // libpq -#include -#include -#include -#include -#include -#include - -#ifdef SOCI_POSTGRESQL_NOPARAMS -#ifndef SOCI_POSTGRESQL_NOBINDBYNAME -#define SOCI_POSTGRESQL_NOBINDBYNAME -#endif // SOCI_POSTGRESQL_NOBINDBYNAME -#endif // SOCI_POSTGRESQL_NOPARAMS - - -using namespace soci; -using namespace soci::details; -using namespace soci::details::postgresql; - - -void postgresql_vector_use_type_backend::bind_by_pos_bulk(int & position, - void * data, exchange_type type, - std::size_t begin, std::size_t * end) -{ - data_ = data; - type_ = type; - begin_ = begin; - end_ = end; - position_ = position++; - - end_var_ = full_size(); -} - -void postgresql_vector_use_type_backend::bind_by_name_bulk( - std::string const & name, void * data, exchange_type type, - std::size_t begin, std::size_t * end) -{ - data_ = data; - type_ = type; - begin_ = begin; - end_ = end; - name_ = name; - - end_var_ = full_size(); -} - -void postgresql_vector_use_type_backend::pre_use(indicator const * ind) -{ - std::size_t vend; - - if (end_ != NULL && *end_ != 0) - { - vend = *end_; - } - else - { - vend = end_var_; - } - - for (size_t i = begin_; i != vend; ++i) - { - char * buf; - - // the data in vector can be either i_ok or i_null - if (ind != NULL && ind[i] == i_null) - { - buf = NULL; - } - else - { - // allocate and fill the buffer with text-formatted client data - switch (type_) - { - case x_char: - { - std::vector * pv - = static_cast *>(data_); - std::vector & v = *pv; - - buf = new char[2]; - buf[0] = v[i]; - buf[1] = '\0'; - } - break; - case x_stdstring: - { - std::vector * pv - = static_cast *>(data_); - std::vector & v = *pv; - - buf = new char[v[i].size() + 1]; - std::strcpy(buf, v[i].c_str()); - } - break; - case x_short: - { - std::vector * pv - = static_cast *>(data_); - std::vector & v = *pv; - - std::size_t const bufSize - = std::numeric_limits::digits10 + 3; - buf = new char[bufSize]; - snprintf(buf, bufSize, "%d", static_cast(v[i])); - } - break; - case x_integer: - { - std::vector * pv - = static_cast *>(data_); - std::vector & v = *pv; - - std::size_t const bufSize - = std::numeric_limits::digits10 + 3; - buf = new char[bufSize]; - snprintf(buf, bufSize, "%d", v[i]); - } - break; - case x_long_long: - { - std::vector* pv - = static_cast*>(data_); - std::vector& v = *pv; - - std::size_t const bufSize - = std::numeric_limits::digits10 + 3; - buf = new char[bufSize]; - snprintf(buf, bufSize, "%" LL_FMT_FLAGS "d", v[i]); - } - break; - case x_unsigned_long_long: - { - std::vector* pv - = static_cast*>(data_); - std::vector& v = *pv; - - std::size_t const bufSize - = std::numeric_limits::digits10 + 2; - buf = new char[bufSize]; - snprintf(buf, bufSize, "%" LL_FMT_FLAGS "u", v[i]); - } - break; - case x_double: - { - std::vector * pv - = static_cast *>(data_); - std::vector & v = *pv; - - std::string const s = double_to_cstring(v[i]); - - buf = new char[s.size() + 1]; - std::strcpy(buf, s.c_str()); - } - break; - case x_stdtm: - { - std::vector * pv - = static_cast *>(data_); - std::vector & v = *pv; - - std::size_t const bufSize = 20; - buf = new char[bufSize]; - - snprintf(buf, bufSize, "%d-%02d-%02d %02d:%02d:%02d", - v[i].tm_year + 1900, v[i].tm_mon + 1, v[i].tm_mday, - v[i].tm_hour, v[i].tm_min, v[i].tm_sec); - } - break; - case x_xmltype: - { - std::vector * pv - = static_cast *>(data_); - std::vector & v = *pv; - - buf = new char[v[i].value.size() + 1]; - std::strcpy(buf, v[i].value.c_str()); - } - break; - case x_longstring: - { - std::vector * pv - = static_cast *>(data_); - std::vector & v = *pv; - - buf = new char[v[i].value.size() + 1]; - std::strcpy(buf, v[i].value.c_str()); - } - break; - - default: - throw soci_error( - "Use vector element used with non-supported type."); - } - } - - buffers_.push_back(buf); - } - - if (position_ > 0) - { - // binding by position - statement_.useByPosBuffers_[position_] = &buffers_[0]; - } - else - { - // binding by name - statement_.useByNameBuffers_[name_] = &buffers_[0]; - } -} - -std::size_t postgresql_vector_use_type_backend::size() -{ - // as a special error-detection measure, check if the actual vector size - // was changed since the original bind (when it was stored in end_var_): - const std::size_t actual_size = full_size(); - if (actual_size != end_var_) - { - // ... and in that case return the actual size - return actual_size; - } - - if (end_ != NULL && *end_ != 0) - { - return *end_ - begin_; - } - else - { - return end_var_; - } -} - -std::size_t postgresql_vector_use_type_backend::full_size() -{ - std::size_t sz = 0; // dummy initialization to please the compiler - switch (type_) - { - // simple cases - case x_char: - sz = get_vector_size(data_); - break; - case x_short: - sz = get_vector_size(data_); - break; - case x_integer: - sz = get_vector_size(data_); - break; - case x_long_long: - sz = get_vector_size(data_); - break; - case x_unsigned_long_long: - sz = get_vector_size(data_); - break; - case x_double: - sz = get_vector_size(data_); - break; - case x_stdstring: - sz = get_vector_size(data_); - break; - case x_stdtm: - sz = get_vector_size(data_); - break; - case x_xmltype: - sz = get_vector_size(data_); - break; - case x_longstring: - sz = get_vector_size(data_); - break; - default: - throw soci_error("Use vector element used with non-supported type."); - } - - return sz; -} - -void postgresql_vector_use_type_backend::clean_up() -{ - std::size_t const bsize = buffers_.size(); - for (std::size_t i = 0; i != bsize; ++i) - { - delete [] buffers_[i]; - } -} diff --git a/src/soci/src/backends/sqlite3/CMakeLists.txt b/src/soci/src/backends/sqlite3/CMakeLists.txt deleted file mode 100644 index cd90b7ae20..0000000000 --- a/src/soci/src/backends/sqlite3/CMakeLists.txt +++ /dev/null @@ -1,16 +0,0 @@ -############################################################################### -# -# This file is part of CMake configuration for SOCI library -# -# Copyright (C) 2010 Mateusz Loskot -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -# -############################################################################### - -soci_backend(SQLite3 - DEPENDS SQLite3 - DESCRIPTION "SOCI backend for SQLite 3" - AUTHORS "Maciej Sobczak, Stephen Hutton, David Courtney" - MAINTAINERS "Maciej Sobczak, Mateusz Loskot") diff --git a/src/soci/src/backends/sqlite3/Makefile.basic b/src/soci/src/backends/sqlite3/Makefile.basic deleted file mode 100644 index 6594dd31e1..0000000000 --- a/src/soci/src/backends/sqlite3/Makefile.basic +++ /dev/null @@ -1,114 +0,0 @@ -# The following variable is specific to this backend and its correct -# values might depend on your environment - feel free to set it accordingly. - -SQLITE3INCLUDEDIR = -I/usr/include -SQLITE3LIBDIR = -L/usr/lib -SQLITE3LIBS = -lsqlite3 - -# The rest of the Makefile is indepentent of the target environment. - -COMPILER = g++ -CXXFLAGS = -Wall -pedantic -Wno-long-long -SHARED_CXXFLAGS = ${CXXFLAGS} -fPIC -INCLUDEDIRS = -I../../../include -I../../../include/private ${SQLITE3INCLUDEDIR} - -SHARED_LIBDIRS = ${SQLITE3LIBDIR} -SHARED_LIBS = ${SQLITE3LIBS} ../../core/libsoci_core.a - -UNAME = $(shell uname) -ifeq ($(UNAME),Darwin) - SHARED_LINK_FLAGS = -dynamiclib -flat_namespace -undefined suppress -else - SHARED_LINK_FLAGS = -shared -endif - - -OBJECTS = blob.o error.o factory.o row-id.o session.o standard-into-type.o \ - standard-use-type.o statement.o vector-into-type.o vector-use-type.o \ - common.o - -SHARED_OBJECTS = blob-s.o factory-s.o row-id-s.o session-s.o \ - standard-into-type-s.o standard-use-type-s.o statement-s.o \ - vector-into-type-s.o vector-use-type-s.o common-s.o - - -libsoci_sqlite3.a : ${OBJECTS} - ar rv $@ $? - rm *.o - - -blob.o : blob.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -error.o : error.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -common.o : common.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -factory.o : factory.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -row-id.o : row-id.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -session.o : session.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -standard-into-type.o : standard-into-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -standard-use-type.o : standard-use-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -statement.o : statement.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -vector-into-type.o : vector-into-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -vector-use-type.o : vector-use-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - - -shared : ${SHARED_OBJECTS} - ${COMPILER} ${SHARED_LINK_FLAGS} -o libsoci_sqlite3.so \ - ${SHARED_OBJECTS} ${SHARED_LIBDIRS} ${SHARED_LIBS} - rm *.o - -blob-s.o : blob.cpp - ${COMPILER} -c -o $@ $? ${SHARED_CXXFLAGS} ${INCLUDEDIRS} - -error-s.o : error.cpp - ${COMPILER} -c -o $@ $? ${CXXFLAGS} ${INCLUDEDIRS} - -common-s.o : common.cpp - ${COMPILER} -c -o $@ $? ${SHARED_CXXFLAGS} ${INCLUDEDIRS} - -factory-s.o : factory.cpp - ${COMPILER} -c -o $@ $? ${SHARED_CXXFLAGS} ${INCLUDEDIRS} - -row-id-s.o : row-id.cpp - ${COMPILER} -c -o $@ $? ${SHARED_CXXFLAGS} ${INCLUDEDIRS} - -session-s.o : session.cpp - ${COMPILER} -c -o $@ $? ${SHARED_CXXFLAGS} ${INCLUDEDIRS} - -standard-into-type-s.o : standard-into-type.cpp - ${COMPILER} -c -o $@ $? ${SHARED_CXXFLAGS} ${INCLUDEDIRS} - -standard-use-type-s.o : standard-use-type.cpp - ${COMPILER} -c -o $@ $? ${SHARED_CXXFLAGS} ${INCLUDEDIRS} - -statement-s.o : statement.cpp - ${COMPILER} -c -o $@ $? ${SHARED_CXXFLAGS} ${INCLUDEDIRS} - -vector-into-type-s.o : vector-into-type.cpp - ${COMPILER} -c -o $@ $? ${SHARED_CXXFLAGS} ${INCLUDEDIRS} - -vector-use-type-s.o : vector-use-type.cpp - ${COMPILER} -c -o $@ $? ${SHARED_CXXFLAGS} ${INCLUDEDIRS} - - -clean : - rm -f libsoci_sqlite3.a libsoci_sqlite3.so diff --git a/src/soci/src/backends/sqlite3/blob.cpp b/src/soci/src/backends/sqlite3/blob.cpp deleted file mode 100644 index 0d9ca60d41..0000000000 --- a/src/soci/src/backends/sqlite3/blob.cpp +++ /dev/null @@ -1,118 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SQLITE3_SOURCE -#include "soci/sqlite3/soci-sqlite3.h" - -#include -#include - -using namespace soci; - -sqlite3_blob_backend::sqlite3_blob_backend(sqlite3_session_backend &session) - : session_(session), buf_(0), len_(0) -{ -} - -sqlite3_blob_backend::~sqlite3_blob_backend() -{ - if (buf_) - { - delete [] buf_; - buf_ = 0; - len_ = 0; - } -} - -std::size_t sqlite3_blob_backend::get_len() -{ - return len_; -} - -std::size_t sqlite3_blob_backend::read( - std::size_t offset, char * buf, std::size_t toRead) -{ - size_t r = toRead; - - // make sure that we don't try to read - // past the end of the data - if (r > len_ - offset) - { - r = len_ - offset; - } - - memcpy(buf, buf_ + offset, r); - - return r; -} - - -std::size_t sqlite3_blob_backend::write( - std::size_t offset, char const * buf, - std::size_t toWrite) -{ - const char* oldBuf = buf_; - std::size_t oldLen = len_; - len_ = (std::max)(len_, offset + toWrite); - - buf_ = new char[len_]; - - if (oldBuf) - { - // we need to copy both old and new buffers - // it is possible that the new does not - // completely cover the old - memcpy(buf_, oldBuf, oldLen); - delete [] oldBuf; - } - memcpy(buf_ + offset, buf, toWrite); - - return len_; -} - - -std::size_t sqlite3_blob_backend::append( - char const * buf, std::size_t toWrite) -{ - const char* oldBuf = buf_; - - buf_ = new char[len_ + toWrite]; - - memcpy(buf_, oldBuf, len_); - - memcpy(buf_ + len_, buf, toWrite); - - delete [] oldBuf; - - len_ += toWrite; - - return len_; -} - - -void sqlite3_blob_backend::trim(std::size_t newLen) -{ - const char* oldBuf = buf_; - len_ = newLen; - - buf_ = new char[len_]; - - memcpy(buf_, oldBuf, len_); - - delete [] oldBuf; -} - -std::size_t sqlite3_blob_backend::set_data(char const *buf, std::size_t toWrite) -{ - if (buf_) - { - delete [] buf_; - buf_ = 0; - len_ = 0; - } - return write(0, buf, toWrite); -} diff --git a/src/soci/src/backends/sqlite3/common.h b/src/soci/src/backends/sqlite3/common.h deleted file mode 100644 index a2bf26a89c..0000000000 --- a/src/soci/src/backends/sqlite3/common.h +++ /dev/null @@ -1,84 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_SQLITE3_COMMON_H_INCLUDED -#define SOCI_SQLITE3_COMMON_H_INCLUDED - -#include "soci/error.h" -#include -#include -#include -#include -#include -#include - -namespace soci { namespace details { namespace sqlite3 { - -// helper for vector operations -template -std::size_t get_vector_size(void *p) -{ - std::vector *v = static_cast *>(p); - return v->size(); -} - -template -void resize_vector(void *p, std::size_t sz) -{ - std::vector *v = static_cast *>(p); - v->resize(sz); -} - -// helper function for parsing integers -template -T string_to_integer(char const * buf) -{ - long long t(0); - int n(0); - int const converted = std::sscanf(buf, "%" LL_FMT_FLAGS "d%n", &t, &n); - if (converted == 1 && static_cast(n) == std::strlen(buf)) - { - // successfully converted to long long - // and no other characters were found in the buffer - - const T max = (std::numeric_limits::max)(); - const T min = (std::numeric_limits::min)(); - if (t <= static_cast(max) && - t >= static_cast(min)) - { - return static_cast(t); - } - } - - throw soci_error("Cannot convert data."); -} - -// helper function for parsing unsigned integers -template -T string_to_unsigned_integer(char const * buf) -{ - unsigned long long t(0); - int n(0); - int const converted = std::sscanf(buf, "%" LL_FMT_FLAGS "u%n", &t, &n); - if (converted == 1 && static_cast(n) == std::strlen(buf)) - { - // successfully converted to unsigned long long - // and no other characters were found in the buffer - - T const max = (std::numeric_limits::max)(); - if (t <= static_cast(max)) - { - return static_cast(t); - } - } - - throw soci_error("Cannot convert data."); -} - -}}} // namespace soci::details::sqlite3 - -#endif // SOCI_SQLITE3_COMMON_H_INCLUDED diff --git a/src/soci/src/backends/sqlite3/error.cpp b/src/soci/src/backends/sqlite3/error.cpp deleted file mode 100644 index ba24da0136..0000000000 --- a/src/soci/src/backends/sqlite3/error.cpp +++ /dev/null @@ -1,23 +0,0 @@ -// -// Copyright 2014 SimpliVT Corporation -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SQLITE3_SOURCE -#include "soci/sqlite3/soci-sqlite3.h" -#include - -using namespace soci; - -sqlite3_soci_error::sqlite3_soci_error( - std::string const & msg, int result) - : soci_error(msg), result_(result) -{ -} - -int sqlite3_soci_error::result() const -{ - return result_; -} diff --git a/src/soci/src/backends/sqlite3/factory.cpp b/src/soci/src/backends/sqlite3/factory.cpp deleted file mode 100644 index f69ec81c2e..0000000000 --- a/src/soci/src/backends/sqlite3/factory.cpp +++ /dev/null @@ -1,42 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SQLITE3_SOURCE -#include "soci/sqlite3/soci-sqlite3.h" -#include "soci/backend-loader.h" - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; - -// concrete factory for Empty concrete strategies -sqlite3_session_backend * sqlite3_backend_factory::make_session( - connection_parameters const & parameters) const -{ - return new sqlite3_session_backend(parameters); -} - -sqlite3_backend_factory const soci::sqlite3; - -extern "C" -{ - -// for dynamic backend loading -SOCI_SQLITE3_DECL backend_factory const * factory_sqlite3() -{ - return &soci::sqlite3; -} - -SOCI_SQLITE3_DECL void register_factory_sqlite3() -{ - soci::dynamic_backends::register_backend("sqlite3", soci::sqlite3); -} - -} // extern "C" diff --git a/src/soci/src/backends/sqlite3/row-id.cpp b/src/soci/src/backends/sqlite3/row-id.cpp deleted file mode 100644 index f7d84d6fb9..0000000000 --- a/src/soci/src/backends/sqlite3/row-id.cpp +++ /dev/null @@ -1,27 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SQLITE3_SOURCE -#include "soci/sqlite3/soci-sqlite3.h" - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; - -sqlite3_rowid_backend::sqlite3_rowid_backend( - sqlite3_session_backend & /* session */) - : value_(0) -{ -} - -sqlite3_rowid_backend::~sqlite3_rowid_backend() -{ - // ... -} diff --git a/src/soci/src/backends/sqlite3/session.cpp b/src/soci/src/backends/sqlite3/session.cpp deleted file mode 100644 index a84c4b87fd..0000000000 --- a/src/soci/src/backends/sqlite3/session.cpp +++ /dev/null @@ -1,170 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SQLITE3_SOURCE -#include "soci/sqlite3/soci-sqlite3.h" - -#include "soci/connection-parameters.h" - -#include -#include - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; -using namespace sqlite_api; - -namespace // anonymous -{ - -// helper function for hardcoded queries -void execude_hardcoded(sqlite_api::sqlite3* conn, char const* const query, char const* const errMsg) -{ - char *zErrMsg = 0; - int const res = sqlite3_exec(conn, query, 0, 0, &zErrMsg); - if (res != SQLITE_OK) - { - std::ostringstream ss; - ss << errMsg << " " << zErrMsg; - sqlite3_free(zErrMsg); - throw sqlite3_soci_error(ss.str(), res); - } -} - -void check_sqlite_err(sqlite_api::sqlite3* conn, int res, char const* const errMsg) -{ - if (SQLITE_OK != res) - { - const char *zErrMsg = sqlite3_errmsg(conn); - std::ostringstream ss; - ss << errMsg << zErrMsg; - sqlite3_close(conn); // connection must be closed here - throw sqlite3_soci_error(ss.str(), res); - } -} - -} // namespace anonymous - - -sqlite3_session_backend::sqlite3_session_backend( - connection_parameters const & parameters) -{ - int timeout = 0; - int connection_flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE; - std::string synchronous; - std::string const & connectString = parameters.get_connect_string(); - std::string dbname(connectString); - std::stringstream ssconn(connectString); - while (!ssconn.eof() && ssconn.str().find('=') != std::string::npos) - { - std::string key, val; - std::getline(ssconn, key, '='); - std::getline(ssconn, val, ' '); - - if (val.size()>0 && val[0]=='\"') - { - std::string quotedVal = val.erase(0, 1); - - if (quotedVal[quotedVal.size()-1] == '\"') - { - quotedVal.erase(val.size()-1); - } - else // space inside value string - { - std::getline(ssconn, val, '\"'); - quotedVal = quotedVal + " " + val; - std::string keepspace; - std::getline(ssconn, keepspace, ' '); - } - - val = quotedVal; - } - - if ("dbname" == key || "db" == key) - { - dbname = val; - } - else if ("timeout" == key) - { - std::istringstream converter(val); - converter >> timeout; - } - else if ("synchronous" == key) - { - synchronous = val; - } - else if ("shared_cache" == key && "true" == val) - { - connection_flags |= SQLITE_OPEN_SHAREDCACHE; - } - } - - int res = sqlite3_open_v2(dbname.c_str(), &conn_, connection_flags, NULL); - check_sqlite_err(conn_, res, "Cannot establish connection to the database. "); - - if (!synchronous.empty()) - { - std::string const query("pragma synchronous=" + synchronous); - std::string const errMsg("Query failed: " + query); - execude_hardcoded(conn_, query.c_str(), errMsg.c_str()); - } - - res = sqlite3_busy_timeout(conn_, timeout * 1000); - check_sqlite_err(conn_, res, "Failed to set busy timeout for connection. "); - -} - -sqlite3_session_backend::~sqlite3_session_backend() -{ - clean_up(); -} - -void sqlite3_session_backend::begin() -{ - execude_hardcoded(conn_, "BEGIN", "Cannot begin transaction."); -} - -void sqlite3_session_backend::commit() -{ - execude_hardcoded(conn_, "COMMIT", "Cannot commit transaction."); -} - -void sqlite3_session_backend::rollback() -{ - execude_hardcoded(conn_, "ROLLBACK", "Cannot rollback transaction."); -} - -bool sqlite3_session_backend::get_last_insert_id( - session & /* s */, std::string const & /* table */, long & value) -{ - value = static_cast(sqlite3_last_insert_rowid(conn_)); - - return true; -} - -void sqlite3_session_backend::clean_up() -{ - sqlite3_close(conn_); -} - -sqlite3_statement_backend * sqlite3_session_backend::make_statement_backend() -{ - return new sqlite3_statement_backend(*this); -} - -sqlite3_rowid_backend * sqlite3_session_backend::make_rowid_backend() -{ - return new sqlite3_rowid_backend(*this); -} - -sqlite3_blob_backend * sqlite3_session_backend::make_blob_backend() -{ - return new sqlite3_blob_backend(*this); -} diff --git a/src/soci/src/backends/sqlite3/standard-into-type.cpp b/src/soci/src/backends/sqlite3/standard-into-type.cpp deleted file mode 100644 index eb7bf5cb20..0000000000 --- a/src/soci/src/backends/sqlite3/standard-into-type.cpp +++ /dev/null @@ -1,177 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SQLITE3_SOURCE -#include "soci/soci-platform.h" -#include "soci/sqlite3/soci-sqlite3.h" -#include "soci/rowid.h" -#include "common.h" -#include "soci/blob.h" -#include "soci-cstrtod.h" -#include "soci-mktime.h" -#include "soci-exchange-cast.h" -// std -#include -#include -#include - -using namespace soci; -using namespace soci::details; -using namespace soci::details::sqlite3; - -void sqlite3_standard_into_type_backend::define_by_pos(int & position, void * data, - exchange_type type) -{ - data_ = data; - type_ = type; - position_ = position++; -} - -void sqlite3_standard_into_type_backend::pre_fetch() -{ - // ... -} - -void sqlite3_standard_into_type_backend::post_fetch(bool gotData, - bool calledFromFetch, - indicator * ind) -{ - if (calledFromFetch == true && gotData == false) - { - // this is a normal end-of-rowset condition, - // no need to do anything (fetch() will return false) - return; - } - - // sqlite columns start at 0 - int const pos = position_ - 1; - - if (gotData) - { - // first, deal with indicators - if (sqlite3_column_type(statement_.stmt_, pos) == SQLITE_NULL) - { - if (ind == NULL) - { - throw soci_error( - "Null value fetched and no indicator defined."); - } - - *ind = i_null; - return; - } - else - { - if (ind != NULL) - { - *ind = i_ok; - } - } - - switch (type_) - { - case x_char: - { - const char *buf = reinterpret_cast( - sqlite3_column_text(statement_.stmt_, pos) - ); - const int bytes = sqlite3_column_bytes(statement_.stmt_, pos); - exchange_type_cast(data_) = (bytes > 0 ? buf[0] : '\0'); - break; - } - - case x_stdstring: - { - const char *buf = reinterpret_cast( - sqlite3_column_text(statement_.stmt_, pos) - ); - const int bytes = sqlite3_column_bytes(statement_.stmt_, pos); - exchange_type_traits::value_type &out - = exchange_type_cast(data_); - out.assign(buf, bytes); - break; - } - - case x_short: - exchange_type_cast(data_) - = static_cast::value_type >( - sqlite3_column_int(statement_.stmt_, pos) - ); - break; - - case x_integer: - exchange_type_cast(data_) - = static_cast::value_type >( - sqlite3_column_int(statement_.stmt_, pos) - ); - break; - - case x_long_long: - exchange_type_cast(data_) - = static_cast::value_type >( - sqlite3_column_int64(statement_.stmt_, pos) - ); - break; - - case x_unsigned_long_long: - exchange_type_cast(data_) - = static_cast::value_type >( - sqlite3_column_int64(statement_.stmt_, pos) - ); - break; - - case x_double: - exchange_type_cast(data_) - = static_cast::value_type >( - sqlite3_column_double(statement_.stmt_, pos) - ); - break; - - case x_stdtm: - { - const char *buf = reinterpret_cast( - sqlite3_column_text(statement_.stmt_, pos) - ); - parse_std_tm((buf ? buf : ""), exchange_type_cast(data_)); - break; - } - - case x_rowid: - { - // RowID is internally identical to unsigned long - rowid *rid = static_cast(data_); - sqlite3_rowid_backend *rbe = static_cast(rid->get_backend()); - rbe->value_ = static_cast(sqlite3_column_int64(statement_.stmt_, pos)); - break; - } - - case x_blob: - { - blob *b = static_cast(data_); - sqlite3_blob_backend *bbe = - static_cast(b->get_backend()); - - const char *buf - = reinterpret_cast( - sqlite3_column_blob(statement_.stmt_, pos) - ); - - int len = sqlite3_column_bytes(statement_.stmt_, pos); - bbe->set_data(buf, len); - break; - } - - default: - throw soci_error("Into element used with non-supported type."); - } - } -} - -void sqlite3_standard_into_type_backend::clean_up() -{ - // ... -} diff --git a/src/soci/src/backends/sqlite3/standard-use-type.cpp b/src/soci/src/backends/sqlite3/standard-use-type.cpp deleted file mode 100644 index f4c8f5f04b..0000000000 --- a/src/soci/src/backends/sqlite3/standard-use-type.cpp +++ /dev/null @@ -1,213 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SQLITE3_SOURCE -#include "soci/soci-platform.h" -#include "soci/sqlite3/soci-sqlite3.h" -#include "soci/rowid.h" -#include "soci/blob.h" -#include "soci-dtocstr.h" -#include "soci-exchange-cast.h" -// std -#include -#include -#include -#include -#include -#include -#include - -using namespace soci; -using namespace soci::details; - -sqlite3_standard_use_type_backend::sqlite3_standard_use_type_backend( - sqlite3_statement_backend &st) - : statement_(st), data_(NULL), type_(x_integer), position_(-1) -{ -} - - -void sqlite3_standard_use_type_backend::bind_by_pos(int& position, void* data, - exchange_type type, bool /*readOnly*/) -{ - if (statement_.boundByName_) - { - throw soci_error( - "Binding for use elements must be either by position or by name."); - } - - data_ = data; - type_ = type; - position_ = position++; - - statement_.boundByPos_ = true; -} - -void sqlite3_standard_use_type_backend::bind_by_name(std::string const& name, - void* data, exchange_type type, bool /*readOnly*/) -{ - if (statement_.boundByPos_) - { - throw soci_error( - "Binding for use elements must be either by position or by name."); - } - - data_ = data; - type_ = type; - name_ = ":" + name; - - statement_.reset_if_needed(); - position_ = sqlite3_bind_parameter_index(statement_.stmt_, name_.c_str()); - - if (0 == position_) - { - std::ostringstream ss; - ss << "Cannot bind to (by name) " << name_; - throw soci_error(ss.str()); - } - statement_.boundByName_ = true; -} - -void sqlite3_standard_use_type_backend::pre_use(indicator const * ind) -{ - statement_.useData_.resize(1); - int const pos = position_ - 1; - - if (statement_.useData_[0].size() < static_cast(position_)) - { - statement_.useData_[0].resize(position_); - } - - sqlite3_column &col = statement_.useData_[0][pos]; - - if (ind != NULL && *ind == i_null) - { - col.isNull_ = true; - return; - } - - col.isNull_ = false; - - // allocate and fill the buffer with text-formatted client data - switch (type_) - { - case x_char: - col.type_ = dt_string; - col.buffer_.constData_ = &exchange_type_cast(data_); - col.buffer_.size_ = 1; - break; - - case x_stdstring: - { - const std::string &s = exchange_type_cast(data_); - col.type_ = dt_string; - col.buffer_.constData_ = s.c_str(); - col.buffer_.size_ = s.size(); - break; - } - - case x_short: - col.type_ = dt_integer; - col.int32_ = exchange_type_cast(data_); - break; - - case x_integer: - col.type_ = dt_integer; - col.int32_ = exchange_type_cast(data_); - break; - - case x_long_long: - col.type_ = dt_long_long; - col.int64_ = exchange_type_cast(data_); - break; - - case x_unsigned_long_long: - col.type_ = dt_long_long; - col.int64_ = exchange_type_cast(data_); - break; - - case x_double: - col.type_ = dt_double; - col.double_ = exchange_type_cast(data_); - break; - - case x_stdtm: - { - col.type_ = dt_date; - static const size_t bufSize = 20; - std::tm &t = exchange_type_cast(data_); - - col.buffer_.data_ = new char[bufSize]; - col.buffer_.size_ - = snprintf( - col.buffer_.data_, bufSize, "%d-%02d-%02d %02d:%02d:%02d", - t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, - t.tm_hour, t.tm_min, t.tm_sec - ); - break; - } - - case x_rowid: - { - col.type_ = dt_long_long; - // RowID is internally identical to unsigned long - rowid *rid = static_cast(data_); - sqlite3_rowid_backend *rbe = static_cast(rid->get_backend()); - - col.int64_ = rbe->value_; - break; - } - - case x_blob: - { - col.type_ = dt_blob; - blob *b = static_cast(data_); - sqlite3_blob_backend *bbe = static_cast(b->get_backend()); - - col.buffer_.constData_ = bbe->get_buffer(); - col.buffer_.size_ = bbe->get_len(); - break; - } - - default: - throw soci_error("Use element used with non-supported type."); - } -} - -void sqlite3_standard_use_type_backend::post_use( - bool /* gotData */, indicator * /* ind */) -{ - // TODO: Is it possible to have the bound element being overwritten - // by the database? - // If not, then nothing to do here, please remove this comment. - // If yes, then use the value of the readOnly parameter: - // - true: the given object should not be modified and the backend - // should detect if the modification was performed on the - // isolated buffer and throw an exception if the buffer was modified - // (this indicates logic error, because the user used const object - // and executed a query that attempted to modified it) - // - false: the modification should be propagated to the given object. - // ... - - // clean up the working buffer, it might be allocated anew in - // the next run of preUse - clean_up(); -} - -void sqlite3_standard_use_type_backend::clean_up() -{ - if (type_ != x_stdtm) - return; - - sqlite3_column &col = statement_.useData_[0][position_ - 1]; - - if (col.isNull_ || !col.buffer_.data_) - return; - - delete[] col.buffer_.data_; - col.buffer_.data_ = NULL; -} diff --git a/src/soci/src/backends/sqlite3/statement.cpp b/src/soci/src/backends/sqlite3/statement.cpp deleted file mode 100644 index 9481b53bfb..0000000000 --- a/src/soci/src/backends/sqlite3/statement.cpp +++ /dev/null @@ -1,558 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SQLITE3_SOURCE -#include "soci/sqlite3/soci-sqlite3.h" -// std -#include -#include -#include -#include - -#include - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif - -using namespace soci; -using namespace soci::details; -using namespace sqlite_api; - -sqlite3_statement_backend::sqlite3_statement_backend( - sqlite3_session_backend &session) - : session_(session) - , stmt_(0) - , dataCache_() - , useData_(0) - , databaseReady_(false) - , boundByName_(false) - , boundByPos_(false) - , rowsAffectedBulk_(-1LL) -{ -} - -void sqlite3_statement_backend::alloc() -{ - // ... -} - -void sqlite3_statement_backend::clean_up() -{ - rowsAffectedBulk_ = -1LL; - - if (stmt_) - { - sqlite3_finalize(stmt_); - stmt_ = 0; - databaseReady_ = false; - } -} - -void sqlite3_statement_backend::prepare(std::string const & query, - statement_type /* eType */) -{ - clean_up(); - - char const* tail = 0; // unused; - int const res = sqlite3_prepare_v2(session_.conn_, - query.c_str(), - static_cast(query.size()), - &stmt_, - &tail); - if (res != SQLITE_OK) - { - char const* zErrMsg = sqlite3_errmsg(session_.conn_); - - std::ostringstream ss; - ss << "sqlite3_statement_backend::prepare: " - << zErrMsg; - throw sqlite3_soci_error(ss.str(), res); - } - databaseReady_ = true; -} - -// sqlite3_reset needs to be called before a prepared statment can -// be executed a second time. -void sqlite3_statement_backend::reset_if_needed() -{ - if (stmt_ && databaseReady_ == false) - { - reset(); - } -} - -void sqlite3_statement_backend::reset() -{ - int const res = sqlite3_reset(stmt_); - if (SQLITE_OK == res) - { - databaseReady_ = true; - } -} - -// This is used by bulk operations -statement_backend::exec_fetch_result -sqlite3_statement_backend::load_rowset(int totalRows) -{ - statement_backend::exec_fetch_result retVal = ef_success; - - int i = 0; - int numCols = 0; - - // just a hack because in some case, describe() is not called, so columns_ is empty - if (columns_.empty()) - { - numCols = sqlite3_column_count(stmt_); - data_type type; - std::string name; - for (int c = 1; c <= numCols; ++c) - describe_column(c, type, name); - } - else - numCols = static_cast(columns_.size()); - - - if (!databaseReady_) - { - retVal = ef_no_data; - } - else - { - // make the vector big enough to hold the data we need - dataCache_.resize(totalRows); - for (sqlite3_recordset::iterator it = dataCache_.begin(), - end = dataCache_.end(); it != end; ++it) - { - (*it).resize(numCols); - } - - for (i = 0; i < totalRows && databaseReady_; ++i) - { - int const res = sqlite3_step(stmt_); - - if (SQLITE_DONE == res) - { - databaseReady_ = false; - retVal = ef_no_data; - break; - } - else if (SQLITE_ROW == res) - { - for (int c = 0; c < numCols; ++c) - { - const sqlite3_column_info &coldef = columns_[c]; - sqlite3_column &col = dataCache_[i][c]; - - if (sqlite3_column_type(stmt_, c) == SQLITE_NULL) - { - col.isNull_ = true; - continue; - } - - col.isNull_ = false; - col.type_ = coldef.type_; - - switch (coldef.type_) - { - case dt_string: - case dt_date: - col.buffer_.size_ = sqlite3_column_bytes(stmt_, c); - col.buffer_.data_ = new char[col.buffer_.size_+1]; - memcpy(col.buffer_.data_, sqlite3_column_text(stmt_, c), col.buffer_.size_+1); - break; - - case dt_double: - col.double_ = sqlite3_column_double(stmt_, c); - break; - - case dt_integer: - col.int32_ = sqlite3_column_int(stmt_, c); - break; - - case dt_long_long: - case dt_unsigned_long_long: - col.int64_ = sqlite3_column_int64(stmt_, c); - break; - - case dt_blob: - col.buffer_.size_ = sqlite3_column_bytes(stmt_, c); - col.buffer_.data_ = (col.buffer_.size_ > 0 ? new char[col.buffer_.size_] : NULL); - memcpy(col.buffer_.data_, sqlite3_column_blob(stmt_, c), col.buffer_.size_); - break; - - case dt_xml: - throw soci_error("XML data type is not supported"); - } - } - } - else - { - char const* zErrMsg = sqlite3_errmsg(session_.conn_); - std::ostringstream ss; - ss << "sqlite3_statement_backend::loadRS: " - << zErrMsg; - throw sqlite3_soci_error(ss.str(), res); - } - } - } - // if we read less than requested then shrink the vector - dataCache_.resize(i); - - return retVal; -} - -// This is used for non-bulk operations -statement_backend::exec_fetch_result -sqlite3_statement_backend::load_one() -{ - if( !databaseReady_ ) - return ef_no_data; - - statement_backend::exec_fetch_result retVal = ef_success; - int const res = sqlite3_step(stmt_); - - if (SQLITE_DONE == res) - { - databaseReady_ = false; - retVal = ef_no_data; - } - else if (SQLITE_ROW == res) - { - } - else - { - char const* zErrMsg = sqlite3_errmsg(session_.conn_); - - std::ostringstream ss; - ss << "sqlite3_statement_backend::loadOne: " - << zErrMsg; - throw sqlite3_soci_error(ss.str(), res); - } - return retVal; -} - -// Execute statements once for every row of useData -statement_backend::exec_fetch_result -sqlite3_statement_backend::bind_and_execute(int number) -{ - statement_backend::exec_fetch_result retVal = ef_no_data; - - long long rowsAffectedBulkTemp = 0; - - rowsAffectedBulk_ = -1; - - int const rows = static_cast(useData_.size()); - for (int row = 0; row < rows; ++row) - { - sqlite3_reset(stmt_); - - int const totalPositions = static_cast(useData_[0].size()); - for (int pos = 1; pos <= totalPositions; ++pos) - { - int bindRes = SQLITE_OK; - const sqlite3_column &col = useData_[row][pos-1]; - if (col.isNull_) - { - bindRes = sqlite3_bind_null(stmt_, pos); - } - else - { - switch (col.type_) - { - case dt_string: - case dt_date: - bindRes = sqlite3_bind_text(stmt_, pos, col.buffer_.constData_, static_cast(col.buffer_.size_), NULL); - break; - - case dt_double: - bindRes = sqlite3_bind_double(stmt_, pos, col.double_); - break; - - case dt_integer: - bindRes = sqlite3_bind_int(stmt_, pos, col.int32_); - break; - - case dt_long_long: - case dt_unsigned_long_long: - bindRes = sqlite3_bind_int64(stmt_, pos, col.int64_); - break; - - case dt_blob: - bindRes = sqlite3_bind_blob(stmt_, pos, col.buffer_.constData_, static_cast(col.buffer_.size_), NULL); - break; - - case dt_xml: - throw soci_error("XML data type is not supported"); - } - } - - if (SQLITE_OK != bindRes) - { - // preserve the number of rows affected so far. - rowsAffectedBulk_ = rowsAffectedBulkTemp; - throw sqlite3_soci_error("Failure to bind on bulk operations", bindRes); - } - } - - // Handle the case where there are both into and use elements - // in the same query and one of the into binds to a vector object. - if (1 == rows && number != rows) - { - return load_rowset(number); - } - - databaseReady_=true; // Mark sqlite engine is ready to perform sqlite3_step - retVal = load_one(); // execute each bound line - rowsAffectedBulkTemp += get_affected_rows(); - } - - rowsAffectedBulk_ = rowsAffectedBulkTemp; - return retVal; -} - -statement_backend::exec_fetch_result -sqlite3_statement_backend::execute(int number) -{ - if (stmt_ == NULL) - { - throw soci_error("No sqlite statement created"); - } - - sqlite3_reset(stmt_); - databaseReady_ = true; - - statement_backend::exec_fetch_result retVal = ef_no_data; - - if (useData_.empty() == false) - { - retVal = bind_and_execute(number); - } - else - { - if (1 == number) - { - retVal = load_one(); - } - else - { - retVal = load_rowset(number); - } - } - - return retVal; -} - -statement_backend::exec_fetch_result -sqlite3_statement_backend::fetch(int number) -{ - if (number > 1) - return load_rowset(number); - else - return load_one(); - -} - -long long sqlite3_statement_backend::get_affected_rows() -{ - if (rowsAffectedBulk_ >= 0) - { - return rowsAffectedBulk_; - } - return sqlite3_changes(session_.conn_); -} - -int sqlite3_statement_backend::get_number_of_rows() -{ - return static_cast(dataCache_.size()); -} - -std::string sqlite3_statement_backend::get_parameter_name(int index) const -{ - // Notice that SQLite host parameters are counted from 1, not 0. - char const* name = sqlite3_bind_parameter_name(stmt_, index + 1); - if (!name) - return std::string(); - - // SQLite returns parameters with the leading colon which is inconsistent - // with the other backends, so get rid of it as well several other - // characters which can be used for named parameters with SQLite. - switch (*name) - { - case ':': - case '?': - case '@': - case '$': - name++; - break; - } - - return name; -} - -std::string sqlite3_statement_backend::rewrite_for_procedure_call( - std::string const &query) -{ - return query; -} - -int sqlite3_statement_backend::prepare_for_describe() -{ - return sqlite3_column_count(stmt_); -} - -typedef std::map sqlite3_data_type_map; -static sqlite3_data_type_map get_data_type_map() -{ - sqlite3_data_type_map m; - - // dt_blob - m["blob"] = dt_blob; - - // dt_date - m["date"] = dt_date; - m["time"] = dt_date; - m["datetime"] = dt_date; - - // dt_double - m["decimal"] = dt_double; - m["double"] = dt_double; - m["double precision"] = dt_double; - m["float"] = dt_double; - m["number"] = dt_double; - m["numeric"] = dt_double; - m["real"] = dt_double; - - // dt_integer - m["boolean"] = dt_integer; - m["int"] = dt_integer; - m["integer"] = dt_integer; - m["int2"] = dt_integer; - m["mediumint"] = dt_integer; - m["smallint"] = dt_integer; - m["tinyint"] = dt_integer; - - // dt_long_long - m["bigint"] = dt_long_long; - m["int8"] = dt_long_long; - - // dt_string - m["char"] = dt_string; - m["character"] = dt_string; - m["clob"] = dt_string; - m["native character"] = dt_string; - m["nchar"] = dt_string; - m["nvarchar"] = dt_string; - m["text"] = dt_string; - m["varchar"] = dt_string; - m["varying character"] = dt_string; - - // dt_unsigned_long_long - m["unsigned big int"] = dt_unsigned_long_long; - - - return m; -} - -void sqlite3_statement_backend::describe_column(int colNum, data_type & type, - std::string & columnName) -{ - static const sqlite3_data_type_map dataTypeMap = get_data_type_map(); - - if (columns_.size() < (size_t)colNum) - columns_.resize(colNum); - sqlite3_column_info &coldef = columns_[colNum - 1]; - - if (!coldef.name_.empty()) - { - columnName = coldef.name_; - type = coldef.type_; - return; - } - - coldef.name_ = columnName = sqlite3_column_name(stmt_, colNum - 1); - - // This is a hack, but the sqlite3 type system does not - // have a date or time field. Also it does not reliably - // id other data types. It has a tendency to see everything - // as text. sqlite3_column_decltype returns the text that is - // used in the create table statement - char const* declType = sqlite3_column_decltype(stmt_, colNum-1); - - if ( declType == NULL ) - { - static char const* s_char = "char"; - declType = s_char; - } - - std::string dt = declType; - - // remove extra characters for example "(20)" in "varchar(20)" - std::string::iterator siter = std::find_if(dt.begin(), dt.end(), std::not1(std::ptr_fun(isalnum))); - if (siter != dt.end()) - dt.resize(siter - dt.begin()); - - // do all comparisons in lower case - std::transform(dt.begin(), dt.end(), dt.begin(), tolower); - - sqlite3_data_type_map::const_iterator iter = dataTypeMap.find(dt); - if (iter != dataTypeMap.end()) - { - coldef.type_ = type = iter->second; - return; - } - - // try to get it from the weak ass type system - - // total hack - execute the statment once to get the column types - // then clear so it can be executed again - sqlite3_step(stmt_); - - int const sqlite3_type = sqlite3_column_type(stmt_, colNum-1); - switch (sqlite3_type) - { - case SQLITE_INTEGER: - type = dt_integer; - break; - case SQLITE_FLOAT: - type = dt_double; - break; - case SQLITE_BLOB: - case SQLITE_TEXT: - type = dt_string; - break; - default: - type = dt_string; - break; - } - coldef.type_ = type; - - sqlite3_reset(stmt_); -} - -sqlite3_standard_into_type_backend * -sqlite3_statement_backend::make_into_type_backend() -{ - return new sqlite3_standard_into_type_backend(*this); -} - -sqlite3_standard_use_type_backend * sqlite3_statement_backend::make_use_type_backend() -{ - return new sqlite3_standard_use_type_backend(*this); -} - -sqlite3_vector_into_type_backend * -sqlite3_statement_backend::make_vector_into_type_backend() -{ - return new sqlite3_vector_into_type_backend(*this); -} - -sqlite3_vector_use_type_backend * -sqlite3_statement_backend::make_vector_use_type_backend() -{ - return new sqlite3_vector_use_type_backend(*this); -} diff --git a/src/soci/src/backends/sqlite3/vector-into-type.cpp b/src/soci/src/backends/sqlite3/vector-into-type.cpp deleted file mode 100644 index 349b0a90d4..0000000000 --- a/src/soci/src/backends/sqlite3/vector-into-type.cpp +++ /dev/null @@ -1,354 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifdef _MSC_VER -#pragma warning(disable : 4512) -#endif - -#define SOCI_SQLITE3_SOURCE -#include "soci-dtocstr.h" -#include "soci-exchange-cast.h" -#include "soci/blob.h" -#include "soci/rowid.h" -#include "soci/soci-platform.h" -#include "soci/sqlite3/soci-sqlite3.h" -#include "soci-cstrtod.h" -#include "soci-mktime.h" -#include "common.h" -// std -#include -#include -#include -#include -#include -#include - -namespace soci -{ - -void sqlite3_vector_into_type_backend::define_by_pos( - int& position, void* data, details::exchange_type type) -{ - data_ = data; - type_ = type; - position_ = position++; -} - -void sqlite3_vector_into_type_backend::pre_fetch() -{ - // ... -} - -namespace // anonymous -{ - -template -void set_in_vector(void* p, int indx, T const& val) -{ - std::vector &v = *static_cast*>(p); - v[indx] = val; -} - -template -void set_number_in_vector(void *p, int idx, const sqlite3_column &col) -{ - using namespace details; - using namespace details::sqlite3; - - switch (col.type_) - { - case dt_date: - case dt_string: - case dt_blob: - set_in_vector(p, idx, string_to_integer(col.buffer_.size_ > 0 ? col.buffer_.constData_ : "")); - break; - - case dt_double: - set_in_vector(p, idx, static_cast(col.double_)); - break; - - case dt_integer: - set_in_vector(p, idx, static_cast(col.int32_)); - break; - - case dt_long_long: - case dt_unsigned_long_long: - set_in_vector(p, idx, static_cast(col.int64_)); - break; - - case dt_xml: - throw soci_error("XML data type is not supported"); - }; -} - -} // namespace anonymous - -void sqlite3_vector_into_type_backend::post_fetch(bool gotData, indicator * ind) -{ - using namespace details; - using namespace details::sqlite3; - - if (!gotData) - { - // no data retrieved - return; - } - - int const endRow = static_cast(statement_.dataCache_.size()); - for (int i = 0; i < endRow; ++i) - { - sqlite3_column &col = statement_.dataCache_[i][position_-1]; - - if (col.isNull_) - { - if (ind == NULL) - { - throw soci_error( - "Null value fetched and no indicator defined."); - } - ind[i] = i_null; - - // nothing to do for null value, go to next row - continue; - } - - if (ind != NULL) - ind[i] = i_ok; - - // conversion - switch (type_) - { - case x_char: - { - switch (col.type_) - { - case dt_date: - case dt_string: - case dt_blob: - set_in_vector(data_, i, (col.buffer_.size_ > 0 ? col.buffer_.constData_[0] : '\0')); - break; - - case dt_double: - set_in_vector(data_, i, double_to_cstring(col.double_)[0]); - break; - - case dt_integer: - { - std::ostringstream ss; - ss << col.int32_; - set_in_vector(data_, i, ss.str()[0]); - break; - } - - case dt_long_long: - case dt_unsigned_long_long: - { - std::ostringstream ss; - ss << col.int64_; - set_in_vector(data_, i, ss.str()[0]); - break; - } - - case dt_xml: - throw soci_error("XML data type is not supported"); - }; - break; - } // x_char - - case x_stdstring: - { - switch (col.type_) - { - case dt_date: - case dt_string: - case dt_blob: - set_in_vector(data_, i, std::string(col.buffer_.constData_, col.buffer_.size_)); - break; - - case dt_double: - set_in_vector(data_, i, double_to_cstring(col.double_)); - break; - - case dt_integer: - { - std::ostringstream ss; - ss << col.int32_; - set_in_vector(data_, i, ss.str()); - break; - } - - case dt_long_long: - case dt_unsigned_long_long: - { - std::ostringstream ss; - ss << col.int64_; - set_in_vector(data_, i, ss.str()); - break; - } - - case dt_xml: - throw soci_error("XML data type is not supported"); - }; - break; - } // x_stdstring - - case x_short: - set_number_in_vector::value_type>(data_, i, col); - break; - - case x_integer: - set_number_in_vector::value_type>(data_, i, col); - break; - - case x_long_long: - set_number_in_vector::value_type>(data_, i, col); - break; - - case x_unsigned_long_long: - set_number_in_vector::value_type>(data_, i, col); - break; - - case x_double: - set_number_in_vector::value_type>(data_, i, col); - break; - - case x_stdtm: - { - switch (col.type_) - { - case dt_date: - case dt_string: - case dt_blob: - { - // attempt to parse the string and convert to std::tm - std::tm t = std::tm(); - parse_std_tm(col.buffer_.constData_, t); - - set_in_vector(data_, i, t); - break; - } - - case dt_double: - case dt_integer: - case dt_long_long: - case dt_unsigned_long_long: - throw soci_error("Into element used with non-convertible type."); - - case dt_xml: - throw soci_error("XML data type is not supported"); - }; - break; - } - - default: - throw soci_error("Into element used with non-supported type."); - } - - // cleanup data - switch (col.type_) - { - case dt_date: - case dt_string: - case dt_blob: - delete[] col.buffer_.data_; - col.buffer_.data_ = NULL; - break; - - case dt_double: - case dt_integer: - case dt_long_long: - case dt_unsigned_long_long: - break; - - case dt_xml: - throw soci_error("XML data type is not supported"); - } - } -} - -void sqlite3_vector_into_type_backend::resize(std::size_t sz) -{ - using namespace details; - using namespace details::sqlite3; - - switch (type_) - { - // simple cases - case x_char: - resize_vector(data_, sz); - break; - case x_short: - resize_vector(data_, sz); - break; - case x_integer: - resize_vector(data_, sz); - break; - case x_long_long: - resize_vector(data_, sz); - break; - case x_unsigned_long_long: - resize_vector(data_, sz); - break; - case x_double: - resize_vector(data_, sz); - break; - case x_stdstring: - resize_vector(data_, sz); - break; - case x_stdtm: - resize_vector(data_, sz); - break; - default: - throw soci_error("Into vector element used with non-supported type."); - } -} - -std::size_t sqlite3_vector_into_type_backend::size() -{ - using namespace details; - using namespace details::sqlite3; - - std::size_t sz = 0; // dummy initialization to please the compiler - switch (type_) - { - // simple cases - case x_char: - sz = get_vector_size(data_); - break; - case x_short: - sz = get_vector_size(data_); - break; - case x_integer: - sz = get_vector_size(data_); - break; - case x_long_long: - sz = get_vector_size(data_); - break; - case x_unsigned_long_long: - sz = get_vector_size(data_); - break; - case x_double: - sz = get_vector_size(data_); - break; - case x_stdstring: - sz = get_vector_size(data_); - break; - case x_stdtm: - sz = get_vector_size(data_); - break; - default: - throw soci_error("Into vector element used with non-supported type."); - } - - return sz; -} - -void sqlite3_vector_into_type_backend::clean_up() -{ -} - -} // namespace soci diff --git a/src/soci/src/backends/sqlite3/vector-use-type.cpp b/src/soci/src/backends/sqlite3/vector-use-type.cpp deleted file mode 100644 index 1ae3ab1007..0000000000 --- a/src/soci/src/backends/sqlite3/vector-use-type.cpp +++ /dev/null @@ -1,215 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SQLITE3_SOURCE -#include "soci-exchange-cast.h" -#include "soci/soci-platform.h" -#include "soci/sqlite3/soci-sqlite3.h" -#include "soci-dtocstr.h" -#include "common.h" -// std -#include -#include -#include -#include -#include - - -using namespace soci; -using namespace soci::details; -using namespace soci::details::sqlite3; - -void sqlite3_vector_use_type_backend::bind_by_pos(int & position, - void * data, - exchange_type type) -{ - if (statement_.boundByName_) - { - throw soci_error( - "Binding for use elements must be either by position or by name."); - } - - data_ = data; - type_ = type; - position_ = position++; - - statement_.boundByPos_ = true; -} - -void sqlite3_vector_use_type_backend::bind_by_name(std::string const & name, - void * data, - exchange_type type) -{ - if (statement_.boundByPos_) - { - throw soci_error( - "Binding for use elements must be either by position or by name."); - } - - data_ = data; - type_ = type; - name_ = ":" + name; - - statement_.reset_if_needed(); - position_ = sqlite3_bind_parameter_index(statement_.stmt_, name_.c_str()); - - if (0 == position_) - { - std::ostringstream ss; - ss << "Cannot bind (by name) to " << name_; - throw soci_error(ss.str()); - } - statement_.boundByName_ = true; -} - -void sqlite3_vector_use_type_backend::pre_use(indicator const * ind) -{ - std::size_t const vsize = size(); - - // make sure that useData can hold enough rows - if (statement_.useData_.size() != vsize) - statement_.useData_.resize(vsize); - - int const pos = position_ - 1; - - for (size_t i = 0; i != vsize; ++i) - { - // make sure that each row can accomodate the number of columns - if (statement_.useData_[i].size() < static_cast(position_)) - statement_.useData_[i].resize(position_); - - sqlite3_column &col = statement_.useData_[i][pos]; - - // the data in vector can be either i_ok or i_null - if (ind != NULL && ind[i] == i_null) - { - col.isNull_ = true; - col.buffer_.data_ = NULL; - continue; - } - - col.isNull_ = false; - - switch (type_) - { - case x_char: - col.type_ = dt_string; - col.buffer_.constData_ = &(*static_cast::value_type> *>(data_))[i]; - col.buffer_.size_ = 1; - break; - - case x_stdstring: - { - std::string &s = (*static_cast::value_type> *>(data_))[i]; - col.type_ = dt_string; - col.buffer_.constData_ = s.c_str(); - col.buffer_.size_ = s.size(); - break; - } - - case x_short: - col.type_ = dt_integer; - col.int32_ = (*static_cast::value_type> *>(data_))[i]; - break; - - case x_integer: - col.type_ = dt_integer; - col.int32_ = (*static_cast::value_type> *>(data_))[i]; - break; - - case x_long_long: - col.type_ = dt_long_long; - col.int64_ = (*static_cast::value_type> *>(data_))[i]; - break; - - case x_unsigned_long_long: - col.type_ = dt_long_long; - col.int64_ = (*static_cast::value_type> *>(data_))[i]; - break; - - case x_double: - col.type_ = dt_double; - col.double_ = (*static_cast::value_type> *>(data_))[i]; - break; - - case x_stdtm: - { - std::tm &tm = (*static_cast::value_type> *>(data_))[i]; - static const size_t bufSize = 20; - - col.type_ = dt_date; - col.buffer_.data_ = new char[bufSize]; - col.buffer_.size_ - = snprintf(col.buffer_.data_, bufSize, "%d-%02d-%02d %02d:%02d:%02d", - tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, - tm.tm_hour, tm.tm_min, tm.tm_sec - ); - break; - } - - default: - throw soci_error( - "Use vector element used with non-supported type."); - } - } -} - -std::size_t sqlite3_vector_use_type_backend::size() -{ - std::size_t sz = 0; // dummy initialization to please the compiler - switch (type_) - { - // simple cases - case x_char: - sz = get_vector_size(data_); - break; - case x_short: - sz = get_vector_size(data_); - break; - case x_integer: - sz = get_vector_size(data_); - break; - case x_long_long: - sz = get_vector_size(data_); - break; - case x_unsigned_long_long: - sz = get_vector_size(data_); - break; - case x_double: - sz = get_vector_size(data_); - break; - case x_stdstring: - sz = get_vector_size(data_); - break; - case x_stdtm: - sz = get_vector_size(data_); - break; - default: - throw soci_error("Use vector element used with non-supported type."); - } - - return sz; -} - -void sqlite3_vector_use_type_backend::clean_up() -{ - if (type_ != x_stdtm) - return; - - int const pos = position_ - 1; - - for (sqlite3_recordset::iterator iter = statement_.useData_.begin(), last = statement_.useData_.end(); - iter != last; ++iter) - { - sqlite3_column &col = (*iter)[pos]; - - if (col.isNull_) - continue; - - delete[] col.buffer_.data_; - } -} diff --git a/src/soci/src/core/.gitignore b/src/soci/src/core/.gitignore deleted file mode 100644 index 64ec3b6829..0000000000 --- a/src/soci/src/core/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -*.o -*.la -*.lo -.deps -.libs diff --git a/src/soci/src/core/CMakeLists.txt b/src/soci/src/core/CMakeLists.txt deleted file mode 100644 index 3916cce4db..0000000000 --- a/src/soci/src/core/CMakeLists.txt +++ /dev/null @@ -1,139 +0,0 @@ -############################################################################### -# -# This file is part of CMake configuration for SOCI library -# -# Copyright (C) 2009-2013 Mateusz Loskot -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -# -############################################################################### -colormsg(_HIBLUE_ "Configuring SOCI core library:") - -# Set INCLUDE_DIRECTORIES -get_directory_property(SOCI_CORE_INCLUDE_DIRS INCLUDE_DIRECTORIES) -list(APPEND SOCI_CORE_INCLUDE_DIRS ${CMAKE_CURRENT_BINARY_DIR}) -set_directory_properties(PROPERTIES - INCLUDE_DIRECTORIES "${SOCI_CORE_INCLUDE_DIRS}") - -# Configure backend loader to also use default install directory. -configure_file(soci_backends_config.h.in - ${CMAKE_CURRENT_BINARY_DIR}/soci_backends_config.h) - -# Core source files -file(GLOB SOCI_CORE_HEADERS ${SOCI_SOURCE_DIR}/include/soci/*.h) -file(GLOB SOCI_CORE_SOURCES *.cpp) - -# Group source files for IDE source explorers (e.g. Visual Studio) -source_group("Header Files" FILES ${SOCI_CORE_HEADERS}) -source_group("Source Files" FILES ${SOCI_CORE_SOURCES}) -source_group("CMake Files" FILES CMakeLists.txt) - -# Core targets configuration -string(TOLOWER "${PROJECT_NAME}" PROJECTNAMEL) -#this command will update parent scope variable -set(SOCI_CORE_TARGET ${PROJECTNAMEL}_core PARENT_SCOPE) -set(SOCI_CORE_TARGET ${PROJECTNAMEL}_core) - -soci_target_output_name(${SOCI_CORE_TARGET} SOCI_CORE_TARGET_OUTPUT_NAME) - -# -# Core shared library -# -if (SOCI_SHARED) - add_library(${SOCI_CORE_TARGET} SHARED ${SOCI_CORE_HEADERS} ${SOCI_CORE_SOURCES}) - - target_link_libraries(${SOCI_CORE_TARGET} ${SOCI_CORE_DEPS_LIBS}) - - if(WIN32) - set_target_properties(${SOCI_CORE_TARGET} - PROPERTIES - DEFINE_SYMBOL SOCI_DLL - OUTPUT_NAME "${SOCI_CORE_TARGET_OUTPUT_NAME}" - VERSION ${SOCI_VERSION} - CLEAN_DIRECT_OUTPUT 1) - else() - set_target_properties(${SOCI_CORE_TARGET} - PROPERTIES - VERSION ${SOCI_VERSION} - SOVERSION ${SOCI_SOVERSION} - INSTALL_NAME_DIR ${CMAKE_INSTALL_PREFIX}/lib - CLEAN_DIRECT_OUTPUT 1) - endif() - - target_include_directories(${SOCI_CORE_TARGET} - PUBLIC - $ - ) - -endif() - -# This adds definitions to all build configurations. SOCI_DEBUG_POSTFIX is passed to soci library -add_definitions(-DSOCI_LIB_PREFIX="${CMAKE_SHARED_LIBRARY_PREFIX}soci_" - -DSOCI_LIB_SUFFIX="${CMAKE_SHARED_LIBRARY_SUFFIX}" - -DSOCI_DEBUG_POSTFIX="${CMAKE_DEBUG_POSTFIX}") - -# -# Core static library -# -if (SOCI_STATIC) - set(SOCI_CORE_TARGET_STATIC ${SOCI_CORE_TARGET}_static) - - add_library(${SOCI_CORE_TARGET_STATIC} STATIC - ${SOCI_CORE_HEADERS} ${SOCI_CORE_SOURCES}) - - # we still need to link against dl if we have it - target_link_libraries (${SOCI_CORE_TARGET_STATIC} - ${SOCI_CORE_DEPS_LIBS} - ) - - set_target_properties(${SOCI_CORE_TARGET_STATIC} - PROPERTIES - OUTPUT_NAME ${SOCI_CORE_TARGET_OUTPUT_NAME} - PREFIX "lib" - CLEAN_DIRECT_OUTPUT 1) - - target_include_directories(${SOCI_CORE_TARGET_STATIC} - PUBLIC - $ - ) - -endif() - - - - -# -# Core installation -# -install(FILES ${SOCI_CORE_HEADERS} DESTINATION ${INCLUDEDIR}/${PROJECTNAMEL}) - -if (SOCI_SHARED) - install(TARGETS ${SOCI_CORE_TARGET} - EXPORT SOCI - RUNTIME DESTINATION ${BINDIR} - LIBRARY DESTINATION ${LIBDIR} - ARCHIVE DESTINATION ${LIBDIR}) -endif() - -if (SOCI_STATIC) - install(TARGETS ${SOCI_CORE_TARGET_STATIC} - EXPORT SOCI - RUNTIME DESTINATION ${BINDIR} - LIBRARY DESTINATION ${LIBDIR} - ARCHIVE DESTINATION ${LIBDIR}) -endif() - -install(EXPORT SOCI NAMESPACE SOCI:: DESTINATION cmake) - -# -# Core configuration summary -# -boost_report_value(SOCI_CORE_TARGET) -boost_report_value(SOCI_CORE_TARGET_OUTPUT_NAME) -boost_report_value(SOCI_CORE_DEPS_LIBS) -boost_report_value(SOCI_CORE_INCLUDE_DIRS) -boost_report_value(WITH_BOOST) -soci_report_directory_property(COMPILE_DEFINITIONS) - -message(STATUS "") diff --git a/src/soci/src/core/Makefile.basic b/src/soci/src/core/Makefile.basic deleted file mode 100644 index bd5f78d869..0000000000 --- a/src/soci/src/core/Makefile.basic +++ /dev/null @@ -1,94 +0,0 @@ -COMPILER = g++ -CXXFLAGS = -Wall -pedantic -Wno-long-long -INCLUDEDIRS = -I../../include -I../../include/private - -BACKENDLOADERDEFS = -DSOCI_LIB_PREFIX=\"libsoci_\" -DSOCI_LIB_SUFFIX=\".so\" - -OBJS = session.o statement.o row.o values.o \ - into-type.o use-type.o \ - blob.o rowid.o procedure.o ref-counted-prepare-info.o ref-counted-statement.o \ - once-temp-type.o prepare-temp-type.o error.o transaction.o backend-loader.o \ - connection-pool.o connection-parameters.o soci-simple.o - - -libsoci_core.a : generated ${OBJS} - ar rv $@ ${OBJS} - rm *.o - -shared : generated ${OBJS} - ${COMPILER} -fPIC -c ${OBJS} ${CXXFLAGS} ${INCLUDEDIRS} - ${COMPILER} -shared -o libsoci_core.so ${OBJS} - rm *.o - -generated : ../../include/soci/soci-config.h ../../include/private/soci_backends_config.h - -# Note: this file is generated without any configured variables, -# full configuration fill is generated by CMake. -../../include/soci/soci-config.h : ../../include/soci/soci-config.h.in - grep -v CONFIGURED_VARIABLES $? > $@ - -# Note: this file is generated with a basic search path, -# full backends search path is generated by CMake. -../../include/private/soci_backends_config.h : soci_backends_config.h.in - echo '#define DEFAULT_BACKENDS_PATH "."' > $@ - -session.o : session.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -statement.o : statement.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -row.o : row.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -values.o : values.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -into-type.o : into-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -use-type.o : use-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -blob.o : blob.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -error.o : error.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -rowid.o : rowid.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -procedure.o : procedure.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -ref-counted-prepare-info.o : ref-counted-prepare-info.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -ref-counted-statement.o : ref-counted-statement.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -once-temp-type.o : once-temp-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -prepare-temp-type.o : prepare-temp-type.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -transaction.o : transaction.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -backend-loader.o : backend-loader.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${BACKENDLOADERDEFS} ${INCLUDEDIRS} - -connection-pool.o : connection-pool.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -connection-parameters.o : connection-parameters.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - -soci-simple.o : soci-simple.cpp - ${COMPILER} -c $? ${CXXFLAGS} ${INCLUDEDIRS} - - -clean : - rm -f libsoci_core.a libsoci_core.so ../../include/private/soci_backends_config.h diff --git a/src/soci/src/core/backend-loader.cpp b/src/soci/src/core/backend-loader.cpp deleted file mode 100644 index 456b2a7588..0000000000 --- a/src/soci/src/core/backend-loader.cpp +++ /dev/null @@ -1,349 +0,0 @@ -// -// Copyright (C) 2008 Maciej Sobczak with contributions from Artyom Tonkikh -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SOURCE -#include "soci/soci-platform.h" -#include "soci/backend-loader.h" -#include "soci/error.h" -#include -#include -#include -#include -#ifndef _MSC_VER -#include -#endif - -#include "soci_backends_config.h" - -using namespace soci; -using namespace soci::dynamic_backends; - -#ifdef _WIN32 - -#include - -typedef CRITICAL_SECTION soci_mutex_t; -typedef HMODULE soci_handler_t; - -#define LOCK(x) EnterCriticalSection(x) -#define UNLOCK(x) LeaveCriticalSection(x) -#define MUTEX_INIT(x) InitializeCriticalSection(x) -#define MUTEX_DEST(x) DeleteCriticalSection(x) -#ifdef _UNICODE -#define DLOPEN(x) LoadLibraryA(x) -#else -#define DLOPEN(x) LoadLibrary(x) -#endif -#define DLCLOSE(x) FreeLibrary(x) -#define DLSYM(x, y) GetProcAddress(x, y) - -#ifdef SOCI_ABI_VERSION - #ifndef NDEBUG - #define LIBNAME(x) (SOCI_LIB_PREFIX + x + "_" SOCI_ABI_VERSION SOCI_DEBUG_POSTFIX SOCI_LIB_SUFFIX) - #else - #define LIBNAME(x) (SOCI_LIB_PREFIX + x + "_" SOCI_ABI_VERSION SOCI_LIB_SUFFIX) - #endif -#else -#define LIBNAME(x) (SOCI_LIB_PREFIX + x + SOCI_LIB_SUFFIX) -#endif // SOCI_ABI_VERSION - -#else - -#include -#include - -typedef pthread_mutex_t soci_mutex_t; -typedef void * soci_handler_t; - -#define LOCK(x) pthread_mutex_lock(x) -#define UNLOCK(x) pthread_mutex_unlock(x) -#define MUTEX_INIT(x) pthread_mutex_init(x, NULL) -#define MUTEX_DEST(x) pthread_mutex_destroy(x) -#define DLOPEN(x) dlopen(x, RTLD_LAZY) -#define DLCLOSE(x) dlclose(x) -#define DLSYM(x, y) dlsym(x, y) - -#ifdef SOCI_ABI_VERSION - -#ifdef __APPLE__ -#define LIBNAME(x) (SOCI_LIB_PREFIX + x + "." SOCI_ABI_VERSION SOCI_LIB_SUFFIX) -#else -#define LIBNAME(x) (SOCI_LIB_PREFIX + x + SOCI_LIB_SUFFIX "." SOCI_ABI_VERSION) -#endif - -#else -#define LIBNAME(x) (SOCI_LIB_PREFIX + x + SOCI_LIB_SUFFIX) -#endif // SOCI_ABI_VERSION - -#endif // _WIN32 - - -namespace // unnamed -{ - -struct info -{ - soci_handler_t handler_; - backend_factory const * factory_; - info() : handler_(0), factory_(0) {} -}; - -typedef std::map factory_map; -factory_map factories_; - -std::vector search_paths_; - -soci_mutex_t mutex_; - -std::vector get_default_paths() -{ - std::vector paths; - - // TODO: may be problem with finding getenv in std namespace in Visual C++ --mloskot - char const* const penv = std::getenv("SOCI_BACKENDS_PATH"); - if (0 == penv) - { - paths.push_back("."); - paths.push_back(DEFAULT_BACKENDS_PATH); - return paths; - } - - std::string const env = penv; - if (env.empty()) - { - paths.push_back("."); - paths.push_back(DEFAULT_BACKENDS_PATH); - return paths; - } - - std::string::size_type searchFrom = 0; - while (searchFrom != env.size()) - { - std::string::size_type const found = env.find(":", searchFrom); - if (found == searchFrom) - { - ++searchFrom; - } - else if (std::string::npos != found) - { - std::string const path(env.substr(searchFrom, found - searchFrom)); - paths.push_back(path); - - searchFrom = found + 1; - } - else // found == npos - { - std::string const path = env.substr(searchFrom); - paths.push_back(path); - - searchFrom = env.size(); - } - } - - return paths; -} - -// used to automatically initialize the global state -struct static_state_mgr -{ - static_state_mgr() - { - MUTEX_INIT(&mutex_); - - search_paths_ = get_default_paths(); - } - - ~static_state_mgr() - { - unload_all(); - - MUTEX_DEST(&mutex_); - } -} static_state_mgr_; - -class scoped_lock -{ -public: - scoped_lock(soci_mutex_t * m) : mptr(m) { LOCK(m); }; - ~scoped_lock() { UNLOCK(mptr); }; -private: - soci_mutex_t * mptr; -}; - -// non-synchronized helper for the other functions -void do_unload(std::string const & name) -{ - factory_map::iterator i = factories_.find(name); - - if (i != factories_.end()) - { - soci_handler_t h = i->second.handler_; - if (h != NULL) - { - DLCLOSE(h); - } - - factories_.erase(i); - } -} - -// non-synchronized helper -void do_register_backend(std::string const & name, std::string const & shared_object) -{ - // The rules for backend search are as follows: - // - if the shared_object is given, - // it names the library file and the search paths are not used - // - otherwise (shared_object not provided or empty): - // - file named libsoci_NAME.so.SOVERSION is searched in the list of search paths - - soci_handler_t h = 0; - if (shared_object.empty() == false) - { - h = DLOPEN(shared_object.c_str()); - } - else - { - // try system paths - h = DLOPEN(LIBNAME(name).c_str()); - if (0 == h) - { - // try all search paths - for (std::size_t i = 0; i != search_paths_.size(); ++i) - { - std::string const fullFileName(search_paths_[i] + "/" + LIBNAME(name)); - h = DLOPEN(fullFileName.c_str()); - if (0 != h) - { - // already found - break; - } - } - } - } - - if (0 == h) - { - throw soci_error("Failed to find shared library for backend " + name); - } - - std::string symbol = "factory_" + name; - - typedef backend_factory const * bfc_ptr; - typedef bfc_ptr (*get_t)(void); - get_t entry; - entry = reinterpret_cast( - reinterpret_cast(DLSYM(h, symbol.c_str()))); - - if (0 == entry) - { - DLCLOSE(h); - throw soci_error("Failed to resolve dynamic symbol: " + symbol); - } - - // unload the existing handler if it's already loaded - - do_unload(name); - - backend_factory const* f = entry(); - - info new_entry; - new_entry.factory_ = f; - new_entry.handler_ = h; - - factories_[name] = new_entry; -} - -} // unnamed namespace - -backend_factory const& dynamic_backends::get(std::string const& name) -{ - scoped_lock lock(&mutex_); - - factory_map::iterator i = factories_.find(name); - - if (i != factories_.end()) - { - return *(i->second.factory_); - } - - // no backend found with this name, try to register it first - - do_register_backend(name, std::string()); - - // second attempt, must succeed (the backend is already loaded) - - i = factories_.find(name); - - return *(i->second.factory_); -} - -SOCI_DECL std::vector& search_paths() -{ - return search_paths_; -} - -SOCI_DECL void dynamic_backends::register_backend( - std::string const& name, std::string const& shared_object) -{ - scoped_lock lock(&mutex_); - - do_register_backend(name, shared_object); -} - -SOCI_DECL void dynamic_backends::register_backend( - std::string const& name, backend_factory const& factory) -{ - scoped_lock lock(&mutex_); - - // unload the existing handler if it's already loaded - - do_unload(name); - - info new_entry; - new_entry.factory_ = &factory; - - factories_[name] = new_entry; -} - -SOCI_DECL std::vector dynamic_backends::list_all() -{ - scoped_lock lock(&mutex_); - - std::vector ret; - ret.reserve(factories_.size()); - - for (factory_map::iterator i = factories_.begin(); i != factories_.end(); ++i) - { - std::string const& name = i->first; - ret.push_back(name); - } - - return ret; -} - -SOCI_DECL void dynamic_backends::unload(std::string const& name) -{ - scoped_lock lock(&mutex_); - - do_unload(name); -} - -SOCI_DECL void dynamic_backends::unload_all() -{ - scoped_lock lock(&mutex_); - - for (factory_map::iterator i = factories_.begin(); i != factories_.end(); ++i) - { - soci_handler_t h = i->second.handler_; - if (0 != h) - { - DLCLOSE(h); - } - } - - factories_.clear(); -} diff --git a/src/soci/src/core/blob.cpp b/src/soci/src/core/blob.cpp deleted file mode 100644 index bcb66f7bef..0000000000 --- a/src/soci/src/core/blob.cpp +++ /dev/null @@ -1,62 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SOURCE -#include "soci/blob.h" -#include "soci/session.h" - -#include - -using namespace soci; - -blob::blob(session & s) -{ - backEnd_ = s.make_blob_backend(); -} - -blob::~blob() -{ - delete backEnd_; -} - -std::size_t blob::get_len() -{ - return backEnd_->get_len(); -} - -std::size_t blob::read(std::size_t offset, char *buf, std::size_t toRead) -{ - return backEnd_->read(offset, buf, toRead); -} - -std::size_t blob::read_from_start(char * buf, std::size_t toRead, - std::size_t offset) -{ - return backEnd_->read_from_start(buf, toRead, offset); -} - -std::size_t blob::write( - std::size_t offset, char const * buf, std::size_t toWrite) -{ - return backEnd_->write(offset, buf, toWrite); -} - -std::size_t blob::write_from_start(const char * buf, std::size_t toWrite, - std::size_t offset) -{ - return backEnd_->write_from_start(buf, toWrite, offset); -} - -std::size_t blob::append(char const * buf, std::size_t toWrite) -{ - return backEnd_->append(buf, toWrite); -} - -void blob::trim(std::size_t newLen) -{ - backEnd_->trim(newLen); -} diff --git a/src/soci/src/core/common.cpp b/src/soci/src/core/common.cpp deleted file mode 100644 index ed8cfd52da..0000000000 --- a/src/soci/src/core/common.cpp +++ /dev/null @@ -1,93 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Copyright (C) 2017 Vadim Zeitlin. -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SOURCE -#include "soci/error.h" -#include "soci-mktime.h" -#include -#include -#include - -namespace // anonymous -{ - -// helper function for parsing decimal data (for std::tm) -int parse10(char const * & p1, char * & p2) -{ - long v = std::strtol(p1, &p2, 10); - if (p2 != p1) - { - if (v < 0) - throw soci::soci_error("Negative date/time field component."); - - if (v > INT_MAX) - throw soci::soci_error("Out of range date/time field component."); - - p1 = p2 + 1; - - // Cast is safe due to check above. - return static_cast(v); - } - else - { - throw soci::soci_error("Cannot parse date/time field component."); - - } -} - -} // namespace anonymous - -void soci::details::parse_std_tm(char const * buf, std::tm & t) -{ - char const * p1 = buf; - char * p2; - char separator; - int a, b, c; - int year = 1900, month = 1, day = 1; - int hour = 0, minute = 0, second = 0; - - a = parse10(p1, p2); - separator = *p2; - b = parse10(p1, p2); - c = parse10(p1, p2); - - if (*p2 == ' ') - { - // there are more elements to parse - // - assume that what was already parsed is a date part - // and that the remaining elements describe the time of day - year = a; - month = b; - day = c; - hour = parse10(p1, p2); - minute = parse10(p1, p2); - second = parse10(p1, p2); - } - else - { - // only three values have been parsed - if (separator == '-') - { - // assume the date value was read - // (leave the time of day as 00:00:00) - year = a; - month = b; - day = c; - } - else - { - // assume the time of day was read - // (leave the date part as 1900-01-01) - hour = a; - minute = b; - second = c; - } - } - - mktime_from_ymdhms(t, year, month, day, hour, minute, second); -} diff --git a/src/soci/src/core/connection-parameters.cpp b/src/soci/src/core/connection-parameters.cpp deleted file mode 100644 index 1b5947071f..0000000000 --- a/src/soci/src/core/connection-parameters.cpp +++ /dev/null @@ -1,62 +0,0 @@ -// -// Copyright (C) 2013 Vadim Zeitlin -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SOURCE -#include "soci/connection-parameters.h" -#include "soci/soci-backend.h" -#include "soci/backend-loader.h" - -using namespace soci; - -namespace // anonymous -{ - -void parseConnectString(std::string const & connectString, - std::string & backendName, - std::string & connectionParameters) -{ - std::string const protocolSeparator = "://"; - - std::string::size_type const p = connectString.find(protocolSeparator); - if (p == std::string::npos) - { - throw soci_error("No backend name found in " + connectString); - } - - backendName = connectString.substr(0, p); - connectionParameters = connectString.substr(p + protocolSeparator.size()); -} - -} // namespace anonymous - -connection_parameters::connection_parameters() - : factory_(NULL) -{ -} - -connection_parameters::connection_parameters(backend_factory const & factory, - std::string const & connectString) - : factory_(&factory), connectString_(connectString) -{ -} - -connection_parameters::connection_parameters(std::string const & backendName, - std::string const & connectString) - : factory_(&dynamic_backends::get(backendName)), connectString_(connectString) -{ -} - -connection_parameters::connection_parameters(std::string const & fullConnectString) -{ - std::string backendName; - std::string connectString; - - parseConnectString(fullConnectString, backendName, connectString); - - factory_ = &dynamic_backends::get(backendName); - connectString_ = connectString; -} diff --git a/src/soci/src/core/connection-pool.cpp b/src/soci/src/core/connection-pool.cpp deleted file mode 100644 index 34a128e3a9..0000000000 --- a/src/soci/src/core/connection-pool.cpp +++ /dev/null @@ -1,326 +0,0 @@ -// -// Copyright (C) 2008 Maciej Sobczak -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SOURCE -#include "soci/connection-pool.h" -#include "soci/error.h" -#include "soci/session.h" -#include -#include - -#ifndef _WIN32 -// POSIX implementation - -#include -#include -#include - -using namespace soci; - -struct connection_pool::connection_pool_impl -{ - bool find_free(std::size_t & pos) - { - for (std::size_t i = 0; i != sessions_.size(); ++i) - { - if (sessions_[i].first) - { - pos = i; - return true; - } - } - - return false; - } - - // by convention, first == true means the entry is free (not used) - std::vector > sessions_; - pthread_mutex_t mtx_; - pthread_cond_t cond_; -}; - -connection_pool::connection_pool(std::size_t size) -{ - if (size == 0) - { - throw soci_error("Invalid pool size"); - } - - pimpl_ = new connection_pool_impl(); - pimpl_->sessions_.resize(size); - for (std::size_t i = 0; i != size; ++i) - { - pimpl_->sessions_[i] = std::make_pair(true, new session()); - } - - int cc = pthread_mutex_init(&(pimpl_->mtx_), NULL); - if (cc != 0) - { - throw soci_error("Synchronization error"); - } - - cc = pthread_cond_init(&(pimpl_->cond_), NULL); - if (cc != 0) - { - throw soci_error("Synchronization error"); - } -} - -connection_pool::~connection_pool() -{ - for (std::size_t i = 0; i != pimpl_->sessions_.size(); ++i) - { - delete pimpl_->sessions_[i].second; - } - - pthread_mutex_destroy(&(pimpl_->mtx_)); - pthread_cond_destroy(&(pimpl_->cond_)); - - delete pimpl_; -} - -bool connection_pool::try_lease(std::size_t & pos, int timeout) -{ - struct timespec tm; - if (timeout >= 0) - { - // timeout is relative in milliseconds - - struct timeval tmv; - gettimeofday(&tmv, NULL); - - tm.tv_sec = tmv.tv_sec + timeout / 1000; - tm.tv_nsec = tmv.tv_usec * 1000 + (timeout % 1000) * 1000 * 1000; - - if (tm.tv_nsec >= 1000 * 1000 * 1000) - { - ++tm.tv_sec; - tm.tv_nsec -= 1000 * 1000 * 1000; - } - } - - int cc = pthread_mutex_lock(&(pimpl_->mtx_)); - if (cc != 0) - { - throw soci_error("Synchronization error"); - } - - while (pimpl_->find_free(pos) == false) - { - if (timeout < 0) - { - // no timeout, allow unlimited blocking - cc = pthread_cond_wait(&(pimpl_->cond_), &(pimpl_->mtx_)); - } - else - { - // wait with timeout - cc = pthread_cond_timedwait( - &(pimpl_->cond_), &(pimpl_->mtx_), &tm); - } - - if (cc == ETIMEDOUT) - { - break; - } - } - - if (cc == 0) - { - pimpl_->sessions_[pos].first = false; - } - - pthread_mutex_unlock(&(pimpl_->mtx_)); - - if (cc != 0) - { - // we can only fail if timeout expired - if (timeout < 0) - { - throw soci_error("Getting connection from the pool unexpectedly failed"); - } - - return false; - } - - return true; -} - -void connection_pool::give_back(std::size_t pos) -{ - if (pos >= pimpl_->sessions_.size()) - { - throw soci_error("Invalid pool position"); - } - - int cc = pthread_mutex_lock(&(pimpl_->mtx_)); - if (cc != 0) - { - throw soci_error("Synchronization error"); - } - - if (pimpl_->sessions_[pos].first) - { - pthread_mutex_unlock(&(pimpl_->mtx_)); - throw soci_error("Cannot release pool entry (already free)"); - } - - pimpl_->sessions_[pos].first = true; - - pthread_mutex_unlock(&(pimpl_->mtx_)); - - pthread_cond_signal(&(pimpl_->cond_)); -} - -#else -// Windows implementation - -#include - -using namespace soci; - -struct connection_pool::connection_pool_impl -{ - bool find_free(std::size_t & pos) - { - for (std::size_t i = 0; i != sessions_.size(); ++i) - { - if (sessions_[i].first) - { - pos = i; - return true; - } - } - - return false; - } - - // by convention, first == true means the entry is free (not used) - std::vector > sessions_; - - CRITICAL_SECTION mtx_; - HANDLE sem_; -}; - -connection_pool::connection_pool(std::size_t size) -{ - if (size == 0) - { - throw soci_error("Invalid pool size"); - } - - pimpl_ = new connection_pool_impl(); - pimpl_->sessions_.resize(size); - for (std::size_t i = 0; i != size; ++i) - { - pimpl_->sessions_[i] = std::make_pair(true, new session()); - } - - InitializeCriticalSection(&(pimpl_->mtx_)); - - // initially all entries are available - HANDLE s = CreateSemaphore(NULL, - static_cast(size), static_cast(size), NULL); - if (s == NULL) - { - throw soci_error("Synchronization error"); - } - - pimpl_->sem_ = s; -} - -connection_pool::~connection_pool() -{ - for (std::size_t i = 0; i != pimpl_->sessions_.size(); ++i) - { - delete pimpl_->sessions_[i].second; - } - - DeleteCriticalSection(&(pimpl_->mtx_)); - CloseHandle(pimpl_->sem_); - - delete pimpl_; -} - -bool connection_pool::try_lease(std::size_t & pos, int timeout) -{ - DWORD cc = WaitForSingleObject(pimpl_->sem_, - timeout >= 0 ? static_cast(timeout) : INFINITE); - if (cc == WAIT_OBJECT_0) - { - // semaphore acquired, there is (at least) one free entry - - EnterCriticalSection(&(pimpl_->mtx_)); - - if (!pimpl_->find_free(pos)) - { - // this should be impossible - throw soci_error("Getting connection from the pool unexpectedly failed"); - } - - pimpl_->sessions_[pos].first = false; - - LeaveCriticalSection(&(pimpl_->mtx_)); - - return true; - } - else if (cc == WAIT_TIMEOUT) - { - return false; - } - else - { - throw soci_error("Synchronization error"); - } -} - -void connection_pool::give_back(std::size_t pos) -{ - if (pos >= pimpl_->sessions_.size()) - { - throw soci_error("Invalid pool position"); - } - - EnterCriticalSection(&(pimpl_->mtx_)); - - if (pimpl_->sessions_[pos].first) - { - LeaveCriticalSection(&(pimpl_->mtx_)); - throw soci_error("Cannot release pool entry (already free)"); - } - - pimpl_->sessions_[pos].first = true; - - LeaveCriticalSection(&(pimpl_->mtx_)); - - ReleaseSemaphore(pimpl_->sem_, 1, NULL); -} - -#endif // _WIN32 - -session & connection_pool::at(std::size_t pos) -{ - if (pos >= pimpl_->sessions_.size()) - { - throw soci_error("Invalid pool position"); - } - - return *(pimpl_->sessions_[pos].second); -} - -std::size_t connection_pool::lease() -{ - // dummy default value avoids compiler warning, never leaks to client - std::size_t pos(0); - - // no timeout, so can't fail - try_lease(pos, -1); - - return pos; -} - - diff --git a/src/soci/src/core/error.cpp b/src/soci/src/core/error.cpp deleted file mode 100644 index 3a83df5358..0000000000 --- a/src/soci/src/core/error.cpp +++ /dev/null @@ -1,147 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Copyright (C) 2015 Vadim Zeitlin -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SOURCE - -#include "soci/error.h" - -#include -#include - -namespace soci -{ - -class soci_error_extra_info -{ -public: - soci_error_extra_info() - { - } - - // Default copy ctor, assignment operator and dtor are fine. - - char const* get_full_message(std::string const& message) - { - if (full_message_.empty()) - { - full_message_ = message; - - if (!contexts_.empty()) - { - // This is a hack, but appending the extra context to the - // message looks much better if we remove the full stop at its - // end first. - if (*full_message_.rbegin() == '.') - full_message_.erase(full_message_.size() - 1); - - // Now do append all the extra context we have. - typedef std::vector::const_iterator iter_type; - for (iter_type i = contexts_.begin(); i != contexts_.end(); ++i) - { - full_message_ += " "; - full_message_ += *i; - } - - // It seems better to always terminate the full message with a - // full stop, even if the original error message didn't have it - // (and if it had, we just restore the one we chopped off). - full_message_ += "."; - } - } - - return full_message_.c_str(); - } - - void add_context(std::string const& context) - { - full_message_.clear(); - contexts_.push_back(context); - } - -private: - // The full error message, we need to store it as a string as we return a - // pointer to its contents from get_full_message(). - std::string full_message_; - - // If non-empty, contains extra context for this exception, e.g. - // information about the SQL statement that resulted in it, with the top - // element corresponding to the most global context. - std::vector contexts_; -}; - -namespace -{ - -// Make a safe, even in presence of exceptions, heap-allocated copy of the -// given object if it's non-null (otherwise just return null pointer). -soci_error_extra_info *make_safe_copy(soci_error_extra_info* info) -{ - try - { - return info ? new soci_error_extra_info(*info) : NULL; - } - catch (...) - { - // Copy ctor of an exception class shouldn't throw to avoid program - // termination, so it's better to lose the extra information than allow - // an exception to except from here. - return NULL; - } -} - -} // anonymous namespace - -soci_error::soci_error(std::string const & msg) - : std::runtime_error(msg) -{ - info_ = NULL; -} - -soci_error::soci_error(soci_error const& e) - : std::runtime_error(e) -{ - info_ = make_safe_copy(e.info_); -} - -soci_error& soci_error::operator=(soci_error const& e) -{ - std::runtime_error::operator=(e); - - delete info_; - info_ = make_safe_copy(e.info_); - - return *this; -} - -soci_error::~soci_error() throw() -{ - delete info_; -} - -std::string soci_error::get_error_message() const -{ - return std::runtime_error::what(); -} - -char const* soci_error::what() const throw() -{ - if (info_) - return info_->get_full_message(get_error_message()); - - return std::runtime_error::what(); -} - -void soci_error::add_context(std::string const& context) -{ - if (!info_) - info_ = new soci_error_extra_info(); - - info_->add_context(context); -} - -} // namespace soci diff --git a/src/soci/src/core/into-type.cpp b/src/soci/src/core/into-type.cpp deleted file mode 100644 index 7a41960835..0000000000 --- a/src/soci/src/core/into-type.cpp +++ /dev/null @@ -1,129 +0,0 @@ -// -// Copyright (C) 2004-2016 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SOURCE -#include "soci/into-type.h" -#include "soci/statement.h" - -using namespace soci; -using namespace soci::details; - -standard_into_type::~standard_into_type() -{ - delete backEnd_; -} - -void standard_into_type::define(statement_impl & st, int & position) -{ - if (backEnd_ == NULL) - { - backEnd_ = st.make_into_type_backend(); - } - - backEnd_->define_by_pos(position, data_, type_); -} - -void standard_into_type::pre_exec(int num) -{ - backEnd_->pre_exec(num); -} - -void standard_into_type::pre_fetch() -{ - backEnd_->pre_fetch(); -} - -void standard_into_type::post_fetch(bool gotData, bool calledFromFetch) -{ - backEnd_->post_fetch(gotData, calledFromFetch, ind_); - - if (gotData) - { - convert_from_base(); - } -} - -void standard_into_type::clean_up() -{ - // backEnd_ might be NULL if IntoType was used - if (backEnd_ != NULL) - { - backEnd_->clean_up(); - } -} - -vector_into_type::~vector_into_type() -{ - delete backEnd_; -} - -void vector_into_type::define(statement_impl & st, int & position) -{ - if (backEnd_ == NULL) - { - backEnd_ = st.make_vector_into_type_backend(); - } - - if (end_ != NULL) - { - backEnd_->define_by_pos_bulk(position, data_, type_, begin_, end_); - } - else - { - backEnd_->define_by_pos(position, data_, type_); - } -} - -void vector_into_type::pre_exec(int num) -{ - backEnd_->pre_exec(num); -} - -void vector_into_type::pre_fetch() -{ - backEnd_->pre_fetch(); -} - -void vector_into_type::post_fetch(bool gotData, bool /* calledFromFetch */) -{ - if (indVec_ != NULL && indVec_->empty() == false) - { - backEnd_->post_fetch(gotData, &(*indVec_)[0]); - } - else - { - backEnd_->post_fetch(gotData, NULL); - } - - if (gotData) - { - convert_from_base(); - } -} - -void vector_into_type::resize(std::size_t sz) -{ - if (indVec_ != NULL && end_ == NULL) - { - indVec_->resize(sz); - } - - backEnd_->resize(sz); -} - -std::size_t vector_into_type::size() const -{ - return backEnd_->size(); -} - -void vector_into_type::clean_up() -{ - if (backEnd_ != NULL) - { - backEnd_->clean_up(); - } -} diff --git a/src/soci/src/core/once-temp-type.cpp b/src/soci/src/core/once-temp-type.cpp deleted file mode 100644 index 12f86bef29..0000000000 --- a/src/soci/src/core/once-temp-type.cpp +++ /dev/null @@ -1,188 +0,0 @@ -// -// Copyright (C) 2004-2016 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SOURCE -#include "soci/once-temp-type.h" -#include "soci/ref-counted-statement.h" -#include "soci/session.h" - -using namespace soci; -using namespace soci::details; - -once_temp_type::once_temp_type(session & s) - : rcst_(new ref_counted_statement(s)) -{ - // this is the beginning of new query - s.get_query_stream().str(""); -} - -once_temp_type::once_temp_type(once_temp_type const & o) - :rcst_(o.rcst_) -{ - rcst_->inc_ref(); -} - -once_temp_type & once_temp_type::operator=(once_temp_type const & o) -{ - o.rcst_->inc_ref(); - rcst_->dec_ref(); - rcst_ = o.rcst_; - - return *this; -} - -once_temp_type::~once_temp_type() SOCI_NOEXCEPT_FALSE -{ - rcst_->dec_ref(); -} - -once_temp_type & once_temp_type::operator,(into_type_ptr const & i) -{ - rcst_->exchange(i); - return *this; -} - -once_temp_type & once_temp_type::operator,(use_type_ptr const & u) -{ - rcst_->exchange(u); - return *this; -} - -ddl_type::ddl_type(session & s) - : s_(&s), rcst_(new ref_counted_statement(s)) -{ - // this is the beginning of new query - s.get_query_stream().str(""); -} - -ddl_type::ddl_type(const ddl_type & d) - :rcst_(d.rcst_) -{ - rcst_->inc_ref(); -} - -ddl_type & ddl_type::operator=(const ddl_type & d) -{ - d.rcst_->inc_ref(); - rcst_->dec_ref(); - rcst_ = d.rcst_; - - return *this; -} - -ddl_type::~ddl_type() SOCI_NOEXCEPT_FALSE -{ - rcst_->dec_ref(); -} - -void ddl_type::create_table(const std::string & tableName) -{ - rcst_->accumulate(s_->get_backend()->create_table(tableName)); -} - -void ddl_type::add_column(const std::string & tableName, - const std::string & columnName, data_type dt, - int precision, int scale) -{ - rcst_->accumulate(s_->get_backend()->add_column( - tableName, columnName, dt, precision, scale)); -} - -void ddl_type::alter_column(const std::string & tableName, - const std::string & columnName, data_type dt, - int precision, int scale) -{ - rcst_->accumulate(s_->get_backend()->alter_column( - tableName, columnName, dt, precision, scale)); -} - -void ddl_type::drop_column(const std::string & tableName, - const std::string & columnName) -{ - rcst_->accumulate(s_->get_backend()->drop_column( - tableName, columnName)); -} - -ddl_type & ddl_type::column(const std::string & columnName, data_type dt, - int precision, int scale) -{ - if (rcst_->get_need_comma()) - { - rcst_->accumulate(", "); - } - - rcst_->accumulate(columnName); - rcst_->accumulate(" "); - rcst_->accumulate( - s_->get_backend()->create_column_type(dt, precision, scale)); - - rcst_->set_need_comma(true); - - return *this; -} - -ddl_type & ddl_type::unique(const std::string & name, - const std::string & columnNames) -{ - if (rcst_->get_need_comma()) - { - rcst_->accumulate(", "); - } - - rcst_->accumulate(s_->get_backend()->constraint_unique( - name, columnNames)); - - rcst_->set_need_comma(true); - - return *this; -} - -ddl_type & ddl_type::primary_key(const std::string & name, - const std::string & columnNames) -{ - if (rcst_->get_need_comma()) - { - rcst_->accumulate(", "); - } - - rcst_->accumulate(s_->get_backend()->constraint_primary_key( - name, columnNames)); - - rcst_->set_need_comma(true); - - return *this; -} - -ddl_type & ddl_type::foreign_key(const std::string & name, - const std::string & columnNames, - const std::string & refTableName, - const std::string & refColumnNames) -{ - if (rcst_->get_need_comma()) - { - rcst_->accumulate(", "); - } - - rcst_->accumulate(s_->get_backend()->constraint_foreign_key( - name, columnNames, refTableName, refColumnNames)); - - rcst_->set_need_comma(true); - - return *this; -} - -ddl_type & ddl_type::operator()(const std::string & arbitrarySql) -{ - rcst_->accumulate(" " + arbitrarySql); - - return *this; -} - -void ddl_type::set_tail(const std::string & tail) -{ - rcst_->set_tail(tail); -} diff --git a/src/soci/src/core/prepare-temp-type.cpp b/src/soci/src/core/prepare-temp-type.cpp deleted file mode 100644 index 1018bc3fa1..0000000000 --- a/src/soci/src/core/prepare-temp-type.cpp +++ /dev/null @@ -1,47 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SOURCE -#include "soci/prepare-temp-type.h" -#include "soci/ref-counted-prepare-info.h" -#include "soci/session.h" - -using namespace soci; -using namespace soci::details; - -prepare_temp_type::prepare_temp_type(session & s) - : rcpi_(new ref_counted_prepare_info(s)) -{ - // this is the beginning of new query - s.get_query_stream().str(""); -} - -prepare_temp_type::prepare_temp_type(prepare_temp_type const & o) - :rcpi_(o.rcpi_) -{ - rcpi_->inc_ref(); -} - -prepare_temp_type & prepare_temp_type::operator=(prepare_temp_type const & o) -{ - o.rcpi_->inc_ref(); - rcpi_->dec_ref(); - rcpi_ = o.rcpi_; - - return *this; -} - -prepare_temp_type::~prepare_temp_type() -{ - rcpi_->dec_ref(); -} - -prepare_temp_type & prepare_temp_type::operator,(into_type_ptr const & i) -{ - rcpi_->exchange(i); - return *this; -} diff --git a/src/soci/src/core/procedure.cpp b/src/soci/src/core/procedure.cpp deleted file mode 100644 index a1775dc772..0000000000 --- a/src/soci/src/core/procedure.cpp +++ /dev/null @@ -1,33 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SOURCE -#include "soci/procedure.h" -#include "soci/statement.h" -#include "soci/prepare-temp-type.h" - -using namespace soci; -using namespace soci::details; - -procedure_impl::procedure_impl(prepare_temp_type const & prep) - : statement_impl(prep.get_prepare_info()->session_), - refCount_(1) -{ - ref_counted_prepare_info * prepInfo = prep.get_prepare_info(); - - // take all bind/define info - intos_.swap(prepInfo->intos_); - uses_.swap(prepInfo->uses_); - - // allocate handle - alloc(); - - // prepare the statement - prepare(rewrite_for_procedure_call(prepInfo->get_query())); - - define_and_bind(); -} diff --git a/src/soci/src/core/ref-counted-prepare-info.cpp b/src/soci/src/core/ref-counted-prepare-info.cpp deleted file mode 100644 index 5094217926..0000000000 --- a/src/soci/src/core/ref-counted-prepare-info.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SOURCE -#include "soci/ref-counted-prepare-info.h" -#include "soci/session.h" - -using namespace soci; -using namespace soci::details; - -void ref_counted_prepare_info::final_action() -{ - // deallocate all bind and define objects - for (std::size_t i = intos_.size(); i > 0; --i) - { - delete intos_[i - 1]; - intos_.resize(i - 1); - } - - for (std::size_t i = uses_.size(); i > 0; --i) - { - delete uses_[i - 1]; - uses_.resize(i - 1); - } -} - -std::string ref_counted_prepare_info::get_query() const -{ - return session_.get_query(); -} diff --git a/src/soci/src/core/ref-counted-statement.cpp b/src/soci/src/core/ref-counted-statement.cpp deleted file mode 100644 index 2fdc9fd718..0000000000 --- a/src/soci/src/core/ref-counted-statement.cpp +++ /dev/null @@ -1,43 +0,0 @@ -// -// Copyright (C) 2004-2016 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SOURCE -#include "soci/ref-counted-statement.h" -#include "soci/session.h" - -using namespace soci; -using namespace soci::details; - -ref_counted_statement_base::ref_counted_statement_base(session& s) - : refCount_(1), session_(s), need_comma_(false) -{ -} - -void ref_counted_statement::final_action() -{ - try - { - st_.alloc(); - st_.prepare(session_.get_query(), st_one_time_query); - st_.define_and_bind(); - - const bool gotData = st_.execute(true); - session_.set_got_data(gotData); - } - catch (...) - { - st_.clean_up(); - throw; - } - - st_.clean_up(); -} - -std::ostringstream& ref_counted_statement_base::get_query_stream() -{ - return session_.get_query_stream(); -} diff --git a/src/soci/src/core/row.cpp b/src/soci/src/core/row.cpp deleted file mode 100644 index 2612e60095..0000000000 --- a/src/soci/src/core/row.cpp +++ /dev/null @@ -1,111 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SOURCE -#include "soci/row.h" - -#include -#include -#include -#include - -using namespace soci; -using namespace details; - -row::row() - : uppercaseColumnNames_(false) - , currentPos_(0) -{} - -row::~row() -{ - clean_up(); -} - -void row::uppercase_column_names(bool forceToUpper) -{ - uppercaseColumnNames_ = forceToUpper; -} - -void row::add_properties(column_properties const &cp) -{ - columns_.push_back(cp); - - std::string columnName; - std::string const & originalName = cp.get_name(); - if (uppercaseColumnNames_) - { - for (std::size_t i = 0; i != originalName.size(); ++i) - { - columnName.push_back(static_cast(std::toupper(originalName[i]))); - } - - // rewrite the column name in the column_properties object - // as well to retain consistent views - - columns_[columns_.size() - 1].set_name(columnName); - } - else - { - columnName = originalName; - } - - index_[columnName] = columns_.size() - 1; -} - -std::size_t row::size() const -{ - return holders_.size(); -} - -void row::clean_up() -{ - std::size_t const hsize = holders_.size(); - for (std::size_t i = 0; i != hsize; ++i) - { - delete holders_[i]; - delete indicators_[i]; - } - - columns_.clear(); - holders_.clear(); - indicators_.clear(); - index_.clear(); -} - -indicator row::get_indicator(std::size_t pos) const -{ - return *indicators_.at(pos); -} - -indicator row::get_indicator(std::string const &name) const -{ - return get_indicator(find_column(name)); -} - -column_properties const & row::get_properties(std::size_t pos) const -{ - return columns_.at(pos); -} - -column_properties const & row::get_properties(std::string const &name) const -{ - return get_properties(find_column(name)); -} - -std::size_t row::find_column(std::string const &name) const -{ - std::map::const_iterator it = index_.find(name); - if (it == index_.end()) - { - std::ostringstream msg; - msg << "Column '" << name << "' not found"; - throw soci_error(msg.str()); - } - - return it->second; -} diff --git a/src/soci/src/core/rowid.cpp b/src/soci/src/core/rowid.cpp deleted file mode 100644 index eed0e2fa22..0000000000 --- a/src/soci/src/core/rowid.cpp +++ /dev/null @@ -1,23 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SOURCE -#include "soci/rowid.h" -#include "soci/session.h" - -using namespace soci; -using namespace soci::details; - -rowid::rowid(session & s) -{ - backEnd_ = s.make_rowid_backend(); -} - -rowid::~rowid() -{ - delete backEnd_; -} diff --git a/src/soci/src/core/session.cpp b/src/soci/src/core/session.cpp deleted file mode 100644 index 9b41954efa..0000000000 --- a/src/soci/src/core/session.cpp +++ /dev/null @@ -1,502 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SOURCE -#include "soci/session.h" -#include "soci/connection-parameters.h" -#include "soci/connection-pool.h" -#include "soci/soci-backend.h" -#include "soci/query_transformation.h" - -using namespace soci; -using namespace soci::details; - -namespace // anonymous -{ - -void ensureConnected(session_backend * backEnd) -{ - if (backEnd == NULL) - { - throw soci_error("Session is not connected."); - } -} - -} // namespace anonymous - -session::session() - : once(this), prepare(this), query_transformation_(NULL), logStream_(NULL), - uppercaseColumnNames_(false), backEnd_(NULL), - isFromPool_(false), pool_(NULL) -{ -} - -session::session(connection_parameters const & parameters) - : once(this), prepare(this), query_transformation_(NULL), logStream_(NULL), - lastConnectParameters_(parameters), - uppercaseColumnNames_(false), backEnd_(NULL), - isFromPool_(false), pool_(NULL) -{ - open(lastConnectParameters_); -} - -session::session(backend_factory const & factory, - std::string const & connectString) - : once(this), prepare(this), query_transformation_(NULL), logStream_(NULL), - lastConnectParameters_(factory, connectString), - uppercaseColumnNames_(false), backEnd_(NULL), - isFromPool_(false), pool_(NULL) -{ - open(lastConnectParameters_); -} - -session::session(std::string const & backendName, - std::string const & connectString) - : once(this), prepare(this), query_transformation_(NULL), logStream_(NULL), - lastConnectParameters_(backendName, connectString), - uppercaseColumnNames_(false), backEnd_(NULL), - isFromPool_(false), pool_(NULL) -{ - open(lastConnectParameters_); -} - -session::session(std::string const & connectString) - : once(this), prepare(this), query_transformation_(NULL), logStream_(NULL), - lastConnectParameters_(connectString), - uppercaseColumnNames_(false), backEnd_(NULL), - isFromPool_(false), pool_(NULL) -{ - open(lastConnectParameters_); -} - -session::session(connection_pool & pool) - : query_transformation_(NULL), logStream_(NULL), isFromPool_(true), pool_(&pool) -{ - poolPosition_ = pool.lease(); - session & pooledSession = pool.at(poolPosition_); - - once.set_session(&pooledSession); - prepare.set_session(&pooledSession); - backEnd_ = pooledSession.get_backend(); -} - -session::~session() -{ - if (isFromPool_) - { - pool_->give_back(poolPosition_); - } - else - { - delete query_transformation_; - delete backEnd_; - } -} - -void session::open(connection_parameters const & parameters) -{ - if (isFromPool_) - { - pool_->at(poolPosition_).open(parameters); - } - else - { - if (backEnd_ != NULL) - { - throw soci_error("Cannot open already connected session."); - } - - backend_factory const * const factory = parameters.get_factory(); - if (factory == NULL) - { - throw soci_error("Cannot connect without a valid backend."); - } - - backEnd_ = factory->make_session(parameters); - lastConnectParameters_ = parameters; - } -} - -void session::open(backend_factory const & factory, - std::string const & connectString) -{ - open(connection_parameters(factory, connectString)); -} - -void session::open(std::string const & backendName, - std::string const & connectString) -{ - open(connection_parameters(backendName, connectString)); -} - -void session::open(std::string const & connectString) -{ - open(connection_parameters(connectString)); -} - -void session::close() -{ - if (isFromPool_) - { - pool_->at(poolPosition_).close(); - backEnd_ = NULL; - } - else - { - delete backEnd_; - backEnd_ = NULL; - } -} - -void session::reconnect() -{ - if (isFromPool_) - { - pool_->at(poolPosition_).reconnect(); - backEnd_ = pool_->at(poolPosition_).get_backend(); - } - else - { - backend_factory const * const lastFactory = lastConnectParameters_.get_factory(); - if (lastFactory == NULL) - { - throw soci_error("Cannot reconnect without previous connection."); - } - - if (backEnd_ != NULL) - { - close(); - } - - backEnd_ = lastFactory->make_session(lastConnectParameters_); - } -} - -void session::begin() -{ - ensureConnected(backEnd_); - - backEnd_->begin(); -} - -void session::commit() -{ - ensureConnected(backEnd_); - - backEnd_->commit(); -} - -void session::rollback() -{ - ensureConnected(backEnd_); - - backEnd_->rollback(); -} - -std::ostringstream & session::get_query_stream() -{ - if (isFromPool_) - { - return pool_->at(poolPosition_).get_query_stream(); - } - else - { - return query_stream_; - } -} - -std::string session::get_query() const -{ - if (isFromPool_) - { - return pool_->at(poolPosition_).get_query(); - } - else - { - // preserve logical constness of get_query, - // stream used as read-only here, - session* pthis = const_cast(this); - - // sole place where any user-defined query transformation is applied - if (query_transformation_) - { - return (*query_transformation_)(pthis->get_query_stream().str()); - } - return pthis->get_query_stream().str(); - } -} - - -void session::set_query_transformation_(cxx_details::auto_ptr& qtf) -{ - if (isFromPool_) - { - pool_->at(poolPosition_).set_query_transformation_(qtf); - } - else - { - delete query_transformation_; - query_transformation_= qtf.release(); - } -} - -void session::set_log_stream(std::ostream * s) -{ - if (isFromPool_) - { - pool_->at(poolPosition_).set_log_stream(s); - } - else - { - logStream_ = s; - } -} - -std::ostream * session::get_log_stream() const -{ - if (isFromPool_) - { - return pool_->at(poolPosition_).get_log_stream(); - } - else - { - return logStream_; - } -} - -void session::log_query(std::string const & query) -{ - if (isFromPool_) - { - pool_->at(poolPosition_).log_query(query); - } - else - { - if (logStream_ != NULL) - { - *logStream_ << query << '\n'; - } - - lastQuery_ = query; - } -} - -std::string session::get_last_query() const -{ - if (isFromPool_) - { - return pool_->at(poolPosition_).get_last_query(); - } - else - { - return lastQuery_; - } -} - -void session::set_got_data(bool gotData) -{ - if (isFromPool_) - { - pool_->at(poolPosition_).set_got_data(gotData); - } - else - { - gotData_ = gotData; - } -} - -bool session::got_data() const -{ - if (isFromPool_) - { - return pool_->at(poolPosition_).got_data(); - } - else - { - return gotData_; - } -} - -void session::uppercase_column_names(bool forceToUpper) -{ - if (isFromPool_) - { - pool_->at(poolPosition_).uppercase_column_names(forceToUpper); - } - else - { - uppercaseColumnNames_ = forceToUpper; - } -} - -bool session::get_uppercase_column_names() const -{ - if (isFromPool_) - { - return pool_->at(poolPosition_).get_uppercase_column_names(); - } - else - { - return uppercaseColumnNames_; - } -} - -bool session::get_next_sequence_value(std::string const & sequence, long & value) -{ - ensureConnected(backEnd_); - - return backEnd_->get_next_sequence_value(*this, sequence, value); -} - -bool session::get_last_insert_id(std::string const & sequence, long & value) -{ - ensureConnected(backEnd_); - - return backEnd_->get_last_insert_id(*this, sequence, value); -} - -details::once_temp_type session::get_table_names() -{ - ensureConnected(backEnd_); - - return once << backEnd_->get_table_names_query(); -} - -details::prepare_temp_type session::prepare_table_names() -{ - ensureConnected(backEnd_); - - return prepare << backEnd_->get_table_names_query(); -} - -details::prepare_temp_type session::prepare_column_descriptions(std::string & table_name) -{ - ensureConnected(backEnd_); - - return prepare << backEnd_->get_column_descriptions_query(), use(table_name, "t"); -} - -ddl_type session::create_table(const std::string & tableName) -{ - ddl_type ddl(*this); - - ddl.create_table(tableName); - ddl.set_tail(")"); - - return ddl; -} - -void session::drop_table(const std::string & tableName) -{ - ensureConnected(backEnd_); - - once << backEnd_->drop_table(tableName); -} - -void session::truncate_table(const std::string & tableName) -{ - ensureConnected(backEnd_); - - once << backEnd_->truncate_table(tableName); -} - -ddl_type session::add_column(const std::string & tableName, - const std::string & columnName, data_type dt, - int precision, int scale) -{ - ddl_type ddl(*this); - - ddl.add_column(tableName, columnName, dt, precision, scale); - - return ddl; -} - -ddl_type session::alter_column(const std::string & tableName, - const std::string & columnName, data_type dt, - int precision, int scale) -{ - ddl_type ddl(*this); - - ddl.alter_column(tableName, columnName, dt, precision, scale); - - return ddl; -} - -ddl_type session::drop_column(const std::string & tableName, - const std::string & columnName) -{ - ddl_type ddl(*this); - - ddl.drop_column(tableName, columnName); - - return ddl; -} - -std::string session::empty_blob() -{ - ensureConnected(backEnd_); - - return backEnd_->empty_blob(); -} - -std::string session::nvl() -{ - ensureConnected(backEnd_); - - return backEnd_->nvl(); -} - -std::string session::get_dummy_from_table() const -{ - ensureConnected(backEnd_); - - return backEnd_->get_dummy_from_table(); -} - -std::string session::get_dummy_from_clause() const -{ - std::string clause = get_dummy_from_table(); - if (!clause.empty()) - clause.insert(0, " from "); - - return clause; -} - -void session::set_failover_callback(failover_callback & callback) -{ - ensureConnected(backEnd_); - - backEnd_->set_failover_callback(callback, *this); -} - -std::string session::get_backend_name() const -{ - ensureConnected(backEnd_); - - return backEnd_->get_backend_name(); -} - -statement_backend * session::make_statement_backend() -{ - ensureConnected(backEnd_); - - return backEnd_->make_statement_backend(); -} - -rowid_backend * session::make_rowid_backend() -{ - ensureConnected(backEnd_); - - return backEnd_->make_rowid_backend(); -} - -blob_backend * session::make_blob_backend() -{ - ensureConnected(backEnd_); - - return backEnd_->make_blob_backend(); -} diff --git a/src/soci/src/core/soci-simple.cpp b/src/soci/src/core/soci-simple.cpp deleted file mode 100644 index 7960b0ef6b..0000000000 --- a/src/soci/src/core/soci-simple.cpp +++ /dev/null @@ -1,2138 +0,0 @@ -// -// Copyright (C) 2008 Maciej Sobczak -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SOURCE - -#include "soci/soci-simple.h" -#include "soci/soci.h" - -#include -#include -#include -#include -#include -#include -#include - -using namespace soci; - -namespace // unnamed -{ - -struct session_wrapper -{ - session sql; - - bool is_ok; - std::string error_message; -}; - -} // namespace unnamed - - -SOCI_DECL session_handle soci_create_session(char const * connection_string) -{ - session_wrapper * wrapper = NULL; - try - { - wrapper = new session_wrapper(); - } - catch (...) - { - return NULL; - } - - try - { - wrapper->sql.open(connection_string); - wrapper->is_ok = true; - } - catch (std::exception const & e) - { - wrapper->is_ok = false; - wrapper->error_message = e.what(); - } - - return wrapper; -} - -SOCI_DECL void soci_destroy_session(session_handle s) -{ - session_wrapper * wrapper = static_cast(s); - delete wrapper; -} - -SOCI_DECL void soci_begin(session_handle s) -{ - session_wrapper * wrapper = static_cast(s); - try - { - wrapper->sql.begin(); - wrapper->is_ok = true; - } - catch (std::exception const & e) - { - wrapper->is_ok = false; - wrapper->error_message = e.what(); - } -} - -SOCI_DECL void soci_commit(session_handle s) -{ - session_wrapper * wrapper = static_cast(s); - try - { - wrapper->sql.commit(); - wrapper->is_ok = true; - } - catch (std::exception const & e) - { - wrapper->is_ok = false; - wrapper->error_message = e.what(); - } -} - -SOCI_DECL void soci_rollback(session_handle s) -{ - session_wrapper * wrapper = static_cast(s); - try - { - wrapper->sql.rollback(); - wrapper->is_ok = true; - } - catch (std::exception const & e) - { - wrapper->is_ok = false; - wrapper->error_message = e.what(); - } -} - -// this will not be needed until dynamic row is exposed -// SOCI_DECL void soci_uppercase_column_names(session_handle s, bool forceToUpper) -// { -// session_wrapper * wrapper = static_cast(s); -// wrapper->sql.uppercase_column_names(forceToUpper); -// wrapper->is_ok = true; -// } - -SOCI_DECL int soci_session_state(session_handle s) -{ - session_wrapper * wrapper = static_cast(s); - - return wrapper->is_ok ? 1 : 0; -} - -SOCI_DECL char const * soci_session_error_message(session_handle s) -{ - session_wrapper * wrapper = static_cast(s); - - return wrapper->error_message.c_str(); -} - - -// blob -struct blob_wrapper -{ - blob_wrapper(session &sql) - : blob_(sql), is_ok(true) {} - - blob blob_; - bool is_ok; - std::string error_message; -}; - -blob_wrapper *soci_create_blob_session(soci::session &sql) -{ - blob_wrapper *bw = NULL; - try - { - bw = new blob_wrapper(sql); - } - catch (...) - { - delete bw; - return NULL; - } - - return bw; -} - -SOCI_DECL blob_handle soci_create_blob(session_handle s) -{ - session_wrapper * session = static_cast(s); - if (!session->is_ok) - return NULL; - - return soci_create_blob_session(session->sql); -} - -SOCI_DECL void soci_destroy_blob(blob_handle b) -{ - blob_wrapper *blob = static_cast(b); - try - { - delete blob; - } - catch (...) - {} -} - -SOCI_DECL int soci_blob_get_len(blob_handle b) -{ - blob_wrapper *blob = static_cast(b); - return static_cast(blob->blob_.get_len()); -} - -SOCI_DECL int soci_blob_read(blob_handle b, int offset, char *buf, int toRead) -{ - blob_wrapper *blob = static_cast(b); - try - { - return static_cast(blob->blob_.read(offset, buf, toRead)); - } - catch (std::exception &e) - { - blob->is_ok = false; - blob->error_message = e.what(); - return -1; - } - catch (...) - { - blob->is_ok = false; - blob->error_message = "unknown exception"; - return -1; - } -} - -SOCI_DECL int soci_blob_write(blob_handle b, int offset, char const *buf, int toWrite) -{ - blob_wrapper *blob = static_cast(b); - try - { - return static_cast(blob->blob_.write(offset, buf, toWrite)); - } - catch (std::exception &e) - { - blob->is_ok = false; - blob->error_message = e.what(); - return -1; - } - catch (...) - { - blob->is_ok = false; - blob->error_message = "unknown exception"; - return -1; - } -} - -SOCI_DECL int soci_blob_append(blob_handle b, char const *buf, int toWrite) -{ - blob_wrapper *blob = static_cast(b); - try - { - return static_cast(blob->blob_.append(buf, toWrite)); - } - catch (std::exception &e) - { - blob->is_ok = false; - blob->error_message = e.what(); - return -1; - } - catch (...) - { - blob->is_ok = false; - blob->error_message = "unknown exception"; - return -1; - } -} - -SOCI_DECL int soci_blob_trim(blob_handle b, int newLen) -{ - blob_wrapper *blob = static_cast(b); - try - { - blob->blob_.trim(newLen); - } - catch (std::exception &e) - { - blob->is_ok = false; - blob->error_message = e.what(); - return -1; - } - catch (...) - { - blob->is_ok = false; - blob->error_message = "unknown exception"; - return -1; - } - - return 0; -} - -SOCI_DECL int soci_blob_state(blob_handle b) -{ - blob_wrapper *blob = static_cast(b); - return (blob->is_ok ? 1 : 0); -} - -SOCI_DECL char const * soci_blob_error_message(blob_handle b) -{ - blob_wrapper *blob = static_cast(b); - return blob->error_message.c_str(); -} - -// statement - - -namespace // unnamed -{ - -struct statement_wrapper -{ - statement_wrapper(session & _sql) - : sql(_sql), st(sql), statement_state(clean), into_kind(empty), use_kind(empty), - next_position(0), is_ok(true) {} - - ~statement_wrapper(); - - session &sql; - statement st; - - enum state { clean, defining, executing } statement_state; - enum kind { empty, single, bulk } into_kind, use_kind; - - // into elements - int next_position; - std::vector into_types; // for both single and bulk - std::vector into_indicators; - std::map into_strings; - std::map into_ints; - std::map into_longlongs; - std::map into_doubles; - std::map into_dates; - std::map into_blob; - - std::vector > into_indicators_v; - std::map > into_strings_v; - std::map > into_ints_v; - std::map > into_longlongs_v; - std::map > into_doubles_v; - std::map > into_dates_v; - - // use elements - std::map use_indicators; - std::map use_strings; - std::map use_ints; - std::map use_longlongs; - std::map use_doubles; - std::map use_dates; - std::map use_blob; - - std::map > use_indicators_v; - std::map > use_strings_v; - std::map > use_ints_v; - std::map > use_longlongs_v; - std::map > use_doubles_v; - std::map > use_dates_v; - - // format is: "YYYY MM DD hh mm ss" - char date_formatted[20]; - - bool is_ok; - std::string error_message; - -private: - SOCI_NOT_COPYABLE(statement_wrapper) -}; - -statement_wrapper::~statement_wrapper() -{ - for (std::map::iterator iter = into_blob.begin(), last = into_blob.end(); - iter != last; ++iter) - { - soci_destroy_blob(iter->second); - } - - for (std::map::iterator iter = use_blob.begin(), last = use_blob.end(); - iter != last; ++iter) - { - soci::indicator &ind = use_indicators[iter->first]; - blob_wrapper *&blob = iter->second; - if (ind == i_null && blob != NULL) - soci_destroy_blob(blob); - } -} - -// helper for checking if the attempt was made to add more into/use elements -// after the statement was set for execution -bool cannot_add_elements(statement_wrapper & wrapper, statement_wrapper::kind k, bool into) -{ - if (wrapper.statement_state == statement_wrapper::executing) - { - wrapper.is_ok = false; - wrapper.error_message = "Cannot add more data items."; - return true; - } - - if (into) - { - if (k == statement_wrapper::single && wrapper.into_kind == statement_wrapper::bulk) - { - wrapper.is_ok = false; - wrapper.error_message = "Cannot add single into data items."; - return true; - } - if (k == statement_wrapper::bulk && wrapper.into_kind == statement_wrapper::single) - { - wrapper.is_ok = false; - wrapper.error_message = "Cannot add vector into data items."; - return true; - } - } - else - { - // trying to add use elements - if (k == statement_wrapper::single && wrapper.use_kind == statement_wrapper::bulk) - { - wrapper.is_ok = false; - wrapper.error_message = "Cannot add single use data items."; - return true; - } - if (k == statement_wrapper::bulk && wrapper.use_kind == statement_wrapper::single) - { - wrapper.is_ok = false; - wrapper.error_message = "Cannot add vector use data items."; - return true; - } - } - - wrapper.is_ok = true; - return false; -} - -// helper for checking if the expected into element exists on the given position -bool position_check_failed(statement_wrapper & wrapper, statement_wrapper::kind k, - int position, data_type expected_type, char const * type_name) -{ - if (position < 0 || position >= wrapper.next_position) - { - wrapper.is_ok = false; - wrapper.error_message = "Invalid position."; - return true; - } - - if (wrapper.into_types[position] != expected_type) - { - wrapper.is_ok = false; - wrapper.error_message = "No into "; - if (k == statement_wrapper::bulk) - { - wrapper.error_message += "vector "; - } - wrapper.error_message += type_name; - wrapper.error_message += " element at this position."; - return true; - } - - wrapper.is_ok = true; - return false; -} - -// helper for checking if the into element on the given position -// is not null -bool not_null_check_failed(statement_wrapper & wrapper, int position) -{ - if (wrapper.into_indicators[position] == i_null) - { - wrapper.is_ok = false; - wrapper.error_message = "Element is null."; - return true; - } - - wrapper.is_ok = true; - return false; -} - -// overloaded version for vectors -bool not_null_check_failed(statement_wrapper & wrapper, int position, int index) -{ - if (wrapper.into_indicators_v[position][index] == i_null) - { - wrapper.is_ok = false; - wrapper.error_message = "Element is null."; - return true; - } - - wrapper.is_ok = true; - return false; -} - -// helper for checking the index value -template -bool index_check_failed(std::vector const & v, - statement_wrapper & wrapper, int index) -{ - if (index < 0 || index >= static_cast(v.size())) - { - wrapper.is_ok = false; - wrapper.error_message = "Invalid index."; - return true; - } - - wrapper.is_ok = true; - return false; -} - -// helper for checking the uniqueness of the use element's name -bool name_unique_check_failed(statement_wrapper & wrapper, - statement_wrapper::kind k, char const * name) -{ - bool is_unique; - if (k == statement_wrapper::single) - { - typedef std::map::const_iterator iterator; - iterator const it = wrapper.use_indicators.find(name); - is_unique = it == wrapper.use_indicators.end(); - } - else - { - // vector version - - typedef std::map - < - std::string, - std::vector - >::const_iterator iterator; - - iterator const it = wrapper.use_indicators_v.find(name); - is_unique = it == wrapper.use_indicators_v.end(); - } - - if (is_unique) - { - wrapper.is_ok = true; - return false; - } - else - { - wrapper.is_ok = false; - wrapper.error_message = "Name of use element should be unique."; - return true; - } -} - -// helper for checking if the use element with the given name exists -bool name_exists_check_failed(statement_wrapper & wrapper, - char const * name, data_type expected_type, - statement_wrapper::kind k, char const * type_name) -{ - bool name_exists = false; - if (k == statement_wrapper::single) - { - switch (expected_type) - { - case dt_string: - { - typedef std::map - < - std::string, - std::string - >::const_iterator iterator; - iterator const it = wrapper.use_strings.find(name); - name_exists = (it != wrapper.use_strings.end()); - } - break; - case dt_integer: - { - typedef std::map::const_iterator iterator; - iterator const it = wrapper.use_ints.find(name); - name_exists = (it != wrapper.use_ints.end()); - } - break; - case dt_long_long: - case dt_unsigned_long_long: - { - typedef std::map::const_iterator - iterator; - iterator const it = wrapper.use_longlongs.find(name); - name_exists = (it != wrapper.use_longlongs.end()); - } - break; - case dt_double: - { - typedef std::map::const_iterator iterator; - iterator const it = wrapper.use_doubles.find(name); - name_exists = (it != wrapper.use_doubles.end()); - } - break; - case dt_date: - { - typedef std::map::const_iterator iterator; - iterator const it = wrapper.use_dates.find(name); - name_exists = (it != wrapper.use_dates.end()); - } - break; - case dt_blob: - { - typedef std::map::const_iterator iterator; - iterator const it = wrapper.use_blob.find(name); - name_exists = (it != wrapper.use_blob.end()); - } - case dt_xml: - // no support for xml - break; - } - } - else - { - // vector version - - switch (expected_type) - { - case dt_string: - { - typedef std::map - < - std::string, - std::vector - >::const_iterator iterator; - iterator const it = wrapper.use_strings_v.find(name); - name_exists = (it != wrapper.use_strings_v.end()); - } - break; - case dt_integer: - { - typedef std::map - < - std::string, - std::vector - >::const_iterator iterator; - iterator const it = wrapper.use_ints_v.find(name); - name_exists = (it != wrapper.use_ints_v.end()); - } - break; - case dt_long_long: - case dt_unsigned_long_long: - { - typedef std::map - < - std::string, - std::vector - >::const_iterator iterator; - iterator const it = wrapper.use_longlongs_v.find(name); - name_exists = (it != wrapper.use_longlongs_v.end()); - } - break; - case dt_double: - { - typedef std::map >::const_iterator iterator; - iterator const it = wrapper.use_doubles_v.find(name); - name_exists = (it != wrapper.use_doubles_v.end()); - } - break; - case dt_date: - { - typedef std::map >::const_iterator iterator; - iterator const it = wrapper.use_dates_v.find(name); - name_exists = (it != wrapper.use_dates_v.end()); - } - break; - case dt_blob: - case dt_xml: - // no support for bulk and xml load - break; - } - } - - if (name_exists) - { - wrapper.is_ok = true; - return false; - } - else - { - wrapper.is_ok = false; - wrapper.error_message = "No use "; - wrapper.error_message += type_name; - wrapper.error_message += " element with this name."; - return true; - } -} - -// helper function for resizing all vectors in the map -template -void resize_in_map(std::map > & m, int new_size) -{ - typedef typename std::map >::iterator iterator; - iterator it = m.begin(); - iterator const end = m.end(); - for ( ; it != end; ++it) - { - std::vector & v = it->second; - v.resize(new_size); - } -} - -// helper for formatting date values -char const * format_date(statement_wrapper & wrapper, std::tm const & d) -{ - std::sprintf(wrapper.date_formatted, "%d %d %d %d %d %d", - d.tm_year + 1900, d.tm_mon + 1, d.tm_mday, - d.tm_hour, d.tm_min, d.tm_sec); - - return wrapper.date_formatted; -} - -bool string_to_date(char const * val, std::tm & /* out */ dt, - statement_wrapper & wrapper) -{ - // format is: "YYYY MM DD hh mm ss" - int year; - int month; - int day; - int hour; - int minute; - int second; - int const converted = std::sscanf(val, "%d %d %d %d %d %d", - &year, &month, &day, &hour, &minute, &second); - if (converted != 6) - { - wrapper.is_ok = false; - wrapper.error_message = "Cannot convert date."; - return false; - } - - wrapper.is_ok = true; - - dt.tm_year = year - 1900; - dt.tm_mon = month - 1; - dt.tm_mday = day; - dt.tm_hour = hour; - dt.tm_min = minute; - dt.tm_sec = second; - -return true; -} - -} // namespace unnamed - - -SOCI_DECL statement_handle soci_create_statement(session_handle s) -{ - session_wrapper * session_w = static_cast(s); - try - { - statement_wrapper * statement_w = new statement_wrapper(session_w->sql); - return statement_w; - } - catch (std::exception const & e) - { - session_w->is_ok = false; - session_w->error_message = e.what(); - return NULL; - } -} - -SOCI_DECL void soci_destroy_statement(statement_handle st) -{ - statement_wrapper * wrapper = static_cast(st); - delete wrapper; -} - -SOCI_DECL int soci_into_string(statement_handle st) -{ - statement_wrapper * wrapper = static_cast(st); - - if (cannot_add_elements(*wrapper, statement_wrapper::single, true)) - { - return -1; - } - - wrapper->statement_state = statement_wrapper::defining; - wrapper->into_kind = statement_wrapper::single; - - wrapper->into_types.push_back(dt_string); - wrapper->into_indicators.push_back(i_ok); - wrapper->into_strings[wrapper->next_position]; // create new entry - return wrapper->next_position++; -} - -SOCI_DECL int soci_into_int(statement_handle st) -{ - statement_wrapper * wrapper = static_cast(st); - - if (cannot_add_elements(*wrapper, statement_wrapper::single, true)) - { - return -1; - } - - wrapper->statement_state = statement_wrapper::defining; - wrapper->into_kind = statement_wrapper::single; - - wrapper->into_types.push_back(dt_integer); - wrapper->into_indicators.push_back(i_ok); - wrapper->into_ints[wrapper->next_position]; // create new entry - return wrapper->next_position++; -} - -SOCI_DECL int soci_into_long_long(statement_handle st) -{ - statement_wrapper * wrapper = static_cast(st); - - if (cannot_add_elements(*wrapper, statement_wrapper::single, true)) - { - return -1; - } - - wrapper->statement_state = statement_wrapper::defining; - wrapper->into_kind = statement_wrapper::single; - - wrapper->into_types.push_back(dt_long_long); - wrapper->into_indicators.push_back(i_ok); - wrapper->into_longlongs[wrapper->next_position]; // create new entry - return wrapper->next_position++; -} - -SOCI_DECL int soci_into_double(statement_handle st) -{ - statement_wrapper * wrapper = static_cast(st); - - if (cannot_add_elements(*wrapper, statement_wrapper::single, true)) - { - return -1; - } - - wrapper->statement_state = statement_wrapper::defining; - wrapper->into_kind = statement_wrapper::single; - - wrapper->into_types.push_back(dt_double); - wrapper->into_indicators.push_back(i_ok); - wrapper->into_doubles[wrapper->next_position]; // create new entry - return wrapper->next_position++; -} - -SOCI_DECL int soci_into_date(statement_handle st) -{ - statement_wrapper * wrapper = static_cast(st); - - if (cannot_add_elements(*wrapper, statement_wrapper::single, true)) - { - return -1; - } - - wrapper->statement_state = statement_wrapper::defining; - wrapper->into_kind = statement_wrapper::single; - - wrapper->into_types.push_back(dt_date); - wrapper->into_indicators.push_back(i_ok); - wrapper->into_dates[wrapper->next_position]; // create new entry - return wrapper->next_position++; -} - -SOCI_DECL int soci_into_blob(statement_handle st) -{ - statement_wrapper * wrapper = static_cast(st); - - if (cannot_add_elements(*wrapper, statement_wrapper::single, true)) - { - return -1; - } - - wrapper->statement_state = statement_wrapper::defining; - wrapper->into_kind = statement_wrapper::single; - - wrapper->into_types.push_back(dt_blob); - wrapper->into_indicators.push_back(i_ok); - wrapper->into_blob[wrapper->next_position] = soci_create_blob_session(wrapper->sql); // create new entry - return wrapper->next_position++; -} - -SOCI_DECL int soci_into_string_v(statement_handle st) -{ - statement_wrapper * wrapper = static_cast(st); - - if (cannot_add_elements(*wrapper, statement_wrapper::bulk, true)) - { - return -1; - } - - wrapper->statement_state = statement_wrapper::defining; - wrapper->into_kind = statement_wrapper::bulk; - - wrapper->into_types.push_back(dt_string); - wrapper->into_indicators_v.push_back(std::vector()); - wrapper->into_strings_v[wrapper->next_position]; - return wrapper->next_position++; -} - -SOCI_DECL int soci_into_int_v(statement_handle st) -{ - statement_wrapper * wrapper = static_cast(st); - - if (cannot_add_elements(*wrapper, statement_wrapper::bulk, true)) - { - return -1; - } - - wrapper->statement_state = statement_wrapper::defining; - wrapper->into_kind = statement_wrapper::bulk; - - wrapper->into_types.push_back(dt_integer); - wrapper->into_indicators_v.push_back(std::vector()); - wrapper->into_ints_v[wrapper->next_position]; - return wrapper->next_position++; -} - -SOCI_DECL int soci_into_long_long_v(statement_handle st) -{ - statement_wrapper * wrapper = static_cast(st); - - if (cannot_add_elements(*wrapper, statement_wrapper::bulk, true)) - { - return -1; - } - - wrapper->statement_state = statement_wrapper::defining; - wrapper->into_kind = statement_wrapper::bulk; - - wrapper->into_types.push_back(dt_long_long); - wrapper->into_indicators_v.push_back(std::vector()); - wrapper->into_longlongs_v[wrapper->next_position]; - return wrapper->next_position++; -} - -SOCI_DECL int soci_into_double_v(statement_handle st) -{ - statement_wrapper * wrapper = static_cast(st); - - if (cannot_add_elements(*wrapper, statement_wrapper::bulk, true)) - { - return -1; - } - - wrapper->statement_state = statement_wrapper::defining; - wrapper->into_kind = statement_wrapper::bulk; - - wrapper->into_types.push_back(dt_double); - wrapper->into_indicators_v.push_back(std::vector()); - wrapper->into_doubles_v[wrapper->next_position]; - return wrapper->next_position++; -} - -SOCI_DECL int soci_into_date_v(statement_handle st) -{ - statement_wrapper * wrapper = static_cast(st); - - if (cannot_add_elements(*wrapper, statement_wrapper::bulk, true)) - { - return -1; - } - - wrapper->statement_state = statement_wrapper::defining; - wrapper->into_kind = statement_wrapper::bulk; - - wrapper->into_types.push_back(dt_date); - wrapper->into_indicators_v.push_back(std::vector()); - wrapper->into_dates_v[wrapper->next_position]; - return wrapper->next_position++; -} - -SOCI_DECL int soci_get_into_state(statement_handle st, int position) -{ - statement_wrapper * wrapper = static_cast(st); - - if (position < 0 || position >= wrapper->next_position) - { - wrapper->is_ok = false; - wrapper->error_message = "Invalid position."; - return 0; - } - - wrapper->is_ok = true; - return wrapper->into_indicators[position] == i_ok ? 1 : 0; -} - -SOCI_DECL char const * soci_get_into_string(statement_handle st, int position) -{ - statement_wrapper * wrapper = static_cast(st); - - if (position_check_failed(*wrapper, - statement_wrapper::single, position, dt_string, "string") || - not_null_check_failed(*wrapper, position)) - { - return ""; - } - - return wrapper->into_strings[position].c_str(); -} - -SOCI_DECL int soci_get_into_int(statement_handle st, int position) -{ - statement_wrapper * wrapper = static_cast(st); - - if (position_check_failed(*wrapper, - statement_wrapper::single, position, dt_integer, "int") || - not_null_check_failed(*wrapper, position)) - { - return 0; - } - - return wrapper->into_ints[position]; -} - -SOCI_DECL long long soci_get_into_long_long(statement_handle st, int position) -{ - statement_wrapper * wrapper = static_cast(st); - - if (position_check_failed(*wrapper, - statement_wrapper::single, position, dt_long_long, "long long") || - not_null_check_failed(*wrapper, position)) - { - return 0LL; - } - - return wrapper->into_longlongs[position]; -} - -SOCI_DECL double soci_get_into_double(statement_handle st, int position) -{ - statement_wrapper * wrapper = static_cast(st); - - if (position_check_failed(*wrapper, - statement_wrapper::single, position, dt_double, "double") || - not_null_check_failed(*wrapper, position)) - { - return 0.0; - } - - return wrapper->into_doubles[position]; -} - -SOCI_DECL char const * soci_get_into_date(statement_handle st, int position) -{ - statement_wrapper * wrapper = static_cast(st); - - if (position_check_failed(*wrapper, - statement_wrapper::single, position, dt_date, "date") || - not_null_check_failed(*wrapper, position)) - { - return ""; - } - - // format is: "YYYY MM DD hh mm ss" - std::tm const & d = wrapper->into_dates[position]; - return format_date(*wrapper, d); -} - -SOCI_DECL blob_handle soci_get_into_blob(statement_handle st, int position) -{ - statement_wrapper * wrapper = static_cast(st); - - if (position_check_failed(*wrapper, - statement_wrapper::single, position, dt_blob, "blob") || - not_null_check_failed(*wrapper, position)) - { - return NULL; - } - - return wrapper->into_blob[position]; -} - -SOCI_DECL int soci_into_get_size_v(statement_handle st) -{ - statement_wrapper * wrapper = static_cast(st); - - if (wrapper->into_kind != statement_wrapper::bulk) - { - wrapper->is_ok = false; - wrapper->error_message = "No vector into elements."; - return -1; - } - - return static_cast(wrapper->into_indicators_v[0].size()); -} - -SOCI_DECL void soci_into_resize_v(statement_handle st, int new_size) -{ - statement_wrapper * wrapper = static_cast(st); - - if (new_size <= 0) - { - wrapper->is_ok = false; - wrapper->error_message = "Invalid size."; - return; - } - - if (wrapper->into_kind != statement_wrapper::bulk) - { - wrapper->is_ok = false; - wrapper->error_message = "No vector into elements."; - return; - } - - for (int i = 0; i != wrapper->next_position; ++i) - { - wrapper->into_indicators_v[i].resize(new_size); - - switch (wrapper->into_types[i]) - { - case dt_string: - wrapper->into_strings_v[i].resize(new_size); - break; - case dt_integer: - wrapper->into_ints_v[i].resize(new_size); - break; - case dt_long_long: - case dt_unsigned_long_long: - wrapper->into_longlongs_v[i].resize(new_size); - break; - case dt_double: - wrapper->into_doubles_v[i].resize(new_size); - break; - case dt_date: - wrapper->into_dates_v[i].resize(new_size); - break; - case dt_blob: - case dt_xml: - // no support for bulk blob - break; - } - } - - wrapper->is_ok = true; -} - -SOCI_DECL int soci_get_into_state_v(statement_handle st, int position, int index) -{ - statement_wrapper * wrapper = static_cast(st); - - if (position < 0 || position >= wrapper->next_position) - { - wrapper->is_ok = false; - wrapper->error_message = "Invalid position."; - return 0; - } - - std::vector const & v = wrapper->into_indicators_v[position]; - if (index_check_failed(v, *wrapper, index)) - { - return 0; - } - - return v[index] == i_ok ? 1 : 0; -} - -SOCI_DECL char const * soci_get_into_string_v(statement_handle st, int position, int index) -{ - statement_wrapper * wrapper = static_cast(st); - - if (position_check_failed(*wrapper, - statement_wrapper::bulk, position, dt_string, "string")) - { - return ""; - } - - std::vector const & v = wrapper->into_strings_v[position]; - if (index_check_failed(v, *wrapper, index) || - not_null_check_failed(*wrapper, position, index)) - { - return ""; - } - - return v[index].c_str(); -} - -SOCI_DECL int soci_get_into_int_v(statement_handle st, int position, int index) -{ - statement_wrapper * wrapper = static_cast(st); - - if (position_check_failed(*wrapper, - statement_wrapper::bulk, position, dt_integer, "int")) - { - return 0; - } - - std::vector const & v = wrapper->into_ints_v[position]; - if (index_check_failed(v, *wrapper, index) || - not_null_check_failed(*wrapper, position, index)) - { - return 0; - } - - return v[index]; -} - -SOCI_DECL long long soci_get_into_long_long_v(statement_handle st, int position, int index) -{ - statement_wrapper * wrapper = static_cast(st); - - if (position_check_failed(*wrapper, - statement_wrapper::bulk, position, dt_long_long, "long long")) - { - return 0; - } - - std::vector const & v = wrapper->into_longlongs_v[position]; - if (index_check_failed(v, *wrapper, index) || - not_null_check_failed(*wrapper, position, index)) - { - return 0; - } - - return v[index]; -} - -SOCI_DECL double soci_get_into_double_v(statement_handle st, int position, int index) -{ - statement_wrapper * wrapper = static_cast(st); - - if (position_check_failed(*wrapper, - statement_wrapper::bulk, position, dt_double, "double")) - { - return 0.0; - } - - std::vector const & v = wrapper->into_doubles_v[position]; - if (index_check_failed(v, *wrapper, index) || - not_null_check_failed(*wrapper, position, index)) - { - return 0.0; - } - - return v[index]; -} - -SOCI_DECL char const * soci_get_into_date_v(statement_handle st, int position, int index) -{ - statement_wrapper * wrapper = static_cast(st); - - if (position_check_failed(*wrapper, - statement_wrapper::bulk, position, dt_date, "date")) - { - return ""; - } - - std::vector const & v = wrapper->into_dates_v[position]; - if (index_check_failed(v, *wrapper, index) || - not_null_check_failed(*wrapper, position, index)) - { - return ""; - } - - return format_date(*wrapper, v[index]); -} - -SOCI_DECL void soci_use_string(statement_handle st, char const * name) -{ - statement_wrapper * wrapper = static_cast(st); - - if (cannot_add_elements(*wrapper, statement_wrapper::single, false) || - name_unique_check_failed(*wrapper, statement_wrapper::single, name)) - { - return; - } - - wrapper->statement_state = statement_wrapper::defining; - wrapper->use_kind = statement_wrapper::single; - - wrapper->use_indicators[name] = i_ok; // create new entry - wrapper->use_strings[name]; // create new entry -} - -SOCI_DECL void soci_use_int(statement_handle st, char const * name) -{ - statement_wrapper * wrapper = static_cast(st); - - if (cannot_add_elements(*wrapper, statement_wrapper::single, false) || - name_unique_check_failed(*wrapper, statement_wrapper::single, name)) - { - return; - } - - wrapper->statement_state = statement_wrapper::defining; - wrapper->use_kind = statement_wrapper::single; - - wrapper->use_indicators[name] = i_ok; // create new entry - wrapper->use_ints[name]; // create new entry -} - -SOCI_DECL void soci_use_long_long(statement_handle st, char const * name) -{ - statement_wrapper * wrapper = static_cast(st); - - if (cannot_add_elements(*wrapper, statement_wrapper::single, false) || - name_unique_check_failed(*wrapper, statement_wrapper::single, name)) - { - return; - } - - wrapper->statement_state = statement_wrapper::defining; - wrapper->use_kind = statement_wrapper::single; - - wrapper->use_indicators[name] = i_ok; // create new entry - wrapper->use_longlongs[name]; // create new entry -} - -SOCI_DECL void soci_use_double(statement_handle st, char const * name) -{ - statement_wrapper * wrapper = static_cast(st); - - if (cannot_add_elements(*wrapper, statement_wrapper::single, false) || - name_unique_check_failed(*wrapper, statement_wrapper::single, name)) - { - return; - } - - wrapper->statement_state = statement_wrapper::defining; - wrapper->use_kind = statement_wrapper::single; - - wrapper->use_indicators[name] = i_ok; // create new entry - wrapper->use_doubles[name]; // create new entry -} - -SOCI_DECL void soci_use_date(statement_handle st, char const * name) -{ - statement_wrapper * wrapper = static_cast(st); - - if (cannot_add_elements(*wrapper, statement_wrapper::single, false) || - name_unique_check_failed(*wrapper, statement_wrapper::single, name)) - { - return; - } - - wrapper->statement_state = statement_wrapper::defining; - wrapper->use_kind = statement_wrapper::single; - - wrapper->use_indicators[name] = i_ok; // create new entry - wrapper->use_dates[name]; // create new entry -} - -SOCI_DECL void soci_use_blob(statement_handle st, char const * name) -{ - statement_wrapper * wrapper = static_cast(st); - - if (cannot_add_elements(*wrapper, statement_wrapper::single, false) || - name_unique_check_failed(*wrapper, statement_wrapper::single, name)) - { - return; - } - - wrapper->statement_state = statement_wrapper::defining; - wrapper->use_kind = statement_wrapper::single; - - wrapper->use_indicators[name] = i_null; // create new entry - wrapper->use_blob[name] = soci_create_blob_session(wrapper->sql); // create new entry -} - -SOCI_DECL void soci_use_string_v(statement_handle st, char const * name) -{ - statement_wrapper * wrapper = static_cast(st); - - if (cannot_add_elements(*wrapper, statement_wrapper::bulk, false) || - name_unique_check_failed(*wrapper, statement_wrapper::bulk, name)) - { - return; - } - - wrapper->statement_state = statement_wrapper::defining; - wrapper->use_kind = statement_wrapper::bulk; - - wrapper->use_indicators_v[name]; // create new entry - wrapper->use_strings_v[name]; // create new entry -} - -SOCI_DECL void soci_use_int_v(statement_handle st, char const * name) -{ - statement_wrapper * wrapper = static_cast(st); - - if (cannot_add_elements(*wrapper, statement_wrapper::bulk, false) || - name_unique_check_failed(*wrapper, statement_wrapper::bulk, name)) - { - return; - } - - wrapper->statement_state = statement_wrapper::defining; - wrapper->use_kind = statement_wrapper::bulk; - - wrapper->use_indicators_v[name]; // create new entry - wrapper->use_ints_v[name]; // create new entry -} - -SOCI_DECL void soci_use_long_long_v(statement_handle st, char const * name) -{ - statement_wrapper * wrapper = static_cast(st); - - if (cannot_add_elements(*wrapper, statement_wrapper::bulk, false) || - name_unique_check_failed(*wrapper, statement_wrapper::bulk, name)) - { - return; - } - - wrapper->statement_state = statement_wrapper::defining; - wrapper->use_kind = statement_wrapper::bulk; - - wrapper->use_indicators_v[name]; // create new entry - wrapper->use_longlongs_v[name]; // create new entry -} - -SOCI_DECL void soci_use_double_v(statement_handle st, char const * name) -{ - statement_wrapper * wrapper = static_cast(st); - - if (cannot_add_elements(*wrapper, statement_wrapper::bulk, false) || - name_unique_check_failed(*wrapper, statement_wrapper::bulk, name)) - { - return; - } - - wrapper->statement_state = statement_wrapper::defining; - wrapper->use_kind = statement_wrapper::bulk; - - wrapper->use_indicators_v[name]; // create new entry - wrapper->use_doubles_v[name]; // create new entry -} - -SOCI_DECL void soci_use_date_v(statement_handle st, char const * name) -{ - statement_wrapper * wrapper = static_cast(st); - - if (cannot_add_elements(*wrapper, statement_wrapper::bulk, false) || - name_unique_check_failed(*wrapper, statement_wrapper::bulk, name)) - { - return; - } - - wrapper->statement_state = statement_wrapper::defining; - wrapper->use_kind = statement_wrapper::bulk; - - wrapper->use_indicators_v[name]; // create new entry - wrapper->use_dates_v[name]; // create new entry -} - -SOCI_DECL void soci_set_use_state(statement_handle st, char const * name, int state) -{ - statement_wrapper * wrapper = static_cast(st); - - typedef std::map::const_iterator iterator; - iterator const it = wrapper->use_indicators.find(name); - if (it == wrapper->use_indicators.end()) - { - wrapper->is_ok = false; - wrapper->error_message = "Invalid name."; - return; - } - - wrapper->is_ok = true; - wrapper->use_indicators[name] = (state != 0 ? i_ok : i_null); -} - -SOCI_DECL void soci_set_use_string(statement_handle st, char const * name, char const * val) -{ - statement_wrapper * wrapper = static_cast(st); - - if (name_exists_check_failed(*wrapper, - name, dt_string, statement_wrapper::single, "string")) - { - return; - } - - wrapper->use_indicators[name] = i_ok; - wrapper->use_strings[name] = val; -} - -SOCI_DECL void soci_set_use_int(statement_handle st, char const * name, int val) -{ - statement_wrapper * wrapper = static_cast(st); - - if (name_exists_check_failed(*wrapper, - name, dt_integer, statement_wrapper::single, "int")) - { - return; - } - - wrapper->use_indicators[name] = i_ok; - wrapper->use_ints[name] = val; -} - -SOCI_DECL void soci_set_use_long_long(statement_handle st, char const * name, long long val) -{ - statement_wrapper * wrapper = static_cast(st); - - if (name_exists_check_failed(*wrapper, - name, dt_long_long, statement_wrapper::single, "long long")) - { - return; - } - - wrapper->use_indicators[name] = i_ok; - wrapper->use_longlongs[name] = val; -} - -SOCI_DECL void soci_set_use_double(statement_handle st, char const * name, double val) -{ - statement_wrapper * wrapper = static_cast(st); - - if (name_exists_check_failed(*wrapper, - name, dt_double, statement_wrapper::single, "double")) - { - return; - } - - wrapper->use_indicators[name] = i_ok; - wrapper->use_doubles[name] = val; -} - -SOCI_DECL void soci_set_use_date(statement_handle st, char const * name, char const * val) -{ - statement_wrapper * wrapper = static_cast(st); - - if (name_exists_check_failed(*wrapper, - name, dt_date, statement_wrapper::single, "date")) - { - return; - } - - std::tm dt = std::tm(); - bool const converted = string_to_date(val, dt, *wrapper); - if (converted == false) - { - return; - } - - wrapper->use_indicators[name] = i_ok; - wrapper->use_dates[name] = dt; -} - -SOCI_DECL void soci_set_use_blob(statement_handle st, char const * name, blob_handle b) -{ - statement_wrapper * wrapper = static_cast(st); - - if (name_exists_check_failed(*wrapper, - name, dt_blob, statement_wrapper::single, "blob")) - { - return; - } - - soci::indicator &ind = wrapper->use_indicators[name]; - blob_wrapper *&blob = wrapper->use_blob[name]; - if (ind == i_null && blob != NULL) - soci_destroy_blob(blob); - - ind = i_ok; - blob = static_cast(b); -} - -SOCI_DECL int soci_use_get_size_v(statement_handle st) -{ - statement_wrapper * wrapper = static_cast(st); - - if (wrapper->use_kind != statement_wrapper::bulk) - { - wrapper->is_ok = false; - wrapper->error_message = "No vector use elements."; - return -1; - } - - if (wrapper->use_indicators_v.empty()) - { - wrapper->is_ok = false; - wrapper->error_message = "Empty indicators vector."; - return -1; - } - - return static_cast(wrapper->use_indicators_v.begin()->second.size()); -} - -SOCI_DECL void soci_use_resize_v(statement_handle st, int new_size) -{ - statement_wrapper * wrapper = static_cast(st); - - if (new_size <= 0) - { - wrapper->is_ok = false; - wrapper->error_message = "Invalid size."; - return; - } - - if (wrapper->use_kind != statement_wrapper::bulk) - { - wrapper->is_ok = false; - wrapper->error_message = "No vector use elements."; - return; - } - - resize_in_map(wrapper->use_indicators_v, new_size); - resize_in_map(wrapper->use_strings_v, new_size); - resize_in_map(wrapper->use_ints_v, new_size); - resize_in_map(wrapper->use_longlongs_v, new_size); - resize_in_map(wrapper->use_doubles_v, new_size); - resize_in_map(wrapper->use_dates_v, new_size); - - wrapper->is_ok = true; -} - -SOCI_DECL void soci_set_use_state_v(statement_handle st, - char const * name, int index, int state) -{ - statement_wrapper * wrapper = static_cast(st); - - typedef std::map >::iterator iterator; - iterator const it = wrapper->use_indicators_v.find(name); - if (it == wrapper->use_indicators_v.end()) - { - wrapper->is_ok = false; - wrapper->error_message = "Invalid name."; - return; - } - - std::vector & v = it->second; - if (index_check_failed(v, *wrapper, index)) - { - return; - } - - v[index] = (state != 0 ? i_ok : i_null); -} - -SOCI_DECL void soci_set_use_string_v(statement_handle st, - char const * name, int index, char const * val) -{ - statement_wrapper * wrapper = static_cast(st); - - if (name_exists_check_failed(*wrapper, - name, dt_string, statement_wrapper::bulk, "vector string")) - { - return; - } - - std::vector & v = wrapper->use_strings_v[name]; - if (index_check_failed(v, *wrapper, index)) - { - return; - } - - wrapper->use_indicators_v[name][index] = i_ok; - v[index] = val; -} - -SOCI_DECL void soci_set_use_int_v(statement_handle st, - char const * name, int index, int val) -{ - statement_wrapper * wrapper = static_cast(st); - - if (name_exists_check_failed(*wrapper, - name, dt_integer, statement_wrapper::bulk, "vector int")) - { - return; - } - - std::vector & v = wrapper->use_ints_v[name]; - if (index_check_failed(v, *wrapper, index)) - { - return; - } - - wrapper->use_indicators_v[name][index] = i_ok; - v[index] = val; -} - -SOCI_DECL void soci_set_use_long_long_v(statement_handle st, - char const * name, int index, long long val) -{ - statement_wrapper * wrapper = static_cast(st); - - if (name_exists_check_failed(*wrapper, - name, dt_long_long, statement_wrapper::bulk, "vector long long")) - { - return; - } - - std::vector & v = wrapper->use_longlongs_v[name]; - if (index_check_failed(v, *wrapper, index)) - { - return; - } - - wrapper->use_indicators_v[name][index] = i_ok; - v[index] = val; -} - -SOCI_DECL void soci_set_use_double_v(statement_handle st, - char const * name, int index, double val) -{ - statement_wrapper * wrapper = static_cast(st); - - if (name_exists_check_failed(*wrapper, - name, dt_double, statement_wrapper::bulk, "vector double")) - { - return; - } - - std::vector & v = wrapper->use_doubles_v[name]; - if (index_check_failed(v, *wrapper, index)) - { - return; - } - - wrapper->use_indicators_v[name][index] = i_ok; - v[index] = val; -} - -SOCI_DECL void soci_set_use_date_v(statement_handle st, - char const * name, int index, char const * val) -{ - statement_wrapper * wrapper = static_cast(st); - - if (name_exists_check_failed(*wrapper, - name, dt_date, statement_wrapper::bulk, "vector date")) - { - return; - } - - std::vector & v = wrapper->use_dates_v[name]; - if (index_check_failed(v, *wrapper, index)) - { - return; - } - - std::tm dt = std::tm(); - bool const converted = string_to_date(val, dt, *wrapper); - if (converted == false) - { - return; - } - - wrapper->use_indicators_v[name][index] = i_ok; - v[index] = dt; -} - -SOCI_DECL int soci_get_use_state(statement_handle st, char const * name) -{ - statement_wrapper * wrapper = static_cast(st); - - typedef std::map::const_iterator iterator; - iterator const it = wrapper->use_indicators.find(name); - if (it == wrapper->use_indicators.end()) - { - wrapper->is_ok = false; - wrapper->error_message = "Invalid name."; - return 0; - } - - wrapper->is_ok = true; - return wrapper->use_indicators[name] == i_ok ? 1 : 0; -} - -SOCI_DECL char const * soci_get_use_string(statement_handle st, char const * name) -{ - statement_wrapper * wrapper = static_cast(st); - - if (name_exists_check_failed(*wrapper, - name, dt_string, statement_wrapper::bulk, "string")) - { - return ""; - } - - return wrapper->use_strings[name].c_str(); -} - -SOCI_DECL int soci_get_use_int(statement_handle st, char const * name) -{ - statement_wrapper * wrapper = static_cast(st); - - if (name_exists_check_failed(*wrapper, - name, dt_integer, statement_wrapper::bulk, "int")) - { - return 0; - } - - return wrapper->use_ints[name]; -} - -SOCI_DECL long long soci_get_use_long_long(statement_handle st, char const * name) -{ - statement_wrapper * wrapper = static_cast(st); - - if (name_exists_check_failed(*wrapper, - name, dt_long_long, statement_wrapper::bulk, "long long")) - { - return 0LL; - } - - return wrapper->use_longlongs[name]; -} - -SOCI_DECL double soci_get_use_double(statement_handle st, char const * name) -{ - statement_wrapper * wrapper = static_cast(st); - - if (name_exists_check_failed(*wrapper, - name, dt_double, statement_wrapper::bulk, "double")) - { - return 0.0; - } - - return wrapper->use_doubles[name]; -} - -SOCI_DECL char const * soci_get_use_date(statement_handle st, char const * name) -{ - statement_wrapper * wrapper = static_cast(st); - - if (name_exists_check_failed(*wrapper, - name, dt_date, statement_wrapper::bulk, "date")) - { - return ""; - } - - // format is: "YYYY MM DD hh mm ss" - std::tm const & d = wrapper->use_dates[name]; - std::sprintf(wrapper->date_formatted, "%d %d %d %d %d %d", - d.tm_year + 1900, d.tm_mon + 1, d.tm_mday, - d.tm_hour, d.tm_min, d.tm_sec); - - return wrapper->date_formatted; -} - -SOCI_DECL blob_handle soci_get_use_blob(statement_handle st, char const * name) -{ - statement_wrapper * wrapper = static_cast(st); - - if (name_exists_check_failed(*wrapper, - name, dt_blob, statement_wrapper::bulk, "blob")) - { - return NULL; - } - - return wrapper->use_blob[name]; -} - -SOCI_DECL void soci_prepare(statement_handle st, char const * query) -{ - statement_wrapper * wrapper = static_cast(st); - - try - { - wrapper->statement_state = statement_wrapper::executing; - - // bind all into elements - - int const into_elements = static_cast(wrapper->into_types.size()); - if (wrapper->into_kind == statement_wrapper::single) - { - for (int i = 0; i != into_elements; ++i) - { - switch (wrapper->into_types[i]) - { - case dt_string: - wrapper->st.exchange( - into(wrapper->into_strings[i], wrapper->into_indicators[i])); - break; - case dt_integer: - wrapper->st.exchange( - into(wrapper->into_ints[i], wrapper->into_indicators[i])); - break; - case dt_long_long: - case dt_unsigned_long_long: - wrapper->st.exchange( - into(wrapper->into_longlongs[i], wrapper->into_indicators[i])); - break; - case dt_double: - wrapper->st.exchange( - into(wrapper->into_doubles[i], wrapper->into_indicators[i])); - break; - case dt_date: - wrapper->st.exchange( - into(wrapper->into_dates[i], wrapper->into_indicators[i])); - break; - case dt_blob: - wrapper->st.exchange( - into(wrapper->into_blob[i]->blob_, wrapper->into_indicators[i])); - break; - case dt_xml: - // no support for xml - break; - } - } - } - else - { - // vector elements - for (int i = 0; i != into_elements; ++i) - { - switch (wrapper->into_types[i]) - { - case dt_string: - wrapper->st.exchange( - into(wrapper->into_strings_v[i], wrapper->into_indicators_v[i])); - break; - case dt_integer: - wrapper->st.exchange( - into(wrapper->into_ints_v[i], wrapper->into_indicators_v[i])); - break; - case dt_long_long: - case dt_unsigned_long_long: - wrapper->st.exchange( - into(wrapper->into_longlongs_v[i], wrapper->into_indicators_v[i])); - break; - case dt_double: - wrapper->st.exchange( - into(wrapper->into_doubles_v[i], wrapper->into_indicators_v[i])); - break; - case dt_date: - wrapper->st.exchange( - into(wrapper->into_dates_v[i], wrapper->into_indicators_v[i])); - break; - case dt_blob: - case dt_xml: - // no support for bulk blob and xml - break; - } - } - } - - // bind all use elements - { - // strings - typedef std::map::iterator iterator; - iterator uit = wrapper->use_strings.begin(); - iterator const uend = wrapper->use_strings.end(); - for ( ; uit != uend; ++uit) - { - std::string const & use_name = uit->first; - std::string & use_string = uit->second; - indicator & use_ind = wrapper->use_indicators[use_name]; - wrapper->st.exchange(use(use_string, use_ind, use_name)); - } - } - { - // ints - typedef std::map::iterator iterator; - iterator uit = wrapper->use_ints.begin(); - iterator const uend = wrapper->use_ints.end(); - for ( ; uit != uend; ++uit) - { - std::string const & use_name = uit->first; - int & use_int = uit->second; - indicator & use_ind = wrapper->use_indicators[use_name]; - wrapper->st.exchange(use(use_int, use_ind, use_name)); - } - } - { - // longlongs - typedef std::map::iterator iterator; - iterator uit = wrapper->use_longlongs.begin(); - iterator const uend = wrapper->use_longlongs.end(); - for ( ; uit != uend; ++uit) - { - std::string const & use_name = uit->first; - long long & use_longlong = uit->second; - indicator & use_ind = wrapper->use_indicators[use_name]; - wrapper->st.exchange(use(use_longlong, use_ind, use_name)); - } - } - { - // doubles - typedef std::map::iterator iterator; - iterator uit = wrapper->use_doubles.begin(); - iterator const uend = wrapper->use_doubles.end(); - for ( ; uit != uend; ++uit) - { - std::string const & use_name = uit->first; - double & use_double = uit->second; - indicator & use_ind = wrapper->use_indicators[use_name]; - wrapper->st.exchange(use(use_double, use_ind, use_name)); - } - } - { - // dates - typedef std::map::iterator iterator; - iterator uit = wrapper->use_dates.begin(); - iterator const uend = wrapper->use_dates.end(); - for ( ; uit != uend; ++uit) - { - std::string const & use_name = uit->first; - std::tm & use_date = uit->second; - indicator & use_ind = wrapper->use_indicators[use_name]; - wrapper->st.exchange(use(use_date, use_ind, use_name)); - } - } - { - // blobs - typedef std::map::iterator iterator; - iterator uit = wrapper->use_blob.begin(); - iterator uend = wrapper->use_blob.end(); - for ( ; uit != uend; ++uit) - { - std::string const & use_name = uit->first; - blob &use_blob = uit->second->blob_; - indicator & use_ind = wrapper->use_indicators[use_name]; - wrapper->st.exchange(use(use_blob, use_ind, use_name)); - } - } - - // bind all use vecctor elements - { - // strings - typedef std::map >::iterator iterator; - iterator uit = wrapper->use_strings_v.begin(); - iterator const uend = wrapper->use_strings_v.end(); - for ( ; uit != uend; ++uit) - { - std::string const & use_name = uit->first; - std::vector & use_string = uit->second; - std::vector & use_ind = - wrapper->use_indicators_v[use_name]; - wrapper->st.exchange(use(use_string, use_ind, use_name)); - } - } - { - // ints - typedef std::map >::iterator iterator; - iterator uit = wrapper->use_ints_v.begin(); - iterator const uend = wrapper->use_ints_v.end(); - for ( ; uit != uend; ++uit) - { - std::string const & use_name = uit->first; - std::vector & use_int = uit->second; - std::vector & use_ind = - wrapper->use_indicators_v[use_name]; - wrapper->st.exchange(use(use_int, use_ind, use_name)); - } - } - { - // longlongs - typedef std::map >::iterator iterator; - iterator uit = wrapper->use_longlongs_v.begin(); - iterator const uend = wrapper->use_longlongs_v.end(); - for ( ; uit != uend; ++uit) - { - std::string const & use_name = uit->first; - std::vector & use_longlong = uit->second; - std::vector & use_ind = - wrapper->use_indicators_v[use_name]; - wrapper->st.exchange(use(use_longlong, use_ind, use_name)); - } - } - { - // doubles - typedef std::map >::iterator iterator; - iterator uit = wrapper->use_doubles_v.begin(); - iterator const uend = wrapper->use_doubles_v.end(); - for ( ; uit != uend; ++uit) - { - std::string const & use_name = uit->first; - std::vector & use_double = uit->second; - std::vector & use_ind = - wrapper->use_indicators_v[use_name]; - wrapper->st.exchange(use(use_double, use_ind, use_name)); - } - } - { - // dates - typedef std::map >::iterator iterator; - iterator uit = wrapper->use_dates_v.begin(); - iterator const uend = wrapper->use_dates_v.end(); - for ( ; uit != uend; ++uit) - { - std::string const & use_name = uit->first; - std::vector & use_date = uit->second; - std::vector & use_ind = - wrapper->use_indicators_v[use_name]; - wrapper->st.exchange(use(use_date, use_ind, use_name)); - } - } - - wrapper->st.alloc(); - wrapper->st.prepare(query); - wrapper->st.define_and_bind(); - - wrapper->is_ok = true; - } - catch (std::exception const & e) - { - wrapper->is_ok = false; - wrapper->error_message = e.what(); - } -} - -SOCI_DECL int soci_execute(statement_handle st, int withDataExchange) -{ - statement_wrapper * wrapper = static_cast(st); - - try - { - bool const gotData = wrapper->st.execute(withDataExchange != 0); - - wrapper->is_ok = true; - - return gotData ? 1 : 0; - } - catch (std::exception const & e) - { - wrapper->is_ok = false; - wrapper->error_message = e.what(); - - return 0; - } -} - -SOCI_DECL long long soci_get_affected_rows(statement_handle st) -{ - statement_wrapper * wrapper = static_cast(st); - - return wrapper->st.get_affected_rows(); -} - -SOCI_DECL int soci_fetch(statement_handle st) -{ - statement_wrapper * wrapper = static_cast(st); - - try - { - bool const gotData = wrapper->st.fetch(); - - wrapper->is_ok = true; - - return gotData ? 1 : 0; - } - catch (std::exception const & e) - { - wrapper->is_ok = false; - wrapper->error_message = e.what(); - - return 0; - } -} - -SOCI_DECL int soci_got_data(statement_handle st) -{ - statement_wrapper * wrapper = static_cast(st); - - return wrapper->st.got_data() ? 1 : 0; -} - -SOCI_DECL int soci_statement_state(statement_handle st) -{ - statement_wrapper * wrapper = static_cast(st); - - return wrapper->is_ok ? 1 : 0; -} - -SOCI_DECL char const * soci_statement_error_message(statement_handle st) -{ - statement_wrapper * wrapper = static_cast(st); - - return wrapper->error_message.c_str(); -} diff --git a/src/soci/src/core/soci_backends_config.h.in b/src/soci/src/core/soci_backends_config.h.in deleted file mode 100644 index 9550611a18..0000000000 --- a/src/soci/src/core/soci_backends_config.h.in +++ /dev/null @@ -1,12 +0,0 @@ -// -// Copyright (C) 2011 Alex Ott -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -#ifndef SOCI_BACKENDS_CONFIG_H -#define SOCI_BACKENDS_CONFIG_H - -#define DEFAULT_BACKENDS_PATH "@CMAKE_INSTALL_PREFIX@/@LIBDIR@" - -#endif // SOCI_BACKENDS_CONFIG_H diff --git a/src/soci/src/core/statement.cpp b/src/soci/src/core/statement.cpp deleted file mode 100644 index ddf19789d5..0000000000 --- a/src/soci/src/core/statement.cpp +++ /dev/null @@ -1,806 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SOURCE -#include "soci/statement.h" -#include "soci/session.h" -#include "soci/into-type.h" -#include "soci/use-type.h" -#include "soci/values.h" -#include "soci-compiler.h" -#include -#include - -using namespace soci; -using namespace soci::details; - - -statement_impl::statement_impl(session & s) - : session_(s), refCount_(1), row_(0), - fetchSize_(1), initialFetchSize_(1), - alreadyDescribed_(false) -{ - backEnd_ = s.make_statement_backend(); -} - -statement_impl::statement_impl(prepare_temp_type const & prep) - : session_(prep.get_prepare_info()->session_), - refCount_(1), row_(0), fetchSize_(1), alreadyDescribed_(false) -{ - backEnd_ = session_.make_statement_backend(); - - ref_counted_prepare_info * prepInfo = prep.get_prepare_info(); - - // take all bind/define info - intos_.swap(prepInfo->intos_); - uses_.swap(prepInfo->uses_); - - // allocate handle - alloc(); - - // prepare the statement - query_ = prepInfo->get_query(); - try - { - prepare(query_); - } - catch(...) - { - clean_up(); - throw; - } - - define_and_bind(); -} - -statement_impl::~statement_impl() -{ - clean_up(); -} - -void statement_impl::alloc() -{ - backEnd_->alloc(); -} - -void statement_impl::bind(values & values) -{ - std::size_t cnt = 0; - - try - { - for (std::vector::iterator it = - values.uses_.begin(); it != values.uses_.end(); ++it) - { - // only bind those variables which are: - // - either named and actually referenced in the statement, - // - or positional - - std::string const& useName = (*it)->get_name(); - if (useName.empty()) - { - // positional use element - - int position = static_cast(uses_.size()); - (*it)->bind(*this, position); - uses_.push_back(*it); - indicators_.push_back(values.indicators_[cnt]); - } - else - { - // named use element - check if it is used - std::string const placeholder = ":" + useName; - - std::size_t pos = query_.find(placeholder); - while (pos != std::string::npos) - { - // Retrieve next char after placeholder - // make sure we do not go out of range on the string - const char nextChar = (pos + placeholder.size()) < query_.size() ? - query_[pos + placeholder.size()] : '\0'; - - if (std::isalnum(nextChar)) - { - // We got a partial match only, - // keep looking for the placeholder - pos = query_.find(placeholder, pos + placeholder.size()); - } - else - { - int position = static_cast(uses_.size()); - (*it)->bind(*this, position); - uses_.push_back(*it); - indicators_.push_back(values.indicators_[cnt]); - // Ok we found it, done - break; - } - } - // In case we couldn't find the placeholder - if (pos == std::string::npos) - { - values.add_unused(*it, values.indicators_[cnt]); - } - } - - cnt++; - } - } - catch (...) - { - for (std::size_t i = ++cnt; i != values.uses_.size(); ++i) - { - values.add_unused(values.uses_[i], values.indicators_[i]); - } - - rethrow_current_exception_with_context("binding parameters of"); - } -} - -void statement_impl::bind_clean_up() -{ - // deallocate all bind and define objects - std::size_t const isize = intos_.size(); - for (std::size_t i = isize; i != 0; --i) - { - intos_[i - 1]->clean_up(); - delete intos_[i - 1]; - intos_.resize(i - 1); - } - - std::size_t const ifrsize = intosForRow_.size(); - for (std::size_t i = ifrsize; i != 0; --i) - { - intosForRow_[i - 1]->clean_up(); - delete intosForRow_[i - 1]; - intosForRow_.resize(i - 1); - } - - std::size_t const usize = uses_.size(); - for (std::size_t i = usize; i != 0; --i) - { - uses_[i - 1]->clean_up(); - delete uses_[i - 1]; - uses_.resize(i - 1); - } - - std::size_t const indsize = indicators_.size(); - for (std::size_t i = 0; i != indsize; ++i) - { - delete indicators_[i]; - indicators_[i] = NULL; - } - - row_ = NULL; - alreadyDescribed_ = false; -} - -void statement_impl::clean_up() -{ - bind_clean_up(); - if (backEnd_ != NULL) - { - backEnd_->clean_up(); - delete backEnd_; - backEnd_ = NULL; - } -} - -void statement_impl::prepare(std::string const & query, - statement_type eType) -{ - try - { - query_ = query; - session_.log_query(query); - - backEnd_->prepare(query, eType); - } - catch (...) - { - rethrow_current_exception_with_context("preparing"); - } -} - -void statement_impl::define_and_bind() -{ - int definePosition = 1; - std::size_t const isize = intos_.size(); - for (std::size_t i = 0; i != isize; ++i) - { - intos_[i]->define(*this, definePosition); - } - - // if there are some implicite into elements - // injected by the row description process, - // they should be defined in the later phase, - // starting at the position where the above loop finished - definePositionForRow_ = definePosition; - - int bindPosition = 1; - std::size_t const usize = uses_.size(); - for (std::size_t i = 0; i != usize; ++i) - { - uses_[i]->bind(*this, bindPosition); - } -} - -void statement_impl::define_for_row() -{ - std::size_t const isize = intosForRow_.size(); - for (std::size_t i = 0; i != isize; ++i) - { - intosForRow_[i]->define(*this, definePositionForRow_); - } -} - -void statement_impl::undefine_and_bind() -{ - std::size_t const isize = intos_.size(); - for (std::size_t i = isize; i != 0; --i) - { - intos_[i - 1]->clean_up(); - } - - std::size_t const ifrsize = intosForRow_.size(); - for (std::size_t i = ifrsize; i != 0; --i) - { - intosForRow_[i - 1]->clean_up(); - } - - std::size_t const usize = uses_.size(); - for (std::size_t i = usize; i != 0; --i) - { - uses_[i - 1]->clean_up(); - } -} - -bool statement_impl::execute(bool withDataExchange) -{ - try - { - initialFetchSize_ = intos_size(); - - if (intos_.empty() == false && initialFetchSize_ == 0) - { - // this can happen only with into-vectors elements - // and is not allowed when calling execute - throw soci_error("Vectors of size 0 are not allowed."); - } - - fetchSize_ = initialFetchSize_; - - // pre-use should be executed before inspecting the sizes of use - // elements, as they can be resized in type conversion routines - - pre_use(); - - std::size_t const bindSize = uses_size(); - - if (bindSize > 1 && fetchSize_ > 1) - { - throw soci_error( - "Bulk insert/update and bulk select not allowed in same query"); - } - - // looks like a hack and it is - row description should happen - // *after* the use elements were completely prepared - // and *before* the into elements are touched, so that the row - // description process can inject more into elements for - // implicit data exchange - if (row_ != NULL && alreadyDescribed_ == false) - { - describe(); - define_for_row(); - } - - int num = 0; - if (withDataExchange) - { - num = 1; - - pre_fetch(); - - if (static_cast(fetchSize_) > num) - { - num = static_cast(fetchSize_); - } - if (static_cast(bindSize) > num) - { - num = static_cast(bindSize); - } - } - - pre_exec(num); - - statement_backend::exec_fetch_result res = backEnd_->execute(num); - - bool gotData = false; - - if (res == statement_backend::ef_success) - { - // the "success" means that the statement executed correctly - // and for select statement this also means that some rows were read - - if (num > 0) - { - gotData = true; - - // ensure into vectors have correct size - resize_intos(static_cast(num)); - } - } - else // res == ef_no_data - { - // the "no data" means that the end-of-rowset condition was hit - // but still some rows might have been read (the last bunch of rows) - // it can also mean that the statement did not produce any results - - gotData = fetchSize_ > 1 ? resize_intos() : false; - } - - if (num > 0) - { - post_fetch(gotData, false); - } - - post_use(gotData); - - session_.set_got_data(gotData); - return gotData; - } - catch (...) - { - rethrow_current_exception_with_context("executing"); - } -} - -long long statement_impl::get_affected_rows() -{ - try - { - return backEnd_->get_affected_rows(); - } - catch (...) - { - rethrow_current_exception_with_context("getting the number of rows affected by"); - } -} - -bool statement_impl::fetch() -{ - try - { - if (fetchSize_ == 0) - { - truncate_intos(); - session_.set_got_data(false); - return false; - } - - bool gotData = false; - - // vectors might have been resized between fetches - std::size_t const newFetchSize = intos_size(); - if (newFetchSize > initialFetchSize_) - { - // this is not allowed, because most likely caused reallocation - // of the vector - this would require complete re-bind - - throw soci_error( - "Increasing the size of the output vector is not supported."); - } - else if (newFetchSize == 0) - { - session_.set_got_data(false); - return false; - } - else - { - // the output vector was downsized or remains the same as before - fetchSize_ = newFetchSize; - } - - statement_backend::exec_fetch_result const res = backEnd_->fetch(static_cast(fetchSize_)); - if (res == statement_backend::ef_success) - { - // the "success" means that some number of rows was read - // and that it is not yet the end-of-rowset (there are more rows) - - gotData = true; - - // ensure into vectors have correct size - resize_intos(fetchSize_); - } - else // res == ef_no_data - { - // end-of-rowset condition - - if (fetchSize_ > 1) - { - // but still the last bunch of rows might have been read - gotData = resize_intos(); - fetchSize_ = 0; - } - else - { - truncate_intos(); - gotData = false; - } - } - - post_fetch(gotData, true); - session_.set_got_data(gotData); - return gotData; - } - catch (...) - { - rethrow_current_exception_with_context("fetching data from"); - } -} - -std::size_t statement_impl::intos_size() -{ - // this function does not need to take into account intosForRow_ elements, - // since their sizes are always 1 (which is the same and the primary - // into(row) element, which has injected them) - - std::size_t intos_size = 0; - std::size_t const isize = intos_.size(); - for (std::size_t i = 0; i != isize; ++i) - { - if (i==0) - { - intos_size = intos_[i]->size(); - } - else if (intos_size != intos_[i]->size()) - { - std::ostringstream msg; - msg << "Bind variable size mismatch (into[" - << static_cast(i) << "] has size " - << static_cast(intos_[i]->size()) - << ", into[0] has size " - << static_cast(intos_size); - throw soci_error(msg.str()); - } - } - return intos_size; -} - -std::size_t statement_impl::uses_size() -{ - std::size_t usesSize = 0; - std::size_t const usize = uses_.size(); - for (std::size_t i = 0; i != usize; ++i) - { - if (i==0) - { - usesSize = uses_[i]->size(); - if (usesSize == 0) - { - // this can happen only for vectors - throw soci_error("Vectors of size 0 are not allowed."); - } - } - else if (usesSize != uses_[i]->size()) - { - std::ostringstream msg; - msg << "Bind variable size mismatch (use[" - << static_cast(i) << "] has size " - << static_cast(uses_[i]->size()) - << ", use[0] has size " - << static_cast(usesSize); - throw soci_error(msg.str()); - } - } - return usesSize; -} - -bool statement_impl::resize_intos(std::size_t upperBound) -{ - // this function does not need to take into account the intosForRow_ - // elements, since they are never used for bulk operations - - int rows = backEnd_->get_number_of_rows(); - if (rows < 0) - { - rows = 0; - } - if (upperBound != 0 && upperBound < static_cast(rows)) - { - rows = static_cast(upperBound); - } - - std::size_t const isize = intos_.size(); - for (std::size_t i = 0; i != isize; ++i) - { - intos_[i]->resize((std::size_t)rows); - } - - return rows > 0 ? true : false; -} - -void statement_impl::truncate_intos() -{ - std::size_t const isize = intos_.size(); - for (std::size_t i = 0; i != isize; ++i) - { - intos_[i]->resize(0); - } -} - -void statement_impl::pre_exec(int num) -{ - std::size_t const isize = intos_.size(); - for (std::size_t i = 0; i != isize; ++i) - { - intos_[i]->pre_exec(num); - } - - std::size_t const ifrsize = intosForRow_.size(); - for (std::size_t i = 0; i != ifrsize; ++i) - { - intosForRow_[i]->pre_exec(num); - } - - std::size_t const usize = uses_.size(); - for (std::size_t i = 0; i != usize; ++i) - { - uses_[i]->pre_exec(num); - } -} - -void statement_impl::pre_fetch() -{ - std::size_t const isize = intos_.size(); - for (std::size_t i = 0; i != isize; ++i) - { - intos_[i]->pre_fetch(); - } - - std::size_t const ifrsize = intosForRow_.size(); - for (std::size_t i = 0; i != ifrsize; ++i) - { - intosForRow_[i]->pre_fetch(); - } -} - -void statement_impl::pre_use() -{ - std::size_t const usize = uses_.size(); - for (std::size_t i = 0; i != usize; ++i) - { - uses_[i]->pre_use(); - } -} - -void statement_impl::post_fetch(bool gotData, bool calledFromFetch) -{ - // first iterate over intosForRow_ elements, since the Row element - // (which is among the intos_ elements) might depend on the - // values of those implicitly injected elements - - std::size_t const ifrsize = intosForRow_.size(); - for (std::size_t i = 0; i != ifrsize; ++i) - { - intosForRow_[i]->post_fetch(gotData, calledFromFetch); - } - - std::size_t const isize = intos_.size(); - for (std::size_t i = 0; i != isize; ++i) - { - intos_[i]->post_fetch(gotData, calledFromFetch); - } -} - -void statement_impl::post_use(bool gotData) -{ - // iterate in reverse order here in case the first item - // is an UseType (since it depends on the other UseTypes) - for (std::size_t i = uses_.size(); i != 0; --i) - { - uses_[i-1]->post_use(gotData); - } -} - -namespace soci -{ -namespace details -{ - -// Map data_types to stock types for dynamic result set support - -template<> -void statement_impl::bind_into() -{ - into_row(); -} - -template<> -void statement_impl::bind_into() -{ - into_row(); -} - -template<> -void statement_impl::bind_into() -{ - into_row(); -} - -template<> -void statement_impl::bind_into() -{ - into_row(); -} - -template<> -void statement_impl::bind_into() -{ - into_row(); -} - -template<> -void statement_impl::bind_into() -{ - into_row(); -} - -void statement_impl::describe() -{ - row_->clean_up(); - - int const numcols = backEnd_->prepare_for_describe(); - for (int i = 1; i <= numcols; ++i) - { - data_type dtype; - std::string columnName; - - backEnd_->describe_column(i, dtype, columnName); - - column_properties props; - props.set_name(columnName); - props.set_data_type(dtype); - - switch (dtype) - { - case dt_string: - bind_into(); - break; - case dt_double: - bind_into(); - break; - case dt_integer: - bind_into(); - break; - case dt_long_long: - bind_into(); - break; - case dt_unsigned_long_long: - bind_into(); - break; - case dt_date: - bind_into(); - break; - default: - std::ostringstream msg; - msg << "db column type " << dtype - <<" not supported for dynamic selects"<add_properties(props); - } - - alreadyDescribed_ = true; -} - -} // namespace details -} // namespace soci - -void statement_impl::set_row(row * r) -{ - if (row_ != NULL) - { - throw soci_error( - "Only one Row element allowed in a single statement."); - } - - row_ = r; - row_->uppercase_column_names(session_.get_uppercase_column_names()); -} - -std::string statement_impl::rewrite_for_procedure_call(std::string const & query) -{ - return backEnd_->rewrite_for_procedure_call(query); -} - -void statement_impl::inc_ref() -{ - ++refCount_; -} - -void statement_impl::dec_ref() -{ - if (--refCount_ == 0) - { - delete this; - } -} - -standard_into_type_backend * -statement_impl::make_into_type_backend() -{ - return backEnd_->make_into_type_backend(); -} - -standard_use_type_backend * -statement_impl::make_use_type_backend() -{ - return backEnd_->make_use_type_backend(); -} - -vector_into_type_backend * -statement_impl::make_vector_into_type_backend() -{ - return backEnd_->make_vector_into_type_backend(); -} - -vector_use_type_backend * -statement_impl::make_vector_use_type_backend() -{ - return backEnd_->make_vector_use_type_backend(); -} - -SOCI_NORETURN -statement_impl::rethrow_current_exception_with_context(char const* operation) -{ - try - { - throw; - } - catch (soci_error& e) - { - if (!query_.empty()) - { - std::ostringstream oss; - oss << "while " << operation << " \"" << query_ << "\""; - - if (!uses_.empty()) - { - oss << " with "; - - std::size_t const usize = uses_.size(); - for (std::size_t i = 0; i != usize; ++i) - { - if (i != 0) - oss << ", "; - - details::use_type_base const& u = *uses_[i]; - - // Use the name specified in the "use()" call if any, - // otherwise get the name of the matching parameter from - // the query itself, as parsed by the backend. - std::string name = u.get_name(); - if (name.empty()) - name = backEnd_->get_parameter_name(static_cast(i)); - - oss << ":"; - if (!name.empty()) - oss << name; - else - oss << (i + 1); - oss << "="; - - u.dump_value(oss); - } - } - - e.add_context(oss.str()); - } - - throw; - } -} diff --git a/src/soci/src/core/transaction.cpp b/src/soci/src/core/transaction.cpp deleted file mode 100644 index bb53d77925..0000000000 --- a/src/soci/src/core/transaction.cpp +++ /dev/null @@ -1,53 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SOURCE -#include "soci/transaction.h" -#include "soci/error.h" - -using namespace soci; - -transaction::transaction(session& sql) - : handled_(false), sql_(sql) -{ - sql_.begin(); -} - -transaction::~transaction() -{ - if (handled_ == false) - { - try - { - rollback(); - } - catch (...) - {} - } -} - -void transaction::commit() -{ - if (handled_) - { - throw soci_error("The transaction object cannot be handled twice."); - } - - sql_.commit(); - handled_ = true; -} - -void transaction::rollback() -{ - if (handled_) - { - throw soci_error("The transaction object cannot be handled twice."); - } - - sql_.rollback(); - handled_ = true; -} diff --git a/src/soci/src/core/use-type.cpp b/src/soci/src/core/use-type.cpp deleted file mode 100644 index 646a9e7db9..0000000000 --- a/src/soci/src/core/use-type.cpp +++ /dev/null @@ -1,219 +0,0 @@ -// -// Copyright (C) 2004-2016 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SOURCE -#include "soci/soci-platform.h" -#include "soci/use-type.h" -#include "soci/statement.h" -#include "soci-exchange-cast.h" - -#include - -using namespace soci; -using namespace soci::details; - -standard_use_type::~standard_use_type() -{ - delete backEnd_; -} - -void standard_use_type::bind(statement_impl & st, int & position) -{ - if (backEnd_ == NULL) - { - backEnd_ = st.make_use_type_backend(); - } - - if (name_.empty()) - { - backEnd_->bind_by_pos(position, data_, type_, readOnly_); - } - else - { - backEnd_->bind_by_name(name_, data_, type_, readOnly_); - } -} - -void standard_use_type::dump_value(std::ostream& os) const -{ - if (ind_ && *ind_ == i_null) - { - os << "NULL"; - return; - } - - switch (type_) - { - case x_char: - os << "'" << exchange_type_cast(data_) << "'"; - return; - - case x_stdstring: - // TODO: Escape quotes? - os << "\"" << exchange_type_cast(data_) << "\""; - return; - - case x_short: - os << exchange_type_cast(data_); - return; - - case x_integer: - os << exchange_type_cast(data_); - return; - - case x_long_long: - os << exchange_type_cast(data_); - return; - - case x_unsigned_long_long: - os << exchange_type_cast(data_); - return; - - case x_double: - os << exchange_type_cast(data_); - return; - - case x_stdtm: - { - std::tm const& t = exchange_type_cast(data_); - - char buf[32]; - snprintf(buf, sizeof(buf), "%04d-%02d-%02d %02d:%02d:%02d", - t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, - t.tm_hour, t.tm_min, t.tm_sec); - - os << buf; - } - return; - - case x_statement: - os << ""; - return; - - case x_rowid: - os << ""; - return; - - case x_blob: - os << ""; - return; - - case x_xmltype: - os << ""; - return; - - case x_longstring: - os << ""; - return; - } - - // This is normally unreachable, but avoid throwing from here as we're - // typically called from an exception handler. - os << ""; -} - -void standard_use_type::pre_exec(int num) -{ - backEnd_->pre_exec(num); -} - -void standard_use_type::pre_use() -{ - // Handle IN direction of parameters of SQL statements and procedures - convert_to_base(); - backEnd_->pre_use(ind_); -} - -void standard_use_type::post_use(bool gotData) -{ - // Handle OUT direction of IN/OUT parameters of stored procedures - backEnd_->post_use(gotData, ind_); - convert_from_base(); - - // IMPORTANT: - // This treatment of input ("use") parameter as output data sink may be - // confusing, but it is necessary to store OUT data back in the same - // object as IN, of IN/OUT parameter. - // As there is no symmetry for IN/OUT in SQL and there are no OUT/IN - // we do not perform convert_to_base() for output ("into") parameter. - // See conversion_use_type::convert_from_base() for more details. -} - -void standard_use_type::clean_up() -{ - if (backEnd_ != NULL) - { - backEnd_->clean_up(); - } -} - -vector_use_type::~vector_use_type() -{ - delete backEnd_; -} - -void vector_use_type::bind(statement_impl & st, int & position) -{ - if (backEnd_ == NULL) - { - backEnd_ = st.make_vector_use_type_backend(); - } - - if (name_.empty()) - { - if (end_ != NULL) - { - backEnd_->bind_by_pos_bulk(position, data_, type_, begin_, end_); - } - else - { - backEnd_->bind_by_pos(position, data_, type_); - } - } - else - { - if (end_ != NULL) - { - backEnd_->bind_by_name_bulk(name_, data_, type_, begin_, end_); - } - else - { - backEnd_->bind_by_name(name_, data_, type_); - } - } -} - -void vector_use_type::dump_value(std::ostream& os) const -{ - // TODO: Provide more information. - os << ""; -} - -void vector_use_type::pre_exec(int num) -{ - backEnd_->pre_exec(num); -} - -void vector_use_type::pre_use() -{ - convert_to_base(); - - backEnd_->pre_use(ind_ ? &ind_->at(0) : NULL); -} - -std::size_t vector_use_type::size() const -{ - return backEnd_->size(); -} - -void vector_use_type::clean_up() -{ - if (backEnd_ != NULL) - { - backEnd_->clean_up(); - } -} diff --git a/src/soci/src/core/values.cpp b/src/soci/src/core/values.cpp deleted file mode 100644 index 7fa9d1a7d1..0000000000 --- a/src/soci/src/core/values.cpp +++ /dev/null @@ -1,69 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#define SOCI_SOURCE -#include "soci/values.h" -#include "soci/row.h" - -#include -#include -#include -#include - -using namespace soci; -using namespace soci::details; - -indicator values::get_indicator(std::size_t pos) const -{ - if (row_) - { - return row_->get_indicator(pos); - } - else - { - return *indicators_[pos]; - } -} - -indicator values::get_indicator(std::string const& name) const -{ - if (row_) - { - return row_->get_indicator(name); - } - else - { - std::map::const_iterator it = index_.find(name); - if (it == index_.end()) - { - std::ostringstream msg; - msg << "Column '" << name << "' not found"; - throw soci_error(msg.str()); - } - return *indicators_[it->second]; - } -} - -column_properties const& values::get_properties(std::size_t pos) const -{ - if (row_) - { - return row_->get_properties(pos); - } - - throw soci_error("Rowset is empty"); -} - -column_properties const& values::get_properties(std::string const& name) const -{ - if (row_) - { - return row_->get_properties(name); - } - - throw soci_error("Rowset is empty"); -} diff --git a/src/soci/tests/CMakeLists.txt b/src/soci/tests/CMakeLists.txt deleted file mode 100644 index dd1b17745f..0000000000 --- a/src/soci/tests/CMakeLists.txt +++ /dev/null @@ -1,32 +0,0 @@ -############################################################################### -# -# This file is part of CMake configuration for SOCI library -# -# Copyright (C) 2013 Mateusz Loskot -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -# -############################################################################### - -colormsg(_HIBLUE_ "Configuring SOCI tests:") - -# Request CATCH to disable all the C++11 features -if (NOT SOCI_CXX_C11) - add_definitions(-DCATCH_CONFIG_NO_CPP11) -endif() - -include_directories( - ${SOCI_SOURCE_DIR}/include/private - ${CMAKE_CURRENT_SOURCE_DIR}) - -file(GLOB SOCI_TESTS_COMMON common-tests.h) - -add_subdirectory(empty) -add_subdirectory(db2) -add_subdirectory(firebird) -add_subdirectory(mysql) -add_subdirectory(odbc) -add_subdirectory(oracle) -add_subdirectory(postgresql) -add_subdirectory(sqlite3) diff --git a/src/soci/tests/README.md b/src/soci/tests/README.md deleted file mode 100644 index 4cce8a3bd1..0000000000 --- a/src/soci/tests/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# soci/tests - -SOCI tests using [CATCH](http://catch-lib.net/) testing framework live here. - -Currently one test is built for each backend, i.e. there are -`soci_oracle_test`, `soci_postgresql_test`, `soci_sqlite3_test` and so on and -for ODBC backend there are multiple versions of the test depending on the ODBC -driver used. Each of these tests can be run with a single parameter describing -the database to use for testing in the backend-specific way as well as any of -the standard [CATCH command line options](https://github.com/philsquared/Catch/blob/master/docs/command-line.md). diff --git a/src/soci/tests/catch.hpp b/src/soci/tests/catch.hpp deleted file mode 100644 index f7681f49ea..0000000000 --- a/src/soci/tests/catch.hpp +++ /dev/null @@ -1,11545 +0,0 @@ -/* - * Catch v1.9.6 - * Generated: 2017-06-27 12:19:54.557875 - * ---------------------------------------------------------- - * This file has been merged from multiple headers. Please don't edit it directly - * Copyright (c) 2012 Two Blue Cubes Ltd. All rights reserved. - * - * Distributed under the Boost Software License, Version 1.0. (See accompanying - * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - */ -#ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED -#define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED - -#define TWOBLUECUBES_CATCH_HPP_INCLUDED - -#ifdef __clang__ -# pragma clang system_header -#elif defined __GNUC__ -# pragma GCC system_header -#endif - -// #included from: internal/catch_suppress_warnings.h - -#ifdef __clang__ -# ifdef __ICC // icpc defines the __clang__ macro -# pragma warning(push) -# pragma warning(disable: 161 1682) -# else // __ICC -# pragma clang diagnostic ignored "-Wglobal-constructors" -# pragma clang diagnostic ignored "-Wvariadic-macros" -# pragma clang diagnostic ignored "-Wc99-extensions" -# pragma clang diagnostic ignored "-Wunused-variable" -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wpadded" -# pragma clang diagnostic ignored "-Wc++98-compat" -# pragma clang diagnostic ignored "-Wc++98-compat-pedantic" -# pragma clang diagnostic ignored "-Wswitch-enum" -# pragma clang diagnostic ignored "-Wcovered-switch-default" -# endif -#elif defined __GNUC__ -# pragma GCC diagnostic ignored "-Wvariadic-macros" -# pragma GCC diagnostic ignored "-Wunused-variable" -# pragma GCC diagnostic ignored "-Wparentheses" - -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wpadded" -#endif -#if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER) -# define CATCH_IMPL -#endif - -#ifdef CATCH_IMPL -# ifndef CLARA_CONFIG_MAIN -# define CLARA_CONFIG_MAIN_NOT_DEFINED -# define CLARA_CONFIG_MAIN -# endif -#endif - -// #included from: internal/catch_notimplemented_exception.h -#define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_H_INCLUDED - -// #included from: catch_common.h -#define TWOBLUECUBES_CATCH_COMMON_H_INCLUDED - -// #included from: catch_compiler_capabilities.h -#define TWOBLUECUBES_CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED - -// Detect a number of compiler features - mostly C++11/14 conformance - by compiler -// The following features are defined: -// -// CATCH_CONFIG_CPP11_NULLPTR : is nullptr supported? -// CATCH_CONFIG_CPP11_NOEXCEPT : is noexcept supported? -// CATCH_CONFIG_CPP11_GENERATED_METHODS : The delete and default keywords for compiler generated methods -// CATCH_CONFIG_CPP11_IS_ENUM : std::is_enum is supported? -// CATCH_CONFIG_CPP11_TUPLE : std::tuple is supported -// CATCH_CONFIG_CPP11_LONG_LONG : is long long supported? -// CATCH_CONFIG_CPP11_OVERRIDE : is override supported? -// CATCH_CONFIG_CPP11_UNIQUE_PTR : is unique_ptr supported (otherwise use auto_ptr) -// CATCH_CONFIG_CPP11_SHUFFLE : is std::shuffle supported? -// CATCH_CONFIG_CPP11_TYPE_TRAITS : are type_traits and enable_if supported? - -// CATCH_CONFIG_CPP11_OR_GREATER : Is C++11 supported? - -// CATCH_CONFIG_VARIADIC_MACROS : are variadic macros supported? -// CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported? -// CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported? -// CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported? -// **************** -// Note to maintainers: if new toggles are added please document them -// in configuration.md, too -// **************** - -// In general each macro has a _NO_ form -// (e.g. CATCH_CONFIG_CPP11_NO_NULLPTR) which disables the feature. -// Many features, at point of detection, define an _INTERNAL_ macro, so they -// can be combined, en-mass, with the _NO_ forms later. - -// All the C++11 features can be disabled with CATCH_CONFIG_NO_CPP11 - -#ifdef __cplusplus - -# if __cplusplus >= 201103L -# define CATCH_CPP11_OR_GREATER -# endif - -# if __cplusplus >= 201402L -# define CATCH_CPP14_OR_GREATER -# endif - -#endif - -#ifdef __clang__ - -# if __has_feature(cxx_nullptr) -# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR -# endif - -# if __has_feature(cxx_noexcept) -# define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT -# endif - -# if defined(CATCH_CPP11_OR_GREATER) -# define CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ - _Pragma( "clang diagnostic push" ) \ - _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) -# define CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \ - _Pragma( "clang diagnostic pop" ) - -# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ - _Pragma( "clang diagnostic push" ) \ - _Pragma( "clang diagnostic ignored \"-Wparentheses\"" ) -# define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \ - _Pragma( "clang diagnostic pop" ) -# endif - -#endif // __clang__ - -//////////////////////////////////////////////////////////////////////////////// -// We know some environments not to support full POSIX signals -#if defined(__CYGWIN__) || defined(__QNX__) - -# if !defined(CATCH_CONFIG_POSIX_SIGNALS) -# define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS -# endif - -#endif - -//////////////////////////////////////////////////////////////////////////////// -// Cygwin -#ifdef __CYGWIN__ - -// Required for some versions of Cygwin to declare gettimeofday -// see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin -# define _BSD_SOURCE - -#endif // __CYGWIN__ - -//////////////////////////////////////////////////////////////////////////////// -// Borland -#ifdef __BORLANDC__ - -#endif // __BORLANDC__ - -//////////////////////////////////////////////////////////////////////////////// -// EDG -#ifdef __EDG_VERSION__ - -#endif // __EDG_VERSION__ - -//////////////////////////////////////////////////////////////////////////////// -// Digital Mars -#ifdef __DMC__ - -#endif // __DMC__ - -//////////////////////////////////////////////////////////////////////////////// -// GCC -#ifdef __GNUC__ - -# if __GNUC__ == 4 && __GNUC_MINOR__ >= 6 && defined(__GXX_EXPERIMENTAL_CXX0X__) -# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR -# endif - -// - otherwise more recent versions define __cplusplus >= 201103L -// and will get picked up below - -#endif // __GNUC__ - -//////////////////////////////////////////////////////////////////////////////// -// Visual C++ -#ifdef _MSC_VER - -#define CATCH_INTERNAL_CONFIG_WINDOWS_SEH - -#if (_MSC_VER >= 1600) -# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR -# define CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR -#endif - -#if (_MSC_VER >= 1900 ) // (VC++ 13 (VS2015)) -#define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT -#define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS -#define CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE -#define CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS -#endif - -#endif // _MSC_VER - -//////////////////////////////////////////////////////////////////////////////// - -// Use variadic macros if the compiler supports them -#if ( defined _MSC_VER && _MSC_VER > 1400 && !defined __EDGE__) || \ - ( defined __WAVE__ && __WAVE_HAS_VARIADICS ) || \ - ( defined __GNUC__ && __GNUC__ >= 3 ) || \ - ( !defined __cplusplus && __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L ) - -#define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS - -#endif - -// Use __COUNTER__ if the compiler supports it -#if ( defined _MSC_VER && _MSC_VER >= 1300 ) || \ - ( defined __GNUC__ && ( __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3 )) ) || \ - ( defined __clang__ && __clang_major__ >= 3 ) - -#define CATCH_INTERNAL_CONFIG_COUNTER - -#endif - -//////////////////////////////////////////////////////////////////////////////// -// C++ language feature support - -// catch all support for C++11 -#if defined(CATCH_CPP11_OR_GREATER) - -# if !defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR) -# define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR -# endif - -# ifndef CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT -# define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT -# endif - -# ifndef CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS -# define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS -# endif - -# ifndef CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM -# define CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM -# endif - -# ifndef CATCH_INTERNAL_CONFIG_CPP11_TUPLE -# define CATCH_INTERNAL_CONFIG_CPP11_TUPLE -# endif - -# ifndef CATCH_INTERNAL_CONFIG_VARIADIC_MACROS -# define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS -# endif - -# if !defined(CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG) -# define CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG -# endif - -# if !defined(CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE) -# define CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE -# endif -# if !defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) -# define CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR -# endif -# if !defined(CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE) -# define CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE -# endif -# if !defined(CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS) -# define CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS -# endif - -#endif // __cplusplus >= 201103L - -// Now set the actual defines based on the above + anything the user has configured -#if defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NO_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_NO_CPP11) -# define CATCH_CONFIG_CPP11_NULLPTR -#endif -#if defined(CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NO_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_NO_CPP11) -# define CATCH_CONFIG_CPP11_NOEXCEPT -#endif -#if defined(CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_NO_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_NO_CPP11) -# define CATCH_CONFIG_CPP11_GENERATED_METHODS -#endif -#if defined(CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_NO_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_NO_CPP11) -# define CATCH_CONFIG_CPP11_IS_ENUM -#endif -#if defined(CATCH_INTERNAL_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_CPP11_NO_TUPLE) && !defined(CATCH_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_NO_CPP11) -# define CATCH_CONFIG_CPP11_TUPLE -#endif -#if defined(CATCH_INTERNAL_CONFIG_VARIADIC_MACROS) && !defined(CATCH_CONFIG_NO_VARIADIC_MACROS) && !defined(CATCH_CONFIG_VARIADIC_MACROS) -# define CATCH_CONFIG_VARIADIC_MACROS -#endif -#if defined(CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG) && !defined(CATCH_CONFIG_CPP11_NO_LONG_LONG) && !defined(CATCH_CONFIG_CPP11_LONG_LONG) && !defined(CATCH_CONFIG_NO_CPP11) -# define CATCH_CONFIG_CPP11_LONG_LONG -#endif -#if defined(CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE) && !defined(CATCH_CONFIG_CPP11_NO_OVERRIDE) && !defined(CATCH_CONFIG_CPP11_OVERRIDE) && !defined(CATCH_CONFIG_NO_CPP11) -# define CATCH_CONFIG_CPP11_OVERRIDE -#endif -#if defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_NO_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_NO_CPP11) -# define CATCH_CONFIG_CPP11_UNIQUE_PTR -#endif -// Use of __COUNTER__ is suppressed if __JETBRAINS_IDE__ is #defined (meaning we're being parsed by a JetBrains IDE for -// analytics) because, at time of writing, __COUNTER__ is not properly handled by it. -// This does not affect compilation -#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) && !defined(__JETBRAINS_IDE__) -# define CATCH_CONFIG_COUNTER -#endif -#if defined(CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE) && !defined(CATCH_CONFIG_CPP11_NO_SHUFFLE) && !defined(CATCH_CONFIG_CPP11_SHUFFLE) && !defined(CATCH_CONFIG_NO_CPP11) -# define CATCH_CONFIG_CPP11_SHUFFLE -#endif -# if defined(CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS) && !defined(CATCH_CONFIG_CPP11_NO_TYPE_TRAITS) && !defined(CATCH_CONFIG_CPP11_TYPE_TRAITS) && !defined(CATCH_CONFIG_NO_CPP11) -# define CATCH_CONFIG_CPP11_TYPE_TRAITS -# endif -#if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) -# define CATCH_CONFIG_WINDOWS_SEH -#endif -// This is set by default, because we assume that unix compilers are posix-signal-compatible by default. -#if !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS) -# define CATCH_CONFIG_POSIX_SIGNALS -#endif - -#if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) -# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS -# define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS -#endif -#if !defined(CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS) -# define CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS -# define CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS -#endif - -// noexcept support: -#if defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_NOEXCEPT) -# define CATCH_NOEXCEPT noexcept -# define CATCH_NOEXCEPT_IS(x) noexcept(x) -#else -# define CATCH_NOEXCEPT throw() -# define CATCH_NOEXCEPT_IS(x) -#endif - -// nullptr support -#ifdef CATCH_CONFIG_CPP11_NULLPTR -# define CATCH_NULL nullptr -#else -# define CATCH_NULL NULL -#endif - -// override support -#ifdef CATCH_CONFIG_CPP11_OVERRIDE -# define CATCH_OVERRIDE override -#else -# define CATCH_OVERRIDE -#endif - -// unique_ptr support -#ifdef CATCH_CONFIG_CPP11_UNIQUE_PTR -# define CATCH_AUTO_PTR( T ) std::unique_ptr -#else -# define CATCH_AUTO_PTR( T ) std::auto_ptr -#endif - -#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line -#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) -#ifdef CATCH_CONFIG_COUNTER -# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ ) -#else -# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ ) -#endif - -#define INTERNAL_CATCH_STRINGIFY2( expr ) #expr -#define INTERNAL_CATCH_STRINGIFY( expr ) INTERNAL_CATCH_STRINGIFY2( expr ) - -#include -#include - -namespace Catch { - - struct IConfig; - - struct CaseSensitive { enum Choice { - Yes, - No - }; }; - - class NonCopyable { -#ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - NonCopyable( NonCopyable const& ) = delete; - NonCopyable( NonCopyable && ) = delete; - NonCopyable& operator = ( NonCopyable const& ) = delete; - NonCopyable& operator = ( NonCopyable && ) = delete; -#else - NonCopyable( NonCopyable const& info ); - NonCopyable& operator = ( NonCopyable const& ); -#endif - - protected: - NonCopyable() {} - virtual ~NonCopyable(); - }; - - class SafeBool { - public: - typedef void (SafeBool::*type)() const; - - static type makeSafe( bool value ) { - return value ? &SafeBool::trueValue : 0; - } - private: - void trueValue() const {} - }; - - template - inline void deleteAll( ContainerT& container ) { - typename ContainerT::const_iterator it = container.begin(); - typename ContainerT::const_iterator itEnd = container.end(); - for(; it != itEnd; ++it ) - delete *it; - } - template - inline void deleteAllValues( AssociativeContainerT& container ) { - typename AssociativeContainerT::const_iterator it = container.begin(); - typename AssociativeContainerT::const_iterator itEnd = container.end(); - for(; it != itEnd; ++it ) - delete it->second; - } - - bool startsWith( std::string const& s, std::string const& prefix ); - bool startsWith( std::string const& s, char prefix ); - bool endsWith( std::string const& s, std::string const& suffix ); - bool endsWith( std::string const& s, char suffix ); - bool contains( std::string const& s, std::string const& infix ); - void toLowerInPlace( std::string& s ); - std::string toLower( std::string const& s ); - std::string trim( std::string const& str ); - bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ); - - struct pluralise { - pluralise( std::size_t count, std::string const& label ); - - friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ); - - std::size_t m_count; - std::string m_label; - }; - - struct SourceLineInfo { - - SourceLineInfo(); - SourceLineInfo( char const* _file, std::size_t _line ); -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - SourceLineInfo(SourceLineInfo const& other) = default; - SourceLineInfo( SourceLineInfo && ) = default; - SourceLineInfo& operator = ( SourceLineInfo const& ) = default; - SourceLineInfo& operator = ( SourceLineInfo && ) = default; -# endif - bool empty() const; - bool operator == ( SourceLineInfo const& other ) const; - bool operator < ( SourceLineInfo const& other ) const; - - char const* file; - std::size_t line; - }; - - std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ); - - // This is just here to avoid compiler warnings with macro constants and boolean literals - inline bool isTrue( bool value ){ return value; } - inline bool alwaysTrue() { return true; } - inline bool alwaysFalse() { return false; } - - void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo ); - - void seedRng( IConfig const& config ); - unsigned int rngSeed(); - - // Use this in variadic streaming macros to allow - // >> +StreamEndStop - // as well as - // >> stuff +StreamEndStop - struct StreamEndStop { - std::string operator+() { - return std::string(); - } - }; - template - T const& operator + ( T const& value, StreamEndStop ) { - return value; - } -} - -#define CATCH_INTERNAL_LINEINFO ::Catch::SourceLineInfo( __FILE__, static_cast( __LINE__ ) ) -#define CATCH_INTERNAL_ERROR( msg ) ::Catch::throwLogicError( msg, CATCH_INTERNAL_LINEINFO ); - -namespace Catch { - - class NotImplementedException : public std::exception - { - public: - NotImplementedException( SourceLineInfo const& lineInfo ); - NotImplementedException( NotImplementedException const& ) {} - - virtual ~NotImplementedException() CATCH_NOEXCEPT {} - - virtual const char* what() const CATCH_NOEXCEPT; - - private: - std::string m_what; - SourceLineInfo m_lineInfo; - }; - -} // end namespace Catch - -/////////////////////////////////////////////////////////////////////////////// -#define CATCH_NOT_IMPLEMENTED throw Catch::NotImplementedException( CATCH_INTERNAL_LINEINFO ) - -// #included from: internal/catch_context.h -#define TWOBLUECUBES_CATCH_CONTEXT_H_INCLUDED - -// #included from: catch_interfaces_generators.h -#define TWOBLUECUBES_CATCH_INTERFACES_GENERATORS_H_INCLUDED - -#include - -namespace Catch { - - struct IGeneratorInfo { - virtual ~IGeneratorInfo(); - virtual bool moveNext() = 0; - virtual std::size_t getCurrentIndex() const = 0; - }; - - struct IGeneratorsForTest { - virtual ~IGeneratorsForTest(); - - virtual IGeneratorInfo& getGeneratorInfo( std::string const& fileInfo, std::size_t size ) = 0; - virtual bool moveNext() = 0; - }; - - IGeneratorsForTest* createGeneratorsForTest(); - -} // end namespace Catch - -// #included from: catch_ptr.hpp -#define TWOBLUECUBES_CATCH_PTR_HPP_INCLUDED - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wpadded" -#endif - -namespace Catch { - - // An intrusive reference counting smart pointer. - // T must implement addRef() and release() methods - // typically implementing the IShared interface - template - class Ptr { - public: - Ptr() : m_p( CATCH_NULL ){} - Ptr( T* p ) : m_p( p ){ - if( m_p ) - m_p->addRef(); - } - Ptr( Ptr const& other ) : m_p( other.m_p ){ - if( m_p ) - m_p->addRef(); - } - ~Ptr(){ - if( m_p ) - m_p->release(); - } - void reset() { - if( m_p ) - m_p->release(); - m_p = CATCH_NULL; - } - Ptr& operator = ( T* p ){ - Ptr temp( p ); - swap( temp ); - return *this; - } - Ptr& operator = ( Ptr const& other ){ - Ptr temp( other ); - swap( temp ); - return *this; - } - void swap( Ptr& other ) { std::swap( m_p, other.m_p ); } - T* get() const{ return m_p; } - T& operator*() const { return *m_p; } - T* operator->() const { return m_p; } - bool operator !() const { return m_p == CATCH_NULL; } - operator SafeBool::type() const { return SafeBool::makeSafe( m_p != CATCH_NULL ); } - - private: - T* m_p; - }; - - struct IShared : NonCopyable { - virtual ~IShared(); - virtual void addRef() const = 0; - virtual void release() const = 0; - }; - - template - struct SharedImpl : T { - - SharedImpl() : m_rc( 0 ){} - - virtual void addRef() const { - ++m_rc; - } - virtual void release() const { - if( --m_rc == 0 ) - delete this; - } - - mutable unsigned int m_rc; - }; - -} // end namespace Catch - -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - -namespace Catch { - - class TestCase; - class Stream; - struct IResultCapture; - struct IRunner; - struct IGeneratorsForTest; - struct IConfig; - - struct IContext - { - virtual ~IContext(); - - virtual IResultCapture* getResultCapture() = 0; - virtual IRunner* getRunner() = 0; - virtual size_t getGeneratorIndex( std::string const& fileInfo, size_t totalSize ) = 0; - virtual bool advanceGeneratorsForCurrentTest() = 0; - virtual Ptr getConfig() const = 0; - }; - - struct IMutableContext : IContext - { - virtual ~IMutableContext(); - virtual void setResultCapture( IResultCapture* resultCapture ) = 0; - virtual void setRunner( IRunner* runner ) = 0; - virtual void setConfig( Ptr const& config ) = 0; - }; - - IContext& getCurrentContext(); - IMutableContext& getCurrentMutableContext(); - void cleanUpContext(); - Stream createStream( std::string const& streamName ); - -} - -// #included from: internal/catch_test_registry.hpp -#define TWOBLUECUBES_CATCH_TEST_REGISTRY_HPP_INCLUDED - -// #included from: catch_interfaces_testcase.h -#define TWOBLUECUBES_CATCH_INTERFACES_TESTCASE_H_INCLUDED - -#include - -namespace Catch { - - class TestSpec; - - struct ITestCase : IShared { - virtual void invoke () const = 0; - protected: - virtual ~ITestCase(); - }; - - class TestCase; - struct IConfig; - - struct ITestCaseRegistry { - virtual ~ITestCaseRegistry(); - virtual std::vector const& getAllTests() const = 0; - virtual std::vector const& getAllTestsSorted( IConfig const& config ) const = 0; - }; - - bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ); - std::vector filterTests( std::vector const& testCases, TestSpec const& testSpec, IConfig const& config ); - std::vector const& getAllTestCasesSorted( IConfig const& config ); - -} - -namespace Catch { - -template -class MethodTestCase : public SharedImpl { - -public: - MethodTestCase( void (C::*method)() ) : m_method( method ) {} - - virtual void invoke() const { - C obj; - (obj.*m_method)(); - } - -private: - virtual ~MethodTestCase() {} - - void (C::*m_method)(); -}; - -typedef void(*TestFunction)(); - -struct NameAndDesc { - NameAndDesc( const char* _name = "", const char* _description= "" ) - : name( _name ), description( _description ) - {} - - const char* name; - const char* description; -}; - -void registerTestCase - ( ITestCase* testCase, - char const* className, - NameAndDesc const& nameAndDesc, - SourceLineInfo const& lineInfo ); - -struct AutoReg { - - AutoReg - ( TestFunction function, - SourceLineInfo const& lineInfo, - NameAndDesc const& nameAndDesc ); - - template - AutoReg - ( void (C::*method)(), - char const* className, - NameAndDesc const& nameAndDesc, - SourceLineInfo const& lineInfo ) { - - registerTestCase - ( new MethodTestCase( method ), - className, - nameAndDesc, - lineInfo ); - } - - ~AutoReg(); - -private: - AutoReg( AutoReg const& ); - void operator= ( AutoReg const& ); -}; - -void registerTestCaseFunction - ( TestFunction function, - SourceLineInfo const& lineInfo, - NameAndDesc const& nameAndDesc ); - -} // end namespace Catch - -#ifdef CATCH_CONFIG_VARIADIC_MACROS - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \ - static void TestName(); \ - CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ - namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &TestName, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); } \ - CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \ - static void TestName() - #define INTERNAL_CATCH_TESTCASE( ... ) \ - INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ ) - - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \ - CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ - namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); } \ - CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS - - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\ - CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ - namespace{ \ - struct TestName : ClassName{ \ - void test(); \ - }; \ - Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &TestName::test, #ClassName, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); \ - } \ - CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \ - void TestName::test() - #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \ - INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ ) - - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \ - CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ - Catch::AutoReg( Function, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); \ - CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS - -#else - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_TESTCASE2( TestName, Name, Desc ) \ - static void TestName(); \ - CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ - namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &TestName, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); }\ - CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \ - static void TestName() - #define INTERNAL_CATCH_TESTCASE( Name, Desc ) \ - INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), Name, Desc ) - - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, Name, Desc ) \ - CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ - namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( Name, Desc ), CATCH_INTERNAL_LINEINFO ); } \ - CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS - - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestCaseName, ClassName, TestName, Desc )\ - CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ - namespace{ \ - struct TestCaseName : ClassName{ \ - void test(); \ - }; \ - Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &TestCaseName::test, #ClassName, Catch::NameAndDesc( TestName, Desc ), CATCH_INTERNAL_LINEINFO ); \ - } \ - CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \ - void TestCaseName::test() - #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, TestName, Desc )\ - INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, TestName, Desc ) - - /////////////////////////////////////////////////////////////////////////////// - #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, Name, Desc ) \ - CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \ - Catch::AutoReg( Function, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); \ - CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS - -#endif - -// #included from: internal/catch_capture.hpp -#define TWOBLUECUBES_CATCH_CAPTURE_HPP_INCLUDED - -// #included from: catch_result_builder.h -#define TWOBLUECUBES_CATCH_RESULT_BUILDER_H_INCLUDED - -// #included from: catch_result_type.h -#define TWOBLUECUBES_CATCH_RESULT_TYPE_H_INCLUDED - -namespace Catch { - - // ResultWas::OfType enum - struct ResultWas { enum OfType { - Unknown = -1, - Ok = 0, - Info = 1, - Warning = 2, - - FailureBit = 0x10, - - ExpressionFailed = FailureBit | 1, - ExplicitFailure = FailureBit | 2, - - Exception = 0x100 | FailureBit, - - ThrewException = Exception | 1, - DidntThrowException = Exception | 2, - - FatalErrorCondition = 0x200 | FailureBit - - }; }; - - inline bool isOk( ResultWas::OfType resultType ) { - return ( resultType & ResultWas::FailureBit ) == 0; - } - inline bool isJustInfo( int flags ) { - return flags == ResultWas::Info; - } - - // ResultDisposition::Flags enum - struct ResultDisposition { enum Flags { - Normal = 0x01, - - ContinueOnFailure = 0x02, // Failures fail test, but execution continues - FalseTest = 0x04, // Prefix expression with ! - SuppressFail = 0x08 // Failures are reported but do not fail the test - }; }; - - inline ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) { - return static_cast( static_cast( lhs ) | static_cast( rhs ) ); - } - - inline bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; } - inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; } - inline bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; } - -} // end namespace Catch - -// #included from: catch_assertionresult.h -#define TWOBLUECUBES_CATCH_ASSERTIONRESULT_H_INCLUDED - -#include - -namespace Catch { - - struct STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison; - - struct DecomposedExpression - { - virtual ~DecomposedExpression() {} - virtual bool isBinaryExpression() const { - return false; - } - virtual void reconstructExpression( std::string& dest ) const = 0; - - // Only simple binary comparisons can be decomposed. - // If more complex check is required then wrap sub-expressions in parentheses. - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator + ( T const& ); - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator - ( T const& ); - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator * ( T const& ); - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator / ( T const& ); - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator % ( T const& ); - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( T const& ); - template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( T const& ); - - private: - DecomposedExpression& operator = (DecomposedExpression const&); - }; - - struct AssertionInfo - { - AssertionInfo() {} - AssertionInfo( char const * _macroName, - SourceLineInfo const& _lineInfo, - char const * _capturedExpression, - ResultDisposition::Flags _resultDisposition, - char const * _secondArg = ""); - - char const * macroName; - SourceLineInfo lineInfo; - char const * capturedExpression; - ResultDisposition::Flags resultDisposition; - char const * secondArg; - }; - - struct AssertionResultData - { - AssertionResultData() : decomposedExpression( CATCH_NULL ) - , resultType( ResultWas::Unknown ) - , negated( false ) - , parenthesized( false ) {} - - void negate( bool parenthesize ) { - negated = !negated; - parenthesized = parenthesize; - if( resultType == ResultWas::Ok ) - resultType = ResultWas::ExpressionFailed; - else if( resultType == ResultWas::ExpressionFailed ) - resultType = ResultWas::Ok; - } - - std::string const& reconstructExpression() const { - if( decomposedExpression != CATCH_NULL ) { - decomposedExpression->reconstructExpression( reconstructedExpression ); - if( parenthesized ) { - reconstructedExpression.insert( 0, 1, '(' ); - reconstructedExpression.append( 1, ')' ); - } - if( negated ) { - reconstructedExpression.insert( 0, 1, '!' ); - } - decomposedExpression = CATCH_NULL; - } - return reconstructedExpression; - } - - mutable DecomposedExpression const* decomposedExpression; - mutable std::string reconstructedExpression; - std::string message; - ResultWas::OfType resultType; - bool negated; - bool parenthesized; - }; - - class AssertionResult { - public: - AssertionResult(); - AssertionResult( AssertionInfo const& info, AssertionResultData const& data ); - ~AssertionResult(); -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - AssertionResult( AssertionResult const& ) = default; - AssertionResult( AssertionResult && ) = default; - AssertionResult& operator = ( AssertionResult const& ) = default; - AssertionResult& operator = ( AssertionResult && ) = default; -# endif - - bool isOk() const; - bool succeeded() const; - ResultWas::OfType getResultType() const; - bool hasExpression() const; - bool hasMessage() const; - std::string getExpression() const; - std::string getExpressionInMacro() const; - bool hasExpandedExpression() const; - std::string getExpandedExpression() const; - std::string getMessage() const; - SourceLineInfo getSourceInfo() const; - std::string getTestMacroName() const; - void discardDecomposedExpression() const; - void expandDecomposedExpression() const; - - protected: - AssertionInfo m_info; - AssertionResultData m_resultData; - }; - -} // end namespace Catch - -// #included from: catch_matchers.hpp -#define TWOBLUECUBES_CATCH_MATCHERS_HPP_INCLUDED - -namespace Catch { -namespace Matchers { - namespace Impl { - - template struct MatchAllOf; - template struct MatchAnyOf; - template struct MatchNotOf; - - class MatcherUntypedBase { - public: - std::string toString() const { - if( m_cachedToString.empty() ) - m_cachedToString = describe(); - return m_cachedToString; - } - - protected: - virtual ~MatcherUntypedBase(); - virtual std::string describe() const = 0; - mutable std::string m_cachedToString; - private: - MatcherUntypedBase& operator = ( MatcherUntypedBase const& ); - }; - - template - struct MatcherMethod { - virtual bool match( ObjectT const& arg ) const = 0; - }; - template - struct MatcherMethod { - virtual bool match( PtrT* arg ) const = 0; - }; - - template - struct MatcherBase : MatcherUntypedBase, MatcherMethod { - - MatchAllOf operator && ( MatcherBase const& other ) const; - MatchAnyOf operator || ( MatcherBase const& other ) const; - MatchNotOf operator ! () const; - }; - - template - struct MatchAllOf : MatcherBase { - virtual bool match( ArgT const& arg ) const CATCH_OVERRIDE { - for( std::size_t i = 0; i < m_matchers.size(); ++i ) { - if (!m_matchers[i]->match(arg)) - return false; - } - return true; - } - virtual std::string describe() const CATCH_OVERRIDE { - std::string description; - description.reserve( 4 + m_matchers.size()*32 ); - description += "( "; - for( std::size_t i = 0; i < m_matchers.size(); ++i ) { - if( i != 0 ) - description += " and "; - description += m_matchers[i]->toString(); - } - description += " )"; - return description; - } - - MatchAllOf& operator && ( MatcherBase const& other ) { - m_matchers.push_back( &other ); - return *this; - } - - std::vector const*> m_matchers; - }; - template - struct MatchAnyOf : MatcherBase { - - virtual bool match( ArgT const& arg ) const CATCH_OVERRIDE { - for( std::size_t i = 0; i < m_matchers.size(); ++i ) { - if (m_matchers[i]->match(arg)) - return true; - } - return false; - } - virtual std::string describe() const CATCH_OVERRIDE { - std::string description; - description.reserve( 4 + m_matchers.size()*32 ); - description += "( "; - for( std::size_t i = 0; i < m_matchers.size(); ++i ) { - if( i != 0 ) - description += " or "; - description += m_matchers[i]->toString(); - } - description += " )"; - return description; - } - - MatchAnyOf& operator || ( MatcherBase const& other ) { - m_matchers.push_back( &other ); - return *this; - } - - std::vector const*> m_matchers; - }; - - template - struct MatchNotOf : MatcherBase { - - MatchNotOf( MatcherBase const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {} - - virtual bool match( ArgT const& arg ) const CATCH_OVERRIDE { - return !m_underlyingMatcher.match( arg ); - } - - virtual std::string describe() const CATCH_OVERRIDE { - return "not " + m_underlyingMatcher.toString(); - } - MatcherBase const& m_underlyingMatcher; - }; - - template - MatchAllOf MatcherBase::operator && ( MatcherBase const& other ) const { - return MatchAllOf() && *this && other; - } - template - MatchAnyOf MatcherBase::operator || ( MatcherBase const& other ) const { - return MatchAnyOf() || *this || other; - } - template - MatchNotOf MatcherBase::operator ! () const { - return MatchNotOf( *this ); - } - - } // namespace Impl - - // The following functions create the actual matcher objects. - // This allows the types to be inferred - // - deprecated: prefer ||, && and ! - template - inline Impl::MatchNotOf Not( Impl::MatcherBase const& underlyingMatcher ) { - return Impl::MatchNotOf( underlyingMatcher ); - } - template - inline Impl::MatchAllOf AllOf( Impl::MatcherBase const& m1, Impl::MatcherBase const& m2 ) { - return Impl::MatchAllOf() && m1 && m2; - } - template - inline Impl::MatchAllOf AllOf( Impl::MatcherBase const& m1, Impl::MatcherBase const& m2, Impl::MatcherBase const& m3 ) { - return Impl::MatchAllOf() && m1 && m2 && m3; - } - template - inline Impl::MatchAnyOf AnyOf( Impl::MatcherBase const& m1, Impl::MatcherBase const& m2 ) { - return Impl::MatchAnyOf() || m1 || m2; - } - template - inline Impl::MatchAnyOf AnyOf( Impl::MatcherBase const& m1, Impl::MatcherBase const& m2, Impl::MatcherBase const& m3 ) { - return Impl::MatchAnyOf() || m1 || m2 || m3; - } - -} // namespace Matchers - -using namespace Matchers; -using Matchers::Impl::MatcherBase; - -} // namespace Catch - -namespace Catch { - - struct TestFailureException{}; - - template class ExpressionLhs; - - struct CopyableStream { - CopyableStream() {} - CopyableStream( CopyableStream const& other ) { - oss << other.oss.str(); - } - CopyableStream& operator=( CopyableStream const& other ) { - oss.str(std::string()); - oss << other.oss.str(); - return *this; - } - std::ostringstream oss; - }; - - class ResultBuilder : public DecomposedExpression { - public: - ResultBuilder( char const* macroName, - SourceLineInfo const& lineInfo, - char const* capturedExpression, - ResultDisposition::Flags resultDisposition, - char const* secondArg = "" ); - ~ResultBuilder(); - - template - ExpressionLhs operator <= ( T const& operand ); - ExpressionLhs operator <= ( bool value ); - - template - ResultBuilder& operator << ( T const& value ) { - m_stream().oss << value; - return *this; - } - - ResultBuilder& setResultType( ResultWas::OfType result ); - ResultBuilder& setResultType( bool result ); - - void endExpression( DecomposedExpression const& expr ); - - virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE; - - AssertionResult build() const; - AssertionResult build( DecomposedExpression const& expr ) const; - - void useActiveException( ResultDisposition::Flags resultDisposition = ResultDisposition::Normal ); - void captureResult( ResultWas::OfType resultType ); - void captureExpression(); - void captureExpectedException( std::string const& expectedMessage ); - void captureExpectedException( Matchers::Impl::MatcherBase const& matcher ); - void handleResult( AssertionResult const& result ); - void react(); - bool shouldDebugBreak() const; - bool allowThrows() const; - - template - void captureMatch( ArgT const& arg, MatcherT const& matcher, char const* matcherString ); - - void setExceptionGuard(); - void unsetExceptionGuard(); - - private: - AssertionInfo m_assertionInfo; - AssertionResultData m_data; - - static CopyableStream &m_stream() - { - static CopyableStream s; - return s; - } - - bool m_shouldDebugBreak; - bool m_shouldThrow; - bool m_guardException; - }; - -} // namespace Catch - -// Include after due to circular dependency: -// #included from: catch_expression_lhs.hpp -#define TWOBLUECUBES_CATCH_EXPRESSION_LHS_HPP_INCLUDED - -// #included from: catch_evaluate.hpp -#define TWOBLUECUBES_CATCH_EVALUATE_HPP_INCLUDED - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4389) // '==' : signed/unsigned mismatch -#pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform) -#endif - -#include - -namespace Catch { -namespace Internal { - - enum Operator { - IsEqualTo, - IsNotEqualTo, - IsLessThan, - IsGreaterThan, - IsLessThanOrEqualTo, - IsGreaterThanOrEqualTo - }; - - template struct OperatorTraits { static const char* getName(){ return "*error*"; } }; - template<> struct OperatorTraits { static const char* getName(){ return "=="; } }; - template<> struct OperatorTraits { static const char* getName(){ return "!="; } }; - template<> struct OperatorTraits { static const char* getName(){ return "<"; } }; - template<> struct OperatorTraits { static const char* getName(){ return ">"; } }; - template<> struct OperatorTraits { static const char* getName(){ return "<="; } }; - template<> struct OperatorTraits{ static const char* getName(){ return ">="; } }; - - template - inline T& opCast(T const& t) { return const_cast(t); } - -// nullptr_t support based on pull request #154 from Konstantin Baumann -#ifdef CATCH_CONFIG_CPP11_NULLPTR - inline std::nullptr_t opCast(std::nullptr_t) { return nullptr; } -#endif // CATCH_CONFIG_CPP11_NULLPTR - - // So the compare overloads can be operator agnostic we convey the operator as a template - // enum, which is used to specialise an Evaluator for doing the comparison. - template - class Evaluator{}; - - template - struct Evaluator { - static bool evaluate( T1 const& lhs, T2 const& rhs) { - return bool( opCast( lhs ) == opCast( rhs ) ); - } - }; - template - struct Evaluator { - static bool evaluate( T1 const& lhs, T2 const& rhs ) { - return bool( opCast( lhs ) != opCast( rhs ) ); - } - }; - template - struct Evaluator { - static bool evaluate( T1 const& lhs, T2 const& rhs ) { - return bool( opCast( lhs ) < opCast( rhs ) ); - } - }; - template - struct Evaluator { - static bool evaluate( T1 const& lhs, T2 const& rhs ) { - return bool( opCast( lhs ) > opCast( rhs ) ); - } - }; - template - struct Evaluator { - static bool evaluate( T1 const& lhs, T2 const& rhs ) { - return bool( opCast( lhs ) >= opCast( rhs ) ); - } - }; - template - struct Evaluator { - static bool evaluate( T1 const& lhs, T2 const& rhs ) { - return bool( opCast( lhs ) <= opCast( rhs ) ); - } - }; - - template - bool applyEvaluator( T1 const& lhs, T2 const& rhs ) { - return Evaluator::evaluate( lhs, rhs ); - } - - // This level of indirection allows us to specialise for integer types - // to avoid signed/ unsigned warnings - - // "base" overload - template - bool compare( T1 const& lhs, T2 const& rhs ) { - return Evaluator::evaluate( lhs, rhs ); - } - - // unsigned X to int - template bool compare( unsigned int lhs, int rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - template bool compare( unsigned long lhs, int rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - template bool compare( unsigned char lhs, int rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - - // unsigned X to long - template bool compare( unsigned int lhs, long rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - template bool compare( unsigned long lhs, long rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - template bool compare( unsigned char lhs, long rhs ) { - return applyEvaluator( lhs, static_cast( rhs ) ); - } - - // int to unsigned X - template bool compare( int lhs, unsigned int rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( int lhs, unsigned long rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( int lhs, unsigned char rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - - // long to unsigned X - template bool compare( long lhs, unsigned int rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( long lhs, unsigned long rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( long lhs, unsigned char rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - - // pointer to long (when comparing against NULL) - template bool compare( long lhs, T* rhs ) { - return Evaluator::evaluate( reinterpret_cast( lhs ), rhs ); - } - template bool compare( T* lhs, long rhs ) { - return Evaluator::evaluate( lhs, reinterpret_cast( rhs ) ); - } - - // pointer to int (when comparing against NULL) - template bool compare( int lhs, T* rhs ) { - return Evaluator::evaluate( reinterpret_cast( lhs ), rhs ); - } - template bool compare( T* lhs, int rhs ) { - return Evaluator::evaluate( lhs, reinterpret_cast( rhs ) ); - } - -#ifdef CATCH_CONFIG_CPP11_LONG_LONG - // long long to unsigned X - template bool compare( long long lhs, unsigned int rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( long long lhs, unsigned long rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( long long lhs, unsigned long long rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( long long lhs, unsigned char rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - - // unsigned long long to X - template bool compare( unsigned long long lhs, int rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( unsigned long long lhs, long rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( unsigned long long lhs, long long rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - template bool compare( unsigned long long lhs, char rhs ) { - return applyEvaluator( static_cast( lhs ), rhs ); - } - - // pointer to long long (when comparing against NULL) - template bool compare( long long lhs, T* rhs ) { - return Evaluator::evaluate( reinterpret_cast( lhs ), rhs ); - } - template bool compare( T* lhs, long long rhs ) { - return Evaluator::evaluate( lhs, reinterpret_cast( rhs ) ); - } -#endif // CATCH_CONFIG_CPP11_LONG_LONG - -#ifdef CATCH_CONFIG_CPP11_NULLPTR - // pointer to nullptr_t (when comparing against nullptr) - template bool compare( std::nullptr_t, T* rhs ) { - return Evaluator::evaluate( nullptr, rhs ); - } - template bool compare( T* lhs, std::nullptr_t ) { - return Evaluator::evaluate( lhs, nullptr ); - } -#endif // CATCH_CONFIG_CPP11_NULLPTR - -} // end of namespace Internal -} // end of namespace Catch - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -// #included from: catch_tostring.h -#define TWOBLUECUBES_CATCH_TOSTRING_H_INCLUDED - -#include -#include -#include -#include -#include - -#ifdef __OBJC__ -// #included from: catch_objc_arc.hpp -#define TWOBLUECUBES_CATCH_OBJC_ARC_HPP_INCLUDED - -#import - -#ifdef __has_feature -#define CATCH_ARC_ENABLED __has_feature(objc_arc) -#else -#define CATCH_ARC_ENABLED 0 -#endif - -void arcSafeRelease( NSObject* obj ); -id performOptionalSelector( id obj, SEL sel ); - -#if !CATCH_ARC_ENABLED -inline void arcSafeRelease( NSObject* obj ) { - [obj release]; -} -inline id performOptionalSelector( id obj, SEL sel ) { - if( [obj respondsToSelector: sel] ) - return [obj performSelector: sel]; - return nil; -} -#define CATCH_UNSAFE_UNRETAINED -#define CATCH_ARC_STRONG -#else -inline void arcSafeRelease( NSObject* ){} -inline id performOptionalSelector( id obj, SEL sel ) { -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Warc-performSelector-leaks" -#endif - if( [obj respondsToSelector: sel] ) - return [obj performSelector: sel]; -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - return nil; -} -#define CATCH_UNSAFE_UNRETAINED __unsafe_unretained -#define CATCH_ARC_STRONG __strong -#endif - -#endif - -#ifdef CATCH_CONFIG_CPP11_TUPLE -#include -#endif - -#ifdef CATCH_CONFIG_CPP11_IS_ENUM -#include -#endif - -namespace Catch { - -// Why we're here. -template -std::string toString( T const& value ); - -// Built in overloads - -std::string toString( std::string const& value ); -std::string toString( std::wstring const& value ); -std::string toString( const char* const value ); -std::string toString( char* const value ); -std::string toString( const wchar_t* const value ); -std::string toString( wchar_t* const value ); -std::string toString( int value ); -std::string toString( unsigned long value ); -std::string toString( unsigned int value ); -std::string toString( const double value ); -std::string toString( const float value ); -std::string toString( bool value ); -std::string toString( char value ); -std::string toString( signed char value ); -std::string toString( unsigned char value ); - -#ifdef CATCH_CONFIG_CPP11_LONG_LONG -std::string toString( long long value ); -std::string toString( unsigned long long value ); -#endif - -#ifdef CATCH_CONFIG_CPP11_NULLPTR -std::string toString( std::nullptr_t ); -#endif - -#ifdef __OBJC__ - std::string toString( NSString const * const& nsstring ); - std::string toString( NSString * CATCH_ARC_STRONG & nsstring ); - std::string toString( NSObject* const& nsObject ); -#endif - -namespace Detail { - - extern const std::string unprintableString; - - #if !defined(CATCH_CONFIG_CPP11_STREAM_INSERTABLE_CHECK) - struct BorgType { - template BorgType( T const& ); - }; - - struct TrueType { char sizer[1]; }; - struct FalseType { char sizer[2]; }; - - TrueType& testStreamable( std::ostream& ); - FalseType testStreamable( FalseType ); - - FalseType operator<<( std::ostream const&, BorgType const& ); - - template - struct IsStreamInsertable { - static std::ostream &s; - static T const&t; - enum { value = sizeof( testStreamable(s << t) ) == sizeof( TrueType ) }; - }; -#else - template - class IsStreamInsertable { - template - static auto test(int) - -> decltype( std::declval() << std::declval(), std::true_type() ); - - template - static auto test(...) -> std::false_type; - - public: - static const bool value = decltype(test(0))::value; - }; -#endif - -#if defined(CATCH_CONFIG_CPP11_IS_ENUM) - template::value - > - struct EnumStringMaker - { - static std::string convert( T const& ) { return unprintableString; } - }; - - template - struct EnumStringMaker - { - static std::string convert( T const& v ) - { - return ::Catch::toString( - static_cast::type>(v) - ); - } - }; -#endif - template - struct StringMakerBase { -#if defined(CATCH_CONFIG_CPP11_IS_ENUM) - template - static std::string convert( T const& v ) - { - return EnumStringMaker::convert( v ); - } -#else - template - static std::string convert( T const& ) { return unprintableString; } -#endif - }; - - template<> - struct StringMakerBase { - template - static std::string convert( T const& _value ) { - std::ostringstream oss; - oss << _value; - return oss.str(); - } - }; - - std::string rawMemoryToString( const void *object, std::size_t size ); - - template - inline std::string rawMemoryToString( const T& object ) { - return rawMemoryToString( &object, sizeof(object) ); - } - -} // end namespace Detail - -template -struct StringMaker : - Detail::StringMakerBase::value> {}; - -template -struct StringMaker { - template - static std::string convert( U* p ) { - if( !p ) - return "NULL"; - else - return Detail::rawMemoryToString( p ); - } -}; - -template -struct StringMaker { - static std::string convert( R C::* p ) { - if( !p ) - return "NULL"; - else - return Detail::rawMemoryToString( p ); - } -}; - -namespace Detail { - template - std::string rangeToString( InputIterator first, InputIterator last ); -} - -//template -//struct StringMaker > { -// static std::string convert( std::vector const& v ) { -// return Detail::rangeToString( v.begin(), v.end() ); -// } -//}; - -template -std::string toString( std::vector const& v ) { - return Detail::rangeToString( v.begin(), v.end() ); -} - -#ifdef CATCH_CONFIG_CPP11_TUPLE - -// toString for tuples -namespace TupleDetail { - template< - typename Tuple, - std::size_t N = 0, - bool = (N < std::tuple_size::value) - > - struct ElementPrinter { - static void print( const Tuple& tuple, std::ostream& os ) - { - os << ( N ? ", " : " " ) - << Catch::toString(std::get(tuple)); - ElementPrinter::print(tuple,os); - } - }; - - template< - typename Tuple, - std::size_t N - > - struct ElementPrinter { - static void print( const Tuple&, std::ostream& ) {} - }; - -} - -template -struct StringMaker> { - - static std::string convert( const std::tuple& tuple ) - { - std::ostringstream os; - os << '{'; - TupleDetail::ElementPrinter>::print( tuple, os ); - os << " }"; - return os.str(); - } -}; -#endif // CATCH_CONFIG_CPP11_TUPLE - -namespace Detail { - template - std::string makeString( T const& value ) { - return StringMaker::convert( value ); - } -} // end namespace Detail - -/// \brief converts any type to a string -/// -/// The default template forwards on to ostringstream - except when an -/// ostringstream overload does not exist - in which case it attempts to detect -/// that and writes {?}. -/// Overload (not specialise) this template for custom typs that you don't want -/// to provide an ostream overload for. -template -std::string toString( T const& value ) { - return StringMaker::convert( value ); -} - - namespace Detail { - template - std::string rangeToString( InputIterator first, InputIterator last ) { - std::ostringstream oss; - oss << "{ "; - if( first != last ) { - oss << Catch::toString( *first ); - for( ++first ; first != last ; ++first ) - oss << ", " << Catch::toString( *first ); - } - oss << " }"; - return oss.str(); - } -} - -} // end namespace Catch - -namespace Catch { - -template -class BinaryExpression; - -template -class MatchExpression; - -// Wraps the LHS of an expression and overloads comparison operators -// for also capturing those and RHS (if any) -template -class ExpressionLhs : public DecomposedExpression { -public: - ExpressionLhs( ResultBuilder& rb, T lhs ) : m_rb( rb ), m_lhs( lhs ), m_truthy(false) {} - - ExpressionLhs& operator = ( const ExpressionLhs& ); - - template - BinaryExpression - operator == ( RhsT const& rhs ) { - return captureExpression( rhs ); - } - - template - BinaryExpression - operator != ( RhsT const& rhs ) { - return captureExpression( rhs ); - } - - template - BinaryExpression - operator < ( RhsT const& rhs ) { - return captureExpression( rhs ); - } - - template - BinaryExpression - operator > ( RhsT const& rhs ) { - return captureExpression( rhs ); - } - - template - BinaryExpression - operator <= ( RhsT const& rhs ) { - return captureExpression( rhs ); - } - - template - BinaryExpression - operator >= ( RhsT const& rhs ) { - return captureExpression( rhs ); - } - - BinaryExpression operator == ( bool rhs ) { - return captureExpression( rhs ); - } - - BinaryExpression operator != ( bool rhs ) { - return captureExpression( rhs ); - } - - void endExpression() { - m_truthy = m_lhs ? true : false; - m_rb - .setResultType( m_truthy ) - .endExpression( *this ); - } - - virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE { - dest = Catch::toString( m_lhs ); - } - -private: - template - BinaryExpression captureExpression( RhsT& rhs ) const { - return BinaryExpression( m_rb, m_lhs, rhs ); - } - - template - BinaryExpression captureExpression( bool rhs ) const { - return BinaryExpression( m_rb, m_lhs, rhs ); - } - -private: - ResultBuilder& m_rb; - T m_lhs; - bool m_truthy; -}; - -template -class BinaryExpression : public DecomposedExpression { -public: - BinaryExpression( ResultBuilder& rb, LhsT lhs, RhsT rhs ) - : m_rb( rb ), m_lhs( lhs ), m_rhs( rhs ) {} - - BinaryExpression& operator = ( BinaryExpression& ); - - void endExpression() const { - m_rb - .setResultType( Internal::compare( m_lhs, m_rhs ) ) - .endExpression( *this ); - } - - virtual bool isBinaryExpression() const CATCH_OVERRIDE { - return true; - } - - virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE { - std::string lhs = Catch::toString( m_lhs ); - std::string rhs = Catch::toString( m_rhs ); - char delim = lhs.size() + rhs.size() < 40 && - lhs.find('\n') == std::string::npos && - rhs.find('\n') == std::string::npos ? ' ' : '\n'; - dest.reserve( 7 + lhs.size() + rhs.size() ); - // 2 for spaces around operator - // 2 for operator - // 2 for parentheses (conditionally added later) - // 1 for negation (conditionally added later) - dest = lhs; - dest += delim; - dest += Internal::OperatorTraits::getName(); - dest += delim; - dest += rhs; - } - -private: - ResultBuilder& m_rb; - LhsT m_lhs; - RhsT m_rhs; -}; - -template -class MatchExpression : public DecomposedExpression { -public: - MatchExpression( ArgT arg, MatcherT matcher, char const* matcherString ) - : m_arg( arg ), m_matcher( matcher ), m_matcherString( matcherString ) {} - - virtual bool isBinaryExpression() const CATCH_OVERRIDE { - return true; - } - - virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE { - std::string matcherAsString = m_matcher.toString(); - dest = Catch::toString( m_arg ); - dest += ' '; - if( matcherAsString == Detail::unprintableString ) - dest += m_matcherString; - else - dest += matcherAsString; - } - -private: - ArgT m_arg; - MatcherT m_matcher; - char const* m_matcherString; -}; - -} // end namespace Catch - - -namespace Catch { - - template - inline ExpressionLhs ResultBuilder::operator <= ( T const& operand ) { - return ExpressionLhs( *this, operand ); - } - - inline ExpressionLhs ResultBuilder::operator <= ( bool value ) { - return ExpressionLhs( *this, value ); - } - - template - inline void ResultBuilder::captureMatch( ArgT const& arg, MatcherT const& matcher, - char const* matcherString ) { - MatchExpression expr( arg, matcher, matcherString ); - setResultType( matcher.match( arg ) ); - endExpression( expr ); - } - -} // namespace Catch - -// #included from: catch_message.h -#define TWOBLUECUBES_CATCH_MESSAGE_H_INCLUDED - -#include - -namespace Catch { - - struct MessageInfo { - MessageInfo( std::string const& _macroName, - SourceLineInfo const& _lineInfo, - ResultWas::OfType _type ); - - std::string macroName; - SourceLineInfo lineInfo; - ResultWas::OfType type; - std::string message; - unsigned int sequence; - - bool operator == ( MessageInfo const& other ) const { - return sequence == other.sequence; - } - bool operator < ( MessageInfo const& other ) const { - return sequence < other.sequence; - } - private: - static unsigned int globalCount; - }; - - struct MessageBuilder { - MessageBuilder( std::string const& macroName, - SourceLineInfo const& lineInfo, - ResultWas::OfType type ) - : m_info( macroName, lineInfo, type ) - {} - - template - MessageBuilder& operator << ( T const& value ) { - m_stream << value; - return *this; - } - - MessageInfo m_info; - std::ostringstream m_stream; - }; - - class ScopedMessage { - public: - ScopedMessage( MessageBuilder const& builder ); - ScopedMessage( ScopedMessage const& other ); - ~ScopedMessage(); - - MessageInfo m_info; - }; - -} // end namespace Catch - -// #included from: catch_interfaces_capture.h -#define TWOBLUECUBES_CATCH_INTERFACES_CAPTURE_H_INCLUDED - -#include - -namespace Catch { - - class TestCase; - class AssertionResult; - struct AssertionInfo; - struct SectionInfo; - struct SectionEndInfo; - struct MessageInfo; - class ScopedMessageBuilder; - struct Counts; - - struct IResultCapture { - - virtual ~IResultCapture(); - - virtual void assertionEnded( AssertionResult const& result ) = 0; - virtual bool sectionStarted( SectionInfo const& sectionInfo, - Counts& assertions ) = 0; - virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0; - virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0; - virtual void pushScopedMessage( MessageInfo const& message ) = 0; - virtual void popScopedMessage( MessageInfo const& message ) = 0; - - virtual std::string getCurrentTestName() const = 0; - virtual const AssertionResult* getLastResult() const = 0; - - virtual void exceptionEarlyReported() = 0; - - virtual void handleFatalErrorCondition( std::string const& message ) = 0; - }; - - IResultCapture& getResultCapture(); -} - -// #included from: catch_debugger.h -#define TWOBLUECUBES_CATCH_DEBUGGER_H_INCLUDED - -// #included from: catch_platform.h -#define TWOBLUECUBES_CATCH_PLATFORM_H_INCLUDED - -#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) -# define CATCH_PLATFORM_MAC -#elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -# define CATCH_PLATFORM_IPHONE -#elif defined(linux) || defined(__linux) || defined(__linux__) -# define CATCH_PLATFORM_LINUX -#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) -# define CATCH_PLATFORM_WINDOWS -# if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX) -# define CATCH_DEFINES_NOMINMAX -# endif -# if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN) -# define CATCH_DEFINES_WIN32_LEAN_AND_MEAN -# endif -#endif - -#include - -namespace Catch{ - - bool isDebuggerActive(); - void writeToDebugConsole( std::string const& text ); -} - -#ifdef CATCH_PLATFORM_MAC - - // The following code snippet based on: - // http://cocoawithlove.com/2008/03/break-into-debugger.html - #if defined(__ppc64__) || defined(__ppc__) - #define CATCH_TRAP() \ - __asm__("li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n" \ - : : : "memory","r0","r3","r4" ) - #else - #define CATCH_TRAP() __asm__("int $3\n" : : ) - #endif - -#elif defined(CATCH_PLATFORM_LINUX) - // If we can use inline assembler, do it because this allows us to break - // directly at the location of the failing check instead of breaking inside - // raise() called from it, i.e. one stack frame below. - #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64)) - #define CATCH_TRAP() asm volatile ("int $3") - #else // Fall back to the generic way. - #include - - #define CATCH_TRAP() raise(SIGTRAP) - #endif -#elif defined(_MSC_VER) - #define CATCH_TRAP() __debugbreak() -#elif defined(__MINGW32__) - extern "C" __declspec(dllimport) void __stdcall DebugBreak(); - #define CATCH_TRAP() DebugBreak() -#endif - -#ifdef CATCH_TRAP - #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } -#else - #define CATCH_BREAK_INTO_DEBUGGER() Catch::alwaysTrue(); -#endif - -// #included from: catch_interfaces_runner.h -#define TWOBLUECUBES_CATCH_INTERFACES_RUNNER_H_INCLUDED - -namespace Catch { - class TestCase; - - struct IRunner { - virtual ~IRunner(); - virtual bool aborting() const = 0; - }; -} - -#if defined(CATCH_CONFIG_FAST_COMPILE) -/////////////////////////////////////////////////////////////////////////////// -// We can speedup compilation significantly by breaking into debugger lower in -// the callstack, because then we don't have to expand CATCH_BREAK_INTO_DEBUGGER -// macro in each assertion -#define INTERNAL_CATCH_REACT( resultBuilder ) \ - resultBuilder.react(); - -/////////////////////////////////////////////////////////////////////////////// -// Another way to speed-up compilation is to omit local try-catch for REQUIRE* -// macros. -// This can potentially cause false negative, if the test code catches -// the exception before it propagates back up to the runner. -#define INTERNAL_CATCH_TEST_NO_TRY( macroName, resultDisposition, expr ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ - __catchResult.setExceptionGuard(); \ - CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ - ( __catchResult <= expr ).endExpression(); \ - CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \ - __catchResult.unsetExceptionGuard(); \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::isTrue( false && static_cast( !!(expr) ) ) ) // expr here is never evaluated at runtime but it forces the compiler to give it a look -// The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&. - -#define INTERNAL_CHECK_THAT_NO_TRY( macroName, matcher, resultDisposition, arg ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #arg ", " #matcher, resultDisposition ); \ - __catchResult.setExceptionGuard(); \ - __catchResult.captureMatch( arg, matcher, #matcher ); \ - __catchResult.unsetExceptionGuard(); \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::alwaysFalse() ) - -#else -/////////////////////////////////////////////////////////////////////////////// -// In the event of a failure works out if the debugger needs to be invoked -// and/or an exception thrown and takes appropriate action. -// This needs to be done as a macro so the debugger will stop in the user -// source code rather than in Catch library code -#define INTERNAL_CATCH_REACT( resultBuilder ) \ - if( resultBuilder.shouldDebugBreak() ) CATCH_BREAK_INTO_DEBUGGER(); \ - resultBuilder.react(); -#endif - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_TEST( macroName, resultDisposition, expr ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ - try { \ - CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ - ( __catchResult <= expr ).endExpression(); \ - CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \ - } \ - catch( ... ) { \ - __catchResult.useActiveException( resultDisposition ); \ - } \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::isTrue( false && static_cast( !!(expr) ) ) ) // expr here is never evaluated at runtime but it forces the compiler to give it a look - // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&. - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_IF( macroName, resultDisposition, expr ) \ - INTERNAL_CATCH_TEST( macroName, resultDisposition, expr ); \ - if( Catch::getResultCapture().getLastResult()->succeeded() ) - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_ELSE( macroName, resultDisposition, expr ) \ - INTERNAL_CATCH_TEST( macroName, resultDisposition, expr ); \ - if( !Catch::getResultCapture().getLastResult()->succeeded() ) - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, expr ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ - try { \ - static_cast(expr); \ - __catchResult.captureResult( Catch::ResultWas::Ok ); \ - } \ - catch( ... ) { \ - __catchResult.useActiveException( resultDisposition ); \ - } \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::alwaysFalse() ) - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_THROWS( macroName, resultDisposition, matcher, expr ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition, #matcher ); \ - if( __catchResult.allowThrows() ) \ - try { \ - static_cast(expr); \ - __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \ - } \ - catch( ... ) { \ - __catchResult.captureExpectedException( matcher ); \ - } \ - else \ - __catchResult.captureResult( Catch::ResultWas::Ok ); \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::alwaysFalse() ) - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr ", " #exceptionType, resultDisposition ); \ - if( __catchResult.allowThrows() ) \ - try { \ - static_cast(expr); \ - __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \ - } \ - catch( exceptionType ) { \ - __catchResult.captureResult( Catch::ResultWas::Ok ); \ - } \ - catch( ... ) { \ - __catchResult.useActiveException( resultDisposition ); \ - } \ - else \ - __catchResult.captureResult( Catch::ResultWas::Ok ); \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::alwaysFalse() ) - -/////////////////////////////////////////////////////////////////////////////// -#ifdef CATCH_CONFIG_VARIADIC_MACROS - #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \ - __catchResult << __VA_ARGS__ + ::Catch::StreamEndStop(); \ - __catchResult.captureResult( messageType ); \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::alwaysFalse() ) -#else - #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, log ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \ - __catchResult << log + ::Catch::StreamEndStop(); \ - __catchResult.captureResult( messageType ); \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::alwaysFalse() ) -#endif - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_INFO( macroName, log ) \ - Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage ) = Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log; - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \ - do { \ - Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #arg ", " #matcher, resultDisposition ); \ - try { \ - __catchResult.captureMatch( arg, matcher, #matcher ); \ - } catch( ... ) { \ - __catchResult.useActiveException( resultDisposition | Catch::ResultDisposition::ContinueOnFailure ); \ - } \ - INTERNAL_CATCH_REACT( __catchResult ) \ - } while( Catch::alwaysFalse() ) - -// #included from: internal/catch_section.h -#define TWOBLUECUBES_CATCH_SECTION_H_INCLUDED - -// #included from: catch_section_info.h -#define TWOBLUECUBES_CATCH_SECTION_INFO_H_INCLUDED - -// #included from: catch_totals.hpp -#define TWOBLUECUBES_CATCH_TOTALS_HPP_INCLUDED - -#include - -namespace Catch { - - struct Counts { - Counts() : passed( 0 ), failed( 0 ), failedButOk( 0 ) {} - - Counts operator - ( Counts const& other ) const { - Counts diff; - diff.passed = passed - other.passed; - diff.failed = failed - other.failed; - diff.failedButOk = failedButOk - other.failedButOk; - return diff; - } - Counts& operator += ( Counts const& other ) { - passed += other.passed; - failed += other.failed; - failedButOk += other.failedButOk; - return *this; - } - - std::size_t total() const { - return passed + failed + failedButOk; - } - bool allPassed() const { - return failed == 0 && failedButOk == 0; - } - bool allOk() const { - return failed == 0; - } - - std::size_t passed; - std::size_t failed; - std::size_t failedButOk; - }; - - struct Totals { - - Totals operator - ( Totals const& other ) const { - Totals diff; - diff.assertions = assertions - other.assertions; - diff.testCases = testCases - other.testCases; - return diff; - } - - Totals delta( Totals const& prevTotals ) const { - Totals diff = *this - prevTotals; - if( diff.assertions.failed > 0 ) - ++diff.testCases.failed; - else if( diff.assertions.failedButOk > 0 ) - ++diff.testCases.failedButOk; - else - ++diff.testCases.passed; - return diff; - } - - Totals& operator += ( Totals const& other ) { - assertions += other.assertions; - testCases += other.testCases; - return *this; - } - - Counts assertions; - Counts testCases; - }; -} - -#include - -namespace Catch { - - struct SectionInfo { - SectionInfo - ( SourceLineInfo const& _lineInfo, - std::string const& _name, - std::string const& _description = std::string() ); - - std::string name; - std::string description; - SourceLineInfo lineInfo; - }; - - struct SectionEndInfo { - SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds ) - : sectionInfo( _sectionInfo ), prevAssertions( _prevAssertions ), durationInSeconds( _durationInSeconds ) - {} - - SectionInfo sectionInfo; - Counts prevAssertions; - double durationInSeconds; - }; - -} // end namespace Catch - -// #included from: catch_timer.h -#define TWOBLUECUBES_CATCH_TIMER_H_INCLUDED - -#ifdef _MSC_VER - -namespace Catch { - typedef unsigned long long UInt64; -} -#else -#include -namespace Catch { - typedef uint64_t UInt64; -} -#endif - -namespace Catch { - class Timer { - public: - Timer() : m_ticks( 0 ) {} - void start(); - unsigned int getElapsedMicroseconds() const; - unsigned int getElapsedMilliseconds() const; - double getElapsedSeconds() const; - - private: - UInt64 m_ticks; - }; - -} // namespace Catch - -#include - -namespace Catch { - - class Section : NonCopyable { - public: - Section( SectionInfo const& info ); - ~Section(); - - // This indicates whether the section should be executed or not - operator bool() const; - - private: - SectionInfo m_info; - - std::string m_name; - Counts m_assertions; - bool m_sectionIncluded; - Timer m_timer; - }; - -} // end namespace Catch - -#ifdef CATCH_CONFIG_VARIADIC_MACROS - #define INTERNAL_CATCH_SECTION( ... ) \ - if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) -#else - #define INTERNAL_CATCH_SECTION( name, desc ) \ - if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, name, desc ) ) -#endif - -// #included from: internal/catch_generators.hpp -#define TWOBLUECUBES_CATCH_GENERATORS_HPP_INCLUDED - -#include -#include -#include - -namespace Catch { - -template -struct IGenerator { - virtual ~IGenerator() {} - virtual T getValue( std::size_t index ) const = 0; - virtual std::size_t size () const = 0; -}; - -template -class BetweenGenerator : public IGenerator { -public: - BetweenGenerator( T from, T to ) : m_from( from ), m_to( to ){} - - virtual T getValue( std::size_t index ) const { - return m_from+static_cast( index ); - } - - virtual std::size_t size() const { - return static_cast( 1+m_to-m_from ); - } - -private: - - T m_from; - T m_to; -}; - -template -class ValuesGenerator : public IGenerator { -public: - ValuesGenerator(){} - - void add( T value ) { - m_values.push_back( value ); - } - - virtual T getValue( std::size_t index ) const { - return m_values[index]; - } - - virtual std::size_t size() const { - return m_values.size(); - } - -private: - std::vector m_values; -}; - -template -class CompositeGenerator { -public: - CompositeGenerator() : m_totalSize( 0 ) {} - - // *** Move semantics, similar to auto_ptr *** - CompositeGenerator( CompositeGenerator& other ) - : m_fileInfo( other.m_fileInfo ), - m_totalSize( 0 ) - { - move( other ); - } - - CompositeGenerator& setFileInfo( const char* fileInfo ) { - m_fileInfo = fileInfo; - return *this; - } - - ~CompositeGenerator() { - deleteAll( m_composed ); - } - - operator T () const { - size_t overallIndex = getCurrentContext().getGeneratorIndex( m_fileInfo, m_totalSize ); - - typename std::vector*>::const_iterator it = m_composed.begin(); - typename std::vector*>::const_iterator itEnd = m_composed.end(); - for( size_t index = 0; it != itEnd; ++it ) - { - const IGenerator* generator = *it; - if( overallIndex >= index && overallIndex < index + generator->size() ) - { - return generator->getValue( overallIndex-index ); - } - index += generator->size(); - } - CATCH_INTERNAL_ERROR( "Indexed past end of generated range" ); - return T(); // Suppress spurious "not all control paths return a value" warning in Visual Studio - if you know how to fix this please do so - } - - void add( const IGenerator* generator ) { - m_totalSize += generator->size(); - m_composed.push_back( generator ); - } - - CompositeGenerator& then( CompositeGenerator& other ) { - move( other ); - return *this; - } - - CompositeGenerator& then( T value ) { - ValuesGenerator* valuesGen = new ValuesGenerator(); - valuesGen->add( value ); - add( valuesGen ); - return *this; - } - -private: - - void move( CompositeGenerator& other ) { - m_composed.insert( m_composed.end(), other.m_composed.begin(), other.m_composed.end() ); - m_totalSize += other.m_totalSize; - other.m_composed.clear(); - } - - std::vector*> m_composed; - std::string m_fileInfo; - size_t m_totalSize; -}; - -namespace Generators -{ - template - CompositeGenerator between( T from, T to ) { - CompositeGenerator generators; - generators.add( new BetweenGenerator( from, to ) ); - return generators; - } - - template - CompositeGenerator values( T val1, T val2 ) { - CompositeGenerator generators; - ValuesGenerator* valuesGen = new ValuesGenerator(); - valuesGen->add( val1 ); - valuesGen->add( val2 ); - generators.add( valuesGen ); - return generators; - } - - template - CompositeGenerator values( T val1, T val2, T val3 ){ - CompositeGenerator generators; - ValuesGenerator* valuesGen = new ValuesGenerator(); - valuesGen->add( val1 ); - valuesGen->add( val2 ); - valuesGen->add( val3 ); - generators.add( valuesGen ); - return generators; - } - - template - CompositeGenerator values( T val1, T val2, T val3, T val4 ) { - CompositeGenerator generators; - ValuesGenerator* valuesGen = new ValuesGenerator(); - valuesGen->add( val1 ); - valuesGen->add( val2 ); - valuesGen->add( val3 ); - valuesGen->add( val4 ); - generators.add( valuesGen ); - return generators; - } - -} // end namespace Generators - -using namespace Generators; - -} // end namespace Catch - -#define INTERNAL_CATCH_LINESTR2( line ) #line -#define INTERNAL_CATCH_LINESTR( line ) INTERNAL_CATCH_LINESTR2( line ) - -#define INTERNAL_CATCH_GENERATE( expr ) expr.setFileInfo( __FILE__ "(" INTERNAL_CATCH_LINESTR( __LINE__ ) ")" ) - -// #included from: internal/catch_interfaces_exception.h -#define TWOBLUECUBES_CATCH_INTERFACES_EXCEPTION_H_INCLUDED - -#include -#include - -// #included from: catch_interfaces_registry_hub.h -#define TWOBLUECUBES_CATCH_INTERFACES_REGISTRY_HUB_H_INCLUDED - -#include - -namespace Catch { - - class TestCase; - struct ITestCaseRegistry; - struct IExceptionTranslatorRegistry; - struct IExceptionTranslator; - struct IReporterRegistry; - struct IReporterFactory; - struct ITagAliasRegistry; - - struct IRegistryHub { - virtual ~IRegistryHub(); - - virtual IReporterRegistry const& getReporterRegistry() const = 0; - virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0; - virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0; - - virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0; - }; - - struct IMutableRegistryHub { - virtual ~IMutableRegistryHub(); - virtual void registerReporter( std::string const& name, Ptr const& factory ) = 0; - virtual void registerListener( Ptr const& factory ) = 0; - virtual void registerTest( TestCase const& testInfo ) = 0; - virtual void registerTranslator( const IExceptionTranslator* translator ) = 0; - virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0; - }; - - IRegistryHub& getRegistryHub(); - IMutableRegistryHub& getMutableRegistryHub(); - void cleanUp(); - std::string translateActiveException(); - -} - -namespace Catch { - - typedef std::string(*exceptionTranslateFunction)(); - - struct IExceptionTranslator; - typedef std::vector ExceptionTranslators; - - struct IExceptionTranslator { - virtual ~IExceptionTranslator(); - virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0; - }; - - struct IExceptionTranslatorRegistry { - virtual ~IExceptionTranslatorRegistry(); - - virtual std::string translateActiveException() const = 0; - }; - - class ExceptionTranslatorRegistrar { - template - class ExceptionTranslator : public IExceptionTranslator { - public: - - ExceptionTranslator( std::string(*translateFunction)( T& ) ) - : m_translateFunction( translateFunction ) - {} - - virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const CATCH_OVERRIDE { - try { - if( it == itEnd ) - throw; - else - return (*it)->translate( it+1, itEnd ); - } - catch( T& ex ) { - return m_translateFunction( ex ); - } - } - - protected: - std::string(*m_translateFunction)( T& ); - }; - - public: - template - ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) { - getMutableRegistryHub().registerTranslator - ( new ExceptionTranslator( translateFunction ) ); - } - }; -} - -/////////////////////////////////////////////////////////////////////////////// -#define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \ - static std::string translatorName( signature ); \ - namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); }\ - static std::string translatorName( signature ) - -#define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) - -// #included from: internal/catch_approx.hpp -#define TWOBLUECUBES_CATCH_APPROX_HPP_INCLUDED - -#include -#include - -#if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS) -#include -#endif - -namespace Catch { -namespace Detail { - - class Approx { - public: - explicit Approx ( double value ) - : m_epsilon( std::numeric_limits::epsilon()*100 ), - m_margin( 0.0 ), - m_scale( 1.0 ), - m_value( value ) - {} - - Approx( Approx const& other ) - : m_epsilon( other.m_epsilon ), - m_margin( other.m_margin ), - m_scale( other.m_scale ), - m_value( other.m_value ) - {} - - static Approx custom() { - return Approx( 0 ); - } - -#if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS) - - template ::value>::type> - Approx operator()( T value ) { - Approx approx( static_cast(value) ); - approx.epsilon( m_epsilon ); - approx.margin( m_margin ); - approx.scale( m_scale ); - return approx; - } - - template ::value>::type> - explicit Approx( T value ): Approx(static_cast(value)) - {} - - template ::value>::type> - friend bool operator == ( const T& lhs, Approx const& rhs ) { - // Thanks to Richard Harris for his help refining this formula - auto lhs_v = double(lhs); - bool relativeOK = std::fabs(lhs_v - rhs.m_value) < rhs.m_epsilon * (rhs.m_scale + (std::max)(std::fabs(lhs_v), std::fabs(rhs.m_value))); - if (relativeOK) { - return true; - } - return std::fabs(lhs_v - rhs.m_value) < rhs.m_margin; - } - - template ::value>::type> - friend bool operator == ( Approx const& lhs, const T& rhs ) { - return operator==( rhs, lhs ); - } - - template ::value>::type> - friend bool operator != ( T lhs, Approx const& rhs ) { - return !operator==( lhs, rhs ); - } - - template ::value>::type> - friend bool operator != ( Approx const& lhs, T rhs ) { - return !operator==( rhs, lhs ); - } - - template ::value>::type> - friend bool operator <= ( T lhs, Approx const& rhs ) { - return double(lhs) < rhs.m_value || lhs == rhs; - } - - template ::value>::type> - friend bool operator <= ( Approx const& lhs, T rhs ) { - return lhs.m_value < double(rhs) || lhs == rhs; - } - - template ::value>::type> - friend bool operator >= ( T lhs, Approx const& rhs ) { - return double(lhs) > rhs.m_value || lhs == rhs; - } - - template ::value>::type> - friend bool operator >= ( Approx const& lhs, T rhs ) { - return lhs.m_value > double(rhs) || lhs == rhs; - } - - template ::value>::type> - Approx& epsilon( T newEpsilon ) { - m_epsilon = double(newEpsilon); - return *this; - } - - template ::value>::type> - Approx& margin( T newMargin ) { - m_margin = double(newMargin); - return *this; - } - - template ::value>::type> - Approx& scale( T newScale ) { - m_scale = double(newScale); - return *this; - } - -#else - - Approx operator()( double value ) { - Approx approx( value ); - approx.epsilon( m_epsilon ); - approx.margin( m_margin ); - approx.scale( m_scale ); - return approx; - } - - friend bool operator == ( double lhs, Approx const& rhs ) { - // Thanks to Richard Harris for his help refining this formula - bool relativeOK = std::fabs( lhs - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( std::fabs(lhs), std::fabs(rhs.m_value) ) ); - if (relativeOK) { - return true; - } - return std::fabs(lhs - rhs.m_value) < rhs.m_margin; - } - - friend bool operator == ( Approx const& lhs, double rhs ) { - return operator==( rhs, lhs ); - } - - friend bool operator != ( double lhs, Approx const& rhs ) { - return !operator==( lhs, rhs ); - } - - friend bool operator != ( Approx const& lhs, double rhs ) { - return !operator==( rhs, lhs ); - } - - friend bool operator <= ( double lhs, Approx const& rhs ) { - return lhs < rhs.m_value || lhs == rhs; - } - - friend bool operator <= ( Approx const& lhs, double rhs ) { - return lhs.m_value < rhs || lhs == rhs; - } - - friend bool operator >= ( double lhs, Approx const& rhs ) { - return lhs > rhs.m_value || lhs == rhs; - } - - friend bool operator >= ( Approx const& lhs, double rhs ) { - return lhs.m_value > rhs || lhs == rhs; - } - - Approx& epsilon( double newEpsilon ) { - m_epsilon = newEpsilon; - return *this; - } - - Approx& margin( double newMargin ) { - m_margin = newMargin; - return *this; - } - - Approx& scale( double newScale ) { - m_scale = newScale; - return *this; - } -#endif - - std::string toString() const { - std::ostringstream oss; - oss << "Approx( " << Catch::toString( m_value ) << " )"; - return oss.str(); - } - - private: - double m_epsilon; - double m_margin; - double m_scale; - double m_value; - }; -} - -template<> -inline std::string toString( Detail::Approx const& value ) { - return value.toString(); -} - -} // end namespace Catch - -// #included from: internal/catch_matchers_string.h -#define TWOBLUECUBES_CATCH_MATCHERS_STRING_H_INCLUDED - -namespace Catch { -namespace Matchers { - - namespace StdString { - - struct CasedString - { - CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity ); - std::string adjustString( std::string const& str ) const; - std::string caseSensitivitySuffix() const; - - CaseSensitive::Choice m_caseSensitivity; - std::string m_str; - }; - - struct StringMatcherBase : MatcherBase { - StringMatcherBase( std::string const& operation, CasedString const& comparator ); - virtual std::string describe() const CATCH_OVERRIDE; - - CasedString m_comparator; - std::string m_operation; - }; - - struct EqualsMatcher : StringMatcherBase { - EqualsMatcher( CasedString const& comparator ); - virtual bool match( std::string const& source ) const CATCH_OVERRIDE; - }; - struct ContainsMatcher : StringMatcherBase { - ContainsMatcher( CasedString const& comparator ); - virtual bool match( std::string const& source ) const CATCH_OVERRIDE; - }; - struct StartsWithMatcher : StringMatcherBase { - StartsWithMatcher( CasedString const& comparator ); - virtual bool match( std::string const& source ) const CATCH_OVERRIDE; - }; - struct EndsWithMatcher : StringMatcherBase { - EndsWithMatcher( CasedString const& comparator ); - virtual bool match( std::string const& source ) const CATCH_OVERRIDE; - }; - - } // namespace StdString - - // The following functions create the actual matcher objects. - // This allows the types to be inferred - - StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); - StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); - StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); - StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); - -} // namespace Matchers -} // namespace Catch - -// #included from: internal/catch_matchers_vector.h -#define TWOBLUECUBES_CATCH_MATCHERS_VECTOR_H_INCLUDED - -namespace Catch { -namespace Matchers { - - namespace Vector { - - template - struct ContainsElementMatcher : MatcherBase, T> { - - ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {} - - bool match(std::vector const &v) const CATCH_OVERRIDE { - return std::find(v.begin(), v.end(), m_comparator) != v.end(); - } - - virtual std::string describe() const CATCH_OVERRIDE { - return "Contains: " + Catch::toString( m_comparator ); - } - - T const& m_comparator; - }; - - template - struct ContainsMatcher : MatcherBase, std::vector > { - - ContainsMatcher(std::vector const &comparator) : m_comparator( comparator ) {} - - bool match(std::vector const &v) const CATCH_OVERRIDE { - // !TBD: see note in EqualsMatcher - if (m_comparator.size() > v.size()) - return false; - for (size_t i = 0; i < m_comparator.size(); ++i) - if (std::find(v.begin(), v.end(), m_comparator[i]) == v.end()) - return false; - return true; - } - virtual std::string describe() const CATCH_OVERRIDE { - return "Contains: " + Catch::toString( m_comparator ); - } - - std::vector const& m_comparator; - }; - - template - struct EqualsMatcher : MatcherBase, std::vector > { - - EqualsMatcher(std::vector const &comparator) : m_comparator( comparator ) {} - - bool match(std::vector const &v) const CATCH_OVERRIDE { - // !TBD: This currently works if all elements can be compared using != - // - a more general approach would be via a compare template that defaults - // to using !=. but could be specialised for, e.g. std::vector etc - // - then just call that directly - if (m_comparator.size() != v.size()) - return false; - for (size_t i = 0; i < v.size(); ++i) - if (m_comparator[i] != v[i]) - return false; - return true; - } - virtual std::string describe() const CATCH_OVERRIDE { - return "Equals: " + Catch::toString( m_comparator ); - } - std::vector const& m_comparator; - }; - - } // namespace Vector - - // The following functions create the actual matcher objects. - // This allows the types to be inferred - - template - Vector::ContainsMatcher Contains( std::vector const& comparator ) { - return Vector::ContainsMatcher( comparator ); - } - - template - Vector::ContainsElementMatcher VectorContains( T const& comparator ) { - return Vector::ContainsElementMatcher( comparator ); - } - - template - Vector::EqualsMatcher Equals( std::vector const& comparator ) { - return Vector::EqualsMatcher( comparator ); - } - -} // namespace Matchers -} // namespace Catch - -// #included from: internal/catch_interfaces_tag_alias_registry.h -#define TWOBLUECUBES_CATCH_INTERFACES_TAG_ALIAS_REGISTRY_H_INCLUDED - -// #included from: catch_tag_alias.h -#define TWOBLUECUBES_CATCH_TAG_ALIAS_H_INCLUDED - -#include - -namespace Catch { - - struct TagAlias { - TagAlias( std::string const& _tag, SourceLineInfo _lineInfo ) : tag( _tag ), lineInfo( _lineInfo ) {} - - std::string tag; - SourceLineInfo lineInfo; - }; - - struct RegistrarForTagAliases { - RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); - }; - -} // end namespace Catch - -#define CATCH_REGISTER_TAG_ALIAS( alias, spec ) namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } -// #included from: catch_option.hpp -#define TWOBLUECUBES_CATCH_OPTION_HPP_INCLUDED - -namespace Catch { - - // An optional type - template - class Option { - public: - Option() : nullableValue( CATCH_NULL ) {} - Option( T const& _value ) - : nullableValue( new( storage ) T( _value ) ) - {} - Option( Option const& _other ) - : nullableValue( _other ? new( storage ) T( *_other ) : CATCH_NULL ) - {} - - ~Option() { - reset(); - } - - Option& operator= ( Option const& _other ) { - if( &_other != this ) { - reset(); - if( _other ) - nullableValue = new( storage ) T( *_other ); - } - return *this; - } - Option& operator = ( T const& _value ) { - reset(); - nullableValue = new( storage ) T( _value ); - return *this; - } - - void reset() { - if( nullableValue ) - nullableValue->~T(); - nullableValue = CATCH_NULL; - } - - T& operator*() { return *nullableValue; } - T const& operator*() const { return *nullableValue; } - T* operator->() { return nullableValue; } - const T* operator->() const { return nullableValue; } - - T valueOr( T const& defaultValue ) const { - return nullableValue ? *nullableValue : defaultValue; - } - - bool some() const { return nullableValue != CATCH_NULL; } - bool none() const { return nullableValue == CATCH_NULL; } - - bool operator !() const { return nullableValue == CATCH_NULL; } - operator SafeBool::type() const { - return SafeBool::makeSafe( some() ); - } - - private: - T *nullableValue; - union { - char storage[sizeof(T)]; - - // These are here to force alignment for the storage - long double dummy1; - void (*dummy2)(); - long double dummy3; -#ifdef CATCH_CONFIG_CPP11_LONG_LONG - long long dummy4; -#endif - }; - }; - -} // end namespace Catch - -namespace Catch { - - struct ITagAliasRegistry { - virtual ~ITagAliasRegistry(); - virtual Option find( std::string const& alias ) const = 0; - virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0; - - static ITagAliasRegistry const& get(); - }; - -} // end namespace Catch - -// These files are included here so the single_include script doesn't put them -// in the conditionally compiled sections -// #included from: internal/catch_test_case_info.h -#define TWOBLUECUBES_CATCH_TEST_CASE_INFO_H_INCLUDED - -#include -#include - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wpadded" -#endif - -namespace Catch { - - struct ITestCase; - - struct TestCaseInfo { - enum SpecialProperties{ - None = 0, - IsHidden = 1 << 1, - ShouldFail = 1 << 2, - MayFail = 1 << 3, - Throws = 1 << 4, - NonPortable = 1 << 5 - }; - - TestCaseInfo( std::string const& _name, - std::string const& _className, - std::string const& _description, - std::set const& _tags, - SourceLineInfo const& _lineInfo ); - - TestCaseInfo( TestCaseInfo const& other ); - - friend void setTags( TestCaseInfo& testCaseInfo, std::set const& tags ); - - bool isHidden() const; - bool throws() const; - bool okToFail() const; - bool expectedToFail() const; - - std::string name; - std::string className; - std::string description; - std::set tags; - std::set lcaseTags; - std::string tagsAsString; - SourceLineInfo lineInfo; - SpecialProperties properties; - }; - - class TestCase : public TestCaseInfo { - public: - - TestCase( ITestCase* testCase, TestCaseInfo const& info ); - TestCase( TestCase const& other ); - - TestCase withName( std::string const& _newName ) const; - - void invoke() const; - - TestCaseInfo const& getTestCaseInfo() const; - - void swap( TestCase& other ); - bool operator == ( TestCase const& other ) const; - bool operator < ( TestCase const& other ) const; - TestCase& operator = ( TestCase const& other ); - - private: - Ptr test; - }; - - TestCase makeTestCase( ITestCase* testCase, - std::string const& className, - std::string const& name, - std::string const& description, - SourceLineInfo const& lineInfo ); -} - -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - - -#ifdef __OBJC__ -// #included from: internal/catch_objc.hpp -#define TWOBLUECUBES_CATCH_OBJC_HPP_INCLUDED - -#import - -#include - -// NB. Any general catch headers included here must be included -// in catch.hpp first to make sure they are included by the single -// header for non obj-usage - -/////////////////////////////////////////////////////////////////////////////// -// This protocol is really only here for (self) documenting purposes, since -// all its methods are optional. -@protocol OcFixture - -@optional - --(void) setUp; --(void) tearDown; - -@end - -namespace Catch { - - class OcMethod : public SharedImpl { - - public: - OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {} - - virtual void invoke() const { - id obj = [[m_cls alloc] init]; - - performOptionalSelector( obj, @selector(setUp) ); - performOptionalSelector( obj, m_sel ); - performOptionalSelector( obj, @selector(tearDown) ); - - arcSafeRelease( obj ); - } - private: - virtual ~OcMethod() {} - - Class m_cls; - SEL m_sel; - }; - - namespace Detail{ - - inline std::string getAnnotation( Class cls, - std::string const& annotationName, - std::string const& testCaseName ) { - NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()]; - SEL sel = NSSelectorFromString( selStr ); - arcSafeRelease( selStr ); - id value = performOptionalSelector( cls, sel ); - if( value ) - return [(NSString*)value UTF8String]; - return ""; - } - } - - inline size_t registerTestMethods() { - size_t noTestMethods = 0; - int noClasses = objc_getClassList( CATCH_NULL, 0 ); - - Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses); - objc_getClassList( classes, noClasses ); - - for( int c = 0; c < noClasses; c++ ) { - Class cls = classes[c]; - { - u_int count; - Method* methods = class_copyMethodList( cls, &count ); - for( u_int m = 0; m < count ; m++ ) { - SEL selector = method_getName(methods[m]); - std::string methodName = sel_getName(selector); - if( startsWith( methodName, "Catch_TestCase_" ) ) { - std::string testCaseName = methodName.substr( 15 ); - std::string name = Detail::getAnnotation( cls, "Name", testCaseName ); - std::string desc = Detail::getAnnotation( cls, "Description", testCaseName ); - const char* className = class_getName( cls ); - - getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, name.c_str(), desc.c_str(), SourceLineInfo() ) ); - noTestMethods++; - } - } - free(methods); - } - } - return noTestMethods; - } - - namespace Matchers { - namespace Impl { - namespace NSStringMatchers { - - struct StringHolder : MatcherBase{ - StringHolder( NSString* substr ) : m_substr( [substr copy] ){} - StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){} - StringHolder() { - arcSafeRelease( m_substr ); - } - - virtual bool match( NSString* arg ) const CATCH_OVERRIDE { - return false; - } - - NSString* m_substr; - }; - - struct Equals : StringHolder { - Equals( NSString* substr ) : StringHolder( substr ){} - - virtual bool match( NSString* str ) const CATCH_OVERRIDE { - return (str != nil || m_substr == nil ) && - [str isEqualToString:m_substr]; - } - - virtual std::string describe() const CATCH_OVERRIDE { - return "equals string: " + Catch::toString( m_substr ); - } - }; - - struct Contains : StringHolder { - Contains( NSString* substr ) : StringHolder( substr ){} - - virtual bool match( NSString* str ) const { - return (str != nil || m_substr == nil ) && - [str rangeOfString:m_substr].location != NSNotFound; - } - - virtual std::string describe() const CATCH_OVERRIDE { - return "contains string: " + Catch::toString( m_substr ); - } - }; - - struct StartsWith : StringHolder { - StartsWith( NSString* substr ) : StringHolder( substr ){} - - virtual bool match( NSString* str ) const { - return (str != nil || m_substr == nil ) && - [str rangeOfString:m_substr].location == 0; - } - - virtual std::string describe() const CATCH_OVERRIDE { - return "starts with: " + Catch::toString( m_substr ); - } - }; - struct EndsWith : StringHolder { - EndsWith( NSString* substr ) : StringHolder( substr ){} - - virtual bool match( NSString* str ) const { - return (str != nil || m_substr == nil ) && - [str rangeOfString:m_substr].location == [str length] - [m_substr length]; - } - - virtual std::string describe() const CATCH_OVERRIDE { - return "ends with: " + Catch::toString( m_substr ); - } - }; - - } // namespace NSStringMatchers - } // namespace Impl - - inline Impl::NSStringMatchers::Equals - Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); } - - inline Impl::NSStringMatchers::Contains - Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); } - - inline Impl::NSStringMatchers::StartsWith - StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); } - - inline Impl::NSStringMatchers::EndsWith - EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); } - - } // namespace Matchers - - using namespace Matchers; - -} // namespace Catch - -/////////////////////////////////////////////////////////////////////////////// -#define OC_TEST_CASE( name, desc )\ -+(NSString*) INTERNAL_CATCH_UNIQUE_NAME( Catch_Name_test ) \ -{\ -return @ name; \ -}\ -+(NSString*) INTERNAL_CATCH_UNIQUE_NAME( Catch_Description_test ) \ -{ \ -return @ desc; \ -} \ --(void) INTERNAL_CATCH_UNIQUE_NAME( Catch_TestCase_test ) - -#endif - -#ifdef CATCH_IMPL - -// !TBD: Move the leak detector code into a separate header -#ifdef CATCH_CONFIG_WINDOWS_CRTDBG -#include -class LeakDetector { -public: - LeakDetector() { - int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); - flag |= _CRTDBG_LEAK_CHECK_DF; - flag |= _CRTDBG_ALLOC_MEM_DF; - _CrtSetDbgFlag(flag); - _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); - _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); - // Change this to leaking allocation's number to break there - _CrtSetBreakAlloc(-1); - } -}; -#else -class LeakDetector {}; -#endif - -LeakDetector leakDetector; - -// #included from: internal/catch_impl.hpp -#define TWOBLUECUBES_CATCH_IMPL_HPP_INCLUDED - -// Collect all the implementation files together here -// These are the equivalent of what would usually be cpp files - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wweak-vtables" -#endif - -// #included from: ../catch_session.hpp -#define TWOBLUECUBES_CATCH_RUNNER_HPP_INCLUDED - -// #included from: internal/catch_commandline.hpp -#define TWOBLUECUBES_CATCH_COMMANDLINE_HPP_INCLUDED - -// #included from: catch_config.hpp -#define TWOBLUECUBES_CATCH_CONFIG_HPP_INCLUDED - -// #included from: catch_test_spec_parser.hpp -#define TWOBLUECUBES_CATCH_TEST_SPEC_PARSER_HPP_INCLUDED - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wpadded" -#endif - -// #included from: catch_test_spec.hpp -#define TWOBLUECUBES_CATCH_TEST_SPEC_HPP_INCLUDED - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wpadded" -#endif - -// #included from: catch_wildcard_pattern.hpp -#define TWOBLUECUBES_CATCH_WILDCARD_PATTERN_HPP_INCLUDED - -#include - -namespace Catch -{ - class WildcardPattern { - enum WildcardPosition { - NoWildcard = 0, - WildcardAtStart = 1, - WildcardAtEnd = 2, - WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd - }; - - public: - - WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity ) - : m_caseSensitivity( caseSensitivity ), - m_wildcard( NoWildcard ), - m_pattern( adjustCase( pattern ) ) - { - if( startsWith( m_pattern, '*' ) ) { - m_pattern = m_pattern.substr( 1 ); - m_wildcard = WildcardAtStart; - } - if( endsWith( m_pattern, '*' ) ) { - m_pattern = m_pattern.substr( 0, m_pattern.size()-1 ); - m_wildcard = static_cast( m_wildcard | WildcardAtEnd ); - } - } - virtual ~WildcardPattern(); - virtual bool matches( std::string const& str ) const { - switch( m_wildcard ) { - case NoWildcard: - return m_pattern == adjustCase( str ); - case WildcardAtStart: - return endsWith( adjustCase( str ), m_pattern ); - case WildcardAtEnd: - return startsWith( adjustCase( str ), m_pattern ); - case WildcardAtBothEnds: - return contains( adjustCase( str ), m_pattern ); - } - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunreachable-code" -#endif - throw std::logic_error( "Unknown enum" ); -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - } - private: - std::string adjustCase( std::string const& str ) const { - return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str; - } - CaseSensitive::Choice m_caseSensitivity; - WildcardPosition m_wildcard; - std::string m_pattern; - }; -} - -#include -#include - -namespace Catch { - - class TestSpec { - struct Pattern : SharedImpl<> { - virtual ~Pattern(); - virtual bool matches( TestCaseInfo const& testCase ) const = 0; - }; - class NamePattern : public Pattern { - public: - NamePattern( std::string const& name ) - : m_wildcardPattern( toLower( name ), CaseSensitive::No ) - {} - virtual ~NamePattern(); - virtual bool matches( TestCaseInfo const& testCase ) const { - return m_wildcardPattern.matches( toLower( testCase.name ) ); - } - private: - WildcardPattern m_wildcardPattern; - }; - - class TagPattern : public Pattern { - public: - TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {} - virtual ~TagPattern(); - virtual bool matches( TestCaseInfo const& testCase ) const { - return testCase.lcaseTags.find( m_tag ) != testCase.lcaseTags.end(); - } - private: - std::string m_tag; - }; - - class ExcludedPattern : public Pattern { - public: - ExcludedPattern( Ptr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {} - virtual ~ExcludedPattern(); - virtual bool matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); } - private: - Ptr m_underlyingPattern; - }; - - struct Filter { - std::vector > m_patterns; - - bool matches( TestCaseInfo const& testCase ) const { - // All patterns in a filter must match for the filter to be a match - for( std::vector >::const_iterator it = m_patterns.begin(), itEnd = m_patterns.end(); it != itEnd; ++it ) { - if( !(*it)->matches( testCase ) ) - return false; - } - return true; - } - }; - - public: - bool hasFilters() const { - return !m_filters.empty(); - } - bool matches( TestCaseInfo const& testCase ) const { - // A TestSpec matches if any filter matches - for( std::vector::const_iterator it = m_filters.begin(), itEnd = m_filters.end(); it != itEnd; ++it ) - if( it->matches( testCase ) ) - return true; - return false; - } - - private: - std::vector m_filters; - - friend class TestSpecParser; - }; -} - -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - -namespace Catch { - - class TestSpecParser { - enum Mode{ None, Name, QuotedName, Tag, EscapedName }; - Mode m_mode; - bool m_exclusion; - std::size_t m_start, m_pos; - std::string m_arg; - std::vector m_escapeChars; - TestSpec::Filter m_currentFilter; - TestSpec m_testSpec; - ITagAliasRegistry const* m_tagAliases; - - public: - TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {} - - TestSpecParser& parse( std::string const& arg ) { - m_mode = None; - m_exclusion = false; - m_start = std::string::npos; - m_arg = m_tagAliases->expandAliases( arg ); - m_escapeChars.clear(); - for( m_pos = 0; m_pos < m_arg.size(); ++m_pos ) - visitChar( m_arg[m_pos] ); - if( m_mode == Name ) - addPattern(); - return *this; - } - TestSpec testSpec() { - addFilter(); - return m_testSpec; - } - private: - void visitChar( char c ) { - if( m_mode == None ) { - switch( c ) { - case ' ': return; - case '~': m_exclusion = true; return; - case '[': return startNewMode( Tag, ++m_pos ); - case '"': return startNewMode( QuotedName, ++m_pos ); - case '\\': return escape(); - default: startNewMode( Name, m_pos ); break; - } - } - if( m_mode == Name ) { - if( c == ',' ) { - addPattern(); - addFilter(); - } - else if( c == '[' ) { - if( subString() == "exclude:" ) - m_exclusion = true; - else - addPattern(); - startNewMode( Tag, ++m_pos ); - } - else if( c == '\\' ) - escape(); - } - else if( m_mode == EscapedName ) - m_mode = Name; - else if( m_mode == QuotedName && c == '"' ) - addPattern(); - else if( m_mode == Tag && c == ']' ) - addPattern(); - } - void startNewMode( Mode mode, std::size_t start ) { - m_mode = mode; - m_start = start; - } - void escape() { - if( m_mode == None ) - m_start = m_pos; - m_mode = EscapedName; - m_escapeChars.push_back( m_pos ); - } - std::string subString() const { return m_arg.substr( m_start, m_pos - m_start ); } - template - void addPattern() { - std::string token = subString(); - for( size_t i = 0; i < m_escapeChars.size(); ++i ) - token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 ); - m_escapeChars.clear(); - if( startsWith( token, "exclude:" ) ) { - m_exclusion = true; - token = token.substr( 8 ); - } - if( !token.empty() ) { - Ptr pattern = new T( token ); - if( m_exclusion ) - pattern = new TestSpec::ExcludedPattern( pattern ); - m_currentFilter.m_patterns.push_back( pattern ); - } - m_exclusion = false; - m_mode = None; - } - void addFilter() { - if( !m_currentFilter.m_patterns.empty() ) { - m_testSpec.m_filters.push_back( m_currentFilter ); - m_currentFilter = TestSpec::Filter(); - } - } - }; - inline TestSpec parseTestSpec( std::string const& arg ) { - return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec(); - } - -} // namespace Catch - -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - -// #included from: catch_interfaces_config.h -#define TWOBLUECUBES_CATCH_INTERFACES_CONFIG_H_INCLUDED - -#include -#include -#include - -namespace Catch { - - struct Verbosity { enum Level { - NoOutput = 0, - Quiet, - Normal - }; }; - - struct WarnAbout { enum What { - Nothing = 0x00, - NoAssertions = 0x01 - }; }; - - struct ShowDurations { enum OrNot { - DefaultForReporter, - Always, - Never - }; }; - struct RunTests { enum InWhatOrder { - InDeclarationOrder, - InLexicographicalOrder, - InRandomOrder - }; }; - struct UseColour { enum YesOrNo { - Auto, - Yes, - No - }; }; - - class TestSpec; - - struct IConfig : IShared { - - virtual ~IConfig(); - - virtual bool allowThrows() const = 0; - virtual std::ostream& stream() const = 0; - virtual std::string name() const = 0; - virtual bool includeSuccessfulResults() const = 0; - virtual bool shouldDebugBreak() const = 0; - virtual bool warnAboutMissingAssertions() const = 0; - virtual int abortAfter() const = 0; - virtual bool showInvisibles() const = 0; - virtual ShowDurations::OrNot showDurations() const = 0; - virtual TestSpec const& testSpec() const = 0; - virtual RunTests::InWhatOrder runOrder() const = 0; - virtual unsigned int rngSeed() const = 0; - virtual UseColour::YesOrNo useColour() const = 0; - virtual std::vector const& getSectionsToRun() const = 0; - - }; -} - -// #included from: catch_stream.h -#define TWOBLUECUBES_CATCH_STREAM_H_INCLUDED - -// #included from: catch_streambuf.h -#define TWOBLUECUBES_CATCH_STREAMBUF_H_INCLUDED - -#include - -namespace Catch { - - class StreamBufBase : public std::streambuf { - public: - virtual ~StreamBufBase() CATCH_NOEXCEPT; - }; -} - -#include -#include -#include -#include - -namespace Catch { - - std::ostream& cout(); - std::ostream& cerr(); - - struct IStream { - virtual ~IStream() CATCH_NOEXCEPT; - virtual std::ostream& stream() const = 0; - }; - - class FileStream : public IStream { - mutable std::ofstream m_ofs; - public: - FileStream( std::string const& filename ); - virtual ~FileStream() CATCH_NOEXCEPT; - public: // IStream - virtual std::ostream& stream() const CATCH_OVERRIDE; - }; - - class CoutStream : public IStream { - mutable std::ostream m_os; - public: - CoutStream(); - virtual ~CoutStream() CATCH_NOEXCEPT; - - public: // IStream - virtual std::ostream& stream() const CATCH_OVERRIDE; - }; - - class DebugOutStream : public IStream { - CATCH_AUTO_PTR( StreamBufBase ) m_streamBuf; - mutable std::ostream m_os; - public: - DebugOutStream(); - virtual ~DebugOutStream() CATCH_NOEXCEPT; - - public: // IStream - virtual std::ostream& stream() const CATCH_OVERRIDE; - }; -} - -#include -#include -#include -#include - -#ifndef CATCH_CONFIG_CONSOLE_WIDTH -#define CATCH_CONFIG_CONSOLE_WIDTH 80 -#endif - -namespace Catch { - - struct ConfigData { - - ConfigData() - : listTests( false ), - listTags( false ), - listReporters( false ), - listTestNamesOnly( false ), - listExtraInfo( false ), - showSuccessfulTests( false ), - shouldDebugBreak( false ), - noThrow( false ), - showHelp( false ), - showInvisibles( false ), - filenamesAsTags( false ), - abortAfter( -1 ), - rngSeed( 0 ), - verbosity( Verbosity::Normal ), - warnings( WarnAbout::Nothing ), - showDurations( ShowDurations::DefaultForReporter ), - runOrder( RunTests::InDeclarationOrder ), - useColour( UseColour::Auto ) - {} - - bool listTests; - bool listTags; - bool listReporters; - bool listTestNamesOnly; - bool listExtraInfo; - - bool showSuccessfulTests; - bool shouldDebugBreak; - bool noThrow; - bool showHelp; - bool showInvisibles; - bool filenamesAsTags; - - int abortAfter; - unsigned int rngSeed; - - Verbosity::Level verbosity; - WarnAbout::What warnings; - ShowDurations::OrNot showDurations; - RunTests::InWhatOrder runOrder; - UseColour::YesOrNo useColour; - - std::string outputFilename; - std::string name; - std::string processName; - - std::vector reporterNames; - std::vector testsOrTags; - std::vector sectionsToRun; - }; - - class Config : public SharedImpl { - private: - Config( Config const& other ); - Config& operator = ( Config const& other ); - virtual void dummy(); - public: - - Config() - {} - - Config( ConfigData const& data ) - : m_data( data ), - m_stream( openStream() ) - { - if( !data.testsOrTags.empty() ) { - TestSpecParser parser( ITagAliasRegistry::get() ); - for( std::size_t i = 0; i < data.testsOrTags.size(); ++i ) - parser.parse( data.testsOrTags[i] ); - m_testSpec = parser.testSpec(); - } - } - - virtual ~Config() {} - - std::string const& getFilename() const { - return m_data.outputFilename ; - } - - bool listTests() const { return m_data.listTests; } - bool listTestNamesOnly() const { return m_data.listTestNamesOnly; } - bool listTags() const { return m_data.listTags; } - bool listReporters() const { return m_data.listReporters; } - bool listExtraInfo() const { return m_data.listExtraInfo; } - - std::string getProcessName() const { return m_data.processName; } - - std::vector const& getReporterNames() const { return m_data.reporterNames; } - std::vector const& getSectionsToRun() const CATCH_OVERRIDE { return m_data.sectionsToRun; } - - virtual TestSpec const& testSpec() const CATCH_OVERRIDE { return m_testSpec; } - - bool showHelp() const { return m_data.showHelp; } - - // IConfig interface - virtual bool allowThrows() const CATCH_OVERRIDE { return !m_data.noThrow; } - virtual std::ostream& stream() const CATCH_OVERRIDE { return m_stream->stream(); } - virtual std::string name() const CATCH_OVERRIDE { return m_data.name.empty() ? m_data.processName : m_data.name; } - virtual bool includeSuccessfulResults() const CATCH_OVERRIDE { return m_data.showSuccessfulTests; } - virtual bool warnAboutMissingAssertions() const CATCH_OVERRIDE { return m_data.warnings & WarnAbout::NoAssertions; } - virtual ShowDurations::OrNot showDurations() const CATCH_OVERRIDE { return m_data.showDurations; } - virtual RunTests::InWhatOrder runOrder() const CATCH_OVERRIDE { return m_data.runOrder; } - virtual unsigned int rngSeed() const CATCH_OVERRIDE { return m_data.rngSeed; } - virtual UseColour::YesOrNo useColour() const CATCH_OVERRIDE { return m_data.useColour; } - virtual bool shouldDebugBreak() const CATCH_OVERRIDE { return m_data.shouldDebugBreak; } - virtual int abortAfter() const CATCH_OVERRIDE { return m_data.abortAfter; } - virtual bool showInvisibles() const CATCH_OVERRIDE { return m_data.showInvisibles; } - - private: - - IStream const* openStream() { - if( m_data.outputFilename.empty() ) - return new CoutStream(); - else if( m_data.outputFilename[0] == '%' ) { - if( m_data.outputFilename == "%debug" ) - return new DebugOutStream(); - else - throw std::domain_error( "Unrecognised stream: " + m_data.outputFilename ); - } - else - return new FileStream( m_data.outputFilename ); - } - ConfigData m_data; - - CATCH_AUTO_PTR( IStream const ) m_stream; - TestSpec m_testSpec; - }; - -} // end namespace Catch - -// #included from: catch_clara.h -#define TWOBLUECUBES_CATCH_CLARA_H_INCLUDED - -// Use Catch's value for console width (store Clara's off to the side, if present) -#ifdef CLARA_CONFIG_CONSOLE_WIDTH -#define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CLARA_CONFIG_CONSOLE_WIDTH -#undef CLARA_CONFIG_CONSOLE_WIDTH -#endif -#define CLARA_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH - -// Declare Clara inside the Catch namespace -#define STITCH_CLARA_OPEN_NAMESPACE namespace Catch { -// #included from: ../external/clara.h - -// Version 0.0.2.4 - -// Only use header guard if we are not using an outer namespace -#if !defined(TWOBLUECUBES_CLARA_H_INCLUDED) || defined(STITCH_CLARA_OPEN_NAMESPACE) - -#ifndef STITCH_CLARA_OPEN_NAMESPACE -#define TWOBLUECUBES_CLARA_H_INCLUDED -#define STITCH_CLARA_OPEN_NAMESPACE -#define STITCH_CLARA_CLOSE_NAMESPACE -#else -#define STITCH_CLARA_CLOSE_NAMESPACE } -#endif - -#define STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE STITCH_CLARA_OPEN_NAMESPACE - -// ----------- #included from tbc_text_format.h ----------- - -// Only use header guard if we are not using an outer namespace -#if !defined(TBC_TEXT_FORMAT_H_INCLUDED) || defined(STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE) -#ifndef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE -#define TBC_TEXT_FORMAT_H_INCLUDED -#endif - -#include -#include -#include -#include -#include - -// Use optional outer namespace -#ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE -namespace STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE { -#endif - -namespace Tbc { - -#ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH - const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH; -#else - const unsigned int consoleWidth = 80; -#endif - - struct TextAttributes { - TextAttributes() - : initialIndent( std::string::npos ), - indent( 0 ), - width( consoleWidth-1 ), - tabChar( '\t' ) - {} - - TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; } - TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; } - TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; } - TextAttributes& setTabChar( char _value ) { tabChar = _value; return *this; } - - std::size_t initialIndent; // indent of first line, or npos - std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos - std::size_t width; // maximum width of text, including indent. Longer text will wrap - char tabChar; // If this char is seen the indent is changed to current pos - }; - - class Text { - public: - Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() ) - : attr( _attr ) - { - std::string wrappableChars = " [({.,/|\\-"; - std::size_t indent = _attr.initialIndent != std::string::npos - ? _attr.initialIndent - : _attr.indent; - std::string remainder = _str; - - while( !remainder.empty() ) { - if( lines.size() >= 1000 ) { - lines.push_back( "... message truncated due to excessive size" ); - return; - } - std::size_t tabPos = std::string::npos; - std::size_t width = (std::min)( remainder.size(), _attr.width - indent ); - std::size_t pos = remainder.find_first_of( '\n' ); - if( pos <= width ) { - width = pos; - } - pos = remainder.find_last_of( _attr.tabChar, width ); - if( pos != std::string::npos ) { - tabPos = pos; - if( remainder[width] == '\n' ) - width--; - remainder = remainder.substr( 0, tabPos ) + remainder.substr( tabPos+1 ); - } - - if( width == remainder.size() ) { - spliceLine( indent, remainder, width ); - } - else if( remainder[width] == '\n' ) { - spliceLine( indent, remainder, width ); - if( width <= 1 || remainder.size() != 1 ) - remainder = remainder.substr( 1 ); - indent = _attr.indent; - } - else { - pos = remainder.find_last_of( wrappableChars, width ); - if( pos != std::string::npos && pos > 0 ) { - spliceLine( indent, remainder, pos ); - if( remainder[0] == ' ' ) - remainder = remainder.substr( 1 ); - } - else { - spliceLine( indent, remainder, width-1 ); - lines.back() += "-"; - } - if( lines.size() == 1 ) - indent = _attr.indent; - if( tabPos != std::string::npos ) - indent += tabPos; - } - } - } - - void spliceLine( std::size_t _indent, std::string& _remainder, std::size_t _pos ) { - lines.push_back( std::string( _indent, ' ' ) + _remainder.substr( 0, _pos ) ); - _remainder = _remainder.substr( _pos ); - } - - typedef std::vector::const_iterator const_iterator; - - const_iterator begin() const { return lines.begin(); } - const_iterator end() const { return lines.end(); } - std::string const& last() const { return lines.back(); } - std::size_t size() const { return lines.size(); } - std::string const& operator[]( std::size_t _index ) const { return lines[_index]; } - std::string toString() const { - std::ostringstream oss; - oss << *this; - return oss.str(); - } - - inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) { - for( Text::const_iterator it = _text.begin(), itEnd = _text.end(); - it != itEnd; ++it ) { - if( it != _text.begin() ) - _stream << "\n"; - _stream << *it; - } - return _stream; - } - - private: - std::string str; - TextAttributes attr; - std::vector lines; - }; - -} // end namespace Tbc - -#ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE -} // end outer namespace -#endif - -#endif // TBC_TEXT_FORMAT_H_INCLUDED - -// ----------- end of #include from tbc_text_format.h ----------- -// ........... back in clara.h - -#undef STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE - -// ----------- #included from clara_compilers.h ----------- - -#ifndef TWOBLUECUBES_CLARA_COMPILERS_H_INCLUDED -#define TWOBLUECUBES_CLARA_COMPILERS_H_INCLUDED - -// Detect a number of compiler features - mostly C++11/14 conformance - by compiler -// The following features are defined: -// -// CLARA_CONFIG_CPP11_NULLPTR : is nullptr supported? -// CLARA_CONFIG_CPP11_NOEXCEPT : is noexcept supported? -// CLARA_CONFIG_CPP11_GENERATED_METHODS : The delete and default keywords for compiler generated methods -// CLARA_CONFIG_CPP11_OVERRIDE : is override supported? -// CLARA_CONFIG_CPP11_UNIQUE_PTR : is unique_ptr supported (otherwise use auto_ptr) - -// CLARA_CONFIG_CPP11_OR_GREATER : Is C++11 supported? - -// CLARA_CONFIG_VARIADIC_MACROS : are variadic macros supported? - -// In general each macro has a _NO_ form -// (e.g. CLARA_CONFIG_CPP11_NO_NULLPTR) which disables the feature. -// Many features, at point of detection, define an _INTERNAL_ macro, so they -// can be combined, en-mass, with the _NO_ forms later. - -// All the C++11 features can be disabled with CLARA_CONFIG_NO_CPP11 - -#ifdef __clang__ - -#if __has_feature(cxx_nullptr) -#define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR -#endif - -#if __has_feature(cxx_noexcept) -#define CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT -#endif - -#endif // __clang__ - -//////////////////////////////////////////////////////////////////////////////// -// GCC -#ifdef __GNUC__ - -#if __GNUC__ == 4 && __GNUC_MINOR__ >= 6 && defined(__GXX_EXPERIMENTAL_CXX0X__) -#define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR -#endif - -// - otherwise more recent versions define __cplusplus >= 201103L -// and will get picked up below - -#endif // __GNUC__ - -//////////////////////////////////////////////////////////////////////////////// -// Visual C++ -#ifdef _MSC_VER - -#if (_MSC_VER >= 1600) -#define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR -#define CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR -#endif - -#if (_MSC_VER >= 1900 ) // (VC++ 13 (VS2015)) -#define CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT -#define CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS -#endif - -#endif // _MSC_VER - -//////////////////////////////////////////////////////////////////////////////// -// C++ language feature support - -// catch all support for C++11 -#if defined(__cplusplus) && __cplusplus >= 201103L - -#define CLARA_CPP11_OR_GREATER - -#if !defined(CLARA_INTERNAL_CONFIG_CPP11_NULLPTR) -#define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR -#endif - -#ifndef CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT -#define CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT -#endif - -#ifndef CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS -#define CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS -#endif - -#if !defined(CLARA_INTERNAL_CONFIG_CPP11_OVERRIDE) -#define CLARA_INTERNAL_CONFIG_CPP11_OVERRIDE -#endif -#if !defined(CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) -#define CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR -#endif - -#endif // __cplusplus >= 201103L - -// Now set the actual defines based on the above + anything the user has configured -#if defined(CLARA_INTERNAL_CONFIG_CPP11_NULLPTR) && !defined(CLARA_CONFIG_CPP11_NO_NULLPTR) && !defined(CLARA_CONFIG_CPP11_NULLPTR) && !defined(CLARA_CONFIG_NO_CPP11) -#define CLARA_CONFIG_CPP11_NULLPTR -#endif -#if defined(CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT) && !defined(CLARA_CONFIG_CPP11_NO_NOEXCEPT) && !defined(CLARA_CONFIG_CPP11_NOEXCEPT) && !defined(CLARA_CONFIG_NO_CPP11) -#define CLARA_CONFIG_CPP11_NOEXCEPT -#endif -#if defined(CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS) && !defined(CLARA_CONFIG_CPP11_NO_GENERATED_METHODS) && !defined(CLARA_CONFIG_CPP11_GENERATED_METHODS) && !defined(CLARA_CONFIG_NO_CPP11) -#define CLARA_CONFIG_CPP11_GENERATED_METHODS -#endif -#if defined(CLARA_INTERNAL_CONFIG_CPP11_OVERRIDE) && !defined(CLARA_CONFIG_NO_OVERRIDE) && !defined(CLARA_CONFIG_CPP11_OVERRIDE) && !defined(CLARA_CONFIG_NO_CPP11) -#define CLARA_CONFIG_CPP11_OVERRIDE -#endif -#if defined(CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) && !defined(CLARA_CONFIG_NO_UNIQUE_PTR) && !defined(CLARA_CONFIG_CPP11_UNIQUE_PTR) && !defined(CLARA_CONFIG_NO_CPP11) -#define CLARA_CONFIG_CPP11_UNIQUE_PTR -#endif - -// noexcept support: -#if defined(CLARA_CONFIG_CPP11_NOEXCEPT) && !defined(CLARA_NOEXCEPT) -#define CLARA_NOEXCEPT noexcept -# define CLARA_NOEXCEPT_IS(x) noexcept(x) -#else -#define CLARA_NOEXCEPT throw() -# define CLARA_NOEXCEPT_IS(x) -#endif - -// nullptr support -#ifdef CLARA_CONFIG_CPP11_NULLPTR -#define CLARA_NULL nullptr -#else -#define CLARA_NULL NULL -#endif - -// override support -#ifdef CLARA_CONFIG_CPP11_OVERRIDE -#define CLARA_OVERRIDE override -#else -#define CLARA_OVERRIDE -#endif - -// unique_ptr support -#ifdef CLARA_CONFIG_CPP11_UNIQUE_PTR -# define CLARA_AUTO_PTR( T ) std::unique_ptr -#else -# define CLARA_AUTO_PTR( T ) std::auto_ptr -#endif - -#endif // TWOBLUECUBES_CLARA_COMPILERS_H_INCLUDED - -// ----------- end of #include from clara_compilers.h ----------- -// ........... back in clara.h - -#include -#include -#include - -#if defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) -#define CLARA_PLATFORM_WINDOWS -#endif - -// Use optional outer namespace -#ifdef STITCH_CLARA_OPEN_NAMESPACE -STITCH_CLARA_OPEN_NAMESPACE -#endif - -namespace Clara { - - struct UnpositionalTag {}; - - extern UnpositionalTag _; - -#ifdef CLARA_CONFIG_MAIN - UnpositionalTag _; -#endif - - namespace Detail { - -#ifdef CLARA_CONSOLE_WIDTH - const unsigned int consoleWidth = CLARA_CONFIG_CONSOLE_WIDTH; -#else - const unsigned int consoleWidth = 80; -#endif - - using namespace Tbc; - - inline bool startsWith( std::string const& str, std::string const& prefix ) { - return str.size() >= prefix.size() && str.substr( 0, prefix.size() ) == prefix; - } - - template struct RemoveConstRef{ typedef T type; }; - template struct RemoveConstRef{ typedef T type; }; - template struct RemoveConstRef{ typedef T type; }; - template struct RemoveConstRef{ typedef T type; }; - - template struct IsBool { static const bool value = false; }; - template<> struct IsBool { static const bool value = true; }; - - template - void convertInto( std::string const& _source, T& _dest ) { - std::stringstream ss; - ss << _source; - ss >> _dest; - if( ss.fail() ) - throw std::runtime_error( "Unable to convert " + _source + " to destination type" ); - } - inline void convertInto( std::string const& _source, std::string& _dest ) { - _dest = _source; - } - char toLowerCh(char c) { - return static_cast( std::tolower( c ) ); - } - inline void convertInto( std::string const& _source, bool& _dest ) { - std::string sourceLC = _source; - std::transform( sourceLC.begin(), sourceLC.end(), sourceLC.begin(), toLowerCh ); - if( sourceLC == "y" || sourceLC == "1" || sourceLC == "true" || sourceLC == "yes" || sourceLC == "on" ) - _dest = true; - else if( sourceLC == "n" || sourceLC == "0" || sourceLC == "false" || sourceLC == "no" || sourceLC == "off" ) - _dest = false; - else - throw std::runtime_error( "Expected a boolean value but did not recognise:\n '" + _source + "'" ); - } - - template - struct IArgFunction { - virtual ~IArgFunction() {} -#ifdef CLARA_CONFIG_CPP11_GENERATED_METHODS - IArgFunction() = default; - IArgFunction( IArgFunction const& ) = default; -#endif - virtual void set( ConfigT& config, std::string const& value ) const = 0; - virtual bool takesArg() const = 0; - virtual IArgFunction* clone() const = 0; - }; - - template - class BoundArgFunction { - public: - BoundArgFunction() : functionObj( CLARA_NULL ) {} - BoundArgFunction( IArgFunction* _functionObj ) : functionObj( _functionObj ) {} - BoundArgFunction( BoundArgFunction const& other ) : functionObj( other.functionObj ? other.functionObj->clone() : CLARA_NULL ) {} - BoundArgFunction& operator = ( BoundArgFunction const& other ) { - IArgFunction* newFunctionObj = other.functionObj ? other.functionObj->clone() : CLARA_NULL; - delete functionObj; - functionObj = newFunctionObj; - return *this; - } - ~BoundArgFunction() { delete functionObj; } - - void set( ConfigT& config, std::string const& value ) const { - functionObj->set( config, value ); - } - bool takesArg() const { return functionObj->takesArg(); } - - bool isSet() const { - return functionObj != CLARA_NULL; - } - private: - IArgFunction* functionObj; - }; - - template - struct NullBinder : IArgFunction{ - virtual void set( C&, std::string const& ) const {} - virtual bool takesArg() const { return true; } - virtual IArgFunction* clone() const { return new NullBinder( *this ); } - }; - - template - struct BoundDataMember : IArgFunction{ - BoundDataMember( M C::* _member ) : member( _member ) {} - virtual void set( C& p, std::string const& stringValue ) const { - convertInto( stringValue, p.*member ); - } - virtual bool takesArg() const { return !IsBool::value; } - virtual IArgFunction* clone() const { return new BoundDataMember( *this ); } - M C::* member; - }; - template - struct BoundUnaryMethod : IArgFunction{ - BoundUnaryMethod( void (C::*_member)( M ) ) : member( _member ) {} - virtual void set( C& p, std::string const& stringValue ) const { - typename RemoveConstRef::type value; - convertInto( stringValue, value ); - (p.*member)( value ); - } - virtual bool takesArg() const { return !IsBool::value; } - virtual IArgFunction* clone() const { return new BoundUnaryMethod( *this ); } - void (C::*member)( M ); - }; - template - struct BoundNullaryMethod : IArgFunction{ - BoundNullaryMethod( void (C::*_member)() ) : member( _member ) {} - virtual void set( C& p, std::string const& stringValue ) const { - bool value; - convertInto( stringValue, value ); - if( value ) - (p.*member)(); - } - virtual bool takesArg() const { return false; } - virtual IArgFunction* clone() const { return new BoundNullaryMethod( *this ); } - void (C::*member)(); - }; - - template - struct BoundUnaryFunction : IArgFunction{ - BoundUnaryFunction( void (*_function)( C& ) ) : function( _function ) {} - virtual void set( C& obj, std::string const& stringValue ) const { - bool value; - convertInto( stringValue, value ); - if( value ) - function( obj ); - } - virtual bool takesArg() const { return false; } - virtual IArgFunction* clone() const { return new BoundUnaryFunction( *this ); } - void (*function)( C& ); - }; - - template - struct BoundBinaryFunction : IArgFunction{ - BoundBinaryFunction( void (*_function)( C&, T ) ) : function( _function ) {} - virtual void set( C& obj, std::string const& stringValue ) const { - typename RemoveConstRef::type value; - convertInto( stringValue, value ); - function( obj, value ); - } - virtual bool takesArg() const { return !IsBool::value; } - virtual IArgFunction* clone() const { return new BoundBinaryFunction( *this ); } - void (*function)( C&, T ); - }; - - } // namespace Detail - - inline std::vector argsToVector( int argc, char const* const* const argv ) { - std::vector args( static_cast( argc ) ); - for( std::size_t i = 0; i < static_cast( argc ); ++i ) - args[i] = argv[i]; - - return args; - } - - class Parser { - enum Mode { None, MaybeShortOpt, SlashOpt, ShortOpt, LongOpt, Positional }; - Mode mode; - std::size_t from; - bool inQuotes; - public: - - struct Token { - enum Type { Positional, ShortOpt, LongOpt }; - Token( Type _type, std::string const& _data ) : type( _type ), data( _data ) {} - Type type; - std::string data; - }; - - Parser() : mode( None ), from( 0 ), inQuotes( false ){} - - void parseIntoTokens( std::vector const& args, std::vector& tokens ) { - const std::string doubleDash = "--"; - for( std::size_t i = 1; i < args.size() && args[i] != doubleDash; ++i ) - parseIntoTokens( args[i], tokens); - } - - void parseIntoTokens( std::string const& arg, std::vector& tokens ) { - for( std::size_t i = 0; i < arg.size(); ++i ) { - char c = arg[i]; - if( c == '"' ) - inQuotes = !inQuotes; - mode = handleMode( i, c, arg, tokens ); - } - mode = handleMode( arg.size(), '\0', arg, tokens ); - } - Mode handleMode( std::size_t i, char c, std::string const& arg, std::vector& tokens ) { - switch( mode ) { - case None: return handleNone( i, c ); - case MaybeShortOpt: return handleMaybeShortOpt( i, c ); - case ShortOpt: - case LongOpt: - case SlashOpt: return handleOpt( i, c, arg, tokens ); - case Positional: return handlePositional( i, c, arg, tokens ); - default: throw std::logic_error( "Unknown mode" ); - } - } - - Mode handleNone( std::size_t i, char c ) { - if( inQuotes ) { - from = i; - return Positional; - } - switch( c ) { - case '-': return MaybeShortOpt; -#ifdef CLARA_PLATFORM_WINDOWS - case '/': from = i+1; return SlashOpt; -#endif - default: from = i; return Positional; - } - } - Mode handleMaybeShortOpt( std::size_t i, char c ) { - switch( c ) { - case '-': from = i+1; return LongOpt; - default: from = i; return ShortOpt; - } - } - - Mode handleOpt( std::size_t i, char c, std::string const& arg, std::vector& tokens ) { - if( std::string( ":=\0", 3 ).find( c ) == std::string::npos ) - return mode; - - std::string optName = arg.substr( from, i-from ); - if( mode == ShortOpt ) - for( std::size_t j = 0; j < optName.size(); ++j ) - tokens.push_back( Token( Token::ShortOpt, optName.substr( j, 1 ) ) ); - else if( mode == SlashOpt && optName.size() == 1 ) - tokens.push_back( Token( Token::ShortOpt, optName ) ); - else - tokens.push_back( Token( Token::LongOpt, optName ) ); - return None; - } - Mode handlePositional( std::size_t i, char c, std::string const& arg, std::vector& tokens ) { - if( inQuotes || std::string( "\0", 1 ).find( c ) == std::string::npos ) - return mode; - - std::string data = arg.substr( from, i-from ); - tokens.push_back( Token( Token::Positional, data ) ); - return None; - } - }; - - template - struct CommonArgProperties { - CommonArgProperties() {} - CommonArgProperties( Detail::BoundArgFunction const& _boundField ) : boundField( _boundField ) {} - - Detail::BoundArgFunction boundField; - std::string description; - std::string detail; - std::string placeholder; // Only value if boundField takes an arg - - bool takesArg() const { - return !placeholder.empty(); - } - void validate() const { - if( !boundField.isSet() ) - throw std::logic_error( "option not bound" ); - } - }; - struct OptionArgProperties { - std::vector shortNames; - std::string longName; - - bool hasShortName( std::string const& shortName ) const { - return std::find( shortNames.begin(), shortNames.end(), shortName ) != shortNames.end(); - } - bool hasLongName( std::string const& _longName ) const { - return _longName == longName; - } - }; - struct PositionalArgProperties { - PositionalArgProperties() : position( -1 ) {} - int position; // -1 means non-positional (floating) - - bool isFixedPositional() const { - return position != -1; - } - }; - - template - class CommandLine { - - struct Arg : CommonArgProperties, OptionArgProperties, PositionalArgProperties { - Arg() {} - Arg( Detail::BoundArgFunction const& _boundField ) : CommonArgProperties( _boundField ) {} - - using CommonArgProperties::placeholder; // !TBD - - std::string dbgName() const { - if( !longName.empty() ) - return "--" + longName; - if( !shortNames.empty() ) - return "-" + shortNames[0]; - return "positional args"; - } - std::string commands() const { - std::ostringstream oss; - bool first = true; - std::vector::const_iterator it = shortNames.begin(), itEnd = shortNames.end(); - for(; it != itEnd; ++it ) { - if( first ) - first = false; - else - oss << ", "; - oss << "-" << *it; - } - if( !longName.empty() ) { - if( !first ) - oss << ", "; - oss << "--" << longName; - } - if( !placeholder.empty() ) - oss << " <" << placeholder << ">"; - return oss.str(); - } - }; - - typedef CLARA_AUTO_PTR( Arg ) ArgAutoPtr; - - friend void addOptName( Arg& arg, std::string const& optName ) - { - if( optName.empty() ) - return; - if( Detail::startsWith( optName, "--" ) ) { - if( !arg.longName.empty() ) - throw std::logic_error( "Only one long opt may be specified. '" - + arg.longName - + "' already specified, now attempting to add '" - + optName + "'" ); - arg.longName = optName.substr( 2 ); - } - else if( Detail::startsWith( optName, "-" ) ) - arg.shortNames.push_back( optName.substr( 1 ) ); - else - throw std::logic_error( "option must begin with - or --. Option was: '" + optName + "'" ); - } - friend void setPositionalArg( Arg& arg, int position ) - { - arg.position = position; - } - - class ArgBuilder { - public: - ArgBuilder( Arg* arg ) : m_arg( arg ) {} - - // Bind a non-boolean data member (requires placeholder string) - template - void bind( M C::* field, std::string const& placeholder ) { - m_arg->boundField = new Detail::BoundDataMember( field ); - m_arg->placeholder = placeholder; - } - // Bind a boolean data member (no placeholder required) - template - void bind( bool C::* field ) { - m_arg->boundField = new Detail::BoundDataMember( field ); - } - - // Bind a method taking a single, non-boolean argument (requires a placeholder string) - template - void bind( void (C::* unaryMethod)( M ), std::string const& placeholder ) { - m_arg->boundField = new Detail::BoundUnaryMethod( unaryMethod ); - m_arg->placeholder = placeholder; - } - - // Bind a method taking a single, boolean argument (no placeholder string required) - template - void bind( void (C::* unaryMethod)( bool ) ) { - m_arg->boundField = new Detail::BoundUnaryMethod( unaryMethod ); - } - - // Bind a method that takes no arguments (will be called if opt is present) - template - void bind( void (C::* nullaryMethod)() ) { - m_arg->boundField = new Detail::BoundNullaryMethod( nullaryMethod ); - } - - // Bind a free function taking a single argument - the object to operate on (no placeholder string required) - template - void bind( void (* unaryFunction)( C& ) ) { - m_arg->boundField = new Detail::BoundUnaryFunction( unaryFunction ); - } - - // Bind a free function taking a single argument - the object to operate on (requires a placeholder string) - template - void bind( void (* binaryFunction)( C&, T ), std::string const& placeholder ) { - m_arg->boundField = new Detail::BoundBinaryFunction( binaryFunction ); - m_arg->placeholder = placeholder; - } - - ArgBuilder& describe( std::string const& description ) { - m_arg->description = description; - return *this; - } - ArgBuilder& detail( std::string const& detail ) { - m_arg->detail = detail; - return *this; - } - - protected: - Arg* m_arg; - }; - - class OptBuilder : public ArgBuilder { - public: - OptBuilder( Arg* arg ) : ArgBuilder( arg ) {} - OptBuilder( OptBuilder& other ) : ArgBuilder( other ) {} - - OptBuilder& operator[]( std::string const& optName ) { - addOptName( *ArgBuilder::m_arg, optName ); - return *this; - } - }; - - public: - - CommandLine() - : m_boundProcessName( new Detail::NullBinder() ), - m_highestSpecifiedArgPosition( 0 ), - m_throwOnUnrecognisedTokens( false ) - {} - CommandLine( CommandLine const& other ) - : m_boundProcessName( other.m_boundProcessName ), - m_options ( other.m_options ), - m_positionalArgs( other.m_positionalArgs ), - m_highestSpecifiedArgPosition( other.m_highestSpecifiedArgPosition ), - m_throwOnUnrecognisedTokens( other.m_throwOnUnrecognisedTokens ) - { - if( other.m_floatingArg.get() ) - m_floatingArg.reset( new Arg( *other.m_floatingArg ) ); - } - - CommandLine& setThrowOnUnrecognisedTokens( bool shouldThrow = true ) { - m_throwOnUnrecognisedTokens = shouldThrow; - return *this; - } - - OptBuilder operator[]( std::string const& optName ) { - m_options.push_back( Arg() ); - addOptName( m_options.back(), optName ); - OptBuilder builder( &m_options.back() ); - return builder; - } - - ArgBuilder operator[]( int position ) { - m_positionalArgs.insert( std::make_pair( position, Arg() ) ); - if( position > m_highestSpecifiedArgPosition ) - m_highestSpecifiedArgPosition = position; - setPositionalArg( m_positionalArgs[position], position ); - ArgBuilder builder( &m_positionalArgs[position] ); - return builder; - } - - // Invoke this with the _ instance - ArgBuilder operator[]( UnpositionalTag ) { - if( m_floatingArg.get() ) - throw std::logic_error( "Only one unpositional argument can be added" ); - m_floatingArg.reset( new Arg() ); - ArgBuilder builder( m_floatingArg.get() ); - return builder; - } - - template - void bindProcessName( M C::* field ) { - m_boundProcessName = new Detail::BoundDataMember( field ); - } - template - void bindProcessName( void (C::*_unaryMethod)( M ) ) { - m_boundProcessName = new Detail::BoundUnaryMethod( _unaryMethod ); - } - - void optUsage( std::ostream& os, std::size_t indent = 0, std::size_t width = Detail::consoleWidth ) const { - typename std::vector::const_iterator itBegin = m_options.begin(), itEnd = m_options.end(), it; - std::size_t maxWidth = 0; - for( it = itBegin; it != itEnd; ++it ) - maxWidth = (std::max)( maxWidth, it->commands().size() ); - - for( it = itBegin; it != itEnd; ++it ) { - Detail::Text usage( it->commands(), Detail::TextAttributes() - .setWidth( maxWidth+indent ) - .setIndent( indent ) ); - Detail::Text desc( it->description, Detail::TextAttributes() - .setWidth( width - maxWidth - 3 ) ); - - for( std::size_t i = 0; i < (std::max)( usage.size(), desc.size() ); ++i ) { - std::string usageCol = i < usage.size() ? usage[i] : ""; - os << usageCol; - - if( i < desc.size() && !desc[i].empty() ) - os << std::string( indent + 2 + maxWidth - usageCol.size(), ' ' ) - << desc[i]; - os << "\n"; - } - } - } - std::string optUsage() const { - std::ostringstream oss; - optUsage( oss ); - return oss.str(); - } - - void argSynopsis( std::ostream& os ) const { - for( int i = 1; i <= m_highestSpecifiedArgPosition; ++i ) { - if( i > 1 ) - os << " "; - typename std::map::const_iterator it = m_positionalArgs.find( i ); - if( it != m_positionalArgs.end() ) - os << "<" << it->second.placeholder << ">"; - else if( m_floatingArg.get() ) - os << "<" << m_floatingArg->placeholder << ">"; - else - throw std::logic_error( "non consecutive positional arguments with no floating args" ); - } - // !TBD No indication of mandatory args - if( m_floatingArg.get() ) { - if( m_highestSpecifiedArgPosition > 1 ) - os << " "; - os << "[<" << m_floatingArg->placeholder << "> ...]"; - } - } - std::string argSynopsis() const { - std::ostringstream oss; - argSynopsis( oss ); - return oss.str(); - } - - void usage( std::ostream& os, std::string const& procName ) const { - validate(); - os << "usage:\n " << procName << " "; - argSynopsis( os ); - if( !m_options.empty() ) { - os << " [options]\n\nwhere options are: \n"; - optUsage( os, 2 ); - } - os << "\n"; - } - std::string usage( std::string const& procName ) const { - std::ostringstream oss; - usage( oss, procName ); - return oss.str(); - } - - ConfigT parse( std::vector const& args ) const { - ConfigT config; - parseInto( args, config ); - return config; - } - - std::vector parseInto( std::vector const& args, ConfigT& config ) const { - std::string processName = args.empty() ? std::string() : args[0]; - std::size_t lastSlash = processName.find_last_of( "/\\" ); - if( lastSlash != std::string::npos ) - processName = processName.substr( lastSlash+1 ); - m_boundProcessName.set( config, processName ); - std::vector tokens; - Parser parser; - parser.parseIntoTokens( args, tokens ); - return populate( tokens, config ); - } - - std::vector populate( std::vector const& tokens, ConfigT& config ) const { - validate(); - std::vector unusedTokens = populateOptions( tokens, config ); - unusedTokens = populateFixedArgs( unusedTokens, config ); - unusedTokens = populateFloatingArgs( unusedTokens, config ); - return unusedTokens; - } - - std::vector populateOptions( std::vector const& tokens, ConfigT& config ) const { - std::vector unusedTokens; - std::vector errors; - for( std::size_t i = 0; i < tokens.size(); ++i ) { - Parser::Token const& token = tokens[i]; - typename std::vector::const_iterator it = m_options.begin(), itEnd = m_options.end(); - for(; it != itEnd; ++it ) { - Arg const& arg = *it; - - try { - if( ( token.type == Parser::Token::ShortOpt && arg.hasShortName( token.data ) ) || - ( token.type == Parser::Token::LongOpt && arg.hasLongName( token.data ) ) ) { - if( arg.takesArg() ) { - if( i == tokens.size()-1 || tokens[i+1].type != Parser::Token::Positional ) - errors.push_back( "Expected argument to option: " + token.data ); - else - arg.boundField.set( config, tokens[++i].data ); - } - else { - arg.boundField.set( config, "true" ); - } - break; - } - } - catch( std::exception& ex ) { - errors.push_back( std::string( ex.what() ) + "\n- while parsing: (" + arg.commands() + ")" ); - } - } - if( it == itEnd ) { - if( token.type == Parser::Token::Positional || !m_throwOnUnrecognisedTokens ) - unusedTokens.push_back( token ); - else if( errors.empty() && m_throwOnUnrecognisedTokens ) - errors.push_back( "unrecognised option: " + token.data ); - } - } - if( !errors.empty() ) { - std::ostringstream oss; - for( std::vector::const_iterator it = errors.begin(), itEnd = errors.end(); - it != itEnd; - ++it ) { - if( it != errors.begin() ) - oss << "\n"; - oss << *it; - } - throw std::runtime_error( oss.str() ); - } - return unusedTokens; - } - std::vector populateFixedArgs( std::vector const& tokens, ConfigT& config ) const { - std::vector unusedTokens; - int position = 1; - for( std::size_t i = 0; i < tokens.size(); ++i ) { - Parser::Token const& token = tokens[i]; - typename std::map::const_iterator it = m_positionalArgs.find( position ); - if( it != m_positionalArgs.end() ) - it->second.boundField.set( config, token.data ); - else - unusedTokens.push_back( token ); - if( token.type == Parser::Token::Positional ) - position++; - } - return unusedTokens; - } - std::vector populateFloatingArgs( std::vector const& tokens, ConfigT& config ) const { - if( !m_floatingArg.get() ) - return tokens; - std::vector unusedTokens; - for( std::size_t i = 0; i < tokens.size(); ++i ) { - Parser::Token const& token = tokens[i]; - if( token.type == Parser::Token::Positional ) - m_floatingArg->boundField.set( config, token.data ); - else - unusedTokens.push_back( token ); - } - return unusedTokens; - } - - void validate() const - { - if( m_options.empty() && m_positionalArgs.empty() && !m_floatingArg.get() ) - throw std::logic_error( "No options or arguments specified" ); - - for( typename std::vector::const_iterator it = m_options.begin(), - itEnd = m_options.end(); - it != itEnd; ++it ) - it->validate(); - } - - private: - Detail::BoundArgFunction m_boundProcessName; - std::vector m_options; - std::map m_positionalArgs; - ArgAutoPtr m_floatingArg; - int m_highestSpecifiedArgPosition; - bool m_throwOnUnrecognisedTokens; - }; - -} // end namespace Clara - -STITCH_CLARA_CLOSE_NAMESPACE -#undef STITCH_CLARA_OPEN_NAMESPACE -#undef STITCH_CLARA_CLOSE_NAMESPACE - -#endif // TWOBLUECUBES_CLARA_H_INCLUDED -#undef STITCH_CLARA_OPEN_NAMESPACE - -// Restore Clara's value for console width, if present -#ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH -#define CLARA_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH -#undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH -#endif - -#include -#include - -namespace Catch { - - inline void abortAfterFirst( ConfigData& config ) { config.abortAfter = 1; } - inline void abortAfterX( ConfigData& config, int x ) { - if( x < 1 ) - throw std::runtime_error( "Value after -x or --abortAfter must be greater than zero" ); - config.abortAfter = x; - } - inline void addTestOrTags( ConfigData& config, std::string const& _testSpec ) { config.testsOrTags.push_back( _testSpec ); } - inline void addSectionToRun( ConfigData& config, std::string const& sectionName ) { config.sectionsToRun.push_back( sectionName ); } - inline void addReporterName( ConfigData& config, std::string const& _reporterName ) { config.reporterNames.push_back( _reporterName ); } - - inline void addWarning( ConfigData& config, std::string const& _warning ) { - if( _warning == "NoAssertions" ) - config.warnings = static_cast( config.warnings | WarnAbout::NoAssertions ); - else - throw std::runtime_error( "Unrecognised warning: '" + _warning + '\'' ); - } - inline void setOrder( ConfigData& config, std::string const& order ) { - if( startsWith( "declared", order ) ) - config.runOrder = RunTests::InDeclarationOrder; - else if( startsWith( "lexical", order ) ) - config.runOrder = RunTests::InLexicographicalOrder; - else if( startsWith( "random", order ) ) - config.runOrder = RunTests::InRandomOrder; - else - throw std::runtime_error( "Unrecognised ordering: '" + order + '\'' ); - } - inline void setRngSeed( ConfigData& config, std::string const& seed ) { - if( seed == "time" ) { - config.rngSeed = static_cast( std::time(0) ); - } - else { - std::stringstream ss; - ss << seed; - ss >> config.rngSeed; - if( ss.fail() ) - throw std::runtime_error( "Argument to --rng-seed should be the word 'time' or a number" ); - } - } - inline void setVerbosity( ConfigData& config, int level ) { - // !TBD: accept strings? - config.verbosity = static_cast( level ); - } - inline void setShowDurations( ConfigData& config, bool _showDurations ) { - config.showDurations = _showDurations - ? ShowDurations::Always - : ShowDurations::Never; - } - inline void setUseColour( ConfigData& config, std::string const& value ) { - std::string mode = toLower( value ); - - if( mode == "yes" ) - config.useColour = UseColour::Yes; - else if( mode == "no" ) - config.useColour = UseColour::No; - else if( mode == "auto" ) - config.useColour = UseColour::Auto; - else - throw std::runtime_error( "colour mode must be one of: auto, yes or no" ); - } - inline void forceColour( ConfigData& config ) { - config.useColour = UseColour::Yes; - } - inline void loadTestNamesFromFile( ConfigData& config, std::string const& _filename ) { - std::ifstream f( _filename.c_str() ); - if( !f.is_open() ) - throw std::domain_error( "Unable to load input file: " + _filename ); - - std::string line; - while( std::getline( f, line ) ) { - line = trim(line); - if( !line.empty() && !startsWith( line, '#' ) ) { - if( !startsWith( line, '"' ) ) - line = '"' + line + '"'; - addTestOrTags( config, line + ',' ); - } - } - } - - inline Clara::CommandLine makeCommandLineParser() { - - using namespace Clara; - CommandLine cli; - - cli.bindProcessName( &ConfigData::processName ); - - cli["-?"]["-h"]["--help"] - .describe( "display usage information" ) - .bind( &ConfigData::showHelp ); - - cli["-l"]["--list-tests"] - .describe( "list all/matching test cases" ) - .bind( &ConfigData::listTests ); - - cli["-t"]["--list-tags"] - .describe( "list all/matching tags" ) - .bind( &ConfigData::listTags ); - - cli["-s"]["--success"] - .describe( "include successful tests in output" ) - .bind( &ConfigData::showSuccessfulTests ); - - cli["-b"]["--break"] - .describe( "break into debugger on failure" ) - .bind( &ConfigData::shouldDebugBreak ); - - cli["-e"]["--nothrow"] - .describe( "skip exception tests" ) - .bind( &ConfigData::noThrow ); - - cli["-i"]["--invisibles"] - .describe( "show invisibles (tabs, newlines)" ) - .bind( &ConfigData::showInvisibles ); - - cli["-o"]["--out"] - .describe( "output filename" ) - .bind( &ConfigData::outputFilename, "filename" ); - - cli["-r"]["--reporter"] -// .placeholder( "name[:filename]" ) - .describe( "reporter to use (defaults to console)" ) - .bind( &addReporterName, "name" ); - - cli["-n"]["--name"] - .describe( "suite name" ) - .bind( &ConfigData::name, "name" ); - - cli["-a"]["--abort"] - .describe( "abort at first failure" ) - .bind( &abortAfterFirst ); - - cli["-x"]["--abortx"] - .describe( "abort after x failures" ) - .bind( &abortAfterX, "no. failures" ); - - cli["-w"]["--warn"] - .describe( "enable warnings" ) - .bind( &addWarning, "warning name" ); - -// - needs updating if reinstated -// cli.into( &setVerbosity ) -// .describe( "level of verbosity (0=no output)" ) -// .shortOpt( "v") -// .longOpt( "verbosity" ) -// .placeholder( "level" ); - - cli[_] - .describe( "which test or tests to use" ) - .bind( &addTestOrTags, "test name, pattern or tags" ); - - cli["-d"]["--durations"] - .describe( "show test durations" ) - .bind( &setShowDurations, "yes|no" ); - - cli["-f"]["--input-file"] - .describe( "load test names to run from a file" ) - .bind( &loadTestNamesFromFile, "filename" ); - - cli["-#"]["--filenames-as-tags"] - .describe( "adds a tag for the filename" ) - .bind( &ConfigData::filenamesAsTags ); - - cli["-c"]["--section"] - .describe( "specify section to run" ) - .bind( &addSectionToRun, "section name" ); - - // Less common commands which don't have a short form - cli["--list-test-names-only"] - .describe( "list all/matching test cases names only" ) - .bind( &ConfigData::listTestNamesOnly ); - - cli["--list-extra-info"] - .describe( "list all/matching test cases with more info" ) - .bind( &ConfigData::listExtraInfo ); - - cli["--list-reporters"] - .describe( "list all reporters" ) - .bind( &ConfigData::listReporters ); - - cli["--order"] - .describe( "test case order (defaults to decl)" ) - .bind( &setOrder, "decl|lex|rand" ); - - cli["--rng-seed"] - .describe( "set a specific seed for random numbers" ) - .bind( &setRngSeed, "'time'|number" ); - - cli["--force-colour"] - .describe( "force colourised output (deprecated)" ) - .bind( &forceColour ); - - cli["--use-colour"] - .describe( "should output be colourised" ) - .bind( &setUseColour, "yes|no" ); - - return cli; - } - -} // end namespace Catch - -// #included from: internal/catch_list.hpp -#define TWOBLUECUBES_CATCH_LIST_HPP_INCLUDED - -// #included from: catch_text.h -#define TWOBLUECUBES_CATCH_TEXT_H_INCLUDED - -#define TBC_TEXT_FORMAT_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH - -#define CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE Catch -// #included from: ../external/tbc_text_format.h -// Only use header guard if we are not using an outer namespace -#ifndef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE -# ifdef TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED -# ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED -# define TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED -# endif -# else -# define TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED -# endif -#endif -#ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED -#include -#include -#include - -// Use optional outer namespace -#ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE -namespace CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE { -#endif - -namespace Tbc { - -#ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH - const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH; -#else - const unsigned int consoleWidth = 80; -#endif - - struct TextAttributes { - TextAttributes() - : initialIndent( std::string::npos ), - indent( 0 ), - width( consoleWidth-1 ) - {} - - TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; } - TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; } - TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; } - - std::size_t initialIndent; // indent of first line, or npos - std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos - std::size_t width; // maximum width of text, including indent. Longer text will wrap - }; - - class Text { - public: - Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() ) - : attr( _attr ) - { - const std::string wrappableBeforeChars = "[({<\t"; - const std::string wrappableAfterChars = "])}>-,./|\\"; - const std::string wrappableInsteadOfChars = " \n\r"; - std::string indent = _attr.initialIndent != std::string::npos - ? std::string( _attr.initialIndent, ' ' ) - : std::string( _attr.indent, ' ' ); - - typedef std::string::const_iterator iterator; - iterator it = _str.begin(); - const iterator strEnd = _str.end(); - - while( it != strEnd ) { - - if( lines.size() >= 1000 ) { - lines.push_back( "... message truncated due to excessive size" ); - return; - } - - std::string suffix; - std::size_t width = (std::min)( static_cast( strEnd-it ), _attr.width-static_cast( indent.size() ) ); - iterator itEnd = it+width; - iterator itNext = _str.end(); - - iterator itNewLine = std::find( it, itEnd, '\n' ); - if( itNewLine != itEnd ) - itEnd = itNewLine; - - if( itEnd != strEnd ) { - bool foundWrapPoint = false; - iterator findIt = itEnd; - do { - if( wrappableAfterChars.find( *findIt ) != std::string::npos && findIt != itEnd ) { - itEnd = findIt+1; - itNext = findIt+1; - foundWrapPoint = true; - } - else if( findIt > it && wrappableBeforeChars.find( *findIt ) != std::string::npos ) { - itEnd = findIt; - itNext = findIt; - foundWrapPoint = true; - } - else if( wrappableInsteadOfChars.find( *findIt ) != std::string::npos ) { - itNext = findIt+1; - itEnd = findIt; - foundWrapPoint = true; - } - if( findIt == it ) - break; - else - --findIt; - } - while( !foundWrapPoint ); - - if( !foundWrapPoint ) { - // No good wrap char, so we'll break mid word and add a hyphen - --itEnd; - itNext = itEnd; - suffix = "-"; - } - else { - while( itEnd > it && wrappableInsteadOfChars.find( *(itEnd-1) ) != std::string::npos ) - --itEnd; - } - } - lines.push_back( indent + std::string( it, itEnd ) + suffix ); - - if( indent.size() != _attr.indent ) - indent = std::string( _attr.indent, ' ' ); - it = itNext; - } - } - - typedef std::vector::const_iterator const_iterator; - - const_iterator begin() const { return lines.begin(); } - const_iterator end() const { return lines.end(); } - std::string const& last() const { return lines.back(); } - std::size_t size() const { return lines.size(); } - std::string const& operator[]( std::size_t _index ) const { return lines[_index]; } - std::string toString() const { - std::ostringstream oss; - oss << *this; - return oss.str(); - } - - inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) { - for( Text::const_iterator it = _text.begin(), itEnd = _text.end(); - it != itEnd; ++it ) { - if( it != _text.begin() ) - _stream << "\n"; - _stream << *it; - } - return _stream; - } - - private: - std::string str; - TextAttributes attr; - std::vector lines; - }; - -} // end namespace Tbc - -#ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE -} // end outer namespace -#endif - -#endif // TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED -#undef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE - -namespace Catch { - using Tbc::Text; - using Tbc::TextAttributes; -} - -// #included from: catch_console_colour.hpp -#define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_HPP_INCLUDED - -namespace Catch { - - struct Colour { - enum Code { - None = 0, - - White, - Red, - Green, - Blue, - Cyan, - Yellow, - Grey, - - Bright = 0x10, - - BrightRed = Bright | Red, - BrightGreen = Bright | Green, - LightGrey = Bright | Grey, - BrightWhite = Bright | White, - - // By intention - FileName = LightGrey, - Warning = Yellow, - ResultError = BrightRed, - ResultSuccess = BrightGreen, - ResultExpectedFailure = Warning, - - Error = BrightRed, - Success = Green, - - OriginalExpression = Cyan, - ReconstructedExpression = Yellow, - - SecondaryText = LightGrey, - Headers = White - }; - - // Use constructed object for RAII guard - Colour( Code _colourCode ); - Colour( Colour const& other ); - ~Colour(); - - // Use static method for one-shot changes - static void use( Code _colourCode ); - - private: - bool m_moved; - }; - - inline std::ostream& operator << ( std::ostream& os, Colour const& ) { return os; } - -} // end namespace Catch - -// #included from: catch_interfaces_reporter.h -#define TWOBLUECUBES_CATCH_INTERFACES_REPORTER_H_INCLUDED - -#include -#include -#include - -namespace Catch -{ - struct ReporterConfig { - explicit ReporterConfig( Ptr const& _fullConfig ) - : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {} - - ReporterConfig( Ptr const& _fullConfig, std::ostream& _stream ) - : m_stream( &_stream ), m_fullConfig( _fullConfig ) {} - - std::ostream& stream() const { return *m_stream; } - Ptr fullConfig() const { return m_fullConfig; } - - private: - std::ostream* m_stream; - Ptr m_fullConfig; - }; - - struct ReporterPreferences { - ReporterPreferences() - : shouldRedirectStdOut( false ) - {} - - bool shouldRedirectStdOut; - }; - - template - struct LazyStat : Option { - LazyStat() : used( false ) {} - LazyStat& operator=( T const& _value ) { - Option::operator=( _value ); - used = false; - return *this; - } - void reset() { - Option::reset(); - used = false; - } - bool used; - }; - - struct TestRunInfo { - TestRunInfo( std::string const& _name ) : name( _name ) {} - std::string name; - }; - struct GroupInfo { - GroupInfo( std::string const& _name, - std::size_t _groupIndex, - std::size_t _groupsCount ) - : name( _name ), - groupIndex( _groupIndex ), - groupsCounts( _groupsCount ) - {} - - std::string name; - std::size_t groupIndex; - std::size_t groupsCounts; - }; - - struct AssertionStats { - AssertionStats( AssertionResult const& _assertionResult, - std::vector const& _infoMessages, - Totals const& _totals ) - : assertionResult( _assertionResult ), - infoMessages( _infoMessages ), - totals( _totals ) - { - if( assertionResult.hasMessage() ) { - // Copy message into messages list. - // !TBD This should have been done earlier, somewhere - MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() ); - builder << assertionResult.getMessage(); - builder.m_info.message = builder.m_stream.str(); - - infoMessages.push_back( builder.m_info ); - } - } - virtual ~AssertionStats(); - -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - AssertionStats( AssertionStats const& ) = default; - AssertionStats( AssertionStats && ) = default; - AssertionStats& operator = ( AssertionStats const& ) = default; - AssertionStats& operator = ( AssertionStats && ) = default; -# endif - - AssertionResult assertionResult; - std::vector infoMessages; - Totals totals; - }; - - struct SectionStats { - SectionStats( SectionInfo const& _sectionInfo, - Counts const& _assertions, - double _durationInSeconds, - bool _missingAssertions ) - : sectionInfo( _sectionInfo ), - assertions( _assertions ), - durationInSeconds( _durationInSeconds ), - missingAssertions( _missingAssertions ) - {} - virtual ~SectionStats(); -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - SectionStats( SectionStats const& ) = default; - SectionStats( SectionStats && ) = default; - SectionStats& operator = ( SectionStats const& ) = default; - SectionStats& operator = ( SectionStats && ) = default; -# endif - - SectionInfo sectionInfo; - Counts assertions; - double durationInSeconds; - bool missingAssertions; - }; - - struct TestCaseStats { - TestCaseStats( TestCaseInfo const& _testInfo, - Totals const& _totals, - std::string const& _stdOut, - std::string const& _stdErr, - bool _aborting ) - : testInfo( _testInfo ), - totals( _totals ), - stdOut( _stdOut ), - stdErr( _stdErr ), - aborting( _aborting ) - {} - virtual ~TestCaseStats(); - -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - TestCaseStats( TestCaseStats const& ) = default; - TestCaseStats( TestCaseStats && ) = default; - TestCaseStats& operator = ( TestCaseStats const& ) = default; - TestCaseStats& operator = ( TestCaseStats && ) = default; -# endif - - TestCaseInfo testInfo; - Totals totals; - std::string stdOut; - std::string stdErr; - bool aborting; - }; - - struct TestGroupStats { - TestGroupStats( GroupInfo const& _groupInfo, - Totals const& _totals, - bool _aborting ) - : groupInfo( _groupInfo ), - totals( _totals ), - aborting( _aborting ) - {} - TestGroupStats( GroupInfo const& _groupInfo ) - : groupInfo( _groupInfo ), - aborting( false ) - {} - virtual ~TestGroupStats(); - -# ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS - TestGroupStats( TestGroupStats const& ) = default; - TestGroupStats( TestGroupStats && ) = default; - TestGroupStats& operator = ( TestGroupStats const& ) = default; - TestGroupStats& operator = ( TestGroupStats && ) = default; -# endif - - GroupInfo groupInfo; - Totals totals; - bool aborting; - }; - - struct TestRunStats { - TestRunStats( TestRunInfo const& _runInfo, - Totals const& _totals, - bool _aborting ) - : runInfo( _runInfo ), - totals( _totals ), - aborting( _aborting ) - {} - virtual ~TestRunStats(); - -# ifndef CATCH_CONFIG_CPP11_GENERATED_METHODS - TestRunStats( TestRunStats const& _other ) - : runInfo( _other.runInfo ), - totals( _other.totals ), - aborting( _other.aborting ) - {} -# else - TestRunStats( TestRunStats const& ) = default; - TestRunStats( TestRunStats && ) = default; - TestRunStats& operator = ( TestRunStats const& ) = default; - TestRunStats& operator = ( TestRunStats && ) = default; -# endif - - TestRunInfo runInfo; - Totals totals; - bool aborting; - }; - - class MultipleReporters; - - struct IStreamingReporter : IShared { - virtual ~IStreamingReporter(); - - // Implementing class must also provide the following static method: - // static std::string getDescription(); - - virtual ReporterPreferences getPreferences() const = 0; - - virtual void noMatchingTestCases( std::string const& spec ) = 0; - - virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0; - virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0; - - virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0; - virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0; - - virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0; - - // The return value indicates if the messages buffer should be cleared: - virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0; - - virtual void sectionEnded( SectionStats const& sectionStats ) = 0; - virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0; - virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0; - virtual void testRunEnded( TestRunStats const& testRunStats ) = 0; - - virtual void skipTest( TestCaseInfo const& testInfo ) = 0; - - virtual MultipleReporters* tryAsMulti() { return CATCH_NULL; } - }; - - struct IReporterFactory : IShared { - virtual ~IReporterFactory(); - virtual IStreamingReporter* create( ReporterConfig const& config ) const = 0; - virtual std::string getDescription() const = 0; - }; - - struct IReporterRegistry { - typedef std::map > FactoryMap; - typedef std::vector > Listeners; - - virtual ~IReporterRegistry(); - virtual IStreamingReporter* create( std::string const& name, Ptr const& config ) const = 0; - virtual FactoryMap const& getFactories() const = 0; - virtual Listeners const& getListeners() const = 0; - }; - - Ptr addReporter( Ptr const& existingReporter, Ptr const& additionalReporter ); - -} - -#include -#include - -namespace Catch { - - inline std::size_t listTests( Config const& config ) { - - TestSpec testSpec = config.testSpec(); - if( config.testSpec().hasFilters() ) - Catch::cout() << "Matching test cases:\n"; - else { - Catch::cout() << "All available test cases:\n"; - testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec(); - } - - std::size_t matchedTests = 0; - TextAttributes nameAttr, descAttr, tagsAttr; - nameAttr.setInitialIndent( 2 ).setIndent( 4 ); - descAttr.setIndent( 4 ); - tagsAttr.setIndent( 6 ); - - std::vector matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); - for( std::vector::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); - it != itEnd; - ++it ) { - matchedTests++; - TestCaseInfo const& testCaseInfo = it->getTestCaseInfo(); - Colour::Code colour = testCaseInfo.isHidden() - ? Colour::SecondaryText - : Colour::None; - Colour colourGuard( colour ); - - Catch::cout() << Text( testCaseInfo.name, nameAttr ) << std::endl; - if( config.listExtraInfo() ) { - Catch::cout() << " " << testCaseInfo.lineInfo << std::endl; - std::string description = testCaseInfo.description; - if( description.empty() ) - description = "(NO DESCRIPTION)"; - Catch::cout() << Text( description, descAttr ) << std::endl; - } - if( !testCaseInfo.tags.empty() ) - Catch::cout() << Text( testCaseInfo.tagsAsString, tagsAttr ) << std::endl; - } - - if( !config.testSpec().hasFilters() ) - Catch::cout() << pluralise( matchedTests, "test case" ) << '\n' << std::endl; - else - Catch::cout() << pluralise( matchedTests, "matching test case" ) << '\n' << std::endl; - return matchedTests; - } - - inline std::size_t listTestsNamesOnly( Config const& config ) { - TestSpec testSpec = config.testSpec(); - if( !config.testSpec().hasFilters() ) - testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec(); - std::size_t matchedTests = 0; - std::vector matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); - for( std::vector::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); - it != itEnd; - ++it ) { - matchedTests++; - TestCaseInfo const& testCaseInfo = it->getTestCaseInfo(); - if( startsWith( testCaseInfo.name, '#' ) ) - Catch::cout() << '"' << testCaseInfo.name << '"'; - else - Catch::cout() << testCaseInfo.name; - if ( config.listExtraInfo() ) - Catch::cout() << "\t@" << testCaseInfo.lineInfo; - Catch::cout() << std::endl; - } - return matchedTests; - } - - struct TagInfo { - TagInfo() : count ( 0 ) {} - void add( std::string const& spelling ) { - ++count; - spellings.insert( spelling ); - } - std::string all() const { - std::string out; - for( std::set::const_iterator it = spellings.begin(), itEnd = spellings.end(); - it != itEnd; - ++it ) - out += "[" + *it + "]"; - return out; - } - std::set spellings; - std::size_t count; - }; - - inline std::size_t listTags( Config const& config ) { - TestSpec testSpec = config.testSpec(); - if( config.testSpec().hasFilters() ) - Catch::cout() << "Tags for matching test cases:\n"; - else { - Catch::cout() << "All available tags:\n"; - testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec(); - } - - std::map tagCounts; - - std::vector matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); - for( std::vector::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); - it != itEnd; - ++it ) { - for( std::set::const_iterator tagIt = it->getTestCaseInfo().tags.begin(), - tagItEnd = it->getTestCaseInfo().tags.end(); - tagIt != tagItEnd; - ++tagIt ) { - std::string tagName = *tagIt; - std::string lcaseTagName = toLower( tagName ); - std::map::iterator countIt = tagCounts.find( lcaseTagName ); - if( countIt == tagCounts.end() ) - countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first; - countIt->second.add( tagName ); - } - } - - for( std::map::const_iterator countIt = tagCounts.begin(), - countItEnd = tagCounts.end(); - countIt != countItEnd; - ++countIt ) { - std::ostringstream oss; - oss << " " << std::setw(2) << countIt->second.count << " "; - Text wrapper( countIt->second.all(), TextAttributes() - .setInitialIndent( 0 ) - .setIndent( oss.str().size() ) - .setWidth( CATCH_CONFIG_CONSOLE_WIDTH-10 ) ); - Catch::cout() << oss.str() << wrapper << '\n'; - } - Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl; - return tagCounts.size(); - } - - inline std::size_t listReporters( Config const& /*config*/ ) { - Catch::cout() << "Available reporters:\n"; - IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories(); - IReporterRegistry::FactoryMap::const_iterator itBegin = factories.begin(), itEnd = factories.end(), it; - std::size_t maxNameLen = 0; - for(it = itBegin; it != itEnd; ++it ) - maxNameLen = (std::max)( maxNameLen, it->first.size() ); - - for(it = itBegin; it != itEnd; ++it ) { - Text wrapper( it->second->getDescription(), TextAttributes() - .setInitialIndent( 0 ) - .setIndent( 7+maxNameLen ) - .setWidth( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 ) ); - Catch::cout() << " " - << it->first - << ':' - << std::string( maxNameLen - it->first.size() + 2, ' ' ) - << wrapper << '\n'; - } - Catch::cout() << std::endl; - return factories.size(); - } - - inline Option list( Config const& config ) { - Option listedCount; - if( config.listTests() || ( config.listExtraInfo() && !config.listTestNamesOnly() ) ) - listedCount = listedCount.valueOr(0) + listTests( config ); - if( config.listTestNamesOnly() ) - listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config ); - if( config.listTags() ) - listedCount = listedCount.valueOr(0) + listTags( config ); - if( config.listReporters() ) - listedCount = listedCount.valueOr(0) + listReporters( config ); - return listedCount; - } - -} // end namespace Catch - -// #included from: internal/catch_run_context.hpp -#define TWOBLUECUBES_CATCH_RUNNER_IMPL_HPP_INCLUDED - -// #included from: catch_test_case_tracker.hpp -#define TWOBLUECUBES_CATCH_TEST_CASE_TRACKER_HPP_INCLUDED - -#include -#include -#include -#include -#include - -CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS - -namespace Catch { -namespace TestCaseTracking { - - struct NameAndLocation { - std::string name; - SourceLineInfo location; - - NameAndLocation( std::string const& _name, SourceLineInfo const& _location ) - : name( _name ), - location( _location ) - {} - }; - - struct ITracker : SharedImpl<> { - virtual ~ITracker(); - - // static queries - virtual NameAndLocation const& nameAndLocation() const = 0; - - // dynamic queries - virtual bool isComplete() const = 0; // Successfully completed or failed - virtual bool isSuccessfullyCompleted() const = 0; - virtual bool isOpen() const = 0; // Started but not complete - virtual bool hasChildren() const = 0; - - virtual ITracker& parent() = 0; - - // actions - virtual void close() = 0; // Successfully complete - virtual void fail() = 0; - virtual void markAsNeedingAnotherRun() = 0; - - virtual void addChild( Ptr const& child ) = 0; - virtual ITracker* findChild( NameAndLocation const& nameAndLocation ) = 0; - virtual void openChild() = 0; - - // Debug/ checking - virtual bool isSectionTracker() const = 0; - virtual bool isIndexTracker() const = 0; - }; - - class TrackerContext { - - enum RunState { - NotStarted, - Executing, - CompletedCycle - }; - - Ptr m_rootTracker; - ITracker* m_currentTracker; - RunState m_runState; - - public: - - static TrackerContext& instance() { - static TrackerContext s_instance; - return s_instance; - } - - TrackerContext() - : m_currentTracker( CATCH_NULL ), - m_runState( NotStarted ) - {} - - ITracker& startRun(); - - void endRun() { - m_rootTracker.reset(); - m_currentTracker = CATCH_NULL; - m_runState = NotStarted; - } - - void startCycle() { - m_currentTracker = m_rootTracker.get(); - m_runState = Executing; - } - void completeCycle() { - m_runState = CompletedCycle; - } - - bool completedCycle() const { - return m_runState == CompletedCycle; - } - ITracker& currentTracker() { - return *m_currentTracker; - } - void setCurrentTracker( ITracker* tracker ) { - m_currentTracker = tracker; - } - }; - - class TrackerBase : public ITracker { - protected: - enum CycleState { - NotStarted, - Executing, - ExecutingChildren, - NeedsAnotherRun, - CompletedSuccessfully, - Failed - }; - class TrackerHasName { - NameAndLocation m_nameAndLocation; - public: - TrackerHasName( NameAndLocation const& nameAndLocation ) : m_nameAndLocation( nameAndLocation ) {} - bool operator ()( Ptr const& tracker ) { - return - tracker->nameAndLocation().name == m_nameAndLocation.name && - tracker->nameAndLocation().location == m_nameAndLocation.location; - } - }; - typedef std::vector > Children; - NameAndLocation m_nameAndLocation; - TrackerContext& m_ctx; - ITracker* m_parent; - Children m_children; - CycleState m_runState; - public: - TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ) - : m_nameAndLocation( nameAndLocation ), - m_ctx( ctx ), - m_parent( parent ), - m_runState( NotStarted ) - {} - virtual ~TrackerBase(); - - virtual NameAndLocation const& nameAndLocation() const CATCH_OVERRIDE { - return m_nameAndLocation; - } - virtual bool isComplete() const CATCH_OVERRIDE { - return m_runState == CompletedSuccessfully || m_runState == Failed; - } - virtual bool isSuccessfullyCompleted() const CATCH_OVERRIDE { - return m_runState == CompletedSuccessfully; - } - virtual bool isOpen() const CATCH_OVERRIDE { - return m_runState != NotStarted && !isComplete(); - } - virtual bool hasChildren() const CATCH_OVERRIDE { - return !m_children.empty(); - } - - virtual void addChild( Ptr const& child ) CATCH_OVERRIDE { - m_children.push_back( child ); - } - - virtual ITracker* findChild( NameAndLocation const& nameAndLocation ) CATCH_OVERRIDE { - Children::const_iterator it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( nameAndLocation ) ); - return( it != m_children.end() ) - ? it->get() - : CATCH_NULL; - } - virtual ITracker& parent() CATCH_OVERRIDE { - assert( m_parent ); // Should always be non-null except for root - return *m_parent; - } - - virtual void openChild() CATCH_OVERRIDE { - if( m_runState != ExecutingChildren ) { - m_runState = ExecutingChildren; - if( m_parent ) - m_parent->openChild(); - } - } - - virtual bool isSectionTracker() const CATCH_OVERRIDE { return false; } - virtual bool isIndexTracker() const CATCH_OVERRIDE { return false; } - - void open() { - m_runState = Executing; - moveToThis(); - if( m_parent ) - m_parent->openChild(); - } - - virtual void close() CATCH_OVERRIDE { - - // Close any still open children (e.g. generators) - while( &m_ctx.currentTracker() != this ) - m_ctx.currentTracker().close(); - - switch( m_runState ) { - case NotStarted: - case CompletedSuccessfully: - case Failed: - throw std::logic_error( "Illogical state" ); - - case NeedsAnotherRun: - break;; - - case Executing: - m_runState = CompletedSuccessfully; - break; - case ExecutingChildren: - if( m_children.empty() || m_children.back()->isComplete() ) - m_runState = CompletedSuccessfully; - break; - - default: - throw std::logic_error( "Unexpected state" ); - } - moveToParent(); - m_ctx.completeCycle(); - } - virtual void fail() CATCH_OVERRIDE { - m_runState = Failed; - if( m_parent ) - m_parent->markAsNeedingAnotherRun(); - moveToParent(); - m_ctx.completeCycle(); - } - virtual void markAsNeedingAnotherRun() CATCH_OVERRIDE { - m_runState = NeedsAnotherRun; - } - private: - void moveToParent() { - assert( m_parent ); - m_ctx.setCurrentTracker( m_parent ); - } - void moveToThis() { - m_ctx.setCurrentTracker( this ); - } - }; - - class SectionTracker : public TrackerBase { - std::vector m_filters; - public: - SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ) - : TrackerBase( nameAndLocation, ctx, parent ) - { - if( parent ) { - while( !parent->isSectionTracker() ) - parent = &parent->parent(); - - SectionTracker& parentSection = static_cast( *parent ); - addNextFilters( parentSection.m_filters ); - } - } - virtual ~SectionTracker(); - - virtual bool isSectionTracker() const CATCH_OVERRIDE { return true; } - - static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) { - SectionTracker* section = CATCH_NULL; - - ITracker& currentTracker = ctx.currentTracker(); - if( ITracker* childTracker = currentTracker.findChild( nameAndLocation ) ) { - assert( childTracker ); - assert( childTracker->isSectionTracker() ); - section = static_cast( childTracker ); - } - else { - section = new SectionTracker( nameAndLocation, ctx, ¤tTracker ); - currentTracker.addChild( section ); - } - if( !ctx.completedCycle() ) - section->tryOpen(); - return *section; - } - - void tryOpen() { - if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) ) - open(); - } - - void addInitialFilters( std::vector const& filters ) { - if( !filters.empty() ) { - m_filters.push_back(""); // Root - should never be consulted - m_filters.push_back(""); // Test Case - not a section filter - m_filters.insert( m_filters.end(), filters.begin(), filters.end() ); - } - } - void addNextFilters( std::vector const& filters ) { - if( filters.size() > 1 ) - m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() ); - } - }; - - class IndexTracker : public TrackerBase { - int m_size; - int m_index; - public: - IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size ) - : TrackerBase( nameAndLocation, ctx, parent ), - m_size( size ), - m_index( -1 ) - {} - virtual ~IndexTracker(); - - virtual bool isIndexTracker() const CATCH_OVERRIDE { return true; } - - static IndexTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size ) { - IndexTracker* tracker = CATCH_NULL; - - ITracker& currentTracker = ctx.currentTracker(); - if( ITracker* childTracker = currentTracker.findChild( nameAndLocation ) ) { - assert( childTracker ); - assert( childTracker->isIndexTracker() ); - tracker = static_cast( childTracker ); - } - else { - tracker = new IndexTracker( nameAndLocation, ctx, ¤tTracker, size ); - currentTracker.addChild( tracker ); - } - - if( !ctx.completedCycle() && !tracker->isComplete() ) { - if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun ) - tracker->moveNext(); - tracker->open(); - } - - return *tracker; - } - - int index() const { return m_index; } - - void moveNext() { - m_index++; - m_children.clear(); - } - - virtual void close() CATCH_OVERRIDE { - TrackerBase::close(); - if( m_runState == CompletedSuccessfully && m_index < m_size-1 ) - m_runState = Executing; - } - }; - - inline ITracker& TrackerContext::startRun() { - m_rootTracker = new SectionTracker( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, CATCH_NULL ); - m_currentTracker = CATCH_NULL; - m_runState = Executing; - return *m_rootTracker; - } - -} // namespace TestCaseTracking - -using TestCaseTracking::ITracker; -using TestCaseTracking::TrackerContext; -using TestCaseTracking::SectionTracker; -using TestCaseTracking::IndexTracker; - -} // namespace Catch - -CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS - -// #included from: catch_fatal_condition.hpp -#define TWOBLUECUBES_CATCH_FATAL_CONDITION_H_INCLUDED - -namespace Catch { - - // Report the error condition - inline void reportFatal( std::string const& message ) { - IContext& context = Catch::getCurrentContext(); - IResultCapture* resultCapture = context.getResultCapture(); - resultCapture->handleFatalErrorCondition( message ); - } - -} // namespace Catch - -#if defined ( CATCH_PLATFORM_WINDOWS ) ///////////////////////////////////////// -// #included from: catch_windows_h_proxy.h - -#define TWOBLUECUBES_CATCH_WINDOWS_H_PROXY_H_INCLUDED - -#ifdef CATCH_DEFINES_NOMINMAX -# define NOMINMAX -#endif -#ifdef CATCH_DEFINES_WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN -#endif - -#ifdef __AFXDLL -#include -#else -#include -#endif - -#ifdef CATCH_DEFINES_NOMINMAX -# undef NOMINMAX -#endif -#ifdef CATCH_DEFINES_WIN32_LEAN_AND_MEAN -# undef WIN32_LEAN_AND_MEAN -#endif - - -# if !defined ( CATCH_CONFIG_WINDOWS_SEH ) - -namespace Catch { - struct FatalConditionHandler { - void reset() {} - }; -} - -# else // CATCH_CONFIG_WINDOWS_SEH is defined - -namespace Catch { - - struct SignalDefs { DWORD id; const char* name; }; - extern SignalDefs signalDefs[]; - // There is no 1-1 mapping between signals and windows exceptions. - // Windows can easily distinguish between SO and SigSegV, - // but SigInt, SigTerm, etc are handled differently. - SignalDefs signalDefs[] = { - { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" }, - { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" }, - { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" }, - { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" }, - }; - - struct FatalConditionHandler { - - static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) { - for (int i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) { - if (ExceptionInfo->ExceptionRecord->ExceptionCode == signalDefs[i].id) { - reportFatal(signalDefs[i].name); - } - } - // If its not an exception we care about, pass it along. - // This stops us from eating debugger breaks etc. - return EXCEPTION_CONTINUE_SEARCH; - } - - FatalConditionHandler() { - isSet = true; - // 32k seems enough for Catch to handle stack overflow, - // but the value was found experimentally, so there is no strong guarantee - guaranteeSize = 32 * 1024; - exceptionHandlerHandle = CATCH_NULL; - // Register as first handler in current chain - exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException); - // Pass in guarantee size to be filled - SetThreadStackGuarantee(&guaranteeSize); - } - - static void reset() { - if (isSet) { - // Unregister handler and restore the old guarantee - RemoveVectoredExceptionHandler(exceptionHandlerHandle); - SetThreadStackGuarantee(&guaranteeSize); - exceptionHandlerHandle = CATCH_NULL; - isSet = false; - } - } - - ~FatalConditionHandler() { - reset(); - } - private: - static bool isSet; - static ULONG guaranteeSize; - static PVOID exceptionHandlerHandle; - }; - - bool FatalConditionHandler::isSet = false; - ULONG FatalConditionHandler::guaranteeSize = 0; - PVOID FatalConditionHandler::exceptionHandlerHandle = CATCH_NULL; - -} // namespace Catch - -# endif // CATCH_CONFIG_WINDOWS_SEH - -#else // Not Windows - assumed to be POSIX compatible ////////////////////////// - -# if !defined(CATCH_CONFIG_POSIX_SIGNALS) - -namespace Catch { - struct FatalConditionHandler { - void reset() {} - }; -} - -# else // CATCH_CONFIG_POSIX_SIGNALS is defined - -#include - -namespace Catch { - - struct SignalDefs { - int id; - const char* name; - }; - extern SignalDefs signalDefs[]; - SignalDefs signalDefs[] = { - { SIGINT, "SIGINT - Terminal interrupt signal" }, - { SIGILL, "SIGILL - Illegal instruction signal" }, - { SIGFPE, "SIGFPE - Floating point error signal" }, - { SIGSEGV, "SIGSEGV - Segmentation violation signal" }, - { SIGTERM, "SIGTERM - Termination request signal" }, - { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" } - }; - - struct FatalConditionHandler { - - static bool isSet; - static struct sigaction oldSigActions [sizeof(signalDefs)/sizeof(SignalDefs)]; - static stack_t oldSigStack; - static char altStackMem[SIGSTKSZ]; - - static void handleSignal( int sig ) { - std::string name = ""; - for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) { - SignalDefs &def = signalDefs[i]; - if (sig == def.id) { - name = def.name; - break; - } - } - reset(); - reportFatal(name); - raise( sig ); - } - - FatalConditionHandler() { - isSet = true; - stack_t sigStack; - sigStack.ss_sp = altStackMem; - sigStack.ss_size = SIGSTKSZ; - sigStack.ss_flags = 0; - sigaltstack(&sigStack, &oldSigStack); - struct sigaction sa = { 0 }; - - sa.sa_handler = handleSignal; - sa.sa_flags = SA_ONSTACK; - for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) { - sigaction(signalDefs[i].id, &sa, &oldSigActions[i]); - } - } - - ~FatalConditionHandler() { - reset(); - } - static void reset() { - if( isSet ) { - // Set signals back to previous values -- hopefully nobody overwrote them in the meantime - for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) { - sigaction(signalDefs[i].id, &oldSigActions[i], CATCH_NULL); - } - // Return the old stack - sigaltstack(&oldSigStack, CATCH_NULL); - isSet = false; - } - } - }; - - bool FatalConditionHandler::isSet = false; - struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {}; - stack_t FatalConditionHandler::oldSigStack = {}; - char FatalConditionHandler::altStackMem[SIGSTKSZ] = {}; - -} // namespace Catch - -# endif // CATCH_CONFIG_POSIX_SIGNALS - -#endif // not Windows - -#include -#include - -namespace Catch { - - class StreamRedirect { - - public: - StreamRedirect( std::ostream& stream, std::string& targetString ) - : m_stream( stream ), - m_prevBuf( stream.rdbuf() ), - m_targetString( targetString ) - { - stream.rdbuf( m_oss.rdbuf() ); - } - - ~StreamRedirect() { - m_targetString += m_oss.str(); - m_stream.rdbuf( m_prevBuf ); - } - - private: - std::ostream& m_stream; - std::streambuf* m_prevBuf; - std::ostringstream m_oss; - std::string& m_targetString; - }; - - /////////////////////////////////////////////////////////////////////////// - - class RunContext : public IResultCapture, public IRunner { - - RunContext( RunContext const& ); - void operator =( RunContext const& ); - - public: - - explicit RunContext( Ptr const& _config, Ptr const& reporter ) - : m_runInfo( _config->name() ), - m_context( getCurrentMutableContext() ), - m_activeTestCase( CATCH_NULL ), - m_config( _config ), - m_reporter( reporter ), - m_shouldReportUnexpected ( true ) - { - m_context.setRunner( this ); - m_context.setConfig( m_config ); - m_context.setResultCapture( this ); - m_reporter->testRunStarting( m_runInfo ); - } - - virtual ~RunContext() { - m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, aborting() ) ); - } - - void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount ) { - m_reporter->testGroupStarting( GroupInfo( testSpec, groupIndex, groupsCount ) ); - } - void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount ) { - m_reporter->testGroupEnded( TestGroupStats( GroupInfo( testSpec, groupIndex, groupsCount ), totals, aborting() ) ); - } - - Totals runTest( TestCase const& testCase ) { - Totals prevTotals = m_totals; - - std::string redirectedCout; - std::string redirectedCerr; - - TestCaseInfo testInfo = testCase.getTestCaseInfo(); - - m_reporter->testCaseStarting( testInfo ); - - m_activeTestCase = &testCase; - - do { - ITracker& rootTracker = m_trackerContext.startRun(); - assert( rootTracker.isSectionTracker() ); - static_cast( rootTracker ).addInitialFilters( m_config->getSectionsToRun() ); - do { - m_trackerContext.startCycle(); - m_testCaseTracker = &SectionTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( testInfo.name, testInfo.lineInfo ) ); - runCurrentTest( redirectedCout, redirectedCerr ); - } - while( !m_testCaseTracker->isSuccessfullyCompleted() && !aborting() ); - } - // !TBD: deprecated - this will be replaced by indexed trackers - while( getCurrentContext().advanceGeneratorsForCurrentTest() && !aborting() ); - - Totals deltaTotals = m_totals.delta( prevTotals ); - if( testInfo.expectedToFail() && deltaTotals.testCases.passed > 0 ) { - deltaTotals.assertions.failed++; - deltaTotals.testCases.passed--; - deltaTotals.testCases.failed++; - } - m_totals.testCases += deltaTotals.testCases; - m_reporter->testCaseEnded( TestCaseStats( testInfo, - deltaTotals, - redirectedCout, - redirectedCerr, - aborting() ) ); - - m_activeTestCase = CATCH_NULL; - m_testCaseTracker = CATCH_NULL; - - return deltaTotals; - } - - Ptr config() const { - return m_config; - } - - private: // IResultCapture - - virtual void assertionEnded( AssertionResult const& result ) { - if( result.getResultType() == ResultWas::Ok ) { - m_totals.assertions.passed++; - } - else if( !result.isOk() ) { - m_totals.assertions.failed++; - } - - // We have no use for the return value (whether messages should be cleared), because messages were made scoped - // and should be let to clear themselves out. - static_cast(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals))); - - // Reset working state - m_lastAssertionInfo = AssertionInfo( "", m_lastAssertionInfo.lineInfo, "{Unknown expression after the reported line}" , m_lastAssertionInfo.resultDisposition ); - m_lastResult = result; - } - - virtual bool sectionStarted ( - SectionInfo const& sectionInfo, - Counts& assertions - ) - { - ITracker& sectionTracker = SectionTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( sectionInfo.name, sectionInfo.lineInfo ) ); - if( !sectionTracker.isOpen() ) - return false; - m_activeSections.push_back( §ionTracker ); - - m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo; - - m_reporter->sectionStarting( sectionInfo ); - - assertions = m_totals.assertions; - - return true; - } - bool testForMissingAssertions( Counts& assertions ) { - if( assertions.total() != 0 ) - return false; - if( !m_config->warnAboutMissingAssertions() ) - return false; - if( m_trackerContext.currentTracker().hasChildren() ) - return false; - m_totals.assertions.failed++; - assertions.failed++; - return true; - } - - virtual void sectionEnded( SectionEndInfo const& endInfo ) { - Counts assertions = m_totals.assertions - endInfo.prevAssertions; - bool missingAssertions = testForMissingAssertions( assertions ); - - if( !m_activeSections.empty() ) { - m_activeSections.back()->close(); - m_activeSections.pop_back(); - } - - m_reporter->sectionEnded( SectionStats( endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions ) ); - m_messages.clear(); - } - - virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) { - if( m_unfinishedSections.empty() ) - m_activeSections.back()->fail(); - else - m_activeSections.back()->close(); - m_activeSections.pop_back(); - - m_unfinishedSections.push_back( endInfo ); - } - - virtual void pushScopedMessage( MessageInfo const& message ) { - m_messages.push_back( message ); - } - - virtual void popScopedMessage( MessageInfo const& message ) { - m_messages.erase( std::remove( m_messages.begin(), m_messages.end(), message ), m_messages.end() ); - } - - virtual std::string getCurrentTestName() const { - return m_activeTestCase - ? m_activeTestCase->getTestCaseInfo().name - : std::string(); - } - - virtual const AssertionResult* getLastResult() const { - return &m_lastResult; - } - - virtual void exceptionEarlyReported() { - m_shouldReportUnexpected = false; - } - - virtual void handleFatalErrorCondition( std::string const& message ) { - // Don't rebuild the result -- the stringification itself can cause more fatal errors - // Instead, fake a result data. - AssertionResultData tempResult; - tempResult.resultType = ResultWas::FatalErrorCondition; - tempResult.message = message; - AssertionResult result(m_lastAssertionInfo, tempResult); - - getResultCapture().assertionEnded(result); - - handleUnfinishedSections(); - - // Recreate section for test case (as we will lose the one that was in scope) - TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); - SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description ); - - Counts assertions; - assertions.failed = 1; - SectionStats testCaseSectionStats( testCaseSection, assertions, 0, false ); - m_reporter->sectionEnded( testCaseSectionStats ); - - TestCaseInfo testInfo = m_activeTestCase->getTestCaseInfo(); - - Totals deltaTotals; - deltaTotals.testCases.failed = 1; - m_reporter->testCaseEnded( TestCaseStats( testInfo, - deltaTotals, - std::string(), - std::string(), - false ) ); - m_totals.testCases.failed++; - testGroupEnded( std::string(), m_totals, 1, 1 ); - m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, false ) ); - } - - public: - // !TBD We need to do this another way! - bool aborting() const { - return m_totals.assertions.failed == static_cast( m_config->abortAfter() ); - } - - private: - - void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr ) { - TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); - SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description ); - m_reporter->sectionStarting( testCaseSection ); - Counts prevAssertions = m_totals.assertions; - double duration = 0; - m_shouldReportUnexpected = true; - try { - m_lastAssertionInfo = AssertionInfo( "TEST_CASE", testCaseInfo.lineInfo, "", ResultDisposition::Normal ); - - seedRng( *m_config ); - - Timer timer; - timer.start(); - if( m_reporter->getPreferences().shouldRedirectStdOut ) { - StreamRedirect coutRedir( Catch::cout(), redirectedCout ); - StreamRedirect cerrRedir( Catch::cerr(), redirectedCerr ); - invokeActiveTestCase(); - } - else { - invokeActiveTestCase(); - } - duration = timer.getElapsedSeconds(); - } - catch( TestFailureException& ) { - // This just means the test was aborted due to failure - } - catch(...) { - // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions - // are reported without translation at the point of origin. - if (m_shouldReportUnexpected) { - makeUnexpectedResultBuilder().useActiveException(); - } - } - m_testCaseTracker->close(); - handleUnfinishedSections(); - m_messages.clear(); - - Counts assertions = m_totals.assertions - prevAssertions; - bool missingAssertions = testForMissingAssertions( assertions ); - - if( testCaseInfo.okToFail() ) { - std::swap( assertions.failedButOk, assertions.failed ); - m_totals.assertions.failed -= assertions.failedButOk; - m_totals.assertions.failedButOk += assertions.failedButOk; - } - - SectionStats testCaseSectionStats( testCaseSection, assertions, duration, missingAssertions ); - m_reporter->sectionEnded( testCaseSectionStats ); - } - - void invokeActiveTestCase() { - FatalConditionHandler fatalConditionHandler; // Handle signals - m_activeTestCase->invoke(); - fatalConditionHandler.reset(); - } - - private: - - ResultBuilder makeUnexpectedResultBuilder() const { - return ResultBuilder( m_lastAssertionInfo.macroName, - m_lastAssertionInfo.lineInfo, - m_lastAssertionInfo.capturedExpression, - m_lastAssertionInfo.resultDisposition ); - } - - void handleUnfinishedSections() { - // If sections ended prematurely due to an exception we stored their - // infos here so we can tear them down outside the unwind process. - for( std::vector::const_reverse_iterator it = m_unfinishedSections.rbegin(), - itEnd = m_unfinishedSections.rend(); - it != itEnd; - ++it ) - sectionEnded( *it ); - m_unfinishedSections.clear(); - } - - TestRunInfo m_runInfo; - IMutableContext& m_context; - TestCase const* m_activeTestCase; - ITracker* m_testCaseTracker; - ITracker* m_currentSectionTracker; - AssertionResult m_lastResult; - - Ptr m_config; - Totals m_totals; - Ptr m_reporter; - std::vector m_messages; - AssertionInfo m_lastAssertionInfo; - std::vector m_unfinishedSections; - std::vector m_activeSections; - TrackerContext m_trackerContext; - bool m_shouldReportUnexpected; - }; - - IResultCapture& getResultCapture() { - if( IResultCapture* capture = getCurrentContext().getResultCapture() ) - return *capture; - else - throw std::logic_error( "No result capture instance" ); - } - -} // end namespace Catch - -// #included from: internal/catch_version.h -#define TWOBLUECUBES_CATCH_VERSION_H_INCLUDED - -namespace Catch { - - // Versioning information - struct Version { - Version( unsigned int _majorVersion, - unsigned int _minorVersion, - unsigned int _patchNumber, - char const * const _branchName, - unsigned int _buildNumber ); - - unsigned int const majorVersion; - unsigned int const minorVersion; - unsigned int const patchNumber; - - // buildNumber is only used if branchName is not null - char const * const branchName; - unsigned int const buildNumber; - - friend std::ostream& operator << ( std::ostream& os, Version const& version ); - - private: - void operator=( Version const& ); - }; - - inline Version libraryVersion(); -} - -#include -#include -#include - -namespace Catch { - - Ptr createReporter( std::string const& reporterName, Ptr const& config ) { - Ptr reporter = getRegistryHub().getReporterRegistry().create( reporterName, config.get() ); - if( !reporter ) { - std::ostringstream oss; - oss << "No reporter registered with name: '" << reporterName << "'"; - throw std::domain_error( oss.str() ); - } - return reporter; - } - - Ptr makeReporter( Ptr const& config ) { - std::vector reporters = config->getReporterNames(); - if( reporters.empty() ) - reporters.push_back( "console" ); - - Ptr reporter; - for( std::vector::const_iterator it = reporters.begin(), itEnd = reporters.end(); - it != itEnd; - ++it ) - reporter = addReporter( reporter, createReporter( *it, config ) ); - return reporter; - } - Ptr addListeners( Ptr const& config, Ptr reporters ) { - IReporterRegistry::Listeners listeners = getRegistryHub().getReporterRegistry().getListeners(); - for( IReporterRegistry::Listeners::const_iterator it = listeners.begin(), itEnd = listeners.end(); - it != itEnd; - ++it ) - reporters = addReporter(reporters, (*it)->create( ReporterConfig( config ) ) ); - return reporters; - } - - Totals runTests( Ptr const& config ) { - - Ptr iconfig = config.get(); - - Ptr reporter = makeReporter( config ); - reporter = addListeners( iconfig, reporter ); - - RunContext context( iconfig, reporter ); - - Totals totals; - - context.testGroupStarting( config->name(), 1, 1 ); - - TestSpec testSpec = config->testSpec(); - if( !testSpec.hasFilters() ) - testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "~[.]" ).testSpec(); // All not hidden tests - - std::vector const& allTestCases = getAllTestCasesSorted( *iconfig ); - for( std::vector::const_iterator it = allTestCases.begin(), itEnd = allTestCases.end(); - it != itEnd; - ++it ) { - if( !context.aborting() && matchTest( *it, testSpec, *iconfig ) ) - totals += context.runTest( *it ); - else - reporter->skipTest( *it ); - } - - context.testGroupEnded( iconfig->name(), totals, 1, 1 ); - return totals; - } - - void applyFilenamesAsTags( IConfig const& config ) { - std::vector const& tests = getAllTestCasesSorted( config ); - for(std::size_t i = 0; i < tests.size(); ++i ) { - TestCase& test = const_cast( tests[i] ); - std::set tags = test.tags; - - std::string filename = test.lineInfo.file; - std::string::size_type lastSlash = filename.find_last_of( "\\/" ); - if( lastSlash != std::string::npos ) - filename = filename.substr( lastSlash+1 ); - - std::string::size_type lastDot = filename.find_last_of( "." ); - if( lastDot != std::string::npos ) - filename = filename.substr( 0, lastDot ); - - tags.insert( "#" + filename ); - setTags( test, tags ); - } - } - - class Session : NonCopyable { - static bool alreadyInstantiated; - - public: - - struct OnUnusedOptions { enum DoWhat { Ignore, Fail }; }; - - Session() - : m_cli( makeCommandLineParser() ) { - if( alreadyInstantiated ) { - std::string msg = "Only one instance of Catch::Session can ever be used"; - Catch::cerr() << msg << std::endl; - throw std::logic_error( msg ); - } - alreadyInstantiated = true; - } - ~Session() { - Catch::cleanUp(); - } - - void showHelp( std::string const& processName ) { - Catch::cout() << "\nCatch v" << libraryVersion() << "\n"; - - m_cli.usage( Catch::cout(), processName ); - Catch::cout() << "For more detail usage please see the project docs\n" << std::endl; - } - - int applyCommandLine( int argc, char const* const* const argv, OnUnusedOptions::DoWhat unusedOptionBehaviour = OnUnusedOptions::Fail ) { - try { - m_cli.setThrowOnUnrecognisedTokens( unusedOptionBehaviour == OnUnusedOptions::Fail ); - m_unusedTokens = m_cli.parseInto( Clara::argsToVector( argc, argv ), m_configData ); - if( m_configData.showHelp ) - showHelp( m_configData.processName ); - m_config.reset(); - } - catch( std::exception& ex ) { - { - Colour colourGuard( Colour::Red ); - Catch::cerr() - << "\nError(s) in input:\n" - << Text( ex.what(), TextAttributes().setIndent(2) ) - << "\n\n"; - } - m_cli.usage( Catch::cout(), m_configData.processName ); - return (std::numeric_limits::max)(); - } - return 0; - } - - void useConfigData( ConfigData const& _configData ) { - m_configData = _configData; - m_config.reset(); - } - - int run( int argc, char const* const* const argv ) { - - int returnCode = applyCommandLine( argc, argv ); - if( returnCode == 0 ) - returnCode = run(); - return returnCode; - } - - #if defined(WIN32) && defined(UNICODE) - int run( int argc, wchar_t const* const* const argv ) { - - char **utf8Argv = new char *[ argc ]; - - for ( int i = 0; i < argc; ++i ) { - int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL ); - - utf8Argv[ i ] = new char[ bufSize ]; - - WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL ); - } - - int returnCode = applyCommandLine( argc, utf8Argv ); - if( returnCode == 0 ) - returnCode = run(); - - for ( int i = 0; i < argc; ++i ) - delete [] utf8Argv[ i ]; - - delete [] utf8Argv; - - return returnCode; - } - #endif - - int run() { - if( m_configData.showHelp ) - return 0; - - try - { - config(); // Force config to be constructed - - seedRng( *m_config ); - - if( m_configData.filenamesAsTags ) - applyFilenamesAsTags( *m_config ); - - // Handle list request - if( Option listed = list( config() ) ) - return static_cast( *listed ); - - return static_cast( runTests( m_config ).assertions.failed ); - } - catch( std::exception& ex ) { - Catch::cerr() << ex.what() << std::endl; - return (std::numeric_limits::max)(); - } - } - - Clara::CommandLine const& cli() const { - return m_cli; - } - std::vector const& unusedTokens() const { - return m_unusedTokens; - } - ConfigData& configData() { - return m_configData; - } - Config& config() { - if( !m_config ) - m_config = new Config( m_configData ); - return *m_config; - } - private: - Clara::CommandLine m_cli; - std::vector m_unusedTokens; - ConfigData m_configData; - Ptr m_config; - }; - - bool Session::alreadyInstantiated = false; - -} // end namespace Catch - -// #included from: catch_registry_hub.hpp -#define TWOBLUECUBES_CATCH_REGISTRY_HUB_HPP_INCLUDED - -// #included from: catch_test_case_registry_impl.hpp -#define TWOBLUECUBES_CATCH_TEST_CASE_REGISTRY_IMPL_HPP_INCLUDED - -#include -#include -#include -#include - -namespace Catch { - - struct RandomNumberGenerator { - typedef std::ptrdiff_t result_type; - - result_type operator()( result_type n ) const { return std::rand() % n; } - -#ifdef CATCH_CONFIG_CPP11_SHUFFLE - static constexpr result_type min() { return 0; } - static constexpr result_type max() { return 1000000; } - result_type operator()() const { return std::rand() % max(); } -#endif - template - static void shuffle( V& vector ) { - RandomNumberGenerator rng; -#ifdef CATCH_CONFIG_CPP11_SHUFFLE - std::shuffle( vector.begin(), vector.end(), rng ); -#else - std::random_shuffle( vector.begin(), vector.end(), rng ); -#endif - } - }; - - inline std::vector sortTests( IConfig const& config, std::vector const& unsortedTestCases ) { - - std::vector sorted = unsortedTestCases; - - switch( config.runOrder() ) { - case RunTests::InLexicographicalOrder: - std::sort( sorted.begin(), sorted.end() ); - break; - case RunTests::InRandomOrder: - { - seedRng( config ); - RandomNumberGenerator::shuffle( sorted ); - } - break; - case RunTests::InDeclarationOrder: - // already in declaration order - break; - } - return sorted; - } - bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) { - return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() ); - } - - void enforceNoDuplicateTestCases( std::vector const& functions ) { - std::set seenFunctions; - for( std::vector::const_iterator it = functions.begin(), itEnd = functions.end(); - it != itEnd; - ++it ) { - std::pair::const_iterator, bool> prev = seenFunctions.insert( *it ); - if( !prev.second ) { - std::ostringstream ss; - - ss << Colour( Colour::Red ) - << "error: TEST_CASE( \"" << it->name << "\" ) already defined.\n" - << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << '\n' - << "\tRedefined at " << it->getTestCaseInfo().lineInfo << std::endl; - - throw std::runtime_error(ss.str()); - } - } - } - - std::vector filterTests( std::vector const& testCases, TestSpec const& testSpec, IConfig const& config ) { - std::vector filtered; - filtered.reserve( testCases.size() ); - for( std::vector::const_iterator it = testCases.begin(), itEnd = testCases.end(); - it != itEnd; - ++it ) - if( matchTest( *it, testSpec, config ) ) - filtered.push_back( *it ); - return filtered; - } - std::vector const& getAllTestCasesSorted( IConfig const& config ) { - return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config ); - } - - class TestRegistry : public ITestCaseRegistry { - public: - TestRegistry() - : m_currentSortOrder( RunTests::InDeclarationOrder ), - m_unnamedCount( 0 ) - {} - virtual ~TestRegistry(); - - virtual void registerTest( TestCase const& testCase ) { - std::string name = testCase.getTestCaseInfo().name; - if( name.empty() ) { - std::ostringstream oss; - oss << "Anonymous test case " << ++m_unnamedCount; - return registerTest( testCase.withName( oss.str() ) ); - } - m_functions.push_back( testCase ); - } - - virtual std::vector const& getAllTests() const { - return m_functions; - } - virtual std::vector const& getAllTestsSorted( IConfig const& config ) const { - if( m_sortedFunctions.empty() ) - enforceNoDuplicateTestCases( m_functions ); - - if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) { - m_sortedFunctions = sortTests( config, m_functions ); - m_currentSortOrder = config.runOrder(); - } - return m_sortedFunctions; - } - - private: - std::vector m_functions; - mutable RunTests::InWhatOrder m_currentSortOrder; - mutable std::vector m_sortedFunctions; - size_t m_unnamedCount; - std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised - }; - - /////////////////////////////////////////////////////////////////////////// - - class FreeFunctionTestCase : public SharedImpl { - public: - - FreeFunctionTestCase( TestFunction fun ) : m_fun( fun ) {} - - virtual void invoke() const { - m_fun(); - } - - private: - virtual ~FreeFunctionTestCase(); - - TestFunction m_fun; - }; - - inline std::string extractClassName( std::string const& classOrQualifiedMethodName ) { - std::string className = classOrQualifiedMethodName; - if( startsWith( className, '&' ) ) - { - std::size_t lastColons = className.rfind( "::" ); - std::size_t penultimateColons = className.rfind( "::", lastColons-1 ); - if( penultimateColons == std::string::npos ) - penultimateColons = 1; - className = className.substr( penultimateColons, lastColons-penultimateColons ); - } - return className; - } - - void registerTestCase - ( ITestCase* testCase, - char const* classOrQualifiedMethodName, - NameAndDesc const& nameAndDesc, - SourceLineInfo const& lineInfo ) { - - getMutableRegistryHub().registerTest - ( makeTestCase - ( testCase, - extractClassName( classOrQualifiedMethodName ), - nameAndDesc.name, - nameAndDesc.description, - lineInfo ) ); - } - void registerTestCaseFunction - ( TestFunction function, - SourceLineInfo const& lineInfo, - NameAndDesc const& nameAndDesc ) { - registerTestCase( new FreeFunctionTestCase( function ), "", nameAndDesc, lineInfo ); - } - - /////////////////////////////////////////////////////////////////////////// - - AutoReg::AutoReg - ( TestFunction function, - SourceLineInfo const& lineInfo, - NameAndDesc const& nameAndDesc ) { - registerTestCaseFunction( function, lineInfo, nameAndDesc ); - } - - AutoReg::~AutoReg() {} - -} // end namespace Catch - -// #included from: catch_reporter_registry.hpp -#define TWOBLUECUBES_CATCH_REPORTER_REGISTRY_HPP_INCLUDED - -#include - -namespace Catch { - - class ReporterRegistry : public IReporterRegistry { - - public: - - virtual ~ReporterRegistry() CATCH_OVERRIDE {} - - virtual IStreamingReporter* create( std::string const& name, Ptr const& config ) const CATCH_OVERRIDE { - FactoryMap::const_iterator it = m_factories.find( name ); - if( it == m_factories.end() ) - return CATCH_NULL; - return it->second->create( ReporterConfig( config ) ); - } - - void registerReporter( std::string const& name, Ptr const& factory ) { - m_factories.insert( std::make_pair( name, factory ) ); - } - void registerListener( Ptr const& factory ) { - m_listeners.push_back( factory ); - } - - virtual FactoryMap const& getFactories() const CATCH_OVERRIDE { - return m_factories; - } - virtual Listeners const& getListeners() const CATCH_OVERRIDE { - return m_listeners; - } - - private: - FactoryMap m_factories; - Listeners m_listeners; - }; -} - -// #included from: catch_exception_translator_registry.hpp -#define TWOBLUECUBES_CATCH_EXCEPTION_TRANSLATOR_REGISTRY_HPP_INCLUDED - -#ifdef __OBJC__ -#import "Foundation/Foundation.h" -#endif - -namespace Catch { - - class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry { - public: - ~ExceptionTranslatorRegistry() { - deleteAll( m_translators ); - } - - virtual void registerTranslator( const IExceptionTranslator* translator ) { - m_translators.push_back( translator ); - } - - virtual std::string translateActiveException() const { - try { -#ifdef __OBJC__ - // In Objective-C try objective-c exceptions first - @try { - return tryTranslators(); - } - @catch (NSException *exception) { - return Catch::toString( [exception description] ); - } -#else - return tryTranslators(); -#endif - } - catch( TestFailureException& ) { - throw; - } - catch( std::exception& ex ) { - return ex.what(); - } - catch( std::string& msg ) { - return msg; - } - catch( const char* msg ) { - return msg; - } - catch(...) { - return "Unknown exception"; - } - } - - std::string tryTranslators() const { - if( m_translators.empty() ) - throw; - else - return m_translators[0]->translate( m_translators.begin()+1, m_translators.end() ); - } - - private: - std::vector m_translators; - }; -} - -// #included from: catch_tag_alias_registry.h -#define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_H_INCLUDED - -#include - -namespace Catch { - - class TagAliasRegistry : public ITagAliasRegistry { - public: - virtual ~TagAliasRegistry(); - virtual Option find( std::string const& alias ) const; - virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const; - void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ); - - private: - std::map m_registry; - }; - -} // end namespace Catch - -namespace Catch { - - namespace { - - class RegistryHub : public IRegistryHub, public IMutableRegistryHub { - - RegistryHub( RegistryHub const& ); - void operator=( RegistryHub const& ); - - public: // IRegistryHub - RegistryHub() { - } - virtual IReporterRegistry const& getReporterRegistry() const CATCH_OVERRIDE { - return m_reporterRegistry; - } - virtual ITestCaseRegistry const& getTestCaseRegistry() const CATCH_OVERRIDE { - return m_testCaseRegistry; - } - virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() CATCH_OVERRIDE { - return m_exceptionTranslatorRegistry; - } - virtual ITagAliasRegistry const& getTagAliasRegistry() const CATCH_OVERRIDE { - return m_tagAliasRegistry; - } - - public: // IMutableRegistryHub - virtual void registerReporter( std::string const& name, Ptr const& factory ) CATCH_OVERRIDE { - m_reporterRegistry.registerReporter( name, factory ); - } - virtual void registerListener( Ptr const& factory ) CATCH_OVERRIDE { - m_reporterRegistry.registerListener( factory ); - } - virtual void registerTest( TestCase const& testInfo ) CATCH_OVERRIDE { - m_testCaseRegistry.registerTest( testInfo ); - } - virtual void registerTranslator( const IExceptionTranslator* translator ) CATCH_OVERRIDE { - m_exceptionTranslatorRegistry.registerTranslator( translator ); - } - virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) CATCH_OVERRIDE { - m_tagAliasRegistry.add( alias, tag, lineInfo ); - } - - private: - TestRegistry m_testCaseRegistry; - ReporterRegistry m_reporterRegistry; - ExceptionTranslatorRegistry m_exceptionTranslatorRegistry; - TagAliasRegistry m_tagAliasRegistry; - }; - - // Single, global, instance - inline RegistryHub*& getTheRegistryHub() { - static RegistryHub* theRegistryHub = CATCH_NULL; - if( !theRegistryHub ) - theRegistryHub = new RegistryHub(); - return theRegistryHub; - } - } - - IRegistryHub& getRegistryHub() { - return *getTheRegistryHub(); - } - IMutableRegistryHub& getMutableRegistryHub() { - return *getTheRegistryHub(); - } - void cleanUp() { - delete getTheRegistryHub(); - getTheRegistryHub() = CATCH_NULL; - cleanUpContext(); - } - std::string translateActiveException() { - return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException(); - } - -} // end namespace Catch - -// #included from: catch_notimplemented_exception.hpp -#define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_HPP_INCLUDED - -#include - -namespace Catch { - - NotImplementedException::NotImplementedException( SourceLineInfo const& lineInfo ) - : m_lineInfo( lineInfo ) { - std::ostringstream oss; - oss << lineInfo << ": function "; - oss << "not implemented"; - m_what = oss.str(); - } - - const char* NotImplementedException::what() const CATCH_NOEXCEPT { - return m_what.c_str(); - } - -} // end namespace Catch - -// #included from: catch_context_impl.hpp -#define TWOBLUECUBES_CATCH_CONTEXT_IMPL_HPP_INCLUDED - -// #included from: catch_stream.hpp -#define TWOBLUECUBES_CATCH_STREAM_HPP_INCLUDED - -#include -#include -#include - -namespace Catch { - - template - class StreamBufImpl : public StreamBufBase { - char data[bufferSize]; - WriterF m_writer; - - public: - StreamBufImpl() { - setp( data, data + sizeof(data) ); - } - - ~StreamBufImpl() CATCH_NOEXCEPT { - sync(); - } - - private: - int overflow( int c ) { - sync(); - - if( c != EOF ) { - if( pbase() == epptr() ) - m_writer( std::string( 1, static_cast( c ) ) ); - else - sputc( static_cast( c ) ); - } - return 0; - } - - int sync() { - if( pbase() != pptr() ) { - m_writer( std::string( pbase(), static_cast( pptr() - pbase() ) ) ); - setp( pbase(), epptr() ); - } - return 0; - } - }; - - /////////////////////////////////////////////////////////////////////////// - - FileStream::FileStream( std::string const& filename ) { - m_ofs.open( filename.c_str() ); - if( m_ofs.fail() ) { - std::ostringstream oss; - oss << "Unable to open file: '" << filename << '\''; - throw std::domain_error( oss.str() ); - } - } - - std::ostream& FileStream::stream() const { - return m_ofs; - } - - struct OutputDebugWriter { - - void operator()( std::string const&str ) { - writeToDebugConsole( str ); - } - }; - - DebugOutStream::DebugOutStream() - : m_streamBuf( new StreamBufImpl() ), - m_os( m_streamBuf.get() ) - {} - - std::ostream& DebugOutStream::stream() const { - return m_os; - } - - // Store the streambuf from cout up-front because - // cout may get redirected when running tests - CoutStream::CoutStream() - : m_os( Catch::cout().rdbuf() ) - {} - - std::ostream& CoutStream::stream() const { - return m_os; - } - -#ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions - std::ostream& cout() { - return std::cout; - } - std::ostream& cerr() { - return std::cerr; - } -#endif -} - -namespace Catch { - - class Context : public IMutableContext { - - Context() : m_config( CATCH_NULL ), m_runner( CATCH_NULL ), m_resultCapture( CATCH_NULL ) {} - Context( Context const& ); - void operator=( Context const& ); - - public: - virtual ~Context() { - deleteAllValues( m_generatorsByTestName ); - } - - public: // IContext - virtual IResultCapture* getResultCapture() { - return m_resultCapture; - } - virtual IRunner* getRunner() { - return m_runner; - } - virtual size_t getGeneratorIndex( std::string const& fileInfo, size_t totalSize ) { - return getGeneratorsForCurrentTest() - .getGeneratorInfo( fileInfo, totalSize ) - .getCurrentIndex(); - } - virtual bool advanceGeneratorsForCurrentTest() { - IGeneratorsForTest* generators = findGeneratorsForCurrentTest(); - return generators && generators->moveNext(); - } - - virtual Ptr getConfig() const { - return m_config; - } - - public: // IMutableContext - virtual void setResultCapture( IResultCapture* resultCapture ) { - m_resultCapture = resultCapture; - } - virtual void setRunner( IRunner* runner ) { - m_runner = runner; - } - virtual void setConfig( Ptr const& config ) { - m_config = config; - } - - friend IMutableContext& getCurrentMutableContext(); - - private: - IGeneratorsForTest* findGeneratorsForCurrentTest() { - std::string testName = getResultCapture()->getCurrentTestName(); - - std::map::const_iterator it = - m_generatorsByTestName.find( testName ); - return it != m_generatorsByTestName.end() - ? it->second - : CATCH_NULL; - } - - IGeneratorsForTest& getGeneratorsForCurrentTest() { - IGeneratorsForTest* generators = findGeneratorsForCurrentTest(); - if( !generators ) { - std::string testName = getResultCapture()->getCurrentTestName(); - generators = createGeneratorsForTest(); - m_generatorsByTestName.insert( std::make_pair( testName, generators ) ); - } - return *generators; - } - - private: - Ptr m_config; - IRunner* m_runner; - IResultCapture* m_resultCapture; - std::map m_generatorsByTestName; - }; - - namespace { - Context* currentContext = CATCH_NULL; - } - IMutableContext& getCurrentMutableContext() { - if( !currentContext ) - currentContext = new Context(); - return *currentContext; - } - IContext& getCurrentContext() { - return getCurrentMutableContext(); - } - - void cleanUpContext() { - delete currentContext; - currentContext = CATCH_NULL; - } -} - -// #included from: catch_console_colour_impl.hpp -#define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_IMPL_HPP_INCLUDED - -// #included from: catch_errno_guard.hpp -#define TWOBLUECUBES_CATCH_ERRNO_GUARD_HPP_INCLUDED - -#include - -namespace Catch { - - class ErrnoGuard { - public: - ErrnoGuard():m_oldErrno(errno){} - ~ErrnoGuard() { errno = m_oldErrno; } - private: - int m_oldErrno; - }; - -} - -namespace Catch { - namespace { - - struct IColourImpl { - virtual ~IColourImpl() {} - virtual void use( Colour::Code _colourCode ) = 0; - }; - - struct NoColourImpl : IColourImpl { - void use( Colour::Code ) {} - - static IColourImpl* instance() { - static NoColourImpl s_instance; - return &s_instance; - } - }; - - } // anon namespace -} // namespace Catch - -#if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI ) -# ifdef CATCH_PLATFORM_WINDOWS -# define CATCH_CONFIG_COLOUR_WINDOWS -# else -# define CATCH_CONFIG_COLOUR_ANSI -# endif -#endif - -#if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) ///////////////////////////////////////// - -namespace Catch { -namespace { - - class Win32ColourImpl : public IColourImpl { - public: - Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) ) - { - CONSOLE_SCREEN_BUFFER_INFO csbiInfo; - GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo ); - originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY ); - originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY ); - } - - virtual void use( Colour::Code _colourCode ) { - switch( _colourCode ) { - case Colour::None: return setTextAttribute( originalForegroundAttributes ); - case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); - case Colour::Red: return setTextAttribute( FOREGROUND_RED ); - case Colour::Green: return setTextAttribute( FOREGROUND_GREEN ); - case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE ); - case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN ); - case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN ); - case Colour::Grey: return setTextAttribute( 0 ); - - case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY ); - case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED ); - case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN ); - case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); - - case Colour::Bright: throw std::logic_error( "not a colour" ); - } - } - - private: - void setTextAttribute( WORD _textAttribute ) { - SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes ); - } - HANDLE stdoutHandle; - WORD originalForegroundAttributes; - WORD originalBackgroundAttributes; - }; - - IColourImpl* platformColourInstance() { - static Win32ColourImpl s_instance; - - Ptr config = getCurrentContext().getConfig(); - UseColour::YesOrNo colourMode = config - ? config->useColour() - : UseColour::Auto; - if( colourMode == UseColour::Auto ) - colourMode = !isDebuggerActive() - ? UseColour::Yes - : UseColour::No; - return colourMode == UseColour::Yes - ? &s_instance - : NoColourImpl::instance(); - } - -} // end anon namespace -} // end namespace Catch - -#elif defined( CATCH_CONFIG_COLOUR_ANSI ) ////////////////////////////////////// - -#include - -namespace Catch { -namespace { - - // use POSIX/ ANSI console terminal codes - // Thanks to Adam Strzelecki for original contribution - // (http://github.com/nanoant) - // https://github.com/philsquared/Catch/pull/131 - class PosixColourImpl : public IColourImpl { - public: - virtual void use( Colour::Code _colourCode ) { - switch( _colourCode ) { - case Colour::None: - case Colour::White: return setColour( "[0m" ); - case Colour::Red: return setColour( "[0;31m" ); - case Colour::Green: return setColour( "[0;32m" ); - case Colour::Blue: return setColour( "[0;34m" ); - case Colour::Cyan: return setColour( "[0;36m" ); - case Colour::Yellow: return setColour( "[0;33m" ); - case Colour::Grey: return setColour( "[1;30m" ); - - case Colour::LightGrey: return setColour( "[0;37m" ); - case Colour::BrightRed: return setColour( "[1;31m" ); - case Colour::BrightGreen: return setColour( "[1;32m" ); - case Colour::BrightWhite: return setColour( "[1;37m" ); - - case Colour::Bright: throw std::logic_error( "not a colour" ); - } - } - static IColourImpl* instance() { - static PosixColourImpl s_instance; - return &s_instance; - } - - private: - void setColour( const char* _escapeCode ) { - Catch::cout() << '\033' << _escapeCode; - } - }; - - IColourImpl* platformColourInstance() { - ErrnoGuard guard; - Ptr config = getCurrentContext().getConfig(); - UseColour::YesOrNo colourMode = config - ? config->useColour() - : UseColour::Auto; - if( colourMode == UseColour::Auto ) - colourMode = (!isDebuggerActive() && isatty(STDOUT_FILENO) ) - ? UseColour::Yes - : UseColour::No; - return colourMode == UseColour::Yes - ? PosixColourImpl::instance() - : NoColourImpl::instance(); - } - -} // end anon namespace -} // end namespace Catch - -#else // not Windows or ANSI /////////////////////////////////////////////// - -namespace Catch { - - static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); } - -} // end namespace Catch - -#endif // Windows/ ANSI/ None - -namespace Catch { - - Colour::Colour( Code _colourCode ) : m_moved( false ) { use( _colourCode ); } - Colour::Colour( Colour const& _other ) : m_moved( false ) { const_cast( _other ).m_moved = true; } - Colour::~Colour(){ if( !m_moved ) use( None ); } - - void Colour::use( Code _colourCode ) { - static IColourImpl* impl = platformColourInstance(); - impl->use( _colourCode ); - } - -} // end namespace Catch - -// #included from: catch_generators_impl.hpp -#define TWOBLUECUBES_CATCH_GENERATORS_IMPL_HPP_INCLUDED - -#include -#include -#include - -namespace Catch { - - struct GeneratorInfo : IGeneratorInfo { - - GeneratorInfo( std::size_t size ) - : m_size( size ), - m_currentIndex( 0 ) - {} - - bool moveNext() { - if( ++m_currentIndex == m_size ) { - m_currentIndex = 0; - return false; - } - return true; - } - - std::size_t getCurrentIndex() const { - return m_currentIndex; - } - - std::size_t m_size; - std::size_t m_currentIndex; - }; - - /////////////////////////////////////////////////////////////////////////// - - class GeneratorsForTest : public IGeneratorsForTest { - - public: - ~GeneratorsForTest() { - deleteAll( m_generatorsInOrder ); - } - - IGeneratorInfo& getGeneratorInfo( std::string const& fileInfo, std::size_t size ) { - std::map::const_iterator it = m_generatorsByName.find( fileInfo ); - if( it == m_generatorsByName.end() ) { - IGeneratorInfo* info = new GeneratorInfo( size ); - m_generatorsByName.insert( std::make_pair( fileInfo, info ) ); - m_generatorsInOrder.push_back( info ); - return *info; - } - return *it->second; - } - - bool moveNext() { - std::vector::const_iterator it = m_generatorsInOrder.begin(); - std::vector::const_iterator itEnd = m_generatorsInOrder.end(); - for(; it != itEnd; ++it ) { - if( (*it)->moveNext() ) - return true; - } - return false; - } - - private: - std::map m_generatorsByName; - std::vector m_generatorsInOrder; - }; - - IGeneratorsForTest* createGeneratorsForTest() - { - return new GeneratorsForTest(); - } - -} // end namespace Catch - -// #included from: catch_assertionresult.hpp -#define TWOBLUECUBES_CATCH_ASSERTIONRESULT_HPP_INCLUDED - -namespace Catch { - - AssertionInfo::AssertionInfo( char const * _macroName, - SourceLineInfo const& _lineInfo, - char const * _capturedExpression, - ResultDisposition::Flags _resultDisposition, - char const * _secondArg) - : macroName( _macroName ), - lineInfo( _lineInfo ), - capturedExpression( _capturedExpression ), - resultDisposition( _resultDisposition ), - secondArg( _secondArg ) - {} - - AssertionResult::AssertionResult() {} - - AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data ) - : m_info( info ), - m_resultData( data ) - {} - - AssertionResult::~AssertionResult() {} - - // Result was a success - bool AssertionResult::succeeded() const { - return Catch::isOk( m_resultData.resultType ); - } - - // Result was a success, or failure is suppressed - bool AssertionResult::isOk() const { - return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition ); - } - - ResultWas::OfType AssertionResult::getResultType() const { - return m_resultData.resultType; - } - - bool AssertionResult::hasExpression() const { - return m_info.capturedExpression[0] != 0; - } - - bool AssertionResult::hasMessage() const { - return !m_resultData.message.empty(); - } - - std::string capturedExpressionWithSecondArgument( char const * capturedExpression, char const * secondArg ) { - return (secondArg[0] == 0 || secondArg[0] == '"' && secondArg[1] == '"') - ? capturedExpression - : std::string(capturedExpression) + ", " + secondArg; - } - - std::string AssertionResult::getExpression() const { - if( isFalseTest( m_info.resultDisposition ) ) - return '!' + capturedExpressionWithSecondArgument(m_info.capturedExpression, m_info.secondArg); - else - return capturedExpressionWithSecondArgument(m_info.capturedExpression, m_info.secondArg); - } - std::string AssertionResult::getExpressionInMacro() const { - if( m_info.macroName[0] == 0 ) - return capturedExpressionWithSecondArgument(m_info.capturedExpression, m_info.secondArg); - else - return std::string(m_info.macroName) + "( " + capturedExpressionWithSecondArgument(m_info.capturedExpression, m_info.secondArg) + " )"; - } - - bool AssertionResult::hasExpandedExpression() const { - return hasExpression() && getExpandedExpression() != getExpression(); - } - - std::string AssertionResult::getExpandedExpression() const { - return m_resultData.reconstructExpression(); - } - - std::string AssertionResult::getMessage() const { - return m_resultData.message; - } - SourceLineInfo AssertionResult::getSourceInfo() const { - return m_info.lineInfo; - } - - std::string AssertionResult::getTestMacroName() const { - return m_info.macroName; - } - - void AssertionResult::discardDecomposedExpression() const { - m_resultData.decomposedExpression = CATCH_NULL; - } - - void AssertionResult::expandDecomposedExpression() const { - m_resultData.reconstructExpression(); - } - -} // end namespace Catch - -// #included from: catch_test_case_info.hpp -#define TWOBLUECUBES_CATCH_TEST_CASE_INFO_HPP_INCLUDED - -#include - -namespace Catch { - - inline TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) { - if( startsWith( tag, '.' ) || - tag == "hide" || - tag == "!hide" ) - return TestCaseInfo::IsHidden; - else if( tag == "!throws" ) - return TestCaseInfo::Throws; - else if( tag == "!shouldfail" ) - return TestCaseInfo::ShouldFail; - else if( tag == "!mayfail" ) - return TestCaseInfo::MayFail; - else if( tag == "!nonportable" ) - return TestCaseInfo::NonPortable; - else - return TestCaseInfo::None; - } - inline bool isReservedTag( std::string const& tag ) { - return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( tag[0] ); - } - inline void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) { - if( isReservedTag( tag ) ) { - std::ostringstream ss; - ss << Colour(Colour::Red) - << "Tag name [" << tag << "] not allowed.\n" - << "Tag names starting with non alpha-numeric characters are reserved\n" - << Colour(Colour::FileName) - << _lineInfo << '\n'; - throw std::runtime_error(ss.str()); - } - } - - TestCase makeTestCase( ITestCase* _testCase, - std::string const& _className, - std::string const& _name, - std::string const& _descOrTags, - SourceLineInfo const& _lineInfo ) - { - bool isHidden( startsWith( _name, "./" ) ); // Legacy support - - // Parse out tags - std::set tags; - std::string desc, tag; - bool inTag = false; - for( std::size_t i = 0; i < _descOrTags.size(); ++i ) { - char c = _descOrTags[i]; - if( !inTag ) { - if( c == '[' ) - inTag = true; - else - desc += c; - } - else { - if( c == ']' ) { - TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag ); - if( prop == TestCaseInfo::IsHidden ) - isHidden = true; - else if( prop == TestCaseInfo::None ) - enforceNotReservedTag( tag, _lineInfo ); - - tags.insert( tag ); - tag.clear(); - inTag = false; - } - else - tag += c; - } - } - if( isHidden ) { - tags.insert( "hide" ); - tags.insert( "." ); - } - - TestCaseInfo info( _name, _className, desc, tags, _lineInfo ); - return TestCase( _testCase, info ); - } - - void setTags( TestCaseInfo& testCaseInfo, std::set const& tags ) - { - testCaseInfo.tags = tags; - testCaseInfo.lcaseTags.clear(); - - std::ostringstream oss; - for( std::set::const_iterator it = tags.begin(), itEnd = tags.end(); it != itEnd; ++it ) { - oss << '[' << *it << ']'; - std::string lcaseTag = toLower( *it ); - testCaseInfo.properties = static_cast( testCaseInfo.properties | parseSpecialTag( lcaseTag ) ); - testCaseInfo.lcaseTags.insert( lcaseTag ); - } - testCaseInfo.tagsAsString = oss.str(); - } - - TestCaseInfo::TestCaseInfo( std::string const& _name, - std::string const& _className, - std::string const& _description, - std::set const& _tags, - SourceLineInfo const& _lineInfo ) - : name( _name ), - className( _className ), - description( _description ), - lineInfo( _lineInfo ), - properties( None ) - { - setTags( *this, _tags ); - } - - TestCaseInfo::TestCaseInfo( TestCaseInfo const& other ) - : name( other.name ), - className( other.className ), - description( other.description ), - tags( other.tags ), - lcaseTags( other.lcaseTags ), - tagsAsString( other.tagsAsString ), - lineInfo( other.lineInfo ), - properties( other.properties ) - {} - - bool TestCaseInfo::isHidden() const { - return ( properties & IsHidden ) != 0; - } - bool TestCaseInfo::throws() const { - return ( properties & Throws ) != 0; - } - bool TestCaseInfo::okToFail() const { - return ( properties & (ShouldFail | MayFail ) ) != 0; - } - bool TestCaseInfo::expectedToFail() const { - return ( properties & (ShouldFail ) ) != 0; - } - - TestCase::TestCase( ITestCase* testCase, TestCaseInfo const& info ) : TestCaseInfo( info ), test( testCase ) {} - - TestCase::TestCase( TestCase const& other ) - : TestCaseInfo( other ), - test( other.test ) - {} - - TestCase TestCase::withName( std::string const& _newName ) const { - TestCase other( *this ); - other.name = _newName; - return other; - } - - void TestCase::swap( TestCase& other ) { - test.swap( other.test ); - name.swap( other.name ); - className.swap( other.className ); - description.swap( other.description ); - tags.swap( other.tags ); - lcaseTags.swap( other.lcaseTags ); - tagsAsString.swap( other.tagsAsString ); - std::swap( TestCaseInfo::properties, static_cast( other ).properties ); - std::swap( lineInfo, other.lineInfo ); - } - - void TestCase::invoke() const { - test->invoke(); - } - - bool TestCase::operator == ( TestCase const& other ) const { - return test.get() == other.test.get() && - name == other.name && - className == other.className; - } - - bool TestCase::operator < ( TestCase const& other ) const { - return name < other.name; - } - TestCase& TestCase::operator = ( TestCase const& other ) { - TestCase temp( other ); - swap( temp ); - return *this; - } - - TestCaseInfo const& TestCase::getTestCaseInfo() const - { - return *this; - } - -} // end namespace Catch - -// #included from: catch_version.hpp -#define TWOBLUECUBES_CATCH_VERSION_HPP_INCLUDED - -namespace Catch { - - Version::Version - ( unsigned int _majorVersion, - unsigned int _minorVersion, - unsigned int _patchNumber, - char const * const _branchName, - unsigned int _buildNumber ) - : majorVersion( _majorVersion ), - minorVersion( _minorVersion ), - patchNumber( _patchNumber ), - branchName( _branchName ), - buildNumber( _buildNumber ) - {} - - std::ostream& operator << ( std::ostream& os, Version const& version ) { - os << version.majorVersion << '.' - << version.minorVersion << '.' - << version.patchNumber; - // branchName is never null -> 0th char is \0 if it is empty - if (version.branchName[0]) { - os << '-' << version.branchName - << '.' << version.buildNumber; - } - return os; - } - - inline Version libraryVersion() { - static Version version( 1, 9, 6, "", 0 ); - return version; - } - -} - -// #included from: catch_message.hpp -#define TWOBLUECUBES_CATCH_MESSAGE_HPP_INCLUDED - -namespace Catch { - - MessageInfo::MessageInfo( std::string const& _macroName, - SourceLineInfo const& _lineInfo, - ResultWas::OfType _type ) - : macroName( _macroName ), - lineInfo( _lineInfo ), - type( _type ), - sequence( ++globalCount ) - {} - - // This may need protecting if threading support is added - unsigned int MessageInfo::globalCount = 0; - - //////////////////////////////////////////////////////////////////////////// - - ScopedMessage::ScopedMessage( MessageBuilder const& builder ) - : m_info( builder.m_info ) - { - m_info.message = builder.m_stream.str(); - getResultCapture().pushScopedMessage( m_info ); - } - ScopedMessage::ScopedMessage( ScopedMessage const& other ) - : m_info( other.m_info ) - {} - - ScopedMessage::~ScopedMessage() { - if ( !std::uncaught_exception() ){ - getResultCapture().popScopedMessage(m_info); - } - } - -} // end namespace Catch - -// #included from: catch_legacy_reporter_adapter.hpp -#define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_HPP_INCLUDED - -// #included from: catch_legacy_reporter_adapter.h -#define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_H_INCLUDED - -namespace Catch -{ - // Deprecated - struct IReporter : IShared { - virtual ~IReporter(); - - virtual bool shouldRedirectStdout() const = 0; - - virtual void StartTesting() = 0; - virtual void EndTesting( Totals const& totals ) = 0; - virtual void StartGroup( std::string const& groupName ) = 0; - virtual void EndGroup( std::string const& groupName, Totals const& totals ) = 0; - virtual void StartTestCase( TestCaseInfo const& testInfo ) = 0; - virtual void EndTestCase( TestCaseInfo const& testInfo, Totals const& totals, std::string const& stdOut, std::string const& stdErr ) = 0; - virtual void StartSection( std::string const& sectionName, std::string const& description ) = 0; - virtual void EndSection( std::string const& sectionName, Counts const& assertions ) = 0; - virtual void NoAssertionsInSection( std::string const& sectionName ) = 0; - virtual void NoAssertionsInTestCase( std::string const& testName ) = 0; - virtual void Aborted() = 0; - virtual void Result( AssertionResult const& result ) = 0; - }; - - class LegacyReporterAdapter : public SharedImpl - { - public: - LegacyReporterAdapter( Ptr const& legacyReporter ); - virtual ~LegacyReporterAdapter(); - - virtual ReporterPreferences getPreferences() const; - virtual void noMatchingTestCases( std::string const& ); - virtual void testRunStarting( TestRunInfo const& ); - virtual void testGroupStarting( GroupInfo const& groupInfo ); - virtual void testCaseStarting( TestCaseInfo const& testInfo ); - virtual void sectionStarting( SectionInfo const& sectionInfo ); - virtual void assertionStarting( AssertionInfo const& ); - virtual bool assertionEnded( AssertionStats const& assertionStats ); - virtual void sectionEnded( SectionStats const& sectionStats ); - virtual void testCaseEnded( TestCaseStats const& testCaseStats ); - virtual void testGroupEnded( TestGroupStats const& testGroupStats ); - virtual void testRunEnded( TestRunStats const& testRunStats ); - virtual void skipTest( TestCaseInfo const& ); - - private: - Ptr m_legacyReporter; - }; -} - -namespace Catch -{ - LegacyReporterAdapter::LegacyReporterAdapter( Ptr const& legacyReporter ) - : m_legacyReporter( legacyReporter ) - {} - LegacyReporterAdapter::~LegacyReporterAdapter() {} - - ReporterPreferences LegacyReporterAdapter::getPreferences() const { - ReporterPreferences prefs; - prefs.shouldRedirectStdOut = m_legacyReporter->shouldRedirectStdout(); - return prefs; - } - - void LegacyReporterAdapter::noMatchingTestCases( std::string const& ) {} - void LegacyReporterAdapter::testRunStarting( TestRunInfo const& ) { - m_legacyReporter->StartTesting(); - } - void LegacyReporterAdapter::testGroupStarting( GroupInfo const& groupInfo ) { - m_legacyReporter->StartGroup( groupInfo.name ); - } - void LegacyReporterAdapter::testCaseStarting( TestCaseInfo const& testInfo ) { - m_legacyReporter->StartTestCase( testInfo ); - } - void LegacyReporterAdapter::sectionStarting( SectionInfo const& sectionInfo ) { - m_legacyReporter->StartSection( sectionInfo.name, sectionInfo.description ); - } - void LegacyReporterAdapter::assertionStarting( AssertionInfo const& ) { - // Not on legacy interface - } - - bool LegacyReporterAdapter::assertionEnded( AssertionStats const& assertionStats ) { - if( assertionStats.assertionResult.getResultType() != ResultWas::Ok ) { - for( std::vector::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end(); - it != itEnd; - ++it ) { - if( it->type == ResultWas::Info ) { - ResultBuilder rb( it->macroName.c_str(), it->lineInfo, "", ResultDisposition::Normal ); - rb << it->message; - rb.setResultType( ResultWas::Info ); - AssertionResult result = rb.build(); - m_legacyReporter->Result( result ); - } - } - } - m_legacyReporter->Result( assertionStats.assertionResult ); - return true; - } - void LegacyReporterAdapter::sectionEnded( SectionStats const& sectionStats ) { - if( sectionStats.missingAssertions ) - m_legacyReporter->NoAssertionsInSection( sectionStats.sectionInfo.name ); - m_legacyReporter->EndSection( sectionStats.sectionInfo.name, sectionStats.assertions ); - } - void LegacyReporterAdapter::testCaseEnded( TestCaseStats const& testCaseStats ) { - m_legacyReporter->EndTestCase - ( testCaseStats.testInfo, - testCaseStats.totals, - testCaseStats.stdOut, - testCaseStats.stdErr ); - } - void LegacyReporterAdapter::testGroupEnded( TestGroupStats const& testGroupStats ) { - if( testGroupStats.aborting ) - m_legacyReporter->Aborted(); - m_legacyReporter->EndGroup( testGroupStats.groupInfo.name, testGroupStats.totals ); - } - void LegacyReporterAdapter::testRunEnded( TestRunStats const& testRunStats ) { - m_legacyReporter->EndTesting( testRunStats.totals ); - } - void LegacyReporterAdapter::skipTest( TestCaseInfo const& ) { - } -} - -// #included from: catch_timer.hpp - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wc++11-long-long" -#endif - -#ifdef CATCH_PLATFORM_WINDOWS - -#else - -#include - -#endif - -namespace Catch { - - namespace { -#ifdef CATCH_PLATFORM_WINDOWS - UInt64 getCurrentTicks() { - static UInt64 hz=0, hzo=0; - if (!hz) { - QueryPerformanceFrequency( reinterpret_cast( &hz ) ); - QueryPerformanceCounter( reinterpret_cast( &hzo ) ); - } - UInt64 t; - QueryPerformanceCounter( reinterpret_cast( &t ) ); - return ((t-hzo)*1000000)/hz; - } -#else - UInt64 getCurrentTicks() { - timeval t; - gettimeofday(&t,CATCH_NULL); - return static_cast( t.tv_sec ) * 1000000ull + static_cast( t.tv_usec ); - } -#endif - } - - void Timer::start() { - m_ticks = getCurrentTicks(); - } - unsigned int Timer::getElapsedMicroseconds() const { - return static_cast(getCurrentTicks() - m_ticks); - } - unsigned int Timer::getElapsedMilliseconds() const { - return static_cast(getElapsedMicroseconds()/1000); - } - double Timer::getElapsedSeconds() const { - return getElapsedMicroseconds()/1000000.0; - } - -} // namespace Catch - -#ifdef __clang__ -#pragma clang diagnostic pop -#endif -// #included from: catch_common.hpp -#define TWOBLUECUBES_CATCH_COMMON_HPP_INCLUDED - -#include -#include - -namespace Catch { - - bool startsWith( std::string const& s, std::string const& prefix ) { - return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin()); - } - bool startsWith( std::string const& s, char prefix ) { - return !s.empty() && s[0] == prefix; - } - bool endsWith( std::string const& s, std::string const& suffix ) { - return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin()); - } - bool endsWith( std::string const& s, char suffix ) { - return !s.empty() && s[s.size()-1] == suffix; - } - bool contains( std::string const& s, std::string const& infix ) { - return s.find( infix ) != std::string::npos; - } - char toLowerCh(char c) { - return static_cast( std::tolower( c ) ); - } - void toLowerInPlace( std::string& s ) { - std::transform( s.begin(), s.end(), s.begin(), toLowerCh ); - } - std::string toLower( std::string const& s ) { - std::string lc = s; - toLowerInPlace( lc ); - return lc; - } - std::string trim( std::string const& str ) { - static char const* whitespaceChars = "\n\r\t "; - std::string::size_type start = str.find_first_not_of( whitespaceChars ); - std::string::size_type end = str.find_last_not_of( whitespaceChars ); - - return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string(); - } - - bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) { - bool replaced = false; - std::size_t i = str.find( replaceThis ); - while( i != std::string::npos ) { - replaced = true; - str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() ); - if( i < str.size()-withThis.size() ) - i = str.find( replaceThis, i+withThis.size() ); - else - i = std::string::npos; - } - return replaced; - } - - pluralise::pluralise( std::size_t count, std::string const& label ) - : m_count( count ), - m_label( label ) - {} - - std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) { - os << pluraliser.m_count << ' ' << pluraliser.m_label; - if( pluraliser.m_count != 1 ) - os << 's'; - return os; - } - - SourceLineInfo::SourceLineInfo() : file(""), line( 0 ){} - SourceLineInfo::SourceLineInfo( char const* _file, std::size_t _line ) - : file( _file ), - line( _line ) - {} - bool SourceLineInfo::empty() const { - return file[0] == '\0'; - } - bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const { - return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0); - } - bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const { - return line < other.line || ( line == other.line && (std::strcmp(file, other.file) < 0)); - } - - void seedRng( IConfig const& config ) { - if( config.rngSeed() != 0 ) - std::srand( config.rngSeed() ); - } - unsigned int rngSeed() { - return getCurrentContext().getConfig()->rngSeed(); - } - - std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) { -#ifndef __GNUG__ - os << info.file << '(' << info.line << ')'; -#else - os << info.file << ':' << info.line; -#endif - return os; - } - - void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo ) { - std::ostringstream oss; - oss << locationInfo << ": Internal Catch error: '" << message << '\''; - if( alwaysTrue() ) - throw std::logic_error( oss.str() ); - } -} - -// #included from: catch_section.hpp -#define TWOBLUECUBES_CATCH_SECTION_HPP_INCLUDED - -namespace Catch { - - SectionInfo::SectionInfo - ( SourceLineInfo const& _lineInfo, - std::string const& _name, - std::string const& _description ) - : name( _name ), - description( _description ), - lineInfo( _lineInfo ) - {} - - Section::Section( SectionInfo const& info ) - : m_info( info ), - m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) ) - { - m_timer.start(); - } - -#if defined(_MSC_VER) -#pragma warning(push) -#pragma warning(disable:4996) // std::uncaught_exception is deprecated in C++17 -#endif - Section::~Section() { - if( m_sectionIncluded ) { - SectionEndInfo endInfo( m_info, m_assertions, m_timer.getElapsedSeconds() ); - if( std::uncaught_exception() ) - getResultCapture().sectionEndedEarly( endInfo ); - else - getResultCapture().sectionEnded( endInfo ); - } - } -#if defined(_MSC_VER) -#pragma warning(pop) -#endif - - // This indicates whether the section should be executed or not - Section::operator bool() const { - return m_sectionIncluded; - } - -} // end namespace Catch - -// #included from: catch_debugger.hpp -#define TWOBLUECUBES_CATCH_DEBUGGER_HPP_INCLUDED - -#ifdef CATCH_PLATFORM_MAC - - #include - #include - #include - #include - #include - - namespace Catch{ - - // The following function is taken directly from the following technical note: - // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html - - // Returns true if the current process is being debugged (either - // running under the debugger or has a debugger attached post facto). - bool isDebuggerActive(){ - - int mib[4]; - struct kinfo_proc info; - size_t size; - - // Initialize the flags so that, if sysctl fails for some bizarre - // reason, we get a predictable result. - - info.kp_proc.p_flag = 0; - - // Initialize mib, which tells sysctl the info we want, in this case - // we're looking for information about a specific process ID. - - mib[0] = CTL_KERN; - mib[1] = KERN_PROC; - mib[2] = KERN_PROC_PID; - mib[3] = getpid(); - - // Call sysctl. - - size = sizeof(info); - if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, CATCH_NULL, 0) != 0 ) { - Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl; - return false; - } - - // We're being debugged if the P_TRACED flag is set. - - return ( (info.kp_proc.p_flag & P_TRACED) != 0 ); - } - } // namespace Catch - -#elif defined(CATCH_PLATFORM_LINUX) - #include - #include - - namespace Catch{ - // The standard POSIX way of detecting a debugger is to attempt to - // ptrace() the process, but this needs to be done from a child and not - // this process itself to still allow attaching to this process later - // if wanted, so is rather heavy. Under Linux we have the PID of the - // "debugger" (which doesn't need to be gdb, of course, it could also - // be strace, for example) in /proc/$PID/status, so just get it from - // there instead. - bool isDebuggerActive(){ - // Libstdc++ has a bug, where std::ifstream sets errno to 0 - // This way our users can properly assert over errno values - ErrnoGuard guard; - std::ifstream in("/proc/self/status"); - for( std::string line; std::getline(in, line); ) { - static const int PREFIX_LEN = 11; - if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) { - // We're traced if the PID is not 0 and no other PID starts - // with 0 digit, so it's enough to check for just a single - // character. - return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0'; - } - } - - return false; - } - } // namespace Catch -#elif defined(_MSC_VER) - extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); - namespace Catch { - bool isDebuggerActive() { - return IsDebuggerPresent() != 0; - } - } -#elif defined(__MINGW32__) - extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); - namespace Catch { - bool isDebuggerActive() { - return IsDebuggerPresent() != 0; - } - } -#else - namespace Catch { - inline bool isDebuggerActive() { return false; } - } -#endif // Platform - -#ifdef CATCH_PLATFORM_WINDOWS - - namespace Catch { - void writeToDebugConsole( std::string const& text ) { - ::OutputDebugStringA( text.c_str() ); - } - } -#else - namespace Catch { - void writeToDebugConsole( std::string const& text ) { - // !TBD: Need a version for Mac/ XCode and other IDEs - Catch::cout() << text; - } - } -#endif // Platform - -// #included from: catch_tostring.hpp -#define TWOBLUECUBES_CATCH_TOSTRING_HPP_INCLUDED - -namespace Catch { - -namespace Detail { - - const std::string unprintableString = "{?}"; - - namespace { - const int hexThreshold = 255; - - struct Endianness { - enum Arch { Big, Little }; - - static Arch which() { - union _{ - int asInt; - char asChar[sizeof (int)]; - } u; - - u.asInt = 1; - return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little; - } - }; - } - - std::string rawMemoryToString( const void *object, std::size_t size ) - { - // Reverse order for little endian architectures - int i = 0, end = static_cast( size ), inc = 1; - if( Endianness::which() == Endianness::Little ) { - i = end-1; - end = inc = -1; - } - - unsigned char const *bytes = static_cast(object); - std::ostringstream os; - os << "0x" << std::setfill('0') << std::hex; - for( ; i != end; i += inc ) - os << std::setw(2) << static_cast(bytes[i]); - return os.str(); - } -} - -std::string toString( std::string const& value ) { - std::string s = value; - if( getCurrentContext().getConfig()->showInvisibles() ) { - for(size_t i = 0; i < s.size(); ++i ) { - std::string subs; - switch( s[i] ) { - case '\n': subs = "\\n"; break; - case '\t': subs = "\\t"; break; - default: break; - } - if( !subs.empty() ) { - s = s.substr( 0, i ) + subs + s.substr( i+1 ); - ++i; - } - } - } - return '"' + s + '"'; -} -std::string toString( std::wstring const& value ) { - - std::string s; - s.reserve( value.size() ); - for(size_t i = 0; i < value.size(); ++i ) - s += value[i] <= 0xff ? static_cast( value[i] ) : '?'; - return Catch::toString( s ); -} - -std::string toString( const char* const value ) { - return value ? Catch::toString( std::string( value ) ) : std::string( "{null string}" ); -} - -std::string toString( char* const value ) { - return Catch::toString( static_cast( value ) ); -} - -std::string toString( const wchar_t* const value ) -{ - return value ? Catch::toString( std::wstring(value) ) : std::string( "{null string}" ); -} - -std::string toString( wchar_t* const value ) -{ - return Catch::toString( static_cast( value ) ); -} - -std::string toString( int value ) { - std::ostringstream oss; - oss << value; - if( value > Detail::hexThreshold ) - oss << " (0x" << std::hex << value << ')'; - return oss.str(); -} - -std::string toString( unsigned long value ) { - std::ostringstream oss; - oss << value; - if( value > Detail::hexThreshold ) - oss << " (0x" << std::hex << value << ')'; - return oss.str(); -} - -std::string toString( unsigned int value ) { - return Catch::toString( static_cast( value ) ); -} - -template -std::string fpToString( T value, int precision ) { - std::ostringstream oss; - oss << std::setprecision( precision ) - << std::fixed - << value; - std::string d = oss.str(); - std::size_t i = d.find_last_not_of( '0' ); - if( i != std::string::npos && i != d.size()-1 ) { - if( d[i] == '.' ) - i++; - d = d.substr( 0, i+1 ); - } - return d; -} - -std::string toString( const double value ) { - return fpToString( value, 10 ); -} -std::string toString( const float value ) { - return fpToString( value, 5 ) + 'f'; -} - -std::string toString( bool value ) { - return value ? "true" : "false"; -} - -std::string toString( char value ) { - if ( value == '\r' ) - return "'\\r'"; - if ( value == '\f' ) - return "'\\f'"; - if ( value == '\n' ) - return "'\\n'"; - if ( value == '\t' ) - return "'\\t'"; - if ( '\0' <= value && value < ' ' ) - return toString( static_cast( value ) ); - char chstr[] = "' '"; - chstr[1] = value; - return chstr; -} - -std::string toString( signed char value ) { - return toString( static_cast( value ) ); -} - -std::string toString( unsigned char value ) { - return toString( static_cast( value ) ); -} - -#ifdef CATCH_CONFIG_CPP11_LONG_LONG -std::string toString( long long value ) { - std::ostringstream oss; - oss << value; - if( value > Detail::hexThreshold ) - oss << " (0x" << std::hex << value << ')'; - return oss.str(); -} -std::string toString( unsigned long long value ) { - std::ostringstream oss; - oss << value; - if( value > Detail::hexThreshold ) - oss << " (0x" << std::hex << value << ')'; - return oss.str(); -} -#endif - -#ifdef CATCH_CONFIG_CPP11_NULLPTR -std::string toString( std::nullptr_t ) { - return "nullptr"; -} -#endif - -#ifdef __OBJC__ - std::string toString( NSString const * const& nsstring ) { - if( !nsstring ) - return "nil"; - return "@" + toString([nsstring UTF8String]); - } - std::string toString( NSString * CATCH_ARC_STRONG & nsstring ) { - if( !nsstring ) - return "nil"; - return "@" + toString([nsstring UTF8String]); - } - std::string toString( NSObject* const& nsObject ) { - return toString( [nsObject description] ); - } -#endif - -} // end namespace Catch - -// #included from: catch_result_builder.hpp -#define TWOBLUECUBES_CATCH_RESULT_BUILDER_HPP_INCLUDED - -namespace Catch { - - ResultBuilder::ResultBuilder( char const* macroName, - SourceLineInfo const& lineInfo, - char const* capturedExpression, - ResultDisposition::Flags resultDisposition, - char const* secondArg ) - : m_assertionInfo( macroName, lineInfo, capturedExpression, resultDisposition, secondArg ), - m_shouldDebugBreak( false ), - m_shouldThrow( false ), - m_guardException( false ) - { - m_stream().oss.str(""); - } - - ResultBuilder::~ResultBuilder() { -#if defined(CATCH_CONFIG_FAST_COMPILE) - if ( m_guardException ) { - m_stream().oss << "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE"; - captureResult( ResultWas::ThrewException ); - getCurrentContext().getResultCapture()->exceptionEarlyReported(); - } -#endif - } - - ResultBuilder& ResultBuilder::setResultType( ResultWas::OfType result ) { - m_data.resultType = result; - return *this; - } - ResultBuilder& ResultBuilder::setResultType( bool result ) { - m_data.resultType = result ? ResultWas::Ok : ResultWas::ExpressionFailed; - return *this; - } - - void ResultBuilder::endExpression( DecomposedExpression const& expr ) { - AssertionResult result = build( expr ); - handleResult( result ); - } - - void ResultBuilder::useActiveException( ResultDisposition::Flags resultDisposition ) { - m_assertionInfo.resultDisposition = resultDisposition; - m_stream().oss << Catch::translateActiveException(); - captureResult( ResultWas::ThrewException ); - } - - void ResultBuilder::captureResult( ResultWas::OfType resultType ) { - setResultType( resultType ); - captureExpression(); - } - - void ResultBuilder::captureExpectedException( std::string const& expectedMessage ) { - if( expectedMessage.empty() ) - captureExpectedException( Matchers::Impl::MatchAllOf() ); - else - captureExpectedException( Matchers::Equals( expectedMessage ) ); - } - - void ResultBuilder::captureExpectedException( Matchers::Impl::MatcherBase const& matcher ) { - - assert( !isFalseTest( m_assertionInfo.resultDisposition ) ); - AssertionResultData data = m_data; - data.resultType = ResultWas::Ok; - data.reconstructedExpression = capturedExpressionWithSecondArgument(m_assertionInfo.capturedExpression, m_assertionInfo.secondArg); - - std::string actualMessage = Catch::translateActiveException(); - if( !matcher.match( actualMessage ) ) { - data.resultType = ResultWas::ExpressionFailed; - data.reconstructedExpression = actualMessage; - } - AssertionResult result( m_assertionInfo, data ); - handleResult( result ); - } - - void ResultBuilder::captureExpression() { - AssertionResult result = build(); - handleResult( result ); - } - - void ResultBuilder::handleResult( AssertionResult const& result ) - { - getResultCapture().assertionEnded( result ); - - if( !result.isOk() ) { - if( getCurrentContext().getConfig()->shouldDebugBreak() ) - m_shouldDebugBreak = true; - if( getCurrentContext().getRunner()->aborting() || (m_assertionInfo.resultDisposition & ResultDisposition::Normal) ) - m_shouldThrow = true; - } - } - - void ResultBuilder::react() { -#if defined(CATCH_CONFIG_FAST_COMPILE) - if (m_shouldDebugBreak) { - /////////////////////////////////////////////////////////////////// - // To inspect the state during test, you need to go one level up the callstack - // To go back to the test and change execution, jump over the throw statement - /////////////////////////////////////////////////////////////////// - CATCH_BREAK_INTO_DEBUGGER(); - } -#endif - if( m_shouldThrow ) - throw Catch::TestFailureException(); - } - - bool ResultBuilder::shouldDebugBreak() const { return m_shouldDebugBreak; } - bool ResultBuilder::allowThrows() const { return getCurrentContext().getConfig()->allowThrows(); } - - AssertionResult ResultBuilder::build() const - { - return build( *this ); - } - - // CAVEAT: The returned AssertionResult stores a pointer to the argument expr, - // a temporary DecomposedExpression, which in turn holds references to - // operands, possibly temporary as well. - // It should immediately be passed to handleResult; if the expression - // needs to be reported, its string expansion must be composed before - // the temporaries are destroyed. - AssertionResult ResultBuilder::build( DecomposedExpression const& expr ) const - { - assert( m_data.resultType != ResultWas::Unknown ); - AssertionResultData data = m_data; - - // Flip bool results if FalseTest flag is set - if( isFalseTest( m_assertionInfo.resultDisposition ) ) { - data.negate( expr.isBinaryExpression() ); - } - - data.message = m_stream().oss.str(); - data.decomposedExpression = &expr; // for lazy reconstruction - return AssertionResult( m_assertionInfo, data ); - } - - void ResultBuilder::reconstructExpression( std::string& dest ) const { - dest = capturedExpressionWithSecondArgument(m_assertionInfo.capturedExpression, m_assertionInfo.secondArg); - } - - void ResultBuilder::setExceptionGuard() { - m_guardException = true; - } - void ResultBuilder::unsetExceptionGuard() { - m_guardException = false; - } - -} // end namespace Catch - -// #included from: catch_tag_alias_registry.hpp -#define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_HPP_INCLUDED - -namespace Catch { - - TagAliasRegistry::~TagAliasRegistry() {} - - Option TagAliasRegistry::find( std::string const& alias ) const { - std::map::const_iterator it = m_registry.find( alias ); - if( it != m_registry.end() ) - return it->second; - else - return Option(); - } - - std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const { - std::string expandedTestSpec = unexpandedTestSpec; - for( std::map::const_iterator it = m_registry.begin(), itEnd = m_registry.end(); - it != itEnd; - ++it ) { - std::size_t pos = expandedTestSpec.find( it->first ); - if( pos != std::string::npos ) { - expandedTestSpec = expandedTestSpec.substr( 0, pos ) + - it->second.tag + - expandedTestSpec.substr( pos + it->first.size() ); - } - } - return expandedTestSpec; - } - - void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) { - - if( !startsWith( alias, "[@" ) || !endsWith( alias, ']' ) ) { - std::ostringstream oss; - oss << Colour( Colour::Red ) - << "error: tag alias, \"" << alias << "\" is not of the form [@alias name].\n" - << Colour( Colour::FileName ) - << lineInfo << '\n'; - throw std::domain_error( oss.str().c_str() ); - } - if( !m_registry.insert( std::make_pair( alias, TagAlias( tag, lineInfo ) ) ).second ) { - std::ostringstream oss; - oss << Colour( Colour::Red ) - << "error: tag alias, \"" << alias << "\" already registered.\n" - << "\tFirst seen at " - << Colour( Colour::Red ) << find(alias)->lineInfo << '\n' - << Colour( Colour::Red ) << "\tRedefined at " - << Colour( Colour::FileName) << lineInfo << '\n'; - throw std::domain_error( oss.str().c_str() ); - } - } - - ITagAliasRegistry::~ITagAliasRegistry() {} - - ITagAliasRegistry const& ITagAliasRegistry::get() { - return getRegistryHub().getTagAliasRegistry(); - } - - RegistrarForTagAliases::RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) { - getMutableRegistryHub().registerTagAlias( alias, tag, lineInfo ); - } - -} // end namespace Catch - -// #included from: catch_matchers_string.hpp - -namespace Catch { -namespace Matchers { - - namespace StdString { - - CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity ) - : m_caseSensitivity( caseSensitivity ), - m_str( adjustString( str ) ) - {} - std::string CasedString::adjustString( std::string const& str ) const { - return m_caseSensitivity == CaseSensitive::No - ? toLower( str ) - : str; - } - std::string CasedString::caseSensitivitySuffix() const { - return m_caseSensitivity == CaseSensitive::No - ? " (case insensitive)" - : std::string(); - } - - StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator ) - : m_comparator( comparator ), - m_operation( operation ) { - } - - std::string StringMatcherBase::describe() const { - std::string description; - description.reserve(5 + m_operation.size() + m_comparator.m_str.size() + - m_comparator.caseSensitivitySuffix().size()); - description += m_operation; - description += ": \""; - description += m_comparator.m_str; - description += "\""; - description += m_comparator.caseSensitivitySuffix(); - return description; - } - - EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {} - - bool EqualsMatcher::match( std::string const& source ) const { - return m_comparator.adjustString( source ) == m_comparator.m_str; - } - - ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {} - - bool ContainsMatcher::match( std::string const& source ) const { - return contains( m_comparator.adjustString( source ), m_comparator.m_str ); - } - - StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {} - - bool StartsWithMatcher::match( std::string const& source ) const { - return startsWith( m_comparator.adjustString( source ), m_comparator.m_str ); - } - - EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {} - - bool EndsWithMatcher::match( std::string const& source ) const { - return endsWith( m_comparator.adjustString( source ), m_comparator.m_str ); - } - - } // namespace StdString - - StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) { - return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) ); - } - StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) { - return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) ); - } - StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) { - return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) ); - } - StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) { - return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) ); - } - -} // namespace Matchers -} // namespace Catch -// #included from: ../reporters/catch_reporter_multi.hpp -#define TWOBLUECUBES_CATCH_REPORTER_MULTI_HPP_INCLUDED - -namespace Catch { - -class MultipleReporters : public SharedImpl { - typedef std::vector > Reporters; - Reporters m_reporters; - -public: - void add( Ptr const& reporter ) { - m_reporters.push_back( reporter ); - } - -public: // IStreamingReporter - - virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE { - return m_reporters[0]->getPreferences(); - } - - virtual void noMatchingTestCases( std::string const& spec ) CATCH_OVERRIDE { - for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); - it != itEnd; - ++it ) - (*it)->noMatchingTestCases( spec ); - } - - virtual void testRunStarting( TestRunInfo const& testRunInfo ) CATCH_OVERRIDE { - for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); - it != itEnd; - ++it ) - (*it)->testRunStarting( testRunInfo ); - } - - virtual void testGroupStarting( GroupInfo const& groupInfo ) CATCH_OVERRIDE { - for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); - it != itEnd; - ++it ) - (*it)->testGroupStarting( groupInfo ); - } - - virtual void testCaseStarting( TestCaseInfo const& testInfo ) CATCH_OVERRIDE { - for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); - it != itEnd; - ++it ) - (*it)->testCaseStarting( testInfo ); - } - - virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE { - for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); - it != itEnd; - ++it ) - (*it)->sectionStarting( sectionInfo ); - } - - virtual void assertionStarting( AssertionInfo const& assertionInfo ) CATCH_OVERRIDE { - for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); - it != itEnd; - ++it ) - (*it)->assertionStarting( assertionInfo ); - } - - // The return value indicates if the messages buffer should be cleared: - virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE { - bool clearBuffer = false; - for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); - it != itEnd; - ++it ) - clearBuffer |= (*it)->assertionEnded( assertionStats ); - return clearBuffer; - } - - virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE { - for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); - it != itEnd; - ++it ) - (*it)->sectionEnded( sectionStats ); - } - - virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE { - for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); - it != itEnd; - ++it ) - (*it)->testCaseEnded( testCaseStats ); - } - - virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE { - for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); - it != itEnd; - ++it ) - (*it)->testGroupEnded( testGroupStats ); - } - - virtual void testRunEnded( TestRunStats const& testRunStats ) CATCH_OVERRIDE { - for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); - it != itEnd; - ++it ) - (*it)->testRunEnded( testRunStats ); - } - - virtual void skipTest( TestCaseInfo const& testInfo ) CATCH_OVERRIDE { - for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); - it != itEnd; - ++it ) - (*it)->skipTest( testInfo ); - } - - virtual MultipleReporters* tryAsMulti() CATCH_OVERRIDE { - return this; - } - -}; - -Ptr addReporter( Ptr const& existingReporter, Ptr const& additionalReporter ) { - Ptr resultingReporter; - - if( existingReporter ) { - MultipleReporters* multi = existingReporter->tryAsMulti(); - if( !multi ) { - multi = new MultipleReporters; - resultingReporter = Ptr( multi ); - if( existingReporter ) - multi->add( existingReporter ); - } - else - resultingReporter = existingReporter; - multi->add( additionalReporter ); - } - else - resultingReporter = additionalReporter; - - return resultingReporter; -} - -} // end namespace Catch - -// #included from: ../reporters/catch_reporter_xml.hpp -#define TWOBLUECUBES_CATCH_REPORTER_XML_HPP_INCLUDED - -// #included from: catch_reporter_bases.hpp -#define TWOBLUECUBES_CATCH_REPORTER_BASES_HPP_INCLUDED - -#include -#include -#include -#include - -namespace Catch { - - namespace { - // Because formatting using c++ streams is stateful, drop down to C is required - // Alternatively we could use stringstream, but its performance is... not good. - std::string getFormattedDuration( double duration ) { - // Max exponent + 1 is required to represent the whole part - // + 1 for decimal point - // + 3 for the 3 decimal places - // + 1 for null terminator - const size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1; - char buffer[maxDoubleSize]; - - // Save previous errno, to prevent sprintf from overwriting it - ErrnoGuard guard; -#ifdef _MSC_VER - sprintf_s(buffer, "%.3f", duration); -#else - sprintf(buffer, "%.3f", duration); -#endif - return std::string(buffer); - } - } - - struct StreamingReporterBase : SharedImpl { - - StreamingReporterBase( ReporterConfig const& _config ) - : m_config( _config.fullConfig() ), - stream( _config.stream() ) - { - m_reporterPrefs.shouldRedirectStdOut = false; - } - - virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE { - return m_reporterPrefs; - } - - virtual ~StreamingReporterBase() CATCH_OVERRIDE; - - virtual void noMatchingTestCases( std::string const& ) CATCH_OVERRIDE {} - - virtual void testRunStarting( TestRunInfo const& _testRunInfo ) CATCH_OVERRIDE { - currentTestRunInfo = _testRunInfo; - } - virtual void testGroupStarting( GroupInfo const& _groupInfo ) CATCH_OVERRIDE { - currentGroupInfo = _groupInfo; - } - - virtual void testCaseStarting( TestCaseInfo const& _testInfo ) CATCH_OVERRIDE { - currentTestCaseInfo = _testInfo; - } - virtual void sectionStarting( SectionInfo const& _sectionInfo ) CATCH_OVERRIDE { - m_sectionStack.push_back( _sectionInfo ); - } - - virtual void sectionEnded( SectionStats const& /* _sectionStats */ ) CATCH_OVERRIDE { - m_sectionStack.pop_back(); - } - virtual void testCaseEnded( TestCaseStats const& /* _testCaseStats */ ) CATCH_OVERRIDE { - currentTestCaseInfo.reset(); - } - virtual void testGroupEnded( TestGroupStats const& /* _testGroupStats */ ) CATCH_OVERRIDE { - currentGroupInfo.reset(); - } - virtual void testRunEnded( TestRunStats const& /* _testRunStats */ ) CATCH_OVERRIDE { - currentTestCaseInfo.reset(); - currentGroupInfo.reset(); - currentTestRunInfo.reset(); - } - - virtual void skipTest( TestCaseInfo const& ) CATCH_OVERRIDE { - // Don't do anything with this by default. - // It can optionally be overridden in the derived class. - } - - Ptr m_config; - std::ostream& stream; - - LazyStat currentTestRunInfo; - LazyStat currentGroupInfo; - LazyStat currentTestCaseInfo; - - std::vector m_sectionStack; - ReporterPreferences m_reporterPrefs; - }; - - struct CumulativeReporterBase : SharedImpl { - template - struct Node : SharedImpl<> { - explicit Node( T const& _value ) : value( _value ) {} - virtual ~Node() {} - - typedef std::vector > ChildNodes; - T value; - ChildNodes children; - }; - struct SectionNode : SharedImpl<> { - explicit SectionNode( SectionStats const& _stats ) : stats( _stats ) {} - virtual ~SectionNode(); - - bool operator == ( SectionNode const& other ) const { - return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo; - } - bool operator == ( Ptr const& other ) const { - return operator==( *other ); - } - - SectionStats stats; - typedef std::vector > ChildSections; - typedef std::vector Assertions; - ChildSections childSections; - Assertions assertions; - std::string stdOut; - std::string stdErr; - }; - - struct BySectionInfo { - BySectionInfo( SectionInfo const& other ) : m_other( other ) {} - BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {} - bool operator() ( Ptr const& node ) const { - return node->stats.sectionInfo.lineInfo == m_other.lineInfo; - } - private: - void operator=( BySectionInfo const& ); - SectionInfo const& m_other; - }; - - typedef Node TestCaseNode; - typedef Node TestGroupNode; - typedef Node TestRunNode; - - CumulativeReporterBase( ReporterConfig const& _config ) - : m_config( _config.fullConfig() ), - stream( _config.stream() ) - { - m_reporterPrefs.shouldRedirectStdOut = false; - } - ~CumulativeReporterBase(); - - virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE { - return m_reporterPrefs; - } - - virtual void testRunStarting( TestRunInfo const& ) CATCH_OVERRIDE {} - virtual void testGroupStarting( GroupInfo const& ) CATCH_OVERRIDE {} - - virtual void testCaseStarting( TestCaseInfo const& ) CATCH_OVERRIDE {} - - virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE { - SectionStats incompleteStats( sectionInfo, Counts(), 0, false ); - Ptr node; - if( m_sectionStack.empty() ) { - if( !m_rootSection ) - m_rootSection = new SectionNode( incompleteStats ); - node = m_rootSection; - } - else { - SectionNode& parentNode = *m_sectionStack.back(); - SectionNode::ChildSections::const_iterator it = - std::find_if( parentNode.childSections.begin(), - parentNode.childSections.end(), - BySectionInfo( sectionInfo ) ); - if( it == parentNode.childSections.end() ) { - node = new SectionNode( incompleteStats ); - parentNode.childSections.push_back( node ); - } - else - node = *it; - } - m_sectionStack.push_back( node ); - m_deepestSection = node; - } - - virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE {} - - virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE { - assert( !m_sectionStack.empty() ); - SectionNode& sectionNode = *m_sectionStack.back(); - sectionNode.assertions.push_back( assertionStats ); - // AssertionResult holds a pointer to a temporary DecomposedExpression, - // which getExpandedExpression() calls to build the expression string. - // Our section stack copy of the assertionResult will likely outlive the - // temporary, so it must be expanded or discarded now to avoid calling - // a destroyed object later. - prepareExpandedExpression( sectionNode.assertions.back().assertionResult ); - return true; - } - virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE { - assert( !m_sectionStack.empty() ); - SectionNode& node = *m_sectionStack.back(); - node.stats = sectionStats; - m_sectionStack.pop_back(); - } - virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE { - Ptr node = new TestCaseNode( testCaseStats ); - assert( m_sectionStack.size() == 0 ); - node->children.push_back( m_rootSection ); - m_testCases.push_back( node ); - m_rootSection.reset(); - - assert( m_deepestSection ); - m_deepestSection->stdOut = testCaseStats.stdOut; - m_deepestSection->stdErr = testCaseStats.stdErr; - } - virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE { - Ptr node = new TestGroupNode( testGroupStats ); - node->children.swap( m_testCases ); - m_testGroups.push_back( node ); - } - virtual void testRunEnded( TestRunStats const& testRunStats ) CATCH_OVERRIDE { - Ptr node = new TestRunNode( testRunStats ); - node->children.swap( m_testGroups ); - m_testRuns.push_back( node ); - testRunEndedCumulative(); - } - virtual void testRunEndedCumulative() = 0; - - virtual void skipTest( TestCaseInfo const& ) CATCH_OVERRIDE {} - - virtual void prepareExpandedExpression( AssertionResult& result ) const { - if( result.isOk() ) - result.discardDecomposedExpression(); - else - result.expandDecomposedExpression(); - } - - Ptr m_config; - std::ostream& stream; - std::vector m_assertions; - std::vector > > m_sections; - std::vector > m_testCases; - std::vector > m_testGroups; - - std::vector > m_testRuns; - - Ptr m_rootSection; - Ptr m_deepestSection; - std::vector > m_sectionStack; - ReporterPreferences m_reporterPrefs; - - }; - - template - char const* getLineOfChars() { - static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0}; - if( !*line ) { - std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 ); - line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0; - } - return line; - } - - struct TestEventListenerBase : StreamingReporterBase { - TestEventListenerBase( ReporterConfig const& _config ) - : StreamingReporterBase( _config ) - {} - - virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE {} - virtual bool assertionEnded( AssertionStats const& ) CATCH_OVERRIDE { - return false; - } - }; - -} // end namespace Catch - -// #included from: ../internal/catch_reporter_registrars.hpp -#define TWOBLUECUBES_CATCH_REPORTER_REGISTRARS_HPP_INCLUDED - -namespace Catch { - - template - class LegacyReporterRegistrar { - - class ReporterFactory : public IReporterFactory { - virtual IStreamingReporter* create( ReporterConfig const& config ) const { - return new LegacyReporterAdapter( new T( config ) ); - } - - virtual std::string getDescription() const { - return T::getDescription(); - } - }; - - public: - - LegacyReporterRegistrar( std::string const& name ) { - getMutableRegistryHub().registerReporter( name, new ReporterFactory() ); - } - }; - - template - class ReporterRegistrar { - - class ReporterFactory : public SharedImpl { - - // *** Please Note ***: - // - If you end up here looking at a compiler error because it's trying to register - // your custom reporter class be aware that the native reporter interface has changed - // to IStreamingReporter. The "legacy" interface, IReporter, is still supported via - // an adapter. Just use REGISTER_LEGACY_REPORTER to take advantage of the adapter. - // However please consider updating to the new interface as the old one is now - // deprecated and will probably be removed quite soon! - // Please contact me via github if you have any questions at all about this. - // In fact, ideally, please contact me anyway to let me know you've hit this - as I have - // no idea who is actually using custom reporters at all (possibly no-one!). - // The new interface is designed to minimise exposure to interface changes in the future. - virtual IStreamingReporter* create( ReporterConfig const& config ) const { - return new T( config ); - } - - virtual std::string getDescription() const { - return T::getDescription(); - } - }; - - public: - - ReporterRegistrar( std::string const& name ) { - getMutableRegistryHub().registerReporter( name, new ReporterFactory() ); - } - }; - - template - class ListenerRegistrar { - - class ListenerFactory : public SharedImpl { - - virtual IStreamingReporter* create( ReporterConfig const& config ) const { - return new T( config ); - } - virtual std::string getDescription() const { - return std::string(); - } - }; - - public: - - ListenerRegistrar() { - getMutableRegistryHub().registerListener( new ListenerFactory() ); - } - }; -} - -#define INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) \ - namespace{ Catch::LegacyReporterRegistrar catch_internal_RegistrarFor##reporterType( name ); } - -#define INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) \ - namespace{ Catch::ReporterRegistrar catch_internal_RegistrarFor##reporterType( name ); } - -// Deprecated - use the form without INTERNAL_ -#define INTERNAL_CATCH_REGISTER_LISTENER( listenerType ) \ - namespace{ Catch::ListenerRegistrar catch_internal_RegistrarFor##listenerType; } - -#define CATCH_REGISTER_LISTENER( listenerType ) \ - namespace{ Catch::ListenerRegistrar catch_internal_RegistrarFor##listenerType; } - -// #included from: ../internal/catch_xmlwriter.hpp -#define TWOBLUECUBES_CATCH_XMLWRITER_HPP_INCLUDED - -#include -#include -#include -#include - -namespace Catch { - - class XmlEncode { - public: - enum ForWhat { ForTextNodes, ForAttributes }; - - XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes ) - : m_str( str ), - m_forWhat( forWhat ) - {} - - void encodeTo( std::ostream& os ) const { - - // Apostrophe escaping not necessary if we always use " to write attributes - // (see: http://www.w3.org/TR/xml/#syntax) - - for( std::size_t i = 0; i < m_str.size(); ++ i ) { - char c = m_str[i]; - switch( c ) { - case '<': os << "<"; break; - case '&': os << "&"; break; - - case '>': - // See: http://www.w3.org/TR/xml/#syntax - if( i > 2 && m_str[i-1] == ']' && m_str[i-2] == ']' ) - os << ">"; - else - os << c; - break; - - case '\"': - if( m_forWhat == ForAttributes ) - os << """; - else - os << c; - break; - - default: - // Escape control chars - based on contribution by @espenalb in PR #465 and - // by @mrpi PR #588 - if ( ( c >= 0 && c < '\x09' ) || ( c > '\x0D' && c < '\x20') || c=='\x7F' ) { - // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0 - os << "\\x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2) - << static_cast( c ); - } - else - os << c; - } - } - } - - friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) { - xmlEncode.encodeTo( os ); - return os; - } - - private: - std::string m_str; - ForWhat m_forWhat; - }; - - class XmlWriter { - public: - - class ScopedElement { - public: - ScopedElement( XmlWriter* writer ) - : m_writer( writer ) - {} - - ScopedElement( ScopedElement const& other ) - : m_writer( other.m_writer ){ - other.m_writer = CATCH_NULL; - } - - ~ScopedElement() { - if( m_writer ) - m_writer->endElement(); - } - - ScopedElement& writeText( std::string const& text, bool indent = true ) { - m_writer->writeText( text, indent ); - return *this; - } - - template - ScopedElement& writeAttribute( std::string const& name, T const& attribute ) { - m_writer->writeAttribute( name, attribute ); - return *this; - } - - private: - mutable XmlWriter* m_writer; - }; - - XmlWriter() - : m_tagIsOpen( false ), - m_needsNewline( false ), - m_os( Catch::cout() ) - { - writeDeclaration(); - } - - XmlWriter( std::ostream& os ) - : m_tagIsOpen( false ), - m_needsNewline( false ), - m_os( os ) - { - writeDeclaration(); - } - - ~XmlWriter() { - while( !m_tags.empty() ) - endElement(); - } - - XmlWriter& startElement( std::string const& name ) { - ensureTagClosed(); - newlineIfNecessary(); - m_os << m_indent << '<' << name; - m_tags.push_back( name ); - m_indent += " "; - m_tagIsOpen = true; - return *this; - } - - ScopedElement scopedElement( std::string const& name ) { - ScopedElement scoped( this ); - startElement( name ); - return scoped; - } - - XmlWriter& endElement() { - newlineIfNecessary(); - m_indent = m_indent.substr( 0, m_indent.size()-2 ); - if( m_tagIsOpen ) { - m_os << "/>"; - m_tagIsOpen = false; - } - else { - m_os << m_indent << ""; - } - m_os << std::endl; - m_tags.pop_back(); - return *this; - } - - XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ) { - if( !name.empty() && !attribute.empty() ) - m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"'; - return *this; - } - - XmlWriter& writeAttribute( std::string const& name, bool attribute ) { - m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"'; - return *this; - } - - template - XmlWriter& writeAttribute( std::string const& name, T const& attribute ) { - std::ostringstream oss; - oss << attribute; - return writeAttribute( name, oss.str() ); - } - - XmlWriter& writeText( std::string const& text, bool indent = true ) { - if( !text.empty() ){ - bool tagWasOpen = m_tagIsOpen; - ensureTagClosed(); - if( tagWasOpen && indent ) - m_os << m_indent; - m_os << XmlEncode( text ); - m_needsNewline = true; - } - return *this; - } - - XmlWriter& writeComment( std::string const& text ) { - ensureTagClosed(); - m_os << m_indent << ""; - m_needsNewline = true; - return *this; - } - - void writeStylesheetRef( std::string const& url ) { - m_os << "\n"; - } - - XmlWriter& writeBlankLine() { - ensureTagClosed(); - m_os << '\n'; - return *this; - } - - void ensureTagClosed() { - if( m_tagIsOpen ) { - m_os << ">" << std::endl; - m_tagIsOpen = false; - } - } - - private: - XmlWriter( XmlWriter const& ); - void operator=( XmlWriter const& ); - - void writeDeclaration() { - m_os << "\n"; - } - - void newlineIfNecessary() { - if( m_needsNewline ) { - m_os << std::endl; - m_needsNewline = false; - } - } - - bool m_tagIsOpen; - bool m_needsNewline; - std::vector m_tags; - std::string m_indent; - std::ostream& m_os; - }; - -} - -namespace Catch { - class XmlReporter : public StreamingReporterBase { - public: - XmlReporter( ReporterConfig const& _config ) - : StreamingReporterBase( _config ), - m_xml(_config.stream()), - m_sectionDepth( 0 ) - { - m_reporterPrefs.shouldRedirectStdOut = true; - } - - virtual ~XmlReporter() CATCH_OVERRIDE; - - static std::string getDescription() { - return "Reports test results as an XML document"; - } - - virtual std::string getStylesheetRef() const { - return std::string(); - } - - void writeSourceInfo( SourceLineInfo const& sourceInfo ) { - m_xml - .writeAttribute( "filename", sourceInfo.file ) - .writeAttribute( "line", sourceInfo.line ); - } - - public: // StreamingReporterBase - - virtual void noMatchingTestCases( std::string const& s ) CATCH_OVERRIDE { - StreamingReporterBase::noMatchingTestCases( s ); - } - - virtual void testRunStarting( TestRunInfo const& testInfo ) CATCH_OVERRIDE { - StreamingReporterBase::testRunStarting( testInfo ); - std::string stylesheetRef = getStylesheetRef(); - if( !stylesheetRef.empty() ) - m_xml.writeStylesheetRef( stylesheetRef ); - m_xml.startElement( "Catch" ); - if( !m_config->name().empty() ) - m_xml.writeAttribute( "name", m_config->name() ); - } - - virtual void testGroupStarting( GroupInfo const& groupInfo ) CATCH_OVERRIDE { - StreamingReporterBase::testGroupStarting( groupInfo ); - m_xml.startElement( "Group" ) - .writeAttribute( "name", groupInfo.name ); - } - - virtual void testCaseStarting( TestCaseInfo const& testInfo ) CATCH_OVERRIDE { - StreamingReporterBase::testCaseStarting(testInfo); - m_xml.startElement( "TestCase" ) - .writeAttribute( "name", trim( testInfo.name ) ) - .writeAttribute( "description", testInfo.description ) - .writeAttribute( "tags", testInfo.tagsAsString ); - - writeSourceInfo( testInfo.lineInfo ); - - if ( m_config->showDurations() == ShowDurations::Always ) - m_testCaseTimer.start(); - m_xml.ensureTagClosed(); - } - - virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE { - StreamingReporterBase::sectionStarting( sectionInfo ); - if( m_sectionDepth++ > 0 ) { - m_xml.startElement( "Section" ) - .writeAttribute( "name", trim( sectionInfo.name ) ) - .writeAttribute( "description", sectionInfo.description ); - writeSourceInfo( sectionInfo.lineInfo ); - m_xml.ensureTagClosed(); - } - } - - virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE { } - - virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE { - - AssertionResult const& result = assertionStats.assertionResult; - - bool includeResults = m_config->includeSuccessfulResults() || !result.isOk(); - - if( includeResults ) { - // Print any info messages in tags. - for( std::vector::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end(); - it != itEnd; - ++it ) { - if( it->type == ResultWas::Info ) { - m_xml.scopedElement( "Info" ) - .writeText( it->message ); - } else if ( it->type == ResultWas::Warning ) { - m_xml.scopedElement( "Warning" ) - .writeText( it->message ); - } - } - } - - // Drop out if result was successful but we're not printing them. - if( !includeResults && result.getResultType() != ResultWas::Warning ) - return true; - - // Print the expression if there is one. - if( result.hasExpression() ) { - m_xml.startElement( "Expression" ) - .writeAttribute( "success", result.succeeded() ) - .writeAttribute( "type", result.getTestMacroName() ); - - writeSourceInfo( result.getSourceInfo() ); - - m_xml.scopedElement( "Original" ) - .writeText( result.getExpression() ); - m_xml.scopedElement( "Expanded" ) - .writeText( result.getExpandedExpression() ); - } - - // And... Print a result applicable to each result type. - switch( result.getResultType() ) { - case ResultWas::ThrewException: - m_xml.startElement( "Exception" ); - writeSourceInfo( result.getSourceInfo() ); - m_xml.writeText( result.getMessage() ); - m_xml.endElement(); - break; - case ResultWas::FatalErrorCondition: - m_xml.startElement( "FatalErrorCondition" ); - writeSourceInfo( result.getSourceInfo() ); - m_xml.writeText( result.getMessage() ); - m_xml.endElement(); - break; - case ResultWas::Info: - m_xml.scopedElement( "Info" ) - .writeText( result.getMessage() ); - break; - case ResultWas::Warning: - // Warning will already have been written - break; - case ResultWas::ExplicitFailure: - m_xml.startElement( "Failure" ); - writeSourceInfo( result.getSourceInfo() ); - m_xml.writeText( result.getMessage() ); - m_xml.endElement(); - break; - default: - break; - } - - if( result.hasExpression() ) - m_xml.endElement(); - - return true; - } - - virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE { - StreamingReporterBase::sectionEnded( sectionStats ); - if( --m_sectionDepth > 0 ) { - XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" ); - e.writeAttribute( "successes", sectionStats.assertions.passed ); - e.writeAttribute( "failures", sectionStats.assertions.failed ); - e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk ); - - if ( m_config->showDurations() == ShowDurations::Always ) - e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds ); - - m_xml.endElement(); - } - } - - virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE { - StreamingReporterBase::testCaseEnded( testCaseStats ); - XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" ); - e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() ); - - if ( m_config->showDurations() == ShowDurations::Always ) - e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() ); - - if( !testCaseStats.stdOut.empty() ) - m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false ); - if( !testCaseStats.stdErr.empty() ) - m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false ); - - m_xml.endElement(); - } - - virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE { - StreamingReporterBase::testGroupEnded( testGroupStats ); - // TODO: Check testGroupStats.aborting and act accordingly. - m_xml.scopedElement( "OverallResults" ) - .writeAttribute( "successes", testGroupStats.totals.assertions.passed ) - .writeAttribute( "failures", testGroupStats.totals.assertions.failed ) - .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk ); - m_xml.endElement(); - } - - virtual void testRunEnded( TestRunStats const& testRunStats ) CATCH_OVERRIDE { - StreamingReporterBase::testRunEnded( testRunStats ); - m_xml.scopedElement( "OverallResults" ) - .writeAttribute( "successes", testRunStats.totals.assertions.passed ) - .writeAttribute( "failures", testRunStats.totals.assertions.failed ) - .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk ); - m_xml.endElement(); - } - - private: - Timer m_testCaseTimer; - XmlWriter m_xml; - int m_sectionDepth; - }; - - INTERNAL_CATCH_REGISTER_REPORTER( "xml", XmlReporter ) - -} // end namespace Catch - -// #included from: ../reporters/catch_reporter_junit.hpp -#define TWOBLUECUBES_CATCH_REPORTER_JUNIT_HPP_INCLUDED - -#include - -namespace Catch { - - namespace { - std::string getCurrentTimestamp() { - // Beware, this is not reentrant because of backward compatibility issues - // Also, UTC only, again because of backward compatibility (%z is C++11) - time_t rawtime; - std::time(&rawtime); - const size_t timeStampSize = sizeof("2017-01-16T17:06:45Z"); - -#ifdef _MSC_VER - std::tm timeInfo = {}; - gmtime_s(&timeInfo, &rawtime); -#else - std::tm* timeInfo; - timeInfo = std::gmtime(&rawtime); -#endif - - char timeStamp[timeStampSize]; - const char * const fmt = "%Y-%m-%dT%H:%M:%SZ"; - -#ifdef _MSC_VER - std::strftime(timeStamp, timeStampSize, fmt, &timeInfo); -#else - std::strftime(timeStamp, timeStampSize, fmt, timeInfo); -#endif - return std::string(timeStamp); - } - - } - - class JunitReporter : public CumulativeReporterBase { - public: - JunitReporter( ReporterConfig const& _config ) - : CumulativeReporterBase( _config ), - xml( _config.stream() ), - m_okToFail( false ) - { - m_reporterPrefs.shouldRedirectStdOut = true; - } - - virtual ~JunitReporter() CATCH_OVERRIDE; - - static std::string getDescription() { - return "Reports test results in an XML format that looks like Ant's junitreport target"; - } - - virtual void noMatchingTestCases( std::string const& /*spec*/ ) CATCH_OVERRIDE {} - - virtual void testRunStarting( TestRunInfo const& runInfo ) CATCH_OVERRIDE { - CumulativeReporterBase::testRunStarting( runInfo ); - xml.startElement( "testsuites" ); - } - - virtual void testGroupStarting( GroupInfo const& groupInfo ) CATCH_OVERRIDE { - suiteTimer.start(); - stdOutForSuite.str(""); - stdErrForSuite.str(""); - unexpectedExceptions = 0; - CumulativeReporterBase::testGroupStarting( groupInfo ); - } - - virtual void testCaseStarting( TestCaseInfo const& testCaseInfo ) CATCH_OVERRIDE { - m_okToFail = testCaseInfo.okToFail(); - } - virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE { - if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail ) - unexpectedExceptions++; - return CumulativeReporterBase::assertionEnded( assertionStats ); - } - - virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE { - stdOutForSuite << testCaseStats.stdOut; - stdErrForSuite << testCaseStats.stdErr; - CumulativeReporterBase::testCaseEnded( testCaseStats ); - } - - virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE { - double suiteTime = suiteTimer.getElapsedSeconds(); - CumulativeReporterBase::testGroupEnded( testGroupStats ); - writeGroup( *m_testGroups.back(), suiteTime ); - } - - virtual void testRunEndedCumulative() CATCH_OVERRIDE { - xml.endElement(); - } - - void writeGroup( TestGroupNode const& groupNode, double suiteTime ) { - XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" ); - TestGroupStats const& stats = groupNode.value; - xml.writeAttribute( "name", stats.groupInfo.name ); - xml.writeAttribute( "errors", unexpectedExceptions ); - xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions ); - xml.writeAttribute( "tests", stats.totals.assertions.total() ); - xml.writeAttribute( "hostname", "tbd" ); // !TBD - if( m_config->showDurations() == ShowDurations::Never ) - xml.writeAttribute( "time", "" ); - else - xml.writeAttribute( "time", suiteTime ); - xml.writeAttribute( "timestamp", getCurrentTimestamp() ); - - // Write test cases - for( TestGroupNode::ChildNodes::const_iterator - it = groupNode.children.begin(), itEnd = groupNode.children.end(); - it != itEnd; - ++it ) - writeTestCase( **it ); - - xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite.str() ), false ); - xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite.str() ), false ); - } - - void writeTestCase( TestCaseNode const& testCaseNode ) { - TestCaseStats const& stats = testCaseNode.value; - - // All test cases have exactly one section - which represents the - // test case itself. That section may have 0-n nested sections - assert( testCaseNode.children.size() == 1 ); - SectionNode const& rootSection = *testCaseNode.children.front(); - - std::string className = stats.testInfo.className; - - if( className.empty() ) { - if( rootSection.childSections.empty() ) - className = "global"; - } - writeSection( className, "", rootSection ); - } - - void writeSection( std::string const& className, - std::string const& rootName, - SectionNode const& sectionNode ) { - std::string name = trim( sectionNode.stats.sectionInfo.name ); - if( !rootName.empty() ) - name = rootName + '/' + name; - - if( !sectionNode.assertions.empty() || - !sectionNode.stdOut.empty() || - !sectionNode.stdErr.empty() ) { - XmlWriter::ScopedElement e = xml.scopedElement( "testcase" ); - if( className.empty() ) { - xml.writeAttribute( "classname", name ); - xml.writeAttribute( "name", "root" ); - } - else { - xml.writeAttribute( "classname", className ); - xml.writeAttribute( "name", name ); - } - xml.writeAttribute( "time", Catch::toString( sectionNode.stats.durationInSeconds ) ); - - writeAssertions( sectionNode ); - - if( !sectionNode.stdOut.empty() ) - xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false ); - if( !sectionNode.stdErr.empty() ) - xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false ); - } - for( SectionNode::ChildSections::const_iterator - it = sectionNode.childSections.begin(), - itEnd = sectionNode.childSections.end(); - it != itEnd; - ++it ) - if( className.empty() ) - writeSection( name, "", **it ); - else - writeSection( className, name, **it ); - } - - void writeAssertions( SectionNode const& sectionNode ) { - for( SectionNode::Assertions::const_iterator - it = sectionNode.assertions.begin(), itEnd = sectionNode.assertions.end(); - it != itEnd; - ++it ) - writeAssertion( *it ); - } - void writeAssertion( AssertionStats const& stats ) { - AssertionResult const& result = stats.assertionResult; - if( !result.isOk() ) { - std::string elementName; - switch( result.getResultType() ) { - case ResultWas::ThrewException: - case ResultWas::FatalErrorCondition: - elementName = "error"; - break; - case ResultWas::ExplicitFailure: - elementName = "failure"; - break; - case ResultWas::ExpressionFailed: - elementName = "failure"; - break; - case ResultWas::DidntThrowException: - elementName = "failure"; - break; - - // We should never see these here: - case ResultWas::Info: - case ResultWas::Warning: - case ResultWas::Ok: - case ResultWas::Unknown: - case ResultWas::FailureBit: - case ResultWas::Exception: - elementName = "internalError"; - break; - } - - XmlWriter::ScopedElement e = xml.scopedElement( elementName ); - - xml.writeAttribute( "message", result.getExpandedExpression() ); - xml.writeAttribute( "type", result.getTestMacroName() ); - - std::ostringstream oss; - if( !result.getMessage().empty() ) - oss << result.getMessage() << '\n'; - for( std::vector::const_iterator - it = stats.infoMessages.begin(), - itEnd = stats.infoMessages.end(); - it != itEnd; - ++it ) - if( it->type == ResultWas::Info ) - oss << it->message << '\n'; - - oss << "at " << result.getSourceInfo(); - xml.writeText( oss.str(), false ); - } - } - - XmlWriter xml; - Timer suiteTimer; - std::ostringstream stdOutForSuite; - std::ostringstream stdErrForSuite; - unsigned int unexpectedExceptions; - bool m_okToFail; - }; - - INTERNAL_CATCH_REGISTER_REPORTER( "junit", JunitReporter ) - -} // end namespace Catch - -// #included from: ../reporters/catch_reporter_console.hpp -#define TWOBLUECUBES_CATCH_REPORTER_CONSOLE_HPP_INCLUDED - -#include -#include - -namespace Catch { - - struct ConsoleReporter : StreamingReporterBase { - ConsoleReporter( ReporterConfig const& _config ) - : StreamingReporterBase( _config ), - m_headerPrinted( false ) - {} - - virtual ~ConsoleReporter() CATCH_OVERRIDE; - static std::string getDescription() { - return "Reports test results as plain lines of text"; - } - - virtual void noMatchingTestCases( std::string const& spec ) CATCH_OVERRIDE { - stream << "No test cases matched '" << spec << '\'' << std::endl; - } - - virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE { - } - - virtual bool assertionEnded( AssertionStats const& _assertionStats ) CATCH_OVERRIDE { - AssertionResult const& result = _assertionStats.assertionResult; - - bool includeResults = m_config->includeSuccessfulResults() || !result.isOk(); - - // Drop out if result was successful but we're not printing them. - if( !includeResults && result.getResultType() != ResultWas::Warning ) - return false; - - lazyPrint(); - - AssertionPrinter printer( stream, _assertionStats, includeResults ); - printer.print(); - stream << std::endl; - return true; - } - - virtual void sectionStarting( SectionInfo const& _sectionInfo ) CATCH_OVERRIDE { - m_headerPrinted = false; - StreamingReporterBase::sectionStarting( _sectionInfo ); - } - virtual void sectionEnded( SectionStats const& _sectionStats ) CATCH_OVERRIDE { - if( _sectionStats.missingAssertions ) { - lazyPrint(); - Colour colour( Colour::ResultError ); - if( m_sectionStack.size() > 1 ) - stream << "\nNo assertions in section"; - else - stream << "\nNo assertions in test case"; - stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl; - } - if( m_config->showDurations() == ShowDurations::Always ) { - stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl; - } - if( m_headerPrinted ) { - m_headerPrinted = false; - } - StreamingReporterBase::sectionEnded( _sectionStats ); - } - - virtual void testCaseEnded( TestCaseStats const& _testCaseStats ) CATCH_OVERRIDE { - StreamingReporterBase::testCaseEnded( _testCaseStats ); - m_headerPrinted = false; - } - virtual void testGroupEnded( TestGroupStats const& _testGroupStats ) CATCH_OVERRIDE { - if( currentGroupInfo.used ) { - printSummaryDivider(); - stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n"; - printTotals( _testGroupStats.totals ); - stream << '\n' << std::endl; - } - StreamingReporterBase::testGroupEnded( _testGroupStats ); - } - virtual void testRunEnded( TestRunStats const& _testRunStats ) CATCH_OVERRIDE { - printTotalsDivider( _testRunStats.totals ); - printTotals( _testRunStats.totals ); - stream << std::endl; - StreamingReporterBase::testRunEnded( _testRunStats ); - } - - private: - - class AssertionPrinter { - void operator= ( AssertionPrinter const& ); - public: - AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages ) - : stream( _stream ), - stats( _stats ), - result( _stats.assertionResult ), - colour( Colour::None ), - message( result.getMessage() ), - messages( _stats.infoMessages ), - printInfoMessages( _printInfoMessages ) - { - switch( result.getResultType() ) { - case ResultWas::Ok: - colour = Colour::Success; - passOrFail = "PASSED"; - //if( result.hasMessage() ) - if( _stats.infoMessages.size() == 1 ) - messageLabel = "with message"; - if( _stats.infoMessages.size() > 1 ) - messageLabel = "with messages"; - break; - case ResultWas::ExpressionFailed: - if( result.isOk() ) { - colour = Colour::Success; - passOrFail = "FAILED - but was ok"; - } - else { - colour = Colour::Error; - passOrFail = "FAILED"; - } - if( _stats.infoMessages.size() == 1 ) - messageLabel = "with message"; - if( _stats.infoMessages.size() > 1 ) - messageLabel = "with messages"; - break; - case ResultWas::ThrewException: - colour = Colour::Error; - passOrFail = "FAILED"; - messageLabel = "due to unexpected exception with "; - if (_stats.infoMessages.size() == 1) - messageLabel += "message"; - if (_stats.infoMessages.size() > 1) - messageLabel += "messages"; - break; - case ResultWas::FatalErrorCondition: - colour = Colour::Error; - passOrFail = "FAILED"; - messageLabel = "due to a fatal error condition"; - break; - case ResultWas::DidntThrowException: - colour = Colour::Error; - passOrFail = "FAILED"; - messageLabel = "because no exception was thrown where one was expected"; - break; - case ResultWas::Info: - messageLabel = "info"; - break; - case ResultWas::Warning: - messageLabel = "warning"; - break; - case ResultWas::ExplicitFailure: - passOrFail = "FAILED"; - colour = Colour::Error; - if( _stats.infoMessages.size() == 1 ) - messageLabel = "explicitly with message"; - if( _stats.infoMessages.size() > 1 ) - messageLabel = "explicitly with messages"; - break; - // These cases are here to prevent compiler warnings - case ResultWas::Unknown: - case ResultWas::FailureBit: - case ResultWas::Exception: - passOrFail = "** internal error **"; - colour = Colour::Error; - break; - } - } - - void print() const { - printSourceInfo(); - if( stats.totals.assertions.total() > 0 ) { - if( result.isOk() ) - stream << '\n'; - printResultType(); - printOriginalExpression(); - printReconstructedExpression(); - } - else { - stream << '\n'; - } - printMessage(); - } - - private: - void printResultType() const { - if( !passOrFail.empty() ) { - Colour colourGuard( colour ); - stream << passOrFail << ":\n"; - } - } - void printOriginalExpression() const { - if( result.hasExpression() ) { - Colour colourGuard( Colour::OriginalExpression ); - stream << " "; - stream << result.getExpressionInMacro(); - stream << '\n'; - } - } - void printReconstructedExpression() const { - if( result.hasExpandedExpression() ) { - stream << "with expansion:\n"; - Colour colourGuard( Colour::ReconstructedExpression ); - stream << Text( result.getExpandedExpression(), TextAttributes().setIndent(2) ) << '\n'; - } - } - void printMessage() const { - if( !messageLabel.empty() ) - stream << messageLabel << ':' << '\n'; - for( std::vector::const_iterator it = messages.begin(), itEnd = messages.end(); - it != itEnd; - ++it ) { - // If this assertion is a warning ignore any INFO messages - if( printInfoMessages || it->type != ResultWas::Info ) - stream << Text( it->message, TextAttributes().setIndent(2) ) << '\n'; - } - } - void printSourceInfo() const { - Colour colourGuard( Colour::FileName ); - stream << result.getSourceInfo() << ": "; - } - - std::ostream& stream; - AssertionStats const& stats; - AssertionResult const& result; - Colour::Code colour; - std::string passOrFail; - std::string messageLabel; - std::string message; - std::vector messages; - bool printInfoMessages; - }; - - void lazyPrint() { - - if( !currentTestRunInfo.used ) - lazyPrintRunInfo(); - if( !currentGroupInfo.used ) - lazyPrintGroupInfo(); - - if( !m_headerPrinted ) { - printTestCaseAndSectionHeader(); - m_headerPrinted = true; - } - } - void lazyPrintRunInfo() { - stream << '\n' << getLineOfChars<'~'>() << '\n'; - Colour colour( Colour::SecondaryText ); - stream << currentTestRunInfo->name - << " is a Catch v" << libraryVersion() << " host application.\n" - << "Run with -? for options\n\n"; - - if( m_config->rngSeed() != 0 ) - stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n"; - - currentTestRunInfo.used = true; - } - void lazyPrintGroupInfo() { - if( !currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1 ) { - printClosedHeader( "Group: " + currentGroupInfo->name ); - currentGroupInfo.used = true; - } - } - void printTestCaseAndSectionHeader() { - assert( !m_sectionStack.empty() ); - printOpenHeader( currentTestCaseInfo->name ); - - if( m_sectionStack.size() > 1 ) { - Colour colourGuard( Colour::Headers ); - - std::vector::const_iterator - it = m_sectionStack.begin()+1, // Skip first section (test case) - itEnd = m_sectionStack.end(); - for( ; it != itEnd; ++it ) - printHeaderString( it->name, 2 ); - } - - SourceLineInfo lineInfo = m_sectionStack.back().lineInfo; - - if( !lineInfo.empty() ){ - stream << getLineOfChars<'-'>() << '\n'; - Colour colourGuard( Colour::FileName ); - stream << lineInfo << '\n'; - } - stream << getLineOfChars<'.'>() << '\n' << std::endl; - } - - void printClosedHeader( std::string const& _name ) { - printOpenHeader( _name ); - stream << getLineOfChars<'.'>() << '\n'; - } - void printOpenHeader( std::string const& _name ) { - stream << getLineOfChars<'-'>() << '\n'; - { - Colour colourGuard( Colour::Headers ); - printHeaderString( _name ); - } - } - - // if string has a : in first line will set indent to follow it on - // subsequent lines - void printHeaderString( std::string const& _string, std::size_t indent = 0 ) { - std::size_t i = _string.find( ": " ); - if( i != std::string::npos ) - i+=2; - else - i = 0; - stream << Text( _string, TextAttributes() - .setIndent( indent+i) - .setInitialIndent( indent ) ) << '\n'; - } - - struct SummaryColumn { - - SummaryColumn( std::string const& _label, Colour::Code _colour ) - : label( _label ), - colour( _colour ) - {} - SummaryColumn addRow( std::size_t count ) { - std::ostringstream oss; - oss << count; - std::string row = oss.str(); - for( std::vector::iterator it = rows.begin(); it != rows.end(); ++it ) { - while( it->size() < row.size() ) - *it = ' ' + *it; - while( it->size() > row.size() ) - row = ' ' + row; - } - rows.push_back( row ); - return *this; - } - - std::string label; - Colour::Code colour; - std::vector rows; - - }; - - void printTotals( Totals const& totals ) { - if( totals.testCases.total() == 0 ) { - stream << Colour( Colour::Warning ) << "No tests ran\n"; - } - else if( totals.assertions.total() > 0 && totals.testCases.allPassed() ) { - stream << Colour( Colour::ResultSuccess ) << "All tests passed"; - stream << " (" - << pluralise( totals.assertions.passed, "assertion" ) << " in " - << pluralise( totals.testCases.passed, "test case" ) << ')' - << '\n'; - } - else { - - std::vector columns; - columns.push_back( SummaryColumn( "", Colour::None ) - .addRow( totals.testCases.total() ) - .addRow( totals.assertions.total() ) ); - columns.push_back( SummaryColumn( "passed", Colour::Success ) - .addRow( totals.testCases.passed ) - .addRow( totals.assertions.passed ) ); - columns.push_back( SummaryColumn( "failed", Colour::ResultError ) - .addRow( totals.testCases.failed ) - .addRow( totals.assertions.failed ) ); - columns.push_back( SummaryColumn( "failed as expected", Colour::ResultExpectedFailure ) - .addRow( totals.testCases.failedButOk ) - .addRow( totals.assertions.failedButOk ) ); - - printSummaryRow( "test cases", columns, 0 ); - printSummaryRow( "assertions", columns, 1 ); - } - } - void printSummaryRow( std::string const& label, std::vector const& cols, std::size_t row ) { - for( std::vector::const_iterator it = cols.begin(); it != cols.end(); ++it ) { - std::string value = it->rows[row]; - if( it->label.empty() ) { - stream << label << ": "; - if( value != "0" ) - stream << value; - else - stream << Colour( Colour::Warning ) << "- none -"; - } - else if( value != "0" ) { - stream << Colour( Colour::LightGrey ) << " | "; - stream << Colour( it->colour ) - << value << ' ' << it->label; - } - } - stream << '\n'; - } - - static std::size_t makeRatio( std::size_t number, std::size_t total ) { - std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number/ total : 0; - return ( ratio == 0 && number > 0 ) ? 1 : ratio; - } - static std::size_t& findMax( std::size_t& i, std::size_t& j, std::size_t& k ) { - if( i > j && i > k ) - return i; - else if( j > k ) - return j; - else - return k; - } - - void printTotalsDivider( Totals const& totals ) { - if( totals.testCases.total() > 0 ) { - std::size_t failedRatio = makeRatio( totals.testCases.failed, totals.testCases.total() ); - std::size_t failedButOkRatio = makeRatio( totals.testCases.failedButOk, totals.testCases.total() ); - std::size_t passedRatio = makeRatio( totals.testCases.passed, totals.testCases.total() ); - while( failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH-1 ) - findMax( failedRatio, failedButOkRatio, passedRatio )++; - while( failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH-1 ) - findMax( failedRatio, failedButOkRatio, passedRatio )--; - - stream << Colour( Colour::Error ) << std::string( failedRatio, '=' ); - stream << Colour( Colour::ResultExpectedFailure ) << std::string( failedButOkRatio, '=' ); - if( totals.testCases.allPassed() ) - stream << Colour( Colour::ResultSuccess ) << std::string( passedRatio, '=' ); - else - stream << Colour( Colour::Success ) << std::string( passedRatio, '=' ); - } - else { - stream << Colour( Colour::Warning ) << std::string( CATCH_CONFIG_CONSOLE_WIDTH-1, '=' ); - } - stream << '\n'; - } - void printSummaryDivider() { - stream << getLineOfChars<'-'>() << '\n'; - } - - private: - bool m_headerPrinted; - }; - - INTERNAL_CATCH_REGISTER_REPORTER( "console", ConsoleReporter ) - -} // end namespace Catch - -// #included from: ../reporters/catch_reporter_compact.hpp -#define TWOBLUECUBES_CATCH_REPORTER_COMPACT_HPP_INCLUDED - -namespace Catch { - - struct CompactReporter : StreamingReporterBase { - - CompactReporter( ReporterConfig const& _config ) - : StreamingReporterBase( _config ) - {} - - virtual ~CompactReporter(); - - static std::string getDescription() { - return "Reports test results on a single line, suitable for IDEs"; - } - - virtual ReporterPreferences getPreferences() const { - ReporterPreferences prefs; - prefs.shouldRedirectStdOut = false; - return prefs; - } - - virtual void noMatchingTestCases( std::string const& spec ) { - stream << "No test cases matched '" << spec << '\'' << std::endl; - } - - virtual void assertionStarting( AssertionInfo const& ) {} - - virtual bool assertionEnded( AssertionStats const& _assertionStats ) { - AssertionResult const& result = _assertionStats.assertionResult; - - bool printInfoMessages = true; - - // Drop out if result was successful and we're not printing those - if( !m_config->includeSuccessfulResults() && result.isOk() ) { - if( result.getResultType() != ResultWas::Warning ) - return false; - printInfoMessages = false; - } - - AssertionPrinter printer( stream, _assertionStats, printInfoMessages ); - printer.print(); - - stream << std::endl; - return true; - } - - virtual void sectionEnded(SectionStats const& _sectionStats) CATCH_OVERRIDE { - if (m_config->showDurations() == ShowDurations::Always) { - stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl; - } - } - - virtual void testRunEnded( TestRunStats const& _testRunStats ) { - printTotals( _testRunStats.totals ); - stream << '\n' << std::endl; - StreamingReporterBase::testRunEnded( _testRunStats ); - } - - private: - class AssertionPrinter { - void operator= ( AssertionPrinter const& ); - public: - AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages ) - : stream( _stream ) - , stats( _stats ) - , result( _stats.assertionResult ) - , messages( _stats.infoMessages ) - , itMessage( _stats.infoMessages.begin() ) - , printInfoMessages( _printInfoMessages ) - {} - - void print() { - printSourceInfo(); - - itMessage = messages.begin(); - - switch( result.getResultType() ) { - case ResultWas::Ok: - printResultType( Colour::ResultSuccess, passedString() ); - printOriginalExpression(); - printReconstructedExpression(); - if ( ! result.hasExpression() ) - printRemainingMessages( Colour::None ); - else - printRemainingMessages(); - break; - case ResultWas::ExpressionFailed: - if( result.isOk() ) - printResultType( Colour::ResultSuccess, failedString() + std::string( " - but was ok" ) ); - else - printResultType( Colour::Error, failedString() ); - printOriginalExpression(); - printReconstructedExpression(); - printRemainingMessages(); - break; - case ResultWas::ThrewException: - printResultType( Colour::Error, failedString() ); - printIssue( "unexpected exception with message:" ); - printMessage(); - printExpressionWas(); - printRemainingMessages(); - break; - case ResultWas::FatalErrorCondition: - printResultType( Colour::Error, failedString() ); - printIssue( "fatal error condition with message:" ); - printMessage(); - printExpressionWas(); - printRemainingMessages(); - break; - case ResultWas::DidntThrowException: - printResultType( Colour::Error, failedString() ); - printIssue( "expected exception, got none" ); - printExpressionWas(); - printRemainingMessages(); - break; - case ResultWas::Info: - printResultType( Colour::None, "info" ); - printMessage(); - printRemainingMessages(); - break; - case ResultWas::Warning: - printResultType( Colour::None, "warning" ); - printMessage(); - printRemainingMessages(); - break; - case ResultWas::ExplicitFailure: - printResultType( Colour::Error, failedString() ); - printIssue( "explicitly" ); - printRemainingMessages( Colour::None ); - break; - // These cases are here to prevent compiler warnings - case ResultWas::Unknown: - case ResultWas::FailureBit: - case ResultWas::Exception: - printResultType( Colour::Error, "** internal error **" ); - break; - } - } - - private: - // Colour::LightGrey - - static Colour::Code dimColour() { return Colour::FileName; } - -#ifdef CATCH_PLATFORM_MAC - static const char* failedString() { return "FAILED"; } - static const char* passedString() { return "PASSED"; } -#else - static const char* failedString() { return "failed"; } - static const char* passedString() { return "passed"; } -#endif - - void printSourceInfo() const { - Colour colourGuard( Colour::FileName ); - stream << result.getSourceInfo() << ':'; - } - - void printResultType( Colour::Code colour, std::string const& passOrFail ) const { - if( !passOrFail.empty() ) { - { - Colour colourGuard( colour ); - stream << ' ' << passOrFail; - } - stream << ':'; - } - } - - void printIssue( std::string const& issue ) const { - stream << ' ' << issue; - } - - void printExpressionWas() { - if( result.hasExpression() ) { - stream << ';'; - { - Colour colour( dimColour() ); - stream << " expression was:"; - } - printOriginalExpression(); - } - } - - void printOriginalExpression() const { - if( result.hasExpression() ) { - stream << ' ' << result.getExpression(); - } - } - - void printReconstructedExpression() const { - if( result.hasExpandedExpression() ) { - { - Colour colour( dimColour() ); - stream << " for: "; - } - stream << result.getExpandedExpression(); - } - } - - void printMessage() { - if ( itMessage != messages.end() ) { - stream << " '" << itMessage->message << '\''; - ++itMessage; - } - } - - void printRemainingMessages( Colour::Code colour = dimColour() ) { - if ( itMessage == messages.end() ) - return; - - // using messages.end() directly yields compilation error: - std::vector::const_iterator itEnd = messages.end(); - const std::size_t N = static_cast( std::distance( itMessage, itEnd ) ); - - { - Colour colourGuard( colour ); - stream << " with " << pluralise( N, "message" ) << ':'; - } - - for(; itMessage != itEnd; ) { - // If this assertion is a warning ignore any INFO messages - if( printInfoMessages || itMessage->type != ResultWas::Info ) { - stream << " '" << itMessage->message << '\''; - if ( ++itMessage != itEnd ) { - Colour colourGuard( dimColour() ); - stream << " and"; - } - } - } - } - - private: - std::ostream& stream; - AssertionStats const& stats; - AssertionResult const& result; - std::vector messages; - std::vector::const_iterator itMessage; - bool printInfoMessages; - }; - - // Colour, message variants: - // - white: No tests ran. - // - red: Failed [both/all] N test cases, failed [both/all] M assertions. - // - white: Passed [both/all] N test cases (no assertions). - // - red: Failed N tests cases, failed M assertions. - // - green: Passed [both/all] N tests cases with M assertions. - - std::string bothOrAll( std::size_t count ) const { - return count == 1 ? std::string() : count == 2 ? "both " : "all " ; - } - - void printTotals( const Totals& totals ) const { - if( totals.testCases.total() == 0 ) { - stream << "No tests ran."; - } - else if( totals.testCases.failed == totals.testCases.total() ) { - Colour colour( Colour::ResultError ); - const std::string qualify_assertions_failed = - totals.assertions.failed == totals.assertions.total() ? - bothOrAll( totals.assertions.failed ) : std::string(); - stream << - "Failed " << bothOrAll( totals.testCases.failed ) - << pluralise( totals.testCases.failed, "test case" ) << ", " - "failed " << qualify_assertions_failed << - pluralise( totals.assertions.failed, "assertion" ) << '.'; - } - else if( totals.assertions.total() == 0 ) { - stream << - "Passed " << bothOrAll( totals.testCases.total() ) - << pluralise( totals.testCases.total(), "test case" ) - << " (no assertions)."; - } - else if( totals.assertions.failed ) { - Colour colour( Colour::ResultError ); - stream << - "Failed " << pluralise( totals.testCases.failed, "test case" ) << ", " - "failed " << pluralise( totals.assertions.failed, "assertion" ) << '.'; - } - else { - Colour colour( Colour::ResultSuccess ); - stream << - "Passed " << bothOrAll( totals.testCases.passed ) - << pluralise( totals.testCases.passed, "test case" ) << - " with " << pluralise( totals.assertions.passed, "assertion" ) << '.'; - } - } - }; - - INTERNAL_CATCH_REGISTER_REPORTER( "compact", CompactReporter ) - -} // end namespace Catch - -namespace Catch { - // These are all here to avoid warnings about not having any out of line - // virtual methods - NonCopyable::~NonCopyable() {} - IShared::~IShared() {} - IStream::~IStream() CATCH_NOEXCEPT {} - FileStream::~FileStream() CATCH_NOEXCEPT {} - CoutStream::~CoutStream() CATCH_NOEXCEPT {} - DebugOutStream::~DebugOutStream() CATCH_NOEXCEPT {} - StreamBufBase::~StreamBufBase() CATCH_NOEXCEPT {} - IContext::~IContext() {} - IResultCapture::~IResultCapture() {} - ITestCase::~ITestCase() {} - ITestCaseRegistry::~ITestCaseRegistry() {} - IRegistryHub::~IRegistryHub() {} - IMutableRegistryHub::~IMutableRegistryHub() {} - IExceptionTranslator::~IExceptionTranslator() {} - IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() {} - IReporter::~IReporter() {} - IReporterFactory::~IReporterFactory() {} - IReporterRegistry::~IReporterRegistry() {} - IStreamingReporter::~IStreamingReporter() {} - AssertionStats::~AssertionStats() {} - SectionStats::~SectionStats() {} - TestCaseStats::~TestCaseStats() {} - TestGroupStats::~TestGroupStats() {} - TestRunStats::~TestRunStats() {} - CumulativeReporterBase::SectionNode::~SectionNode() {} - CumulativeReporterBase::~CumulativeReporterBase() {} - - StreamingReporterBase::~StreamingReporterBase() {} - ConsoleReporter::~ConsoleReporter() {} - CompactReporter::~CompactReporter() {} - IRunner::~IRunner() {} - IMutableContext::~IMutableContext() {} - IConfig::~IConfig() {} - XmlReporter::~XmlReporter() {} - JunitReporter::~JunitReporter() {} - TestRegistry::~TestRegistry() {} - FreeFunctionTestCase::~FreeFunctionTestCase() {} - IGeneratorInfo::~IGeneratorInfo() {} - IGeneratorsForTest::~IGeneratorsForTest() {} - WildcardPattern::~WildcardPattern() {} - TestSpec::Pattern::~Pattern() {} - TestSpec::NamePattern::~NamePattern() {} - TestSpec::TagPattern::~TagPattern() {} - TestSpec::ExcludedPattern::~ExcludedPattern() {} - Matchers::Impl::MatcherUntypedBase::~MatcherUntypedBase() {} - - void Config::dummy() {} - - namespace TestCaseTracking { - ITracker::~ITracker() {} - TrackerBase::~TrackerBase() {} - SectionTracker::~SectionTracker() {} - IndexTracker::~IndexTracker() {} - } -} - -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - -#endif - -#ifdef CATCH_CONFIG_MAIN -// #included from: internal/catch_default_main.hpp -#define TWOBLUECUBES_CATCH_DEFAULT_MAIN_HPP_INCLUDED - -#ifndef __OBJC__ - -#if defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN) -// Standard C/C++ Win32 Unicode wmain entry point -extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) { -#else -// Standard C/C++ main entry point -int main (int argc, char * argv[]) { -#endif - - int result = Catch::Session().run( argc, argv ); - return ( result < 0xff ? result : 0xff ); -} - -#else // __OBJC__ - -// Objective-C entry point -int main (int argc, char * const argv[]) { -#if !CATCH_ARC_ENABLED - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; -#endif - - Catch::registerTestMethods(); - int result = Catch::Session().run( argc, (char* const*)argv ); - -#if !CATCH_ARC_ENABLED - [pool drain]; -#endif - - return ( result < 0xff ? result : 0xff ); -} - -#endif // __OBJC__ - -#endif - -#ifdef CLARA_CONFIG_MAIN_NOT_DEFINED -# undef CLARA_CONFIG_MAIN -#endif - -////// - -// If this config identifier is defined then all CATCH macros are prefixed with CATCH_ -#ifdef CATCH_CONFIG_PREFIX_ALL - -#if defined(CATCH_CONFIG_FAST_COMPILE) -#define CATCH_REQUIRE( expr ) INTERNAL_CATCH_TEST_NO_TRY( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, expr ) -#define CATCH_REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST_NO_TRY( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, expr ) -#else -#define CATCH_REQUIRE( expr ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, expr ) -#define CATCH_REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, expr ) -#endif - -#define CATCH_REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", expr ) -#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr ) -#define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) -#define CATCH_REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, expr ) - -#define CATCH_CHECK( expr ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, expr ) -#define CATCH_CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, expr ) -#define CATCH_CHECKED_IF( expr ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, expr ) -#define CATCH_CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, expr ) -#define CATCH_CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, expr ) - -#define CATCH_CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", expr ) -#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr ) -#define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) -#define CATCH_CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, expr ) - -#define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg ) - -#if defined(CATCH_CONFIG_FAST_COMPILE) -#define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT_NO_TRY( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) -#else -#define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) -#endif - -#define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg ) -#define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg ) -#define CATCH_SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg ) -#define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CATCH_CAPTURE", #msg " := " << Catch::toString(msg) ) -#define CATCH_SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CATCH_CAPTURE", #msg " := " << Catch::toString(msg) ) - -#ifdef CATCH_CONFIG_VARIADIC_MACROS - #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) - #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) - #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) - #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) - #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) - #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ ) - #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) - #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) -#else - #define CATCH_TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description ) - #define CATCH_TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description ) - #define CATCH_METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description ) - #define CATCH_REGISTER_TEST_CASE( function, name, description ) INTERNAL_CATCH_REGISTER_TESTCASE( function, name, description ) - #define CATCH_SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description ) - #define CATCH_FAIL( msg ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, msg ) - #define CATCH_FAIL_CHECK( msg ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, msg ) - #define CATCH_SUCCEED( msg ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, msg ) -#endif -#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" ) - -#define CATCH_REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) -#define CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) - -#define CATCH_GENERATE( expr) INTERNAL_CATCH_GENERATE( expr ) - -// "BDD-style" convenience wrappers -#ifdef CATCH_CONFIG_VARIADIC_MACROS -#define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ ) -#define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) -#else -#define CATCH_SCENARIO( name, tags ) CATCH_TEST_CASE( "Scenario: " name, tags ) -#define CATCH_SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " name, tags ) -#endif -#define CATCH_GIVEN( desc ) CATCH_SECTION( std::string( "Given: ") + desc, "" ) -#define CATCH_WHEN( desc ) CATCH_SECTION( std::string( " When: ") + desc, "" ) -#define CATCH_AND_WHEN( desc ) CATCH_SECTION( std::string( " And: ") + desc, "" ) -#define CATCH_THEN( desc ) CATCH_SECTION( std::string( " Then: ") + desc, "" ) -#define CATCH_AND_THEN( desc ) CATCH_SECTION( std::string( " And: ") + desc, "" ) - -// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required -#else - -#if defined(CATCH_CONFIG_FAST_COMPILE) -#define REQUIRE( expr ) INTERNAL_CATCH_TEST_NO_TRY( "REQUIRE", Catch::ResultDisposition::Normal, expr ) -#define REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST_NO_TRY( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, expr ) - -#else -#define REQUIRE( expr ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, expr ) -#define REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, expr ) -#endif - -#define REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", expr ) -#define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr ) -#define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) -#define REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, expr ) - -#define CHECK( expr ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, expr ) -#define CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, expr ) -#define CHECKED_IF( expr ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, expr ) -#define CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, expr ) -#define CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, expr ) - -#define CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", expr ) -#define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr ) -#define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) -#define CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, expr ) - -#define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg ) - -#if defined(CATCH_CONFIG_FAST_COMPILE) -#define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT_NO_TRY( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) -#else -#define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) -#endif - -#define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg ) -#define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg ) -#define SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg ) -#define CAPTURE( msg ) INTERNAL_CATCH_INFO( "CAPTURE", #msg " := " << Catch::toString(msg) ) -#define SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CAPTURE", #msg " := " << Catch::toString(msg) ) - -#ifdef CATCH_CONFIG_VARIADIC_MACROS -#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) -#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) -#define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) -#define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) -#define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) -#define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ ) -#define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) -#define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) -#else -#define TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description ) - #define TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description ) - #define METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description ) - #define REGISTER_TEST_CASE( method, name, description ) INTERNAL_CATCH_REGISTER_TESTCASE( method, name, description ) - #define SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description ) - #define FAIL( msg ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, msg ) - #define FAIL_CHECK( msg ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, msg ) - #define SUCCEED( msg ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, msg ) -#endif -#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" ) - -#define REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) -#define REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) - -#define GENERATE( expr) INTERNAL_CATCH_GENERATE( expr ) - -#endif - -#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) - -// "BDD-style" convenience wrappers -#ifdef CATCH_CONFIG_VARIADIC_MACROS -#define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ ) -#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) -#else -#define SCENARIO( name, tags ) TEST_CASE( "Scenario: " name, tags ) -#define SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " name, tags ) -#endif -#define GIVEN( desc ) SECTION( std::string(" Given: ") + desc, "" ) -#define WHEN( desc ) SECTION( std::string(" When: ") + desc, "" ) -#define AND_WHEN( desc ) SECTION( std::string("And when: ") + desc, "" ) -#define THEN( desc ) SECTION( std::string(" Then: ") + desc, "" ) -#define AND_THEN( desc ) SECTION( std::string(" And: ") + desc, "" ) - -using Catch::Detail::Approx; - -// #included from: internal/catch_reenable_warnings.h - -#define TWOBLUECUBES_CATCH_REENABLE_WARNINGS_H_INCLUDED - -#ifdef __clang__ -# ifdef __ICC // icpc defines the __clang__ macro -# pragma warning(pop) -# else -# pragma clang diagnostic pop -# endif -#elif defined __GNUC__ -# pragma GCC diagnostic pop -#endif - -#endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED - diff --git a/src/soci/tests/common-tests.h b/src/soci/tests/common-tests.h deleted file mode 100644 index c899bc1944..0000000000 --- a/src/soci/tests/common-tests.h +++ /dev/null @@ -1,4426 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#ifndef SOCI_COMMON_TESTS_H_INCLUDED -#define SOCI_COMMON_TESTS_H_INCLUDED - -#include "soci/soci.h" - -#ifdef SOCI_HAVE_BOOST -// explicitly pull conversions for Boost's optional, tuple and fusion: -#include -#include "soci/boost-optional.h" -#include "soci/boost-tuple.h" -#include "soci/boost-gregorian-date.h" -#if defined(BOOST_VERSION) && BOOST_VERSION >= 103500 -#include "soci/boost-fusion.h" -#endif // BOOST_VERSION -#endif // SOCI_HAVE_BOOST - -#include "soci-compiler.h" - -#define CATCH_CONFIG_RUNNER -#include - -#if defined(_MSC_VER) && (_MSC_VER < 1500) -#undef SECTION -#define SECTION(name) INTERNAL_CATCH_SECTION(name, "dummy-for-vc8") -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Although SQL standard mandates right padding CHAR(N) values to their length -// with spaces, some backends don't confirm to it: -// -// - Firebird does pad the string but to the byte-size (not character size) of -// the column (i.e. CHAR(10) NONE is padded to 10 bytes but CHAR(10) UTF8 -- -// to 40). -// - For MySql PAD_CHAR_TO_FULL_LENGTH option must be set, otherwise the value -// is trimmed. -// - SQLite never behaves correctly at all. -// -// This method will check result string from column defined as fixed char It -// will check only bytes up to the original string size. If padded string is -// bigger than expected string then all remaining chars must be spaces so if -// any non-space character is found it will fail. -void -checkEqualPadded(const std::string& padded_str, const std::string& expected_str) -{ - size_t const len = expected_str.length(); - std::string const start_str(padded_str, 0, len); - - if (start_str != expected_str) - { - throw soci::soci_error( - "Expected string \"" + expected_str + "\" " - "is different from the padded string \"" + padded_str + "\"" - ); - } - - if (padded_str.length() > len) - { - std::string const end_str(padded_str, len); - if (end_str != std::string(padded_str.length() - len, ' ')) - { - throw soci::soci_error( - "\"" + padded_str + "\" starts with \"" + padded_str + - "\" but non-space characater(s) are found aftewards" - ); - } - } -} - -#define CHECK_EQUAL_PADDED(padded_str, expected_str) \ - CHECK_NOTHROW(checkEqualPadded(padded_str, expected_str)); - -// Objects used later in tests 14,15 -struct PhonebookEntry -{ - std::string name; - std::string phone; -}; - -struct PhonebookEntry2 : public PhonebookEntry -{ -}; - -class PhonebookEntry3 -{ -public: - void setName(std::string const & n) { name_ = n; } - std::string getName() const { return name_; } - - void setPhone(std::string const & p) { phone_ = p; } - std::string getPhone() const { return phone_; } - -public: - std::string name_; - std::string phone_; -}; - -// user-defined object for test26 and test28 -class MyInt -{ -public: - MyInt() : i_() {} - MyInt(int i) : i_(i) {} - void set(int i) { i_ = i; } - int get() const { return i_; } -private: - int i_; -}; - -namespace soci -{ - -// basic type conversion for user-defined type with single base value -template<> struct type_conversion -{ - typedef int base_type; - - static void from_base(int i, indicator ind, MyInt &mi) - { - if (ind == i_ok) - { - mi.set(i); - } - } - - static void to_base(MyInt const &mi, int &i, indicator &ind) - { - i = mi.get(); - ind = i_ok; - } -}; - -// basic type conversion on many values (ORM) -template<> struct type_conversion -{ - typedef soci::values base_type; - - static void from_base(values const &v, indicator /* ind */, PhonebookEntry &pe) - { - // here we ignore the possibility the the whole object might be NULL - pe.name = v.get("NAME"); - pe.phone = v.get("PHONE", ""); - } - - static void to_base(PhonebookEntry const &pe, values &v, indicator &ind) - { - v.set("NAME", pe.name); - v.set("PHONE", pe.phone, pe.phone.empty() ? i_null : i_ok); - ind = i_ok; - } -}; - -// type conversion which directly calls values::get_indicator() -template<> struct type_conversion -{ - typedef soci::values base_type; - - static void from_base(values const &v, indicator /* ind */, PhonebookEntry2 &pe) - { - // here we ignore the possibility the the whole object might be NULL - - pe.name = v.get("NAME"); - indicator ind = v.get_indicator("PHONE"); //another way to test for null - pe.phone = ind == i_null ? "" : v.get("PHONE"); - } - - static void to_base(PhonebookEntry2 const &pe, values &v, indicator &ind) - { - v.set("NAME", pe.name); - v.set("PHONE", pe.phone, pe.phone.empty() ? i_null : i_ok); - ind = i_ok; - } -}; - -template<> struct type_conversion -{ - typedef soci::values base_type; - - static void from_base(values const &v, indicator /* ind */, PhonebookEntry3 &pe) - { - // here we ignore the possibility the the whole object might be NULL - - pe.setName(v.get("NAME")); - pe.setPhone(v.get("PHONE", "")); - } - - static void to_base(PhonebookEntry3 const &pe, values &v, indicator &ind) - { - v.set("NAME", pe.getName()); - v.set("PHONE", pe.getPhone(), pe.getPhone().empty() ? i_null : i_ok); - ind = i_ok; - } -}; - -} // namespace soci - -namespace soci -{ -namespace tests -{ - -// TODO: improve cleanup capabilities by subtypes, soci_test name may be omitted --mloskot -// i.e. optional ctor param accepting custom table name -class table_creator_base -{ -public: - table_creator_base(session& sql) - : msession(sql) { drop(); } - - virtual ~table_creator_base() { drop();} -private: - void drop() - { - try - { - msession << "drop table soci_test"; - } - catch (soci_error const& e) - { - //std::cerr << e.what() << std::endl; - e.what(); - } - } - session& msession; - - SOCI_NOT_COPYABLE(table_creator_base) -}; - -class procedure_creator_base -{ -public: - procedure_creator_base(session& sql) - : msession(sql) { drop(); } - - virtual ~procedure_creator_base() { drop();} -private: - void drop() - { - try { msession << "drop procedure soci_test"; } catch (soci_error&) {} - } - session& msession; - - SOCI_NOT_COPYABLE(procedure_creator_base) -}; - -class function_creator_base -{ -public: - function_creator_base(session& sql) - : msession(sql) { drop(); } - - virtual ~function_creator_base() { drop();} - -protected: - virtual std::string dropstatement() - { - return "drop function soci_test"; - } - -private: - void drop() - { - try { msession << dropstatement(); } catch (soci_error&) {} - } - session& msession; - - SOCI_NOT_COPYABLE(function_creator_base) -}; - -// This is a singleton class, at any given time there is at most one test -// context alive and common_tests fixture class uses it. -class test_context_base -{ -public: - test_context_base(backend_factory const &backEnd, - std::string const &connectString) - : backEndFactory_(backEnd), - connectString_(connectString) - { - // This can't be a CHECK() because the test context is constructed - // outside of any test. - assert(!the_test_context_); - - the_test_context_ = this; - - // To allow running tests in non-default ("C") locale, the following - // environment variable can be set and then the current default locale - // (which can itself be changed by setting LC_ALL environment variable) - // will then be used. - if (std::getenv("SOCI_TEST_USE_LC_ALL")) - std::setlocale(LC_ALL, ""); - } - - static test_context_base const& get_instance() - { - REQUIRE(the_test_context_); - - return *the_test_context_; - } - - backend_factory const & get_backend_factory() const - { - return backEndFactory_; - } - - std::string get_connect_string() const - { - return connectString_; - } - - virtual std::string to_date_time(std::string const &dateTime) const = 0; - - virtual table_creator_base* table_creator_1(session&) const = 0; - virtual table_creator_base* table_creator_2(session&) const = 0; - virtual table_creator_base* table_creator_3(session&) const = 0; - virtual table_creator_base* table_creator_4(session&) const = 0; - - // Override this to return the table creator for a simple table containing - // an integer "id" column and CLOB "s" one. - // - // Returns null by default to indicate that CLOB is not supported. - virtual table_creator_base* table_creator_clob(session&) const { return NULL; } - - // Override this to return the table creator for a simple table containing - // an integer "id" column and XML "x" one. - // - // Returns null by default to indicate that XML is not supported. - virtual table_creator_base* table_creator_xml(session&) const { return NULL; } - - // Return the casts that must be used to convert the between the database - // XML type and the query parameters. - // - // By default no special casts are done. - virtual std::string to_xml(std::string const& x) const { return x; } - virtual std::string from_xml(std::string const& x) const { return x; } - - // Override this if the backend not only supports working with XML values - // (and so returns a non-null value from table_creator_xml()), but the - // database itself has real XML support instead of just allowing to store - // and retrieve XML as text. "Real" support means at least preventing the - // application from storing malformed XML in the database. - virtual bool has_real_xml_support() const { return false; } - - // Override this if the backend doesn't handle floating point values - // correctly, i.e. writing a value and reading it back doesn't return - // *exactly* the same value. - virtual bool has_fp_bug() const { return false; } - - // Override this if the backend doesn't handle multiple active select - // statements at the same time, i.e. a result set must be entirely consumed - // before creating a new one (this is the case of MS SQL without MARS). - virtual bool has_multiple_select_bug() const { return false; } - - // Override this if the backend may not have transactions support. - virtual bool has_transactions_support(session&) const { return true; } - - // Override this if the backend silently truncates string values too long - // to fit by default. - virtual bool has_silent_truncate_bug(session&) const { return false; } - - // Override this to call commit() if it's necessary for the DDL statements - // to be taken into account (currently this is only the case for Firebird). - virtual void on_after_ddl(session&) const { } - - // Put the database in SQL-complient mode for CHAR(N) values, return false - // if it's impossible, i.e. if the database doesn't behave correctly - // whatever we do. - virtual bool enable_std_char_padding(session&) const { return true; } - - // Return the SQL expression giving the length of the specified string, - // i.e. "char_length(s)" in standard SQL but often "len(s)" or "length(s)" - // in practice and sometimes even worse (thanks Oracle). - virtual std::string sql_length(std::string const& s) const = 0; - - virtual ~test_context_base() - { - the_test_context_ = NULL; - } - -private: - backend_factory const &backEndFactory_; - std::string const connectString_; - - static test_context_base* the_test_context_; - - SOCI_NOT_COPYABLE(test_context_base) -}; - -// Currently all tests consist of just a single source file, so we can define -// this member here because this header is included exactly once. -tests::test_context_base* tests::test_context_base::the_test_context_ = NULL; - - -// Compare doubles for approximate equality. This has to be used everywhere -// where we write "3.14" (or "6.28") to the database as a string and then -// compare the value read back with the literal 3.14 floating point constant -// because they are not the same. -// -// It is also used for the backends which currently don't handle doubles -// correctly. -// -// Notice that this function is normally not used directly but rather from the -// macro below. -inline bool are_doubles_approx_equal(double const a, double const b) -{ - // The formula taken from CATCH test framework - // https://github.com/philsquared/Catch/ - // Thanks to Richard Harris for his help refining this formula - double const epsilon(std::numeric_limits::epsilon() * 100); - double const scale(1.0); - return std::fabs(a - b) < epsilon * (scale + (std::max)(std::fabs(a), std::fabs(b))); -} - -// This is a macro to ensure we use the correct line numbers. The weird -// do/while construction is used to make this a statement and the even weirder -// condition in while ensures that the loop is executed exactly once without -// triggering warnings from MSVC about the condition being always false. -#define ASSERT_EQUAL_APPROX(a, b) \ - do { \ - if (!are_doubles_approx_equal((a), (b))) { \ - FAIL( "Approximate equality check failed: " \ - << std::fixed \ - << std::setprecision(std::numeric_limits::digits10 + 1) \ - << (a) << " != " << (b) ); \ - } \ - } while ( (void)0, 0 ) - - -// Exact double comparison function. We need one, instead of writing "a == b", -// only in order to have some place to put the pragmas disabling gcc warnings. -inline bool -are_doubles_exactly_equal(double a, double b) -{ - // Avoid g++ warnings: we do really want the exact equality here. - GCC_WARNING_SUPPRESS(float-equal) - - return a == b; - - GCC_WARNING_RESTORE(float-equal) -} - -#define ASSERT_EQUAL_EXACT(a, b) \ - do { \ - if (!are_doubles_exactly_equal((a), (b))) { \ - FAIL( "Exact equality check failed: " \ - << std::fixed \ - << std::setprecision(std::numeric_limits::digits10 + 1) \ - << (a) << " != " << (b) ); \ - } \ - } while ( (void)0, 0 ) - - -// Compare two floating point numbers either exactly or approximately depending -// on test_context::has_fp_bug() return value. -inline bool -are_doubles_equal(test_context_base const& tc, double a, double b) -{ - return tc.has_fp_bug() - ? are_doubles_approx_equal(a, b) - : are_doubles_exactly_equal(a, b); -} - -// This macro should be used when where we don't have any problems with string -// literals vs floating point literals mismatches described above and would -// ideally compare the numbers exactly but, unfortunately, currently can't do -// this unconditionally because at least some backends are currently buggy and -// don't handle the floating point values correctly. -// -// This can be only used from inside the common_tests class as it relies on -// having an accessible "tc_" variable to determine whether exact or -// approximate comparison should be used. -#define ASSERT_EQUAL(a, b) \ - do { \ - if (!are_doubles_equal(tc_, (a), (b))) { \ - FAIL( "Equality check failed: " \ - << std::fixed \ - << std::setprecision(std::numeric_limits::digits10 + 1) \ - << (a) << " != " << (b) ); \ - } \ - } while ( (void)0, 0 ) - - -class common_tests -{ -public: - common_tests() - : tc_(test_context_base::get_instance()), - backEndFactory_(tc_.get_backend_factory()), - connectString_(tc_.get_connect_string()) - {} - -protected: - test_context_base const & tc_; - backend_factory const &backEndFactory_; - std::string const connectString_; - - SOCI_NOT_COPYABLE(common_tests) -}; - -typedef cxx_details::auto_ptr auto_table_creator; - -// Define the test cases in their own namespace to avoid clashes with the test -// cases defined in individual backend tests: as only line number is used for -// building the name of the "anonymous" function by the TEST_CASE macro, we -// could have a conflict between a test defined here and in some backend if -// they happened to start on the same line. -namespace test_cases -{ - -TEST_CASE_METHOD(common_tests, "Exception on not connected", "[core][exception]") -{ - soci::session sql; // no connection - - // ensure connection is checked, no crash occurs - CHECK_THROWS_AS(sql.begin(), soci_error); - CHECK_THROWS_AS(sql.commit(), soci_error); - CHECK_THROWS_AS(sql.rollback(), soci_error); - CHECK_THROWS_AS(sql.get_backend_name(), soci_error); - CHECK_THROWS_AS(sql.make_statement_backend(), soci_error); - CHECK_THROWS_AS(sql.make_rowid_backend(), soci_error); - CHECK_THROWS_AS(sql.make_blob_backend(), soci_error); - - std::string s; - long l; - CHECK_THROWS_AS(sql.get_next_sequence_value(s, l), soci_error); - CHECK_THROWS_AS(sql.get_last_insert_id(s, l), soci_error); -} - -TEST_CASE_METHOD(common_tests, "Basic functionality", "[core][basics]") -{ - soci::session sql(backEndFactory_, connectString_); - - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - - CHECK_THROWS_AS(sql << "drop table soci_test_nosuchtable", soci_error); - - sql << "insert into soci_test (id) values (" << 123 << ")"; - int id; - sql << "select id from soci_test", into(id); - CHECK(id == 123); - - sql << "insert into soci_test (id) values (" << 234 << ")"; - sql << "insert into soci_test (id) values (" << 345 << ")"; - // Test prepare, execute, fetch correctness - statement st = (sql.prepare << "select id from soci_test", into(id)); - st.execute(); - int count = 0; - while(st.fetch()) - count++; - CHECK(count == 3 ); - bool fetchEnd = st.fetch(); // All the data has been read here so additional fetch must return false - CHECK(fetchEnd == false); -} - -// "into" tests, type conversions, etc. -TEST_CASE_METHOD(common_tests, "Use and into", "[core][into]") -{ - soci::session sql(backEndFactory_, connectString_); - - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - - SECTION("Round trip works for char") - { - char c('a'); - sql << "insert into soci_test(c) values(:c)", use(c); - sql << "select c from soci_test", into(c); - CHECK(c == 'a'); - } - - SECTION("Round trip works for string") - { - std::string helloSOCI("Hello, SOCI!"); - sql << "insert into soci_test(str) values(:s)", use(helloSOCI); - std::string str; - sql << "select str from soci_test", into(str); - CHECK(str == "Hello, SOCI!"); - } - - SECTION("Round trip works for short") - { - short three(3); - sql << "insert into soci_test(sh) values(:id)", use(three); - short sh(0); - sql << "select sh from soci_test", into(sh); - CHECK(sh == 3); - } - - SECTION("Round trip works for int") - { - int five(5); - sql << "insert into soci_test(id) values(:id)", use(five); - int i(0); - sql << "select id from soci_test", into(i); - CHECK(i == 5); - } - - SECTION("Round trip works for unsigned long") - { - unsigned long seven(7); - sql << "insert into soci_test(ul) values(:ul)", use(seven); - unsigned long ul(0); - sql << "select ul from soci_test", into(ul); - CHECK(ul == 7); - } - - SECTION("Round trip works for double") - { - double pi(3.14159265); - sql << "insert into soci_test(d) values(:d)", use(pi); - double d(0.0); - sql << "select d from soci_test", into(d); - ASSERT_EQUAL(d, pi); - } - - SECTION("Round trip works for date without time") - { - std::tm nov15 = std::tm(); - nov15.tm_year = 105; - nov15.tm_mon = 10; - nov15.tm_mday = 15; - nov15.tm_hour = 0; - nov15.tm_min = 0; - nov15.tm_sec = 0; - - sql << "insert into soci_test(tm) values(:tm)", use(nov15); - - std::tm t = std::tm(); - sql << "select tm from soci_test", into(t); - CHECK(t.tm_year == 105); - CHECK(t.tm_mon == 10); - CHECK(t.tm_mday == 15); - CHECK(t.tm_hour == 0); - CHECK(t.tm_min == 0); - CHECK(t.tm_sec == 0); - } - - SECTION("Round trip works for date with time") - { - std::tm nov15 = std::tm(); - nov15.tm_year = 105; - nov15.tm_mon = 10; - nov15.tm_mday = 15; - nov15.tm_hour = 22; - nov15.tm_min = 14; - nov15.tm_sec = 17; - - sql << "insert into soci_test(tm) values(:tm)", use(nov15); - - std::tm t = std::tm(); - sql << "select tm from soci_test", into(t); - CHECK(t.tm_year == 105); - CHECK(t.tm_mon == 10); - CHECK(t.tm_mday == 15); - CHECK(t.tm_hour == 22); - CHECK(t.tm_min == 14); - CHECK(t.tm_sec == 17); - } - - SECTION("Indicator is filled correctly in the simplest case") - { - int id(1); - std::string str("Hello"); - sql << "insert into soci_test(id, str) values(:id, :str)", - use(id), use(str); - - int i; - indicator ind; - sql << "select id from soci_test", into(i, ind); - CHECK(ind == i_ok); - } - - SECTION("Indicators work correctly more generally") - { - sql << "insert into soci_test(id,tm) values(NULL,NULL)"; - int i; - indicator ind; - sql << "select id from soci_test", into(i, ind); - CHECK(ind == i_null); - - // additional test for NULL with std::tm - std::tm t = std::tm(); - sql << "select tm from soci_test", into(t, ind); - CHECK(ind == i_null); - - try - { - // expect error - sql << "select id from soci_test", into(i); - FAIL("expected exception not thrown"); - } - catch (soci_error const &e) - { - CHECK(e.get_error_message() == - "Null value fetched and no indicator defined."); - } - - sql << "select id from soci_test where id = 1000", into(i, ind); - CHECK(sql.got_data() == false); - - // no data expected - sql << "select id from soci_test where id = 1000", into(i); - CHECK(sql.got_data() == false); - - // no data expected, test correct behaviour with use - int id = 1000; - sql << "select id from soci_test where id = :id", use(id), into(i); - CHECK(sql.got_data() == false); - } -} - -// repeated fetch and bulk fetch -TEST_CASE_METHOD(common_tests, "Repeated and bulk fetch", "[core][bulk]") -{ - soci::session sql(backEndFactory_, connectString_); - - // create and populate the test table - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - - SECTION("char") - { - char c; - for (c = 'a'; c <= 'z'; ++c) - { - sql << "insert into soci_test(c) values(\'" << c << "\')"; - } - - int count; - sql << "select count(*) from soci_test", into(count); - CHECK(count == 'z' - 'a' + 1); - - { - char c2 = 'a'; - - statement st = (sql.prepare << - "select c from soci_test order by c", into(c)); - - st.execute(); - while (st.fetch()) - { - CHECK(c == c2); - ++c2; - } - CHECK(c2 == 'a' + count); - } - { - char c2 = 'a'; - - std::vector vec(10); - statement st = (sql.prepare << - "select c from soci_test order by c", into(vec)); - st.execute(); - while (st.fetch()) - { - for (std::size_t i = 0; i != vec.size(); ++i) - { - CHECK(c2 == vec[i]); - ++c2; - } - - vec.resize(10); - } - CHECK(c2 == 'a' + count); - } - - { - // verify an exception is thrown when empty vector is used - std::vector vec; - try - { - sql << "select c from soci_test", into(vec); - FAIL("expected exception not thrown"); - } - catch (soci_error const &e) - { - CHECK(e.get_error_message() == - "Vectors of size 0 are not allowed."); - } - } - - } - - // repeated fetch and bulk fetch of std::string - SECTION("std::string") - { - int const rowsToTest = 10; - for (int i = 0; i != rowsToTest; ++i) - { - std::ostringstream ss; - ss << "Hello_" << i; - - sql << "insert into soci_test(str) values(\'" - << ss.str() << "\')"; - } - - int count; - sql << "select count(*) from soci_test", into(count); - CHECK(count == rowsToTest); - - { - int i = 0; - std::string s; - statement st = (sql.prepare << - "select str from soci_test order by str", into(s)); - - st.execute(); - while (st.fetch()) - { - std::ostringstream ss; - ss << "Hello_" << i; - CHECK(s == ss.str()); - ++i; - } - CHECK(i == rowsToTest); - } - { - int i = 0; - - std::vector vec(4); - statement st = (sql.prepare << - "select str from soci_test order by str", into(vec)); - st.execute(); - while (st.fetch()) - { - for (std::size_t j = 0; j != vec.size(); ++j) - { - std::ostringstream ss; - ss << "Hello_" << i; - CHECK(ss.str() == vec[j]); - ++i; - } - - vec.resize(4); - } - CHECK(i == rowsToTest); - } - } - - SECTION("short") - { - short const rowsToTest = 100; - short sh; - for (sh = 0; sh != rowsToTest; ++sh) - { - sql << "insert into soci_test(sh) values(" << sh << ")"; - } - - int count; - sql << "select count(*) from soci_test", into(count); - CHECK(count == rowsToTest); - - { - short sh2 = 0; - - statement st = (sql.prepare << - "select sh from soci_test order by sh", into(sh)); - - st.execute(); - while (st.fetch()) - { - CHECK(sh == sh2); - ++sh2; - } - CHECK(sh2 == rowsToTest); - } - { - short sh2 = 0; - - std::vector vec(8); - statement st = (sql.prepare << - "select sh from soci_test order by sh", into(vec)); - st.execute(); - while (st.fetch()) - { - for (std::size_t i = 0; i != vec.size(); ++i) - { - CHECK(sh2 == vec[i]); - ++sh2; - } - - vec.resize(8); - } - CHECK(sh2 == rowsToTest); - } - } - - SECTION("int") - { - int const rowsToTest = 100; - int i; - for (i = 0; i != rowsToTest; ++i) - { - sql << "insert into soci_test(id) values(" << i << ")"; - } - - int count; - sql << "select count(*) from soci_test", into(count); - CHECK(count == rowsToTest); - - { - int i2 = 0; - - statement st = (sql.prepare << - "select id from soci_test order by id", into(i)); - - st.execute(); - while (st.fetch()) - { - CHECK(i == i2); - ++i2; - } - CHECK(i2 == rowsToTest); - } - { - // additional test with the use element - - int i2 = 0; - int cond = 0; // this condition is always true - - statement st = (sql.prepare << - "select id from soci_test where id >= :cond order by id", - use(cond), into(i)); - - st.execute(); - while (st.fetch()) - { - CHECK(i == i2); - ++i2; - } - CHECK(i2 == rowsToTest); - } - { - int i2 = 0; - - std::vector vec(8); - statement st = (sql.prepare << - "select id from soci_test order by id", into(vec)); - st.execute(); - while (st.fetch()) - { - for (std::size_t n = 0; n != vec.size(); ++n) - { - CHECK(i2 == vec[n]); - ++i2; - } - - vec.resize(8); - } - CHECK(i2 == rowsToTest); - } - } - - SECTION("unsigned int") - { - unsigned int const rowsToTest = 100; - unsigned int ul; - for (ul = 0; ul != rowsToTest; ++ul) - { - sql << "insert into soci_test(ul) values(" << ul << ")"; - } - - int count; - sql << "select count(*) from soci_test", into(count); - CHECK(count == static_cast(rowsToTest)); - - { - unsigned int ul2 = 0; - - statement st = (sql.prepare << - "select ul from soci_test order by ul", into(ul)); - - st.execute(); - while (st.fetch()) - { - CHECK(ul == ul2); - ++ul2; - } - CHECK(ul2 == rowsToTest); - } - { - unsigned int ul2 = 0; - - std::vector vec(8); - statement st = (sql.prepare << - "select ul from soci_test order by ul", into(vec)); - st.execute(); - while (st.fetch()) - { - for (std::size_t i = 0; i != vec.size(); ++i) - { - CHECK(ul2 == vec[i]); - ++ul2; - } - - vec.resize(8); - } - CHECK(ul2 == rowsToTest); - } - } - - SECTION("double") - { - int const rowsToTest = 100; - double d = 0.0; - - statement sti = (sql.prepare << - "insert into soci_test(d) values(:d)", use(d)); - for (int i = 0; i != rowsToTest; ++i) - { - sti.execute(true); - d += 0.6; - } - - int count; - sql << "select count(*) from soci_test", into(count); - CHECK(count == rowsToTest); - - { - double d2 = 0.0; - int i = 0; - - statement st = (sql.prepare << - "select d from soci_test order by d", into(d)); - - st.execute(); - while (st.fetch()) - { - ASSERT_EQUAL(d, d2); - d2 += 0.6; - ++i; - } - CHECK(i == rowsToTest); - } - { - double d2 = 0.0; - int i = 0; - - std::vector vec(8); - statement st = (sql.prepare << - "select d from soci_test order by d", into(vec)); - st.execute(); - while (st.fetch()) - { - for (std::size_t j = 0; j != vec.size(); ++j) - { - ASSERT_EQUAL(d2, vec[j]); - d2 += 0.6; - ++i; - } - - vec.resize(8); - } - CHECK(i == rowsToTest); - } - } - - SECTION("std::tm") - { - int const rowsToTest = 8; - for (int i = 0; i != rowsToTest; ++i) - { - std::ostringstream ss; - ss << 2000 + i << "-0" << 1 + i << '-' << 20 - i << ' ' - << 15 + i << ':' << 50 - i << ':' << 40 + i; - - sql << "insert into soci_test(id, tm) values(" << i - << ", " << tc_.to_date_time(ss.str()) << ")"; - } - - int count; - sql << "select count(*) from soci_test", into(count); - CHECK(count == rowsToTest); - - { - std::tm t = std::tm(); - int i = 0; - - statement st = (sql.prepare << - "select tm from soci_test order by id", into(t)); - - st.execute(); - while (st.fetch()) - { - CHECK(t.tm_year == 2000 - 1900 + i); - CHECK(t.tm_mon == i); - CHECK(t.tm_mday == 20 - i); - CHECK(t.tm_hour == 15 + i); - CHECK(t.tm_min == 50 - i); - CHECK(t.tm_sec == 40 + i); - - ++i; - } - CHECK(i == rowsToTest); - } - { - int i = 0; - - std::vector vec(3); - statement st = (sql.prepare << - "select tm from soci_test order by id", into(vec)); - st.execute(); - while (st.fetch()) - { - for (std::size_t j = 0; j != vec.size(); ++j) - { - CHECK(vec[j].tm_year == 2000 - 1900 + i); - CHECK(vec[j].tm_mon == i); - CHECK(vec[j].tm_mday == 20 - i); - CHECK(vec[j].tm_hour == 15 + i); - CHECK(vec[j].tm_min == 50 - i); - CHECK(vec[j].tm_sec == 40 + i); - - ++i; - } - - vec.resize(3); - } - CHECK(i == rowsToTest); - } - } -} - -// test for indicators (repeated fetch and bulk) -TEST_CASE_METHOD(common_tests, "Indicators", "[core][indicator]") -{ - soci::session sql(backEndFactory_, connectString_); - - // create and populate the test table - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - { - sql << "insert into soci_test(id, val) values(1, 10)"; - sql << "insert into soci_test(id, val) values(2, 11)"; - sql << "insert into soci_test(id, val) values(3, NULL)"; - sql << "insert into soci_test(id, val) values(4, NULL)"; - sql << "insert into soci_test(id, val) values(5, 12)"; - - { - int val; - indicator ind; - - statement st = (sql.prepare << - "select val from soci_test order by id", into(val, ind)); - - st.execute(); - bool gotData = st.fetch(); - CHECK(gotData); - CHECK(ind == i_ok); - CHECK(val == 10); - gotData = st.fetch(); - CHECK(gotData); - CHECK(ind == i_ok); - CHECK(val == 11); - gotData = st.fetch(); - CHECK(gotData); - CHECK(ind == i_null); - gotData = st.fetch(); - CHECK(gotData); - CHECK(ind == i_null); - gotData = st.fetch(); - CHECK(gotData); - CHECK(ind == i_ok); - CHECK(val == 12); - gotData = st.fetch(); - CHECK(gotData == false); - } - { - std::vector vals(3); - std::vector inds(3); - - statement st = (sql.prepare << - "select val from soci_test order by id", into(vals, inds)); - - st.execute(); - bool gotData = st.fetch(); - CHECK(gotData); - CHECK(vals.size() == 3); - CHECK(inds.size() == 3); - CHECK(inds[0] == i_ok); - CHECK(vals[0] == 10); - CHECK(inds[1] == i_ok); - CHECK(vals[1] == 11); - CHECK(inds[2] == i_null); - gotData = st.fetch(); - CHECK(gotData); - CHECK(vals.size() == 2); - CHECK(inds[0] == i_null); - CHECK(inds[1] == i_ok); - CHECK(vals[1] == 12); - gotData = st.fetch(); - CHECK(gotData == false); - } - - // additional test for "no data" condition - { - std::vector vals(3); - std::vector inds(3); - - statement st = (sql.prepare << - "select val from soci_test where 0 = 1", into(vals, inds)); - - bool gotData = st.execute(true); - CHECK(gotData == false); - - // for convenience, vectors should be truncated - CHECK(vals.empty()); - CHECK(inds.empty()); - - // for even more convenience, fetch should not fail - // but just report end of rowset - // (and vectors should be truncated) - - vals.resize(1); - inds.resize(1); - - gotData = st.fetch(); - CHECK(gotData == false); - CHECK(vals.empty()); - CHECK(inds.empty()); - } - - // additional test for "no data" without prepared statement - { - std::vector vals(3); - std::vector inds(3); - - sql << "select val from soci_test where 0 = 1", - into(vals, inds); - - // vectors should be truncated - CHECK(vals.empty()); - CHECK(inds.empty()); - } - } - -} - -// test for different sizes of data vector and indicators vector -// (library should force ind. vector to have same size as data vector) -TEST_CASE_METHOD(common_tests, "Indicators vector", "[core][indicator][vector]") -{ - soci::session sql(backEndFactory_, connectString_); - - // create and populate the test table - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - { - sql << "insert into soci_test(id, str, val) values(1, 'ten', 10)"; - sql << "insert into soci_test(id, str, val) values(2, 'elf', 11)"; - sql << "insert into soci_test(id, str, val) values(3, NULL, NULL)"; - sql << "insert into soci_test(id, str, val) values(4, NULL, NULL)"; - sql << "insert into soci_test(id, str, val) values(5, 'xii', 12)"; - - { - std::vector vals(4); - std::vector inds; - - statement st = (sql.prepare << - "select val from soci_test order by id", into(vals, inds)); - - st.execute(); - st.fetch(); - CHECK(vals.size() == 4); - CHECK(inds.size() == 4); - vals.resize(3); - st.fetch(); - CHECK(vals.size() == 1); - CHECK(inds.size() == 1); - - std::vector strs(5); - sql << "select str from soci_test order by id", into(strs, inds); - REQUIRE(inds.size() == 5); - CHECK(inds[0] == i_ok); - CHECK(inds[1] == i_ok); - CHECK(inds[2] == i_null); - CHECK(inds[3] == i_null); - CHECK(inds[4] == i_ok); - } - } - -} - -// Note: this functionality is not available with older PostgreSQL -#ifndef SOCI_POSTGRESQL_NOPARAMS - -// "use" tests, type conversions, etc. -TEST_CASE_METHOD(common_tests, "Use type conversion", "[core][use]") -{ - soci::session sql(backEndFactory_, connectString_); - - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - - SECTION("char") - { - char c('a'); - sql << "insert into soci_test(c) values(:c)", use(c); - - c = 'b'; - sql << "select c from soci_test", into(c); - CHECK(c == 'a'); - - } - - SECTION("std::string") - { - std::string s = "Hello SOCI!"; - sql << "insert into soci_test(str) values(:s)", use(s); - - std::string str; - sql << "select str from soci_test", into(str); - - CHECK(str == "Hello SOCI!"); - } - - SECTION("short") - { - short s = 123; - sql << "insert into soci_test(id) values(:id)", use(s); - - short s2 = 0; - sql << "select id from soci_test", into(s2); - - CHECK(s2 == 123); - } - - SECTION("int") - { - int i = -12345678; - sql << "insert into soci_test(id) values(:i)", use(i); - - int i2 = 0; - sql << "select id from soci_test", into(i2); - - CHECK(i2 == -12345678); - } - - SECTION("unsigned long") - { - unsigned long ul = 4000000000ul; - sql << "insert into soci_test(ul) values(:num)", use(ul); - - unsigned long ul2 = 0; - sql << "select ul from soci_test", into(ul2); - - CHECK(ul2 == 4000000000ul); - } - - SECTION("double") - { - double d = 3.14159265; - sql << "insert into soci_test(d) values(:d)", use(d); - - double d2 = 0; - sql << "select d from soci_test", into(d2); - - ASSERT_EQUAL(d2, d); - } - - SECTION("std::tm") - { - std::tm t = std::tm(); - t.tm_year = 105; - t.tm_mon = 10; - t.tm_mday = 19; - t.tm_hour = 21; - t.tm_min = 39; - t.tm_sec = 57; - sql << "insert into soci_test(tm) values(:t)", use(t); - - std::tm t2 = std::tm(); - t2.tm_year = 0; - t2.tm_mon = 0; - t2.tm_mday = 0; - t2.tm_hour = 0; - t2.tm_min = 0; - t2.tm_sec = 0; - - sql << "select tm from soci_test", into(t2); - - CHECK(t.tm_year == 105); - CHECK(t.tm_mon == 10); - CHECK(t.tm_mday == 19); - CHECK(t.tm_hour == 21); - CHECK(t.tm_min == 39); - CHECK(t.tm_sec == 57); - } - - SECTION("repeated use") - { - int i; - statement st = (sql.prepare - << "insert into soci_test(id) values(:id)", use(i)); - - i = 5; - st.execute(true); - i = 6; - st.execute(true); - i = 7; - st.execute(true); - - std::vector v(5); - sql << "select id from soci_test order by id", into(v); - - CHECK(v.size() == 3); - CHECK(v[0] == 5); - CHECK(v[1] == 6); - CHECK(v[2] == 7); - } - - // tests for use of const objects - - SECTION("const char") - { - char const c('a'); - sql << "insert into soci_test(c) values(:c)", use(c); - - char c2 = 'b'; - sql << "select c from soci_test", into(c2); - CHECK(c2 == 'a'); - - } - - SECTION("const std::string") - { - std::string const s = "Hello const SOCI!"; - sql << "insert into soci_test(str) values(:s)", use(s); - - std::string str; - sql << "select str from soci_test", into(str); - - CHECK(str == "Hello const SOCI!"); - } - - SECTION("const short") - { - short const s = 123; - sql << "insert into soci_test(id) values(:id)", use(s); - - short s2 = 0; - sql << "select id from soci_test", into(s2); - - CHECK(s2 == 123); - } - - SECTION("const int") - { - int const i = -12345678; - sql << "insert into soci_test(id) values(:i)", use(i); - - int i2 = 0; - sql << "select id from soci_test", into(i2); - - CHECK(i2 == -12345678); - } - - SECTION("const unsigned long") - { - unsigned long const ul = 4000000000ul; - sql << "insert into soci_test(ul) values(:num)", use(ul); - - unsigned long ul2 = 0; - sql << "select ul from soci_test", into(ul2); - - CHECK(ul2 == 4000000000ul); - } - - SECTION("const double") - { - double const d = 3.14159265; - sql << "insert into soci_test(d) values(:d)", use(d); - - double d2 = 0; - sql << "select d from soci_test", into(d2); - - ASSERT_EQUAL(d2, d); - } - - SECTION("const std::tm") - { - std::tm t = std::tm(); - t.tm_year = 105; - t.tm_mon = 10; - t.tm_mday = 19; - t.tm_hour = 21; - t.tm_min = 39; - t.tm_sec = 57; - std::tm const & ct = t; - sql << "insert into soci_test(tm) values(:t)", use(ct); - - std::tm t2 = std::tm(); - t2.tm_year = 0; - t2.tm_mon = 0; - t2.tm_mday = 0; - t2.tm_hour = 0; - t2.tm_min = 0; - t2.tm_sec = 0; - - sql << "select tm from soci_test", into(t2); - - CHECK(t.tm_year == 105); - CHECK(t.tm_mon == 10); - CHECK(t.tm_mday == 19); - CHECK(t.tm_hour == 21); - CHECK(t.tm_min == 39); - CHECK(t.tm_sec == 57); - } -} - -#endif // SOCI_POSTGRESQL_NOPARAMS - -// test for multiple use (and into) elements -TEST_CASE_METHOD(common_tests, "Multiple use and into", "[core][use][into]") -{ - soci::session sql(backEndFactory_, connectString_); - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - - { - int i1 = 5; - int i2 = 6; - int i3 = 7; - -#ifndef SOCI_POSTGRESQL_NOPARAMS - - sql << "insert into soci_test(i1, i2, i3) values(:i1, :i2, :i3)", - use(i1), use(i2), use(i3); - -#else - // Older PostgreSQL does not support use elements. - - sql << "insert into soci_test(i1, i2, i3) values(5, 6, 7)"; - -#endif // SOCI_POSTGRESQL_NOPARAMS - - i1 = 0; - i2 = 0; - i3 = 0; - sql << "select i1, i2, i3 from soci_test", - into(i1), into(i2), into(i3); - - CHECK(i1 == 5); - CHECK(i2 == 6); - CHECK(i3 == 7); - - // same for vectors - sql << "delete from soci_test"; - - i1 = 0; - i2 = 0; - i3 = 0; - -#ifndef SOCI_POSTGRESQL_NOPARAMS - - statement st = (sql.prepare - << "insert into soci_test(i1, i2, i3) values(:i1, :i2, :i3)", - use(i1), use(i2), use(i3)); - - i1 = 1; - i2 = 2; - i3 = 3; - st.execute(true); - i1 = 4; - i2 = 5; - i3 = 6; - st.execute(true); - i1 = 7; - i2 = 8; - i3 = 9; - st.execute(true); - -#else - // Older PostgreSQL does not support use elements. - - sql << "insert into soci_test(i1, i2, i3) values(1, 2, 3)"; - sql << "insert into soci_test(i1, i2, i3) values(4, 5, 6)"; - sql << "insert into soci_test(i1, i2, i3) values(7, 8, 9)"; - -#endif // SOCI_POSTGRESQL_NOPARAMS - - std::vector v1(5); - std::vector v2(5); - std::vector v3(5); - - sql << "select i1, i2, i3 from soci_test order by i1", - into(v1), into(v2), into(v3); - - CHECK(v1.size() == 3); - CHECK(v2.size() == 3); - CHECK(v3.size() == 3); - CHECK(v1[0] == 1); - CHECK(v1[1] == 4); - CHECK(v1[2] == 7); - CHECK(v2[0] == 2); - CHECK(v2[1] == 5); - CHECK(v2[2] == 8); - CHECK(v3[0] == 3); - CHECK(v3[1] == 6); - CHECK(v3[2] == 9); - } -} - -// Not supported with older PostgreSQL -#ifndef SOCI_POSTGRESQL_NOPARAMS - -// use vector elements -TEST_CASE_METHOD(common_tests, "Use vector", "[core][use][vector]") -{ - soci::session sql(backEndFactory_, connectString_); - - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - - SECTION("char") - { - std::vector v; - v.push_back('a'); - v.push_back('b'); - v.push_back('c'); - v.push_back('d'); - - sql << "insert into soci_test(c) values(:c)", use(v); - - std::vector v2(4); - - sql << "select c from soci_test order by c", into(v2); - CHECK(v2.size() == 4); - CHECK(v2[0] == 'a'); - CHECK(v2[1] == 'b'); - CHECK(v2[2] == 'c'); - CHECK(v2[3] == 'd'); - } - - SECTION("std::string") - { - std::vector v; - v.push_back("ala"); - v.push_back("ma"); - v.push_back("kota"); - - sql << "insert into soci_test(str) values(:s)", use(v); - - std::vector v2(4); - - sql << "select str from soci_test order by str", into(v2); - CHECK(v2.size() == 3); - CHECK(v2[0] == "ala"); - CHECK(v2[1] == "kota"); - CHECK(v2[2] == "ma"); - } - - SECTION("short") - { - std::vector v; - v.push_back(-5); - v.push_back(6); - v.push_back(7); - v.push_back(123); - - sql << "insert into soci_test(sh) values(:sh)", use(v); - - std::vector v2(4); - - sql << "select sh from soci_test order by sh", into(v2); - CHECK(v2.size() == 4); - CHECK(v2[0] == -5); - CHECK(v2[1] == 6); - CHECK(v2[2] == 7); - CHECK(v2[3] == 123); - } - - SECTION("int") - { - std::vector v; - v.push_back(-2000000000); - v.push_back(0); - v.push_back(1); - v.push_back(2000000000); - - sql << "insert into soci_test(id) values(:i)", use(v); - - std::vector v2(4); - - sql << "select id from soci_test order by id", into(v2); - CHECK(v2.size() == 4); - CHECK(v2[0] == -2000000000); - CHECK(v2[1] == 0); - CHECK(v2[2] == 1); - CHECK(v2[3] == 2000000000); - } - - SECTION("unsigned int") - { - std::vector v; - v.push_back(0); - v.push_back(1); - v.push_back(123); - v.push_back(1000); - - sql << "insert into soci_test(ul) values(:ul)", use(v); - - std::vector v2(4); - - sql << "select ul from soci_test order by ul", into(v2); - CHECK(v2.size() == 4); - CHECK(v2[0] == 0); - CHECK(v2[1] == 1); - CHECK(v2[2] == 123); - CHECK(v2[3] == 1000); - } - - SECTION("double") - { - std::vector v; - v.push_back(0); - v.push_back(-0.0001); - v.push_back(0.0001); - v.push_back(3.1415926); - - sql << "insert into soci_test(d) values(:d)", use(v); - - std::vector v2(4); - - sql << "select d from soci_test order by d", into(v2); - CHECK(v2.size() == 4); - ASSERT_EQUAL(v2[0],-0.0001); - ASSERT_EQUAL(v2[1], 0); - ASSERT_EQUAL(v2[2], 0.0001); - ASSERT_EQUAL(v2[3], 3.1415926); - } - - SECTION("std::tm") - { - std::vector v; - std::tm t = std::tm(); - t.tm_year = 105; - t.tm_mon = 10; - t.tm_mday = 26; - t.tm_hour = 22; - t.tm_min = 45; - t.tm_sec = 17; - - v.push_back(t); - - t.tm_sec = 37; - v.push_back(t); - - t.tm_mday = 25; - v.push_back(t); - - sql << "insert into soci_test(tm) values(:t)", use(v); - - std::vector v2(4); - - sql << "select tm from soci_test order by tm", into(v2); - CHECK(v2.size() == 3); - CHECK(v2[0].tm_year == 105); - CHECK(v2[0].tm_mon == 10); - CHECK(v2[0].tm_mday == 25); - CHECK(v2[0].tm_hour == 22); - CHECK(v2[0].tm_min == 45); - CHECK(v2[0].tm_sec == 37); - CHECK(v2[1].tm_year == 105); - CHECK(v2[1].tm_mon == 10); - CHECK(v2[1].tm_mday == 26); - CHECK(v2[1].tm_hour == 22); - CHECK(v2[1].tm_min == 45); - CHECK(v2[1].tm_sec == 17); - CHECK(v2[2].tm_year == 105); - CHECK(v2[2].tm_mon == 10); - CHECK(v2[2].tm_mday == 26); - CHECK(v2[2].tm_hour == 22); - CHECK(v2[2].tm_min == 45); - CHECK(v2[2].tm_sec == 37); - } - - SECTION("const int") - { - std::vector v; - v.push_back(-2000000000); - v.push_back(0); - v.push_back(1); - v.push_back(2000000000); - - std::vector const & cv = v; - - sql << "insert into soci_test(id) values(:i)", use(cv); - - std::vector v2(4); - - sql << "select id from soci_test order by id", into(v2); - CHECK(v2.size() == 4); - CHECK(v2[0] == -2000000000); - CHECK(v2[1] == 0); - CHECK(v2[2] == 1); - CHECK(v2[3] == 2000000000); - } -} - -// test for named binding -TEST_CASE_METHOD(common_tests, "Named parameters", "[core][use][named-params]") -{ - soci::session sql(backEndFactory_, connectString_); - { - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - - int i1 = 7; - int i2 = 8; - - // verify the exception is thrown if both by position - // and by name use elements are specified - try - { - sql << "insert into soci_test(i1, i2) values(:i1, :i2)", - use(i1, "i1"), use(i2); - - FAIL("expected exception not thrown"); - } - catch (soci_error const& e) - { - CHECK(e.get_error_message() == - "Binding for use elements must be either by position " - "or by name."); - } - - // normal test - sql << "insert into soci_test(i1, i2) values(:i1, :i2)", - use(i1, "i1"), use(i2, "i2"); - - i1 = 0; - i2 = 0; - sql << "select i1, i2 from soci_test", into(i1), into(i2); - CHECK(i1 == 7); - CHECK(i2 == 8); - - i2 = 0; - sql << "select i2 from soci_test where i1 = :i1", into(i2), use(i1); - CHECK(i2 == 8); - - sql << "delete from soci_test"; - - // test vectors - - std::vector v1; - v1.push_back(1); - v1.push_back(2); - v1.push_back(3); - - std::vector v2; - v2.push_back(4); - v2.push_back(5); - v2.push_back(6); - - sql << "insert into soci_test(i1, i2) values(:i1, :i2)", - use(v1, "i1"), use(v2, "i2"); - - sql << "select i2, i1 from soci_test order by i1 desc", - into(v1), into(v2); - CHECK(v1.size() == 3); - CHECK(v2.size() == 3); - CHECK(v1[0] == 6); - CHECK(v1[1] == 5); - CHECK(v1[2] == 4); - CHECK(v2[0] == 3); - CHECK(v2[1] == 2); - CHECK(v2[2] == 1); - } -} - -#endif // SOCI_POSTGRESQL_NOPARAMS - -// transaction test -TEST_CASE_METHOD(common_tests, "Transactions", "[core][transaction]") -{ - soci::session sql(backEndFactory_, connectString_); - - if (!tc_.has_transactions_support(sql)) - { - WARN("Transactions not supported by the database, skipping the test."); - return; - } - - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - - int count; - sql << "select count(*) from soci_test", into(count); - CHECK(count == 0); - - { - transaction tr(sql); - - sql << "insert into soci_test (id, name) values(1, 'John')"; - sql << "insert into soci_test (id, name) values(2, 'Anna')"; - sql << "insert into soci_test (id, name) values(3, 'Mike')"; - - tr.commit(); - } - { - transaction tr(sql); - - sql << "select count(*) from soci_test", into(count); - CHECK(count == 3); - - sql << "insert into soci_test (id, name) values(4, 'Stan')"; - - sql << "select count(*) from soci_test", into(count); - CHECK(count == 4); - - tr.rollback(); - - sql << "select count(*) from soci_test", into(count); - CHECK(count == 3); - } - { - transaction tr(sql); - - sql << "delete from soci_test"; - - sql << "select count(*) from soci_test", into(count); - CHECK(count == 0); - - tr.rollback(); - - sql << "select count(*) from soci_test", into(count); - CHECK(count == 3); - } - { - // additional test for detection of double commit - transaction tr(sql); - tr.commit(); - try - { - tr.commit(); - FAIL("expected exception not thrown"); - } - catch (soci_error const &e) - { - CHECK(e.get_error_message() == - "The transaction object cannot be handled twice."); - } - } -} - -#ifndef SOCI_POSTGRESQL_NOPARAMS - -std::tm generate_tm() -{ - std::tm t = std::tm(); - t.tm_year = 105; - t.tm_mon = 10; - t.tm_mday = 15; - t.tm_hour = 22; - t.tm_min = 14; - t.tm_sec = 17; - return t; -} - -// test of use elements with indicators -TEST_CASE_METHOD(common_tests, "Use with indicators", "[core][use][indicator]") -{ - soci::session sql(backEndFactory_, connectString_); - - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - - indicator ind1 = i_ok; - indicator ind2 = i_ok; - indicator ind3 = i_ok; - - int id = 1; - int val = 10; - char const* insert = "insert into soci_test(id, val, tm) values(:id, :val, :tm)"; - sql << insert, use(id, ind1), use(val, ind2), use(generate_tm(), ind3); - - id = 2; - val = 11; - ind2 = i_null; - std::tm tm = std::tm(); - ind3 = i_null; - - sql << "insert into soci_test(id, val, tm) values(:id, :val, :tm)", - use(id, ind1), use(val, ind2), use(tm, ind3); - - sql << "select val from soci_test where id = 1", into(val, ind2); - CHECK(ind2 == i_ok); - CHECK(val == 10); - sql << "select val, tm from soci_test where id = 2", into(val, ind2), into(tm, ind3); - CHECK(ind2 == i_null); - CHECK(ind3 == i_null); - - std::vector ids; - ids.push_back(3); - ids.push_back(4); - ids.push_back(5); - std::vector vals; - vals.push_back(12); - vals.push_back(13); - vals.push_back(14); - std::vector inds; - inds.push_back(i_ok); - inds.push_back(i_null); - inds.push_back(i_ok); - - sql << "insert into soci_test(id, val) values(:id, :val)", - use(ids), use(vals, inds); - - ids.resize(5); - vals.resize(5); - sql << "select id, val from soci_test order by id desc", - into(ids), into(vals, inds); - - CHECK(ids.size() == 5); - CHECK(ids[0] == 5); - CHECK(ids[1] == 4); - CHECK(ids[2] == 3); - CHECK(ids[3] == 2); - CHECK(ids[4] == 1); - CHECK(inds.size() == 5); - CHECK(inds[0] == i_ok); - CHECK(inds[1] == i_null); - CHECK(inds[2] == i_ok); - CHECK(inds[3] == i_null); - CHECK(inds[4] == i_ok); - CHECK(vals.size() == 5); - CHECK(vals[0] == 14); - CHECK(vals[2] == 12); - CHECK(vals[4] == 10); -} - -#endif // SOCI_POSTGRESQL_NOPARAMS - -// Dynamic binding to Row objects -TEST_CASE_METHOD(common_tests, "Dynamic row binding", "[core][dynamic]") -{ - soci::session sql(backEndFactory_, connectString_); - - sql.uppercase_column_names(true); - - auto_table_creator tableCreator(tc_.table_creator_2(sql)); - - row r; - sql << "select * from soci_test", into(r); - CHECK(sql.got_data() == false); - - sql << "insert into soci_test" - " values(3.14, 123, \'Johny\'," - << tc_.to_date_time("2005-12-19 22:14:17") - << ", 'a')"; - - // select into a row - { - statement st = (sql.prepare << - "select * from soci_test", into(r)); - st.execute(true); - CHECK(r.size() == 5); - - CHECK(r.get_properties(0).get_data_type() == dt_double); - CHECK(r.get_properties(1).get_data_type() == dt_integer); - CHECK(r.get_properties(2).get_data_type() == dt_string); - CHECK(r.get_properties(3).get_data_type() == dt_date); - - // type char is visible as string - // - to comply with the implementation for Oracle - CHECK(r.get_properties(4).get_data_type() == dt_string); - - CHECK(r.get_properties("NUM_INT").get_data_type() == dt_integer); - - CHECK(r.get_properties(0).get_name() == "NUM_FLOAT"); - CHECK(r.get_properties(1).get_name() == "NUM_INT"); - CHECK(r.get_properties(2).get_name() == "NAME"); - CHECK(r.get_properties(3).get_name() == "SOMETIME"); - CHECK(r.get_properties(4).get_name() == "CHR"); - - ASSERT_EQUAL_APPROX(r.get(0), 3.14); - CHECK(r.get(1) == 123); - CHECK(r.get(2) == "Johny"); - CHECK(r.get(3).tm_year == 105); - - // again, type char is visible as string - CHECK_EQUAL_PADDED(r.get(4), "a"); - - ASSERT_EQUAL_APPROX(r.get("NUM_FLOAT"), 3.14); - CHECK(r.get("NUM_INT") == 123); - CHECK(r.get("NAME") == "Johny"); - CHECK_EQUAL_PADDED(r.get("CHR"), "a"); - - CHECK(r.get_indicator(0) == i_ok); - - // verify exception thrown on invalid get<> - bool caught = false; - try - { - r.get(0); - } - catch (std::bad_cast const &) - { - caught = true; - } - CHECK(caught); - - // additional test for stream-like extraction - { - double d; - int i; - std::string s; - std::tm t = std::tm(); - std::string c; - - r >> d >> i >> s >> t >> c; - - ASSERT_EQUAL_APPROX(d, 3.14); - CHECK(i == 123); - CHECK(s == "Johny"); - CHECK(t.tm_year == 105); - CHECK(t.tm_mon == 11); - CHECK(t.tm_mday == 19); - CHECK(t.tm_hour == 22); - CHECK(t.tm_min == 14); - CHECK(t.tm_sec == 17); - CHECK_EQUAL_PADDED(c, "a"); - } - } - - // additional test to check if the row object can be - // reused between queries - { - sql << "select * from soci_test", into(r); - - CHECK(r.size() == 5); - - CHECK(r.get_properties(0).get_data_type() == dt_double); - CHECK(r.get_properties(1).get_data_type() == dt_integer); - CHECK(r.get_properties(2).get_data_type() == dt_string); - CHECK(r.get_properties(3).get_data_type() == dt_date); - - sql << "select name, num_int from soci_test", into(r); - - CHECK(r.size() == 2); - - CHECK(r.get_properties(0).get_data_type() == dt_string); - CHECK(r.get_properties(1).get_data_type() == dt_integer); - } -} - -// more dynamic bindings -TEST_CASE_METHOD(common_tests, "Dynamic row binding 2", "[core][dynamic]") -{ - soci::session sql(backEndFactory_, connectString_); - - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - - sql << "insert into soci_test(id, val) values(1, 10)"; - sql << "insert into soci_test(id, val) values(2, 20)"; - sql << "insert into soci_test(id, val) values(3, 30)"; - -#ifndef SOCI_POSTGRESQL_NOPARAMS - { - int id = 2; - row r; - sql << "select val from soci_test where id = :id", use(id), into(r); - - CHECK(r.size() == 1); - CHECK(r.get_properties(0).get_data_type() == dt_integer); - CHECK(r.get(0) == 20); - } - { - int id; - row r; - statement st = (sql.prepare << - "select val from soci_test where id = :id", use(id), into(r)); - - id = 2; - st.execute(true); - CHECK(r.size() == 1); - CHECK(r.get_properties(0).get_data_type() == dt_integer); - CHECK(r.get(0) == 20); - - id = 3; - st.execute(true); - CHECK(r.size() == 1); - CHECK(r.get_properties(0).get_data_type() == dt_integer); - CHECK(r.get(0) == 30); - - id = 1; - st.execute(true); - CHECK(r.size() == 1); - CHECK(r.get_properties(0).get_data_type() == dt_integer); - CHECK(r.get(0) == 10); - } -#else - { - row r; - sql << "select val from soci_test where id = 2", into(r); - - CHECK(r.size() == 1); - CHECK(r.get_properties(0).get_data_type() == dt_integer); - CHECK(r.get(0) == 20); - } -#endif // SOCI_POSTGRESQL_NOPARAMS -} - -// More Dynamic binding to row objects -TEST_CASE_METHOD(common_tests, "Dynamic row binding 3", "[core][dynamic]") -{ - soci::session sql(backEndFactory_, connectString_); - - sql.uppercase_column_names(true); - - auto_table_creator tableCreator(tc_.table_creator_3(sql)); - - row r1; - sql << "select * from soci_test", into(r1); - CHECK(sql.got_data() == false); - - sql << "insert into soci_test values('david', '(404)123-4567')"; - sql << "insert into soci_test values('john', '(404)123-4567')"; - sql << "insert into soci_test values('doe', '(404)123-4567')"; - - row r2; - statement st = (sql.prepare << "select * from soci_test", into(r2)); - st.execute(); - - CHECK(r2.size() == 2); - - int count = 0; - while (st.fetch()) - { - ++count; - CHECK(r2.get("PHONE") == "(404)123-4567"); - } - CHECK(count == 3); -} - -// This is like the previous test but with a type_conversion instead of a row -TEST_CASE_METHOD(common_tests, "Dynamic binding with type conversions", "[core][dynamic][type_conversion]") -{ - soci::session sql(backEndFactory_, connectString_); - - sql.uppercase_column_names(true); - - SECTION("simple conversions") - { - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - - SECTION("between single basic type and user type") - { - MyInt mi; - mi.set(123); - sql << "insert into soci_test(id) values(:id)", use(mi); - - int i; - sql << "select id from soci_test", into(i); - CHECK(i == 123); - - sql << "update soci_test set id = id + 1"; - - sql << "select id from soci_test", into(mi); - CHECK(mi.get() == 124); - } - - SECTION("with use const") - { - MyInt mi; - mi.set(123); - - MyInt const & cmi = mi; - sql << "insert into soci_test(id) values(:id)", use(cmi); - - int i; - sql << "select id from soci_test", into(i); - CHECK(i == 123); - } - } - - SECTION("ORM conversions") - { - auto_table_creator tableCreator(tc_.table_creator_3(sql)); - - SECTION("conversions based on values") - { - PhonebookEntry p1; - sql << "select * from soci_test", into(p1); - CHECK(p1.name == ""); - CHECK(p1.phone == ""); - - p1.name = "david"; - - // Note: uppercase column names are used here (and later on) - // for consistency with how they can be read from database - // (which means forced to uppercase on Oracle) and how they are - // set/get in the type conversion routines for PhonebookEntry. - // In short, IF the database is Oracle, - // then all column names for binding should be uppercase. - sql << "insert into soci_test values(:NAME, :PHONE)", use(p1); - sql << "insert into soci_test values('john', '(404)123-4567')"; - sql << "insert into soci_test values('doe', '(404)123-4567')"; - - PhonebookEntry p2; - statement st = (sql.prepare << "select * from soci_test", into(p2)); - st.execute(); - - int count = 0; - while (st.fetch()) - { - ++count; - if (p2.name == "david") - { - // see type_conversion - CHECK(p2.phone ==""); - } - else - { - CHECK(p2.phone == "(404)123-4567"); - } - } - CHECK(count == 3); - } - - SECTION("conversions based on values with use const") - { - PhonebookEntry p1; - p1.name = "Joe Coder"; - p1.phone = "123-456"; - - PhonebookEntry const & cp1 = p1; - - sql << "insert into soci_test values(:NAME, :PHONE)", use(cp1); - - PhonebookEntry p2; - sql << "select * from soci_test", into(p2); - CHECK(sql.got_data()); - - CHECK(p2.name == "Joe Coder"); - CHECK(p2.phone == "123-456"); - } - - SECTION("conversions based on accessor functions (as opposed to direct variable bindings)") - { - PhonebookEntry3 p1; - p1.setName("Joe Hacker"); - p1.setPhone("10010110"); - - sql << "insert into soci_test values(:NAME, :PHONE)", use(p1); - - PhonebookEntry3 p2; - sql << "select * from soci_test", into(p2); - CHECK(sql.got_data()); - - CHECK(p2.getName() == "Joe Hacker"); - CHECK(p2.getPhone() == "10010110"); - } - - SECTION("PhonebookEntry2 type conversion to test calls to values::get_indicator()") - { - PhonebookEntry2 p1; - sql << "select * from soci_test", into(p1); - CHECK(p1.name == ""); - CHECK(p1.phone == ""); - p1.name = "david"; - - sql << "insert into soci_test values(:NAME, :PHONE)", use(p1); - sql << "insert into soci_test values('john', '(404)123-4567')"; - sql << "insert into soci_test values('doe', '(404)123-4567')"; - - PhonebookEntry2 p2; - statement st = (sql.prepare << "select * from soci_test", into(p2)); - st.execute(); - - int count = 0; - while (st.fetch()) - { - ++count; - if (p2.name == "david") - { - // see type_conversion - CHECK(p2.phone ==""); - } - else - { - CHECK(p2.phone == "(404)123-4567"); - } - } - CHECK(count == 3); - } - } -} - -TEST_CASE_METHOD(common_tests, "Prepared insert with ORM", "[core][orm]") -{ - soci::session sql(backEndFactory_, connectString_); - - sql.uppercase_column_names(true); - auto_table_creator tableCreator(tc_.table_creator_3(sql)); - - PhonebookEntry temp; - PhonebookEntry e1 = { "name1", "phone1" }; - PhonebookEntry e2 = { "name2", "phone2" }; - - //sql << "insert into soci_test values (:NAME, :PHONE)", use(temp); - statement insertStatement = (sql.prepare << "insert into soci_test values (:NAME, :PHONE)", use(temp)); - - temp = e1; - insertStatement.execute(true); - temp = e2; - insertStatement.execute(true); - - int count = 0; - - sql << "select count(*) from soci_test where NAME in ('name1', 'name2')", into(count); - - CHECK(count == 2); -} - -TEST_CASE_METHOD(common_tests, "Partial match with ORM", "[core][orm]") -{ - soci::session sql(backEndFactory_, connectString_); - sql.uppercase_column_names(true); - auto_table_creator tableCreator(tc_.table_creator_3(sql)); - - PhonebookEntry in = { "name1", "phone1" }; - std::string name = "nameA"; - sql << "insert into soci_test values (:NAMED, :PHONE)", use(in), use(name, "NAMED"); - - PhonebookEntry out; - sql << "select * from soci_test where PHONE = 'phone1'", into(out); - CHECK(out.name == "nameA"); - CHECK(out.phone == "phone1"); -} - -TEST_CASE_METHOD(common_tests, "Numeric round trip", "[core][float]") -{ - soci::session sql(backEndFactory_, connectString_); - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - - double d1 = 0.003958, - d2; - - sql << "insert into soci_test(num76) values (:d1)", use(d1); - sql << "select num76 from soci_test", into(d2); - - // The numeric value should make the round trip unchanged, we really want - // to use exact comparisons here. - ASSERT_EQUAL_EXACT(d1, d2); - - // test negative doubles too - sql << "delete from soci_test"; - d1 = -d1; - - sql << "insert into soci_test(num76) values (:d1)", use(d1); - sql << "select num76 from soci_test", into(d2); - - ASSERT_EQUAL_EXACT(d1, d2); -} - -#ifndef SOCI_POSTGRESQL_NOPARAMS - -// test for bulk fetch with single use -TEST_CASE_METHOD(common_tests, "Bulk fetch with single use", "[core][bulk]") -{ - soci::session sql(backEndFactory_, connectString_); - - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - - sql << "insert into soci_test(name, id) values('john', 1)"; - sql << "insert into soci_test(name, id) values('george', 2)"; - sql << "insert into soci_test(name, id) values('anthony', 1)"; - sql << "insert into soci_test(name, id) values('marc', 3)"; - sql << "insert into soci_test(name, id) values('julian', 1)"; - - int code = 1; - std::vector names(10); - sql << "select name from soci_test where id = :id order by name", - into(names), use(code); - - CHECK(names.size() == 3); - CHECK(names[0] == "anthony"); - CHECK(names[1] == "john"); - CHECK(names[2] == "julian"); -} - -#endif // SOCI_POSTGRESQL_NOPARAMS - -// test for basic logging support -TEST_CASE_METHOD(common_tests, "Basic logging support", "[core][logging]") -{ - soci::session sql(backEndFactory_, connectString_); - - std::ostringstream log; - sql.set_log_stream(&log); - - try - { - sql << "drop table soci_test1"; - } - catch (...) {} - - CHECK(sql.get_last_query() == "drop table soci_test1"); - - sql.set_log_stream(NULL); - - try - { - sql << "drop table soci_test2"; - } - catch (...) {} - - CHECK(sql.get_last_query() == "drop table soci_test2"); - - sql.set_log_stream(&log); - - try - { - sql << "drop table soci_test3"; - } - catch (...) {} - - CHECK(sql.get_last_query() == "drop table soci_test3"); - CHECK(log.str() == - "drop table soci_test1\n" - "drop table soci_test3\n"); - -} - -// test for rowset creation and copying -TEST_CASE_METHOD(common_tests, "Rowset creation and copying", "[core][rowset]") -{ - soci::session sql(backEndFactory_, connectString_); - - // create and populate the test table - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - { - // Open empty rowset - rowset rs1 = (sql.prepare << "select * from soci_test"); - CHECK(rs1.begin() == rs1.end()); - } - - { - // Copy construction - rowset rs1 = (sql.prepare << "select * from soci_test"); - rowset rs2(rs1); - rowset rs3(rs1); - rowset rs4(rs3); - - CHECK(rs1.begin() == rs2.begin()); - CHECK(rs1.begin() == rs3.begin()); - CHECK(rs1.end() == rs2.end()); - CHECK(rs1.end() == rs3.end()); - } - - if (!tc_.has_multiple_select_bug()) - { - // Assignment - rowset rs1 = (sql.prepare << "select * from soci_test"); - rowset rs2 = (sql.prepare << "select * from soci_test"); - rowset rs3 = (sql.prepare << "select * from soci_test"); - rs1 = rs2; - rs3 = rs2; - - CHECK(rs1.begin() == rs2.begin()); - CHECK(rs1.begin() == rs3.begin()); - CHECK(rs1.end() == rs2.end()); - CHECK(rs1.end() == rs3.end()); - } -} - -// test for simple iterating using rowset iterator (without reading data) -TEST_CASE_METHOD(common_tests, "Rowset iteration", "[core][rowset]") -{ - soci::session sql(backEndFactory_, connectString_); - - // create and populate the test table - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - { - sql << "insert into soci_test(id, val) values(1, 10)"; - sql << "insert into soci_test(id, val) values(2, 11)"; - sql << "insert into soci_test(id, val) values(3, NULL)"; - sql << "insert into soci_test(id, val) values(4, NULL)"; - sql << "insert into soci_test(id, val) values(5, 12)"; - { - rowset rs = (sql.prepare << "select * from soci_test"); - - CHECK(5 == std::distance(rs.begin(), rs.end())); - } - } - -} - -// test for reading rowset using iterator -TEST_CASE_METHOD(common_tests, "Reading rows from rowset", "[core][row][rowset]") -{ - soci::session sql(backEndFactory_, connectString_); - - sql.uppercase_column_names(true); - - // create and populate the test table - auto_table_creator tableCreator(tc_.table_creator_2(sql)); - { - { - // Empty rowset - rowset rs = (sql.prepare << "select * from soci_test"); - CHECK(0 == std::distance(rs.begin(), rs.end())); - } - - { - // Non-empty rowset - sql << "insert into soci_test values(3.14, 123, \'Johny\'," - << tc_.to_date_time("2005-12-19 22:14:17") - << ", 'a')"; - sql << "insert into soci_test values(6.28, 246, \'Robert\'," - << tc_.to_date_time("2004-10-01 18:44:10") - << ", 'b')"; - - rowset rs = (sql.prepare << "select * from soci_test"); - - rowset::const_iterator it = rs.begin(); - CHECK(it != rs.end()); - - // - // First row - // - row const & r1 = (*it); - - // Properties - CHECK(r1.size() == 5); - CHECK(r1.get_properties(0).get_data_type() == dt_double); - CHECK(r1.get_properties(1).get_data_type() == dt_integer); - CHECK(r1.get_properties(2).get_data_type() == dt_string); - CHECK(r1.get_properties(3).get_data_type() == dt_date); - CHECK(r1.get_properties(4).get_data_type() == dt_string); - CHECK(r1.get_properties("NUM_INT").get_data_type() == dt_integer); - - // Data - - // Since we didn't specify order by in the above query, - // the 2 rows may be returned in either order - // (If we specify order by, we can't do it in a cross db - // compatible way, because the Oracle table for this has been - // created with lower case column names) - - std::string name = r1.get(2); - - if (name == "Johny") - { - ASSERT_EQUAL_APPROX(r1.get(0), 3.14); - CHECK(r1.get(1) == 123); - CHECK(r1.get(2) == "Johny"); - std::tm t1 = std::tm(); - t1 = r1.get(3); - CHECK(t1.tm_year == 105); - CHECK_EQUAL_PADDED(r1.get(4), "a"); - ASSERT_EQUAL_APPROX(r1.get("NUM_FLOAT"), 3.14); - CHECK(r1.get("NUM_INT") == 123); - CHECK(r1.get("NAME") == "Johny"); - CHECK_EQUAL_PADDED(r1.get("CHR"), "a"); - } - else if (name == "Robert") - { - ASSERT_EQUAL(r1.get(0), 6.28); - CHECK(r1.get(1) == 246); - CHECK(r1.get(2) == "Robert"); - std::tm t1 = r1.get(3); - CHECK(t1.tm_year == 104); - CHECK(r1.get(4) == "b"); - ASSERT_EQUAL(r1.get("NUM_FLOAT"), 6.28); - CHECK(r1.get("NUM_INT") == 246); - CHECK(r1.get("NAME") == "Robert"); - CHECK_EQUAL_PADDED(r1.get("CHR"), "b"); - } - else - { - CAPTURE(name); - FAIL("expected \"Johny\" or \"Robert\""); - } - - // - // Iterate to second row - // - ++it; - CHECK(it != rs.end()); - - // - // Second row - // - row const & r2 = (*it); - - // Properties - CHECK(r2.size() == 5); - CHECK(r2.get_properties(0).get_data_type() == dt_double); - CHECK(r2.get_properties(1).get_data_type() == dt_integer); - CHECK(r2.get_properties(2).get_data_type() == dt_string); - CHECK(r2.get_properties(3).get_data_type() == dt_date); - CHECK(r2.get_properties(4).get_data_type() == dt_string); - CHECK(r2.get_properties("NUM_INT").get_data_type() == dt_integer); - - std::string newName = r2.get(2); - CHECK(name != newName); - - if (newName == "Johny") - { - ASSERT_EQUAL_APPROX(r2.get(0), 3.14); - CHECK(r2.get(1) == 123); - CHECK(r2.get(2) == "Johny"); - std::tm t2 = r2.get(3); - CHECK(t2.tm_year == 105); - CHECK(r2.get(4) == "a"); - ASSERT_EQUAL_APPROX(r2.get("NUM_FLOAT"), 3.14); - CHECK(r2.get("NUM_INT") == 123); - CHECK(r2.get("NAME") == "Johny"); - CHECK(r2.get("CHR") == "a"); - } - else if (newName == "Robert") - { - ASSERT_EQUAL_APPROX(r2.get(0), 6.28); - CHECK(r2.get(1) == 246); - CHECK(r2.get(2) == "Robert"); - std::tm t2 = r2.get(3); - CHECK(t2.tm_year == 104); - CHECK_EQUAL_PADDED(r2.get(4), "b"); - ASSERT_EQUAL_APPROX(r2.get("NUM_FLOAT"), 6.28); - CHECK(r2.get("NUM_INT") == 246); - CHECK(r2.get("NAME") == "Robert"); - CHECK_EQUAL_PADDED(r2.get("CHR"), "b"); - } - else - { - CAPTURE(newName); - FAIL("expected \"Johny\" or \"Robert\""); - } - } - - { - // Non-empty rowset with NULL values - sql << "insert into soci_test " - << "(num_int, num_float , name, sometime, chr) " - << "values (0, NULL, NULL, NULL, NULL)"; - - rowset rs = (sql.prepare - << "select num_int, num_float, name, sometime, chr " - << "from soci_test where num_int = 0"); - - rowset::const_iterator it = rs.begin(); - CHECK(it != rs.end()); - - // - // First row - // - row const& r1 = (*it); - - // Properties - CHECK(r1.size() == 5); - CHECK(r1.get_properties(0).get_data_type() == dt_integer); - CHECK(r1.get_properties(1).get_data_type() == dt_double); - CHECK(r1.get_properties(2).get_data_type() == dt_string); - CHECK(r1.get_properties(3).get_data_type() == dt_date); - CHECK(r1.get_properties(4).get_data_type() == dt_string); - - // Data - CHECK(r1.get_indicator(0) == soci::i_ok); - CHECK(r1.get(0) == 0); - CHECK(r1.get_indicator(1) == soci::i_null); - CHECK(r1.get_indicator(2) == soci::i_null); - CHECK(r1.get_indicator(3) == soci::i_null); - CHECK(r1.get_indicator(4) == soci::i_null); - } - } -} - -// test for reading rowset using iterator -TEST_CASE_METHOD(common_tests, "Reading ints from rowset", "[core][rowset]") -{ - soci::session sql(backEndFactory_, connectString_); - - // create and populate the test table - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - { - sql << "insert into soci_test(id) values(1)"; - sql << "insert into soci_test(id) values(2)"; - sql << "insert into soci_test(id) values(3)"; - sql << "insert into soci_test(id) values(4)"; - sql << "insert into soci_test(id) values(5)"; - { - rowset rs = (sql.prepare << "select id from soci_test order by id asc"); - - // 1st row - rowset::const_iterator pos = rs.begin(); - CHECK(1 == (*pos)); - - // 3rd row - std::advance(pos, 2); - CHECK(3 == (*pos)); - - // 5th row - std::advance(pos, 2); - CHECK(5 == (*pos)); - - // The End - ++pos; - CHECK(pos == rs.end()); - } - } - -} - -// test for handling 'use' and reading rowset using iterator -TEST_CASE_METHOD(common_tests, "Reading strings from rowset", "[core][rowset]") -{ - soci::session sql(backEndFactory_, connectString_); - - // create and populate the test table - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - { - sql << "insert into soci_test(str) values('abc')"; - sql << "insert into soci_test(str) values('def')"; - sql << "insert into soci_test(str) values('ghi')"; - sql << "insert into soci_test(str) values('jkl')"; - { - // Expected result in numbers - std::string idle("def"); - rowset rs1 = (sql.prepare - << "select str from soci_test where str = :idle", - use(idle)); - - CHECK(1 == std::distance(rs1.begin(), rs1.end())); - - // Expected result in value - idle = "jkl"; - rowset rs2 = (sql.prepare - << "select str from soci_test where str = :idle", - use(idle)); - - CHECK(idle == *(rs2.begin())); - } - } - -} - -// test for handling troublemaker -TEST_CASE_METHOD(common_tests, "Rowset expected exception", "[core][exception][rowset]") -{ - soci::session sql(backEndFactory_, connectString_); - - // create and populate the test table - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - sql << "insert into soci_test(str) values('abc')"; - - std::string troublemaker; - CHECK_THROWS_AS( - rowset((sql.prepare << "select str from soci_test", into(troublemaker))), - soci_error - ); -} - -// functor for next test -struct THelper -{ - THelper() - : val_() - { - } - void operator()(int i) - { - val_ = i; - } - int val_; -}; - -// test for handling NULL values with expected exception: -// "Null value fetched and no indicator defined." -TEST_CASE_METHOD(common_tests, "NULL expected exception", "[core][exception][null]") -{ - soci::session sql(backEndFactory_, connectString_); - - // create and populate the test table - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - sql << "insert into soci_test(val) values(1)"; - sql << "insert into soci_test(val) values(2)"; - sql << "insert into soci_test(val) values(NULL)"; - sql << "insert into soci_test(val) values(3)"; - - rowset rs = (sql.prepare << "select val from soci_test order by val asc"); - - CHECK_THROWS_AS( std::for_each(rs.begin(), rs.end(), THelper()), soci_error ); -} - -// This is like the first dynamic binding test but with rowset and iterators use -TEST_CASE_METHOD(common_tests, "Dynamic binding with rowset", "[core][dynamic][type_conversion]") -{ - soci::session sql(backEndFactory_, connectString_); - - sql.uppercase_column_names(true); - - { - auto_table_creator tableCreator(tc_.table_creator_3(sql)); - - PhonebookEntry p1; - sql << "select * from soci_test", into(p1); - CHECK(p1.name == ""); - CHECK(p1.phone == ""); - - p1.name = "david"; - - sql << "insert into soci_test values(:NAME, :PHONE)", use(p1); - sql << "insert into soci_test values('john', '(404)123-4567')"; - sql << "insert into soci_test values('doe', '(404)123-4567')"; - - rowset rs = (sql.prepare << "select * from soci_test"); - - int count = 0; - for (rowset::const_iterator it = rs.begin(); it != rs.end(); ++it) - { - ++count; - PhonebookEntry const& p2 = (*it); - if (p2.name == "david") - { - // see type_conversion - CHECK(p2.phone ==""); - } - else - { - CHECK(p2.phone == "(404)123-4567"); - } - } - - CHECK(3 == count); - } -} - -#ifdef SOCI_HAVE_BOOST - -// test for handling NULL values with boost::optional -// (both into and use) -TEST_CASE_METHOD(common_tests, "NULL with optional", "[core][boost][null]") -{ - - soci::session sql(backEndFactory_, connectString_); - - // create and populate the test table - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - { - sql << "insert into soci_test(val) values(7)"; - - { - // verify non-null value is fetched correctly - boost::optional opt; - sql << "select val from soci_test", into(opt); - CHECK(opt.is_initialized()); - CHECK(opt.get() == 7); - - // indicators can be used with optional - // (although that's just a consequence of implementation, - // not an intended feature - but let's test it anyway) - indicator ind; - opt.reset(); - sql << "select val from soci_test", into(opt, ind); - CHECK(opt.is_initialized()); - CHECK(opt.get() == 7); - CHECK(ind == i_ok); - - // verify null value is fetched correctly - sql << "select i1 from soci_test", into(opt); - CHECK(opt.is_initialized() == false); - - // and with indicator - opt = 5; - sql << "select i1 from soci_test", into(opt, ind); - CHECK(opt.is_initialized() == false); - CHECK(ind == i_null); - - // verify non-null is inserted correctly - opt = 3; - sql << "update soci_test set val = :v", use(opt); - int j = 0; - sql << "select val from soci_test", into(j); - CHECK(j == 3); - - // verify null is inserted correctly - opt.reset(); - sql << "update soci_test set val = :v", use(opt); - ind = i_ok; - sql << "select val from soci_test", into(j, ind); - CHECK(ind == i_null); - } - - // vector tests (select) - - { - sql << "delete from soci_test"; - - // simple readout of non-null data - - sql << "insert into soci_test(id, val, str) values(1, 5, \'abc\')"; - sql << "insert into soci_test(id, val, str) values(2, 6, \'def\')"; - sql << "insert into soci_test(id, val, str) values(3, 7, \'ghi\')"; - sql << "insert into soci_test(id, val, str) values(4, 8, null)"; - sql << "insert into soci_test(id, val, str) values(5, 9, \'mno\')"; - - std::vector > v(10); - sql << "select val from soci_test order by val", into(v); - - CHECK(v.size() == 5); - CHECK(v[0].is_initialized()); - CHECK(v[0].get() == 5); - CHECK(v[1].is_initialized()); - CHECK(v[1].get() == 6); - CHECK(v[2].is_initialized()); - CHECK(v[2].get() == 7); - CHECK(v[3].is_initialized()); - CHECK(v[3].get() == 8); - CHECK(v[4].is_initialized()); - CHECK(v[4].get() == 9); - - // readout of nulls - - sql << "update soci_test set val = null where id = 2 or id = 4"; - - std::vector ids(5); - sql << "select id, val from soci_test order by id", into(ids), into(v); - - CHECK(v.size() == 5); - CHECK(ids.size() == 5); - CHECK(v[0].is_initialized()); - CHECK(v[0].get() == 5); - CHECK(v[1].is_initialized() == false); - CHECK(v[2].is_initialized()); - CHECK(v[2].get() == 7); - CHECK(v[3].is_initialized() == false); - CHECK(v[4].is_initialized()); - CHECK(v[4].get() == 9); - - // readout with statement preparation - - int id = 1; - - ids.resize(3); - v.resize(3); - statement st = (sql.prepare << - "select id, val from soci_test order by id", into(ids), into(v)); - st.execute(); - while (st.fetch()) - { - for (std::size_t i = 0; i != v.size(); ++i) - { - CHECK(id == ids[i]); - - if (id == 2 || id == 4) - { - CHECK(v[i].is_initialized() == false); - } - else - { - CHECK(v[i].is_initialized()); - CHECK(v[i].get() == id + 4); - } - - ++id; - } - - ids.resize(3); - v.resize(3); - } - CHECK(id == 6); - } - - // and why not stress iterators and the dynamic binding, too! - - { - rowset rs = (sql.prepare << "select id, val, str from soci_test order by id"); - - rowset::const_iterator it = rs.begin(); - CHECK(it != rs.end()); - - row const& r1 = (*it); - - CHECK(r1.size() == 3); - - // Note: for the reason of differences between number(x,y) type and - // binary representation of integers, the following commented assertions - // do not work for Oracle. - // The problem is that for this single table the data type used in Oracle - // table creator for the id column is number(10,0), - // which allows to insert all int values. - // On the other hand, the column description scheme used in the Oracle - // backend figures out that the natural type for such a column - // is eUnsignedInt - this makes the following assertions fail. - // Other database backends (like PostgreSQL) use other types like int - // and this not only allows to insert all int values (obviously), - // but is also recognized as int (obviously). - // There is a similar problem with stream-like extraction, - // where internally get is called and the type mismatch is detected - // for the id column - that's why the code below skips this column - // and tests the remaining column only. - - //CHECK(r1.get_properties(0).get_data_type() == dt_integer); - CHECK(r1.get_properties(1).get_data_type() == dt_integer); - CHECK(r1.get_properties(2).get_data_type() == dt_string); - //CHECK(r1.get(0) == 1); - CHECK(r1.get(1) == 5); - CHECK(r1.get(2) == "abc"); - CHECK(r1.get >(1).is_initialized()); - CHECK(r1.get >(1).get() == 5); - CHECK(r1.get >(2).is_initialized()); - CHECK(r1.get >(2).get() == "abc"); - - ++it; - - row const& r2 = (*it); - - CHECK(r2.size() == 3); - - // CHECK(r2.get_properties(0).get_data_type() == dt_integer); - CHECK(r2.get_properties(1).get_data_type() == dt_integer); - CHECK(r2.get_properties(2).get_data_type() == dt_string); - //CHECK(r2.get(0) == 2); - try - { - // expect exception here, this is NULL value - (void)r1.get(1); - FAIL("expected exception not thrown"); - } - catch (soci_error const &) {} - - // but we can read it as optional - CHECK(r2.get >(1).is_initialized() == false); - - // stream-like data extraction - - ++it; - row const &r3 = (*it); - - boost::optional io; - boost::optional so; - - r3.skip(); // move to val and str columns - r3 >> io >> so; - - CHECK(io.is_initialized()); - CHECK(io.get() == 7); - CHECK(so.is_initialized()); - CHECK(so.get() == "ghi"); - - ++it; - row const &r4 = (*it); - - r3.skip(); // move to val and str columns - r4 >> io >> so; - - CHECK(io.is_initialized() == false); - CHECK(so.is_initialized() == false); - } - - // bulk inserts of non-null data - - { - sql << "delete from soci_test"; - - std::vector ids; - std::vector > v; - - ids.push_back(10); v.push_back(20); - ids.push_back(11); v.push_back(21); - ids.push_back(12); v.push_back(22); - ids.push_back(13); v.push_back(23); - - sql << "insert into soci_test(id, val) values(:id, :val)", - use(ids, "id"), use(v, "val"); - - int sum; - sql << "select sum(val) from soci_test", into(sum); - CHECK(sum == 86); - - // bulk inserts of some-null data - - sql << "delete from soci_test"; - - v[2].reset(); - v[3].reset(); - - sql << "insert into soci_test(id, val) values(:id, :val)", - use(ids, "id"), use(v, "val"); - - sql << "select sum(val) from soci_test", into(sum); - CHECK(sum == 41); - } - - // composability with user conversions - - { - sql << "delete from soci_test"; - - boost::optional omi1; - boost::optional omi2; - - omi1 = MyInt(125); - omi2.reset(); - - sql << "insert into soci_test(id, val) values(:id, :val)", - use(omi1), use(omi2); - - sql << "select id, val from soci_test", into(omi2), into(omi1); - - CHECK(omi1.is_initialized() == false); - CHECK(omi2.is_initialized()); - CHECK(omi2.get().get() == 125); - } - - // use with const optional and user conversions - - { - sql << "delete from soci_test"; - - boost::optional omi1; - boost::optional omi2; - - omi1 = MyInt(125); - omi2.reset(); - - boost::optional const & comi1 = omi1; - boost::optional const & comi2 = omi2; - - sql << "insert into soci_test(id, val) values(:id, :val)", - use(comi1), use(comi2); - - sql << "select id, val from soci_test", into(omi2), into(omi1); - - CHECK(omi1.is_initialized() == false); - CHECK(omi2.is_initialized()); - CHECK(omi2.get().get() == 125); - } - - // use with rowset and table containing null values - - { - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - - sql << "insert into soci_test(id, val) values(1, 10)"; - sql << "insert into soci_test(id, val) values(2, 11)"; - sql << "insert into soci_test(id, val) values(3, NULL)"; - sql << "insert into soci_test(id, val) values(4, 13)"; - - rowset > rs = (sql.prepare << - "select val from soci_test order by id asc"); - - // 1st row - rowset >::const_iterator pos = rs.begin(); - CHECK((*pos).is_initialized()); - CHECK(10 == (*pos).get()); - - // 2nd row - ++pos; - CHECK((*pos).is_initialized()); - CHECK(11 == (*pos).get()); - - // 3rd row - ++pos; - CHECK((*pos).is_initialized() == false); - - // 4th row - ++pos; - CHECK((*pos).is_initialized()); - CHECK(13 == (*pos).get()); - } - } -} - -#endif // SOCI_HAVE_BOOST - -// connection and reconnection tests -TEST_CASE_METHOD(common_tests, "Connection and reconnection", "[core][connect]") -{ - { - // empty session - soci::session sql; - - // idempotent: - sql.close(); - - try - { - sql.reconnect(); - FAIL("expected exception not thrown"); - } - catch (soci_error const &e) - { - CHECK(e.get_error_message() == - "Cannot reconnect without previous connection."); - } - - // open from empty session - sql.open(backEndFactory_, connectString_); - sql.close(); - - // reconnecting from closed session - sql.reconnect(); - - // opening already connected session - try - { - sql.open(backEndFactory_, connectString_); - FAIL("expected exception not thrown"); - } - catch (soci_error const &e) - { - CHECK(e.get_error_message() == - "Cannot open already connected session."); - } - - sql.close(); - - // open from closed - sql.open(backEndFactory_, connectString_); - - // reconnect from already connected session - sql.reconnect(); - } - - { - soci::session sql; - - try - { - sql << "this statement cannot execute"; - FAIL("expected exception not thrown"); - } - catch (soci_error const &e) - { - CHECK(e.get_error_message() == - "Session is not connected."); - } - } - -} - -#ifdef SOCI_HAVE_BOOST - -TEST_CASE_METHOD(common_tests, "Boost tuple", "[core][boost][tuple]") -{ - soci::session sql(backEndFactory_, connectString_); - - auto_table_creator tableCreator(tc_.table_creator_2(sql)); - { - boost::tuple t1(3.5, 7, "Joe Hacker"); - ASSERT_EQUAL(t1.get<0>(), 3.5); - CHECK(t1.get<1>() == 7); - CHECK(t1.get<2>() == "Joe Hacker"); - - sql << "insert into soci_test(num_float, num_int, name) values(:d, :i, :s)", use(t1); - - // basic query - - boost::tuple t2; - sql << "select num_float, num_int, name from soci_test", into(t2); - - ASSERT_EQUAL(t2.get<0>(), 3.5); - CHECK(t2.get<1>() == 7); - CHECK(t2.get<2>() == "Joe Hacker"); - - sql << "delete from soci_test"; - } - - { - // composability with boost::optional - - // use: - boost::tuple, std::string> t1( - 3.5, boost::optional(7), "Joe Hacker"); - ASSERT_EQUAL(t1.get<0>(), 3.5); - CHECK(t1.get<1>().is_initialized()); - CHECK(t1.get<1>().get() == 7); - CHECK(t1.get<2>() == "Joe Hacker"); - - sql << "insert into soci_test(num_float, num_int, name) values(:d, :i, :s)", use(t1); - - // into: - boost::tuple, std::string> t2; - sql << "select num_float, num_int, name from soci_test", into(t2); - - ASSERT_EQUAL(t2.get<0>(), 3.5); - CHECK(t2.get<1>().is_initialized()); - CHECK(t2.get<1>().get() == 7); - CHECK(t2.get<2>() == "Joe Hacker"); - - sql << "delete from soci_test"; - } - - { - // composability with user-provided conversions - - // use: - boost::tuple t1(3.5, 7, "Joe Hacker"); - ASSERT_EQUAL(t1.get<0>(), 3.5); - CHECK(t1.get<1>().get() == 7); - CHECK(t1.get<2>() == "Joe Hacker"); - - sql << "insert into soci_test(num_float, num_int, name) values(:d, :i, :s)", use(t1); - - // into: - boost::tuple t2; - - sql << "select num_float, num_int, name from soci_test", into(t2); - - ASSERT_EQUAL(t2.get<0>(), 3.5); - CHECK(t2.get<1>().get() == 7); - CHECK(t2.get<2>() == "Joe Hacker"); - - sql << "delete from soci_test"; - } - - { - // let's have fun - composition of tuple, optional and user-defined type - - // use: - boost::tuple, std::string> t1( - 3.5, boost::optional(7), "Joe Hacker"); - ASSERT_EQUAL(t1.get<0>(), 3.5); - CHECK(t1.get<1>().is_initialized()); - CHECK(t1.get<1>().get().get() == 7); - CHECK(t1.get<2>() == "Joe Hacker"); - - sql << "insert into soci_test(num_float, num_int, name) values(:d, :i, :s)", use(t1); - - // into: - boost::tuple, std::string> t2; - - sql << "select num_float, num_int, name from soci_test", into(t2); - - ASSERT_EQUAL(t2.get<0>(), 3.5); - CHECK(t2.get<1>().is_initialized()); - CHECK(t2.get<1>().get().get() == 7); - CHECK(t2.get<2>() == "Joe Hacker"); - - sql << "update soci_test set num_int = NULL"; - - sql << "select num_float, num_int, name from soci_test", into(t2); - - ASSERT_EQUAL(t2.get<0>(), 3.5); - CHECK(t2.get<1>().is_initialized() == false); - CHECK(t2.get<2>() == "Joe Hacker"); - } - - { - // rowset - - sql << "insert into soci_test(num_float, num_int, name) values(4.0, 8, 'Tony Coder')"; - sql << "insert into soci_test(num_float, num_int, name) values(4.5, NULL, 'Cecile Sharp')"; - sql << "insert into soci_test(num_float, num_int, name) values(5.0, 10, 'Djhava Ravaa')"; - - typedef boost::tuple, std::string> T; - - rowset rs = (sql.prepare - << "select num_float, num_int, name from soci_test order by num_float asc"); - - rowset::const_iterator pos = rs.begin(); - - ASSERT_EQUAL(pos->get<0>(), 3.5); - CHECK(pos->get<1>().is_initialized() == false); - CHECK(pos->get<2>() == "Joe Hacker"); - - ++pos; - ASSERT_EQUAL(pos->get<0>(), 4.0); - CHECK(pos->get<1>().is_initialized()); - CHECK(pos->get<1>().get() == 8); - CHECK(pos->get<2>() == "Tony Coder"); - - ++pos; - ASSERT_EQUAL(pos->get<0>(), 4.5); - CHECK(pos->get<1>().is_initialized() == false); - CHECK(pos->get<2>() == "Cecile Sharp"); - - ++pos; - ASSERT_EQUAL(pos->get<0>(), 5.0); - CHECK(pos->get<1>().is_initialized()); - CHECK(pos->get<1>().get() == 10); - CHECK(pos->get<2>() == "Djhava Ravaa"); - - ++pos; - CHECK(pos == rs.end()); - } -} - -#if defined(BOOST_VERSION) && BOOST_VERSION >= 103500 - -TEST_CASE_METHOD(common_tests, "Boost fusion", "[core][boost][fusion]") -{ - - soci::session sql(backEndFactory_, connectString_); - - auto_table_creator tableCreator(tc_.table_creator_2(sql)); - { - boost::fusion::vector t1(3.5, 7, "Joe Hacker"); - ASSERT_EQUAL(boost::fusion::at_c<0>(t1), 3.5); - CHECK(boost::fusion::at_c<1>(t1) == 7); - CHECK(boost::fusion::at_c<2>(t1) == "Joe Hacker"); - - sql << "insert into soci_test(num_float, num_int, name) values(:d, :i, :s)", use(t1); - - // basic query - - boost::fusion::vector t2; - sql << "select num_float, num_int, name from soci_test", into(t2); - - ASSERT_EQUAL(boost::fusion::at_c<0>(t2), 3.5); - CHECK(boost::fusion::at_c<1>(t2) == 7); - CHECK(boost::fusion::at_c<2>(t2) == "Joe Hacker"); - - sql << "delete from soci_test"; - } - - { - // composability with boost::optional - - // use: - boost::fusion::vector, std::string> t1( - 3.5, boost::optional(7), "Joe Hacker"); - ASSERT_EQUAL(boost::fusion::at_c<0>(t1), 3.5); - CHECK(boost::fusion::at_c<1>(t1).is_initialized()); - CHECK(boost::fusion::at_c<1>(t1).get() == 7); - CHECK(boost::fusion::at_c<2>(t1) == "Joe Hacker"); - - sql << "insert into soci_test(num_float, num_int, name) values(:d, :i, :s)", use(t1); - - // into: - boost::fusion::vector, std::string> t2; - sql << "select num_float, num_int, name from soci_test", into(t2); - - ASSERT_EQUAL(boost::fusion::at_c<0>(t2), 3.5); - CHECK(boost::fusion::at_c<1>(t2).is_initialized()); - CHECK(boost::fusion::at_c<1>(t2) == 7); - CHECK(boost::fusion::at_c<2>(t2) == "Joe Hacker"); - - sql << "delete from soci_test"; - } - - { - // composability with user-provided conversions - - // use: - boost::fusion::vector t1(3.5, 7, "Joe Hacker"); - ASSERT_EQUAL(boost::fusion::at_c<0>(t1), 3.5); - CHECK(boost::fusion::at_c<1>(t1).get() == 7); - CHECK(boost::fusion::at_c<2>(t1) == "Joe Hacker"); - - sql << "insert into soci_test(num_float, num_int, name) values(:d, :i, :s)", use(t1); - - // into: - boost::fusion::vector t2; - - sql << "select num_float, num_int, name from soci_test", into(t2); - - ASSERT_EQUAL(boost::fusion::at_c<0>(t2), 3.5); - CHECK(boost::fusion::at_c<1>(t2).get() == 7); - CHECK(boost::fusion::at_c<2>(t2) == "Joe Hacker"); - - sql << "delete from soci_test"; - } - - { - // let's have fun - composition of tuple, optional and user-defined type - - // use: - boost::fusion::vector, std::string> t1( - 3.5, boost::optional(7), "Joe Hacker"); - ASSERT_EQUAL(boost::fusion::at_c<0>(t1), 3.5); - CHECK(boost::fusion::at_c<1>(t1).is_initialized()); - CHECK(boost::fusion::at_c<1>(t1).get().get() == 7); - CHECK(boost::fusion::at_c<2>(t1) == "Joe Hacker"); - - sql << "insert into soci_test(num_float, num_int, name) values(:d, :i, :s)", use(t1); - - // into: - boost::fusion::vector, std::string> t2; - - sql << "select num_float, num_int, name from soci_test", into(t2); - - ASSERT_EQUAL(boost::fusion::at_c<0>(t2), 3.5); - CHECK(boost::fusion::at_c<1>(t2).is_initialized()); - CHECK(boost::fusion::at_c<1>(t2).get().get() == 7); - CHECK(boost::fusion::at_c<2>(t2) == "Joe Hacker"); - - sql << "update soci_test set num_int = NULL"; - - sql << "select num_float, num_int, name from soci_test", into(t2); - - ASSERT_EQUAL(boost::fusion::at_c<0>(t2), 3.5); - CHECK(boost::fusion::at_c<1>(t2).is_initialized() == false); - CHECK(boost::fusion::at_c<2>(t2) == "Joe Hacker"); - } - - { - // rowset - - sql << "insert into soci_test(num_float, num_int, name) values(4.0, 8, 'Tony Coder')"; - sql << "insert into soci_test(num_float, num_int, name) values(4.5, NULL, 'Cecile Sharp')"; - sql << "insert into soci_test(num_float, num_int, name) values(5.0, 10, 'Djhava Ravaa')"; - - typedef boost::fusion::vector, std::string> T; - - rowset rs = (sql.prepare - << "select num_float, num_int, name from soci_test order by num_float asc"); - - rowset::const_iterator pos = rs.begin(); - - ASSERT_EQUAL(boost::fusion::at_c<0>(*pos), 3.5); - CHECK(boost::fusion::at_c<1>(*pos).is_initialized() == false); - CHECK(boost::fusion::at_c<2>(*pos) == "Joe Hacker"); - - ++pos; - ASSERT_EQUAL(boost::fusion::at_c<0>(*pos), 4.0); - CHECK(boost::fusion::at_c<1>(*pos).is_initialized()); - CHECK(boost::fusion::at_c<1>(*pos).get() == 8); - CHECK(boost::fusion::at_c<2>(*pos) == "Tony Coder"); - - ++pos; - ASSERT_EQUAL(boost::fusion::at_c<0>(*pos), 4.5); - CHECK(boost::fusion::at_c<1>(*pos).is_initialized() == false); - CHECK(boost::fusion::at_c<2>(*pos) == "Cecile Sharp"); - - ++pos; - ASSERT_EQUAL(boost::fusion::at_c<0>(*pos), 5.0); - CHECK(boost::fusion::at_c<1>(*pos).is_initialized()); - CHECK(boost::fusion::at_c<1>(*pos).get() == 10); - CHECK(boost::fusion::at_c<2>(*pos) == "Djhava Ravaa"); - - ++pos; - CHECK(pos == rs.end()); - } -} - -#endif // defined(BOOST_VERSION) && BOOST_VERSION >= 103500 - -// test for boost::gregorian::date -TEST_CASE_METHOD(common_tests, "Boost date", "[core][boost][datetime]") -{ - soci::session sql(backEndFactory_, connectString_); - - { - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - - std::tm nov15 = std::tm(); - nov15.tm_year = 105; - nov15.tm_mon = 10; - nov15.tm_mday = 15; - nov15.tm_hour = 0; - nov15.tm_min = 0; - nov15.tm_sec = 0; - - sql << "insert into soci_test(tm) values(:tm)", use(nov15); - - boost::gregorian::date bgd; - sql << "select tm from soci_test", into(bgd); - - CHECK(bgd.year() == 2005); - CHECK(bgd.month() == 11); - CHECK(bgd.day() == 15); - - sql << "update soci_test set tm = NULL"; - try - { - sql << "select tm from soci_test", into(bgd); - FAIL("expected exception not thrown"); - } - catch (soci_error const & e) - { - CHECK(e.get_error_message() == - "Null value not allowed for this type"); - } - } - - { - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - - boost::gregorian::date bgd(2008, boost::gregorian::May, 5); - - sql << "insert into soci_test(tm) values(:tm)", use(bgd); - - std::tm t = std::tm(); - sql << "select tm from soci_test", into(t); - - CHECK(t.tm_year == 108); - CHECK(t.tm_mon == 4); - CHECK(t.tm_mday == 5); - } - -} - -#endif // SOCI_HAVE_BOOST - -// connection pool - simple sequential test, no multiple threads -TEST_CASE_METHOD(common_tests, "Connection pool", "[core][connection][pool]") -{ - // phase 1: preparation - const size_t pool_size = 10; - connection_pool pool(pool_size); - - for (std::size_t i = 0; i != pool_size; ++i) - { - session & sql = pool.at(i); - sql.open(backEndFactory_, connectString_); - } - - // phase 2: usage - for (std::size_t i = 0; i != pool_size; ++i) - { - // poor man way to lease more than one connection - soci::session sql_unused1(pool); - soci::session sql(pool); - soci::session sql_unused2(pool); - { - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - - char c('a'); - sql << "insert into soci_test(c) values(:c)", use(c); - sql << "select c from soci_test", into(c); - CHECK(c == 'a'); - } - } -} - -// Issue 66 - test query transformation callback feature -static std::string no_op_transform(std::string query) -{ - return query; -} - -static std::string lower_than_g(std::string query) -{ - return query + " WHERE c < 'g'"; -} - -struct where_condition : std::unary_function -{ - where_condition(std::string const& where) - : where_(where) - {} - - result_type operator()(argument_type query) const - { - return query + " WHERE " + where_; - } - - std::string where_; -}; - - -void run_query_transformation_test(test_context_base const& tc, session& sql) -{ - // create and populate the test table - auto_table_creator tableCreator(tc.table_creator_1(sql)); - - for (char c = 'a'; c <= 'z'; ++c) - { - sql << "insert into soci_test(c) values(\'" << c << "\')"; - } - - char const* query = "select count(*) from soci_test"; - - // free function, no-op - { - sql.set_query_transformation(no_op_transform); - int count; - sql << query, into(count); - CHECK(count == 'z' - 'a' + 1); - } - - // free function - { - sql.set_query_transformation(lower_than_g); - int count; - sql << query, into(count); - CHECK(count == 'g' - 'a'); - } - - // function object with state - { - sql.set_query_transformation(where_condition("c > 'g' AND c < 'j'")); - int count = 0; - sql << query, into(count); - CHECK(count == 'j' - 'h'); - count = 0; - sql.set_query_transformation(where_condition("c > 's' AND c <= 'z'")); - sql << query, into(count); - CHECK(count == 'z' - 's'); - } - -#if 0 - // lambda is just presented as an example to curious users - { - sql.set_query_transformation( - [](std::string const& query) { - return query + " WHERE c > 'g' AND c < 'j'"; - }); - - int count = 0; - sql << query, into(count); - CHECK(count == 'j' - 'h'); - } -#endif - - // prepared statements - - // constant effect (pre-prepare set transformation) - { - // set transformation after statement is prepared - sql.set_query_transformation(lower_than_g); - // prepare statement - int count; - statement st = (sql.prepare << query, into(count)); - // observe transformation effect - st.execute(true); - CHECK(count == 'g' - 'a'); - // reset transformation - sql.set_query_transformation(no_op_transform); - // observe the same transformation, no-op set above has no effect - count = 0; - st.execute(true); - CHECK(count == 'g' - 'a'); - } - - // no effect (post-prepare set transformation) - { - // reset - sql.set_query_transformation(no_op_transform); - - // prepare statement - int count; - statement st = (sql.prepare << query, into(count)); - // set transformation after statement is prepared - sql.set_query_transformation(lower_than_g); - // observe no effect of WHERE clause injection - st.execute(true); - CHECK(count == 'z' - 'a' + 1); - } -} - -TEST_CASE_METHOD(common_tests, "Query transformation", "[core][query-transform]") -{ - soci::session sql(backEndFactory_, connectString_); - run_query_transformation_test(tc_, sql); -} - -TEST_CASE_METHOD(common_tests, "Query transformation with connection pool", "[core][query-transform][pool]") -{ - // phase 1: preparation - const size_t pool_size = 10; - connection_pool pool(pool_size); - - for (std::size_t i = 0; i != pool_size; ++i) - { - session & sql = pool.at(i); - sql.open(backEndFactory_, connectString_); - } - - soci::session sql(pool); - run_query_transformation_test(tc_, sql); -} - -// Originally, submitted to SQLite3 backend and later moved to common test. -// Test commit b394d039530f124802d06c3b1a969c3117683152 -// Author: Mika Fischer -// Date: Thu Nov 17 13:28:07 2011 +0100 -// Implement get_affected_rows for SQLite3 backend -TEST_CASE_METHOD(common_tests, "Get affected rows", "[core][affected-rows]") -{ - soci::session sql(backEndFactory_, connectString_); - auto_table_creator tableCreator(tc_.table_creator_4(sql)); - if (!tableCreator.get()) - { - std::cout << "test get_affected_rows skipped (function not implemented)" << std::endl; - return; - } - - - for (int i = 0; i != 10; i++) - { - sql << "insert into soci_test(val) values(:val)", use(i); - } - - int step = 2; - statement st1 = (sql.prepare << - "update soci_test set val = val + :step where val = 5", use(step, "step")); - st1.execute(true); - CHECK(st1.get_affected_rows() == 1); - - // attempts to run the query again, no rows should be affected - st1.execute(true); - CHECK(st1.get_affected_rows() == 0); - - statement st2 = (sql.prepare << - "update soci_test set val = val + 1"); - st2.execute(true); - - CHECK(st2.get_affected_rows() == 10); - - statement st3 = (sql.prepare << - "delete from soci_test where val <= 5"); - st3.execute(true); - - CHECK(st3.get_affected_rows() == 5); - - statement st4 = (sql.prepare << - "update soci_test set val = val + 1"); - st4.execute(true); - - CHECK(st4.get_affected_rows() == 5); - - std::vector v(5, 0); - for (std::size_t i = 0; i < v.size(); ++i) - { - v[i] = (7 + static_cast(i)); - } - - // test affected rows for bulk operations. - statement st5 = (sql.prepare << - "delete from soci_test where val = :v", use(v)); - st5.execute(true); - - CHECK(st5.get_affected_rows() == 5); - - std::vector w(2, "1"); - w[1] = "a"; // this invalid value may cause an exception. - statement st6 = (sql.prepare << - "insert into soci_test(val) values(:val)", use(w)); - try { st6.execute(true); } - catch(...) {} - - // confirm the partial insertion. - int val = 0; - sql << "select count(val) from soci_test", into(val); - if(val != 0) - { - // Notice that some ODBC drivers don't return the number of updated - // rows at all in the case of partially executed statement like this - // one, while MySQL ODBC driver wrongly returns 2 affected rows even - // though only one was actually inserted. - // - // So we can't check for "get_affected_rows() == val" here, it would - // fail in too many cases -- just check that the backend doesn't lie to - // us about no rows being affected at all (even if it just honestly - // admits that it has no idea by returning -1). - CHECK(st6.get_affected_rows() != 0); - } -} - -// test fix for: Backend is not set properly with connection pool (pull #5) -TEST_CASE_METHOD(common_tests, "Backend with connection pool", "[core][pool]") -{ - const size_t pool_size = 1; - connection_pool pool(pool_size); - - for (std::size_t i = 0; i != pool_size; ++i) - { - session & sql = pool.at(i); - sql.open(backEndFactory_, connectString_); - } - - soci::session sql(pool); - sql.reconnect(); - sql.begin(); // no crash expected -} - -// issue 67 - Allocated statement backend memory leaks on exception -// If the test runs under memory debugger and it passes, then -// soci::details::statement_impl::backEnd_ must not leak -TEST_CASE_METHOD(common_tests, "Backend memory leak", "[core][leak]") -{ - soci::session sql(backEndFactory_, connectString_); - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - try - { - rowset rs1 = (sql.prepare << "select * from soci_testX"); - - // TODO: On Linux, no exception thrown; neither from prepare, nor from execute? - // soci_odbc_test_postgresql: - // /home/travis/build/SOCI/soci/src/core/test/common-tests.h:3505: - // void soci::tests::common_tests::test_issue67(): Assertion `!"exception expected"' failed. - //FAIL("exception expected"); // relax temporarily - } - catch (soci_error const &e) - { - (void)e; - } -} - -// issue 154 - Calling undefine_and_bind and then define_and_bind causes a leak. -// If the test runs under memory debugger and it passes, then -// soci::details::standard_use_type_backend and vector_use_type_backend must not leak -TEST_CASE_METHOD(common_tests, "Bind memory leak", "[core][leak]") -{ - soci::session sql(backEndFactory_, connectString_); - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - sql << "insert into soci_test(id) values (1)"; - { - int id = 1; - int val = 0; - statement st(sql); - st.exchange(use(id)); - st.alloc(); - st.prepare("select id from soci_test where id = :1"); - st.define_and_bind(); - st.undefine_and_bind(); - st.exchange(soci::into(val)); - st.define_and_bind(); - st.execute(true); - CHECK(val == 1); - } - // vector variation - { - std::vector ids(1, 2); - std::vector vals(1, 1); - int val = 0; - statement st(sql); - st.exchange(use(ids)); - st.alloc(); - st.prepare("insert into soci_test(id, val) values (:1, :2)"); - st.define_and_bind(); - st.undefine_and_bind(); - st.exchange(use(vals)); - st.define_and_bind(); - st.execute(true); - sql << "select val from soci_test where id = 2", into(val); - CHECK(val == 1); - } -} - -TEST_CASE_METHOD(common_tests, "Insert error", "[core][insert][exception]") -{ - soci::session sql(backEndFactory_, connectString_); - - struct pk_table_creator : table_creator_base - { - explicit pk_table_creator(session& sql) : table_creator_base(sql) - { - // For some backends (at least Firebird), it is important to - // execute the DDL statements in a separate transaction, so start - // one here and commit it before using the new table below. - sql.begin(); - sql << "create table soci_test(" - "name varchar(100) not null primary key, " - "age integer not null" - ")"; - sql.commit(); - } - } table_creator(sql); - - SECTION("literal SQL queries appear in the error message") - { - sql << "insert into soci_test(name, age) values ('John', 74)"; - sql << "insert into soci_test(name, age) values ('Paul', 72)"; - sql << "insert into soci_test(name, age) values ('George', 72)"; - - try - { - // Oops, this should have been 'Ringo' - sql << "insert into soci_test(name, age) values ('John', 74)"; - - FAIL("exception expected on unique constraint violation not thrown"); - } - catch (soci_error const &e) - { - std::string const msg = e.what(); - CAPTURE(msg); - - CHECK(msg.find("John") != std::string::npos); - } - } - - SECTION("SQL queries parameters appear in the error message") - { - char const* const names[] = { "John", "Paul", "George", "John", NULL }; - int const ages[] = { 74, 72, 72, 74, 0 }; - - std::string name; - int age; - - statement st = (sql.prepare << - "insert into soci_test(name, age) values (:name, :age)", - use(name), use(age)); - try - { - int const *a = ages; - for (char const* const* n = names; n; ++n, ++a) - { - name = *n; - age = *a; - st.execute(true); - } - } - catch (soci_error const &e) - { - std::string const msg = e.what(); - CAPTURE(msg); - - CHECK(msg.find("John") != std::string::npos); - } - } -} - -namespace -{ - -// This is just a helper to avoid duplicating the same code in two sections in -// the test below, it's logically part of it. -void check_for_exception_on_truncation(session& sql) -{ - // As the name column has length 20, inserting a longer string into it - // shouldn't work, unless we're dealing with a database that doesn't - // respect column types at all (hello SQLite). - try - { - std::string const long_name("George Raymond Richard Martin"); - sql << "insert into soci_test(name) values(:name)", use(long_name); - - // If insert didn't throw, it should have at least preserved the data - // (only SQLite does this currently). - std::string name; - sql << "select name from soci_test", into(name); - CHECK(name == long_name); - } - catch (soci_error const &) - { - // Unfortunately the contents of the message differ too much between - // the backends (most give an error about value being "too long", - // Oracle says "too large" while SQL Server (via ODBC) just says that - // it "would be truncated"), so we can't really check that we received - // the right error here -- be optimistic and hope that we did. - } -} - -// And another helper for the test below. -void check_for_no_truncation(session& sql) -{ - const std::string str20 = "exactly of length 20"; - - sql << "delete from soci_test"; - - // Also check that there is no truncation when inserting a string of - // the same length as the column size. - CHECK_NOTHROW( (sql << "insert into soci_test(name) values(:s)", use(str20)) ); - - std::string s; - sql << "select name from soci_test", into(s); - CHECK( s == str20 ); -} - -} // anonymous namespace - -TEST_CASE_METHOD(common_tests, "Truncation error", "[core][insert][truncate][exception]") -{ - soci::session sql(backEndFactory_, connectString_); - - if (tc_.has_silent_truncate_bug(sql)) - { - WARN("Database is broken and silently truncates input data."); - return; - } - - SECTION("Error given for char column") - { - struct fixed_name_table_creator : table_creator_base - { - fixed_name_table_creator(session& sql) - : table_creator_base(sql) - { - sql << "create table soci_test(name char(20))"; - } - } tableCreator(sql); - - tc_.on_after_ddl(sql); - - check_for_exception_on_truncation(sql); - - check_for_no_truncation(sql); - } - - SECTION("Error given for varchar column") - { - // Reuse one of the standard tables which has a varchar(20) column. - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - - check_for_exception_on_truncation(sql); - - check_for_no_truncation(sql); - } -} - -TEST_CASE_METHOD(common_tests, "Blank padding", "[core][insert][exception]") -{ - soci::session sql(backEndFactory_, connectString_); - if (!tc_.enable_std_char_padding(sql)) - { - WARN("This backend doesn't pad CHAR(N) correctly, skipping test."); - return; - } - - struct fixed_name_table_creator : table_creator_base - { - fixed_name_table_creator(session& sql) - : table_creator_base(sql) - { - sql.begin(); - sql << "create table soci_test(sc char, name char(10), name2 varchar(10))"; - sql.commit(); - } - } tableCreator(sql); - - std::string test1 = "abcde "; - std::string singleChar = "a"; - sql << "insert into soci_test(sc, name,name2) values(:sc,:name,:name2)", - use(singleChar), use(test1), use(test1); - - std::string sc, tchar,tvarchar; - sql << "select sc,name,name2 from soci_test", - into(sc), into(tchar), into(tvarchar); - - // Firebird can pad "a" to "a " when using UTF-8 encoding. - CHECK_EQUAL_PADDED(sc, singleChar); - CHECK_EQUAL_PADDED(tchar, test1); - CHECK(tvarchar == test1); - - // Check 10-space string - same as inserting empty string since spaces will - // be padded up to full size of the column. - test1 = " "; - singleChar = " "; - sql << "update soci_test set sc=:sc, name=:name, name2=:name2", - use(singleChar), use(test1), use(test1); - sql << "select sc, name,name2 from soci_test", - into(sc), into(tchar), into(tvarchar); - - CHECK_EQUAL_PADDED(sc, singleChar); - CHECK_EQUAL_PADDED(tchar, test1); - CHECK(tvarchar == test1); -} - -TEST_CASE_METHOD(common_tests, "Select without table", "[core][select][dummy_from]") -{ - soci::session sql(backEndFactory_, connectString_); - - int plus17; - sql << ("select abs(-17)" + sql.get_dummy_from_clause()), - into(plus17); - - CHECK(plus17 == 17); -} - -TEST_CASE_METHOD(common_tests, "String length", "[core][string][length]") -{ - soci::session sql(backEndFactory_, connectString_); - - auto_table_creator tableCreator(tc_.table_creator_1(sql)); - - std::string s("123"); - REQUIRE_NOTHROW(( - sql << "insert into soci_test(str) values(:s)", use(s) - )); - - std::string sout; - size_t slen; - REQUIRE_NOTHROW(( - sql << "select str," + tc_.sql_length("str") + " from soci_test", - into(sout), into(slen) - )); - CHECK(slen == 3); - CHECK(sout.length() == 3); - CHECK(sout == s); - - sql << "delete from soci_test"; - - - std::vector v; - v.push_back("Hello"); - v.push_back(""); - v.push_back("whole of varchar(20)"); - - REQUIRE_NOTHROW(( - sql << "insert into soci_test(str) values(:s)", use(v) - )); - - std::vector vout(10); - // Although none of the strings here is really null, Oracle handles the - // empty string as being null, so to avoid an error about not providing - // the indicator when retrieving a null value, we must provide it here. - std::vector vind(10); - std::vector vlen(10); - - REQUIRE_NOTHROW(( - sql << "select str," + tc_.sql_length("str") + " from soci_test" - " order by " + tc_.sql_length("str"), - into(vout, vind), into(vlen) - )); - - REQUIRE(vout.size() == 3); - REQUIRE(vlen.size() == 3); - - CHECK(vlen[0] == 0); - CHECK(vout[0].length() == 0); - - CHECK(vlen[1] == 5); - CHECK(vout[1].length() == 5); - - CHECK(vlen[2] == 20); - CHECK(vout[2].length() == 20); -} - -// Helper function used in two tests below. -static std::string make_long_xml_string() -{ - std::string s; - s.reserve(6 + 200*26 + 7); - - s += ""; - for (int i = 0; i != 200; ++i) - { - s += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - } - s += ""; - - return s; -} - -TEST_CASE_METHOD(common_tests, "CLOB", "[core][clob]") -{ - soci::session sql(backEndFactory_, connectString_); - - auto_table_creator tableCreator(tc_.table_creator_clob(sql)); - if (!tableCreator.get()) - { - WARN("CLOB type not supported by the database, skipping the test."); - return; - } - - long_string s1; // empty - sql << "insert into soci_test(id, s) values (1, :s)", use(s1); - - long_string s2; - s2.value = "hello"; - sql << "select s from soci_test where id = 1", into(s2); - - CHECK(s2.value.size() == 0); - - s1.value = make_long_xml_string(); - - sql << "update soci_test set s = :s where id = 1", use(s1); - - sql << "select s from soci_test where id = 1", into(s2); - - CHECK(s2.value == s1.value); -} - -TEST_CASE_METHOD(common_tests, "XML", "[core][xml]") -{ - soci::session sql(backEndFactory_, connectString_); - - auto_table_creator tableCreator(tc_.table_creator_xml(sql)); - if (!tableCreator.get()) - { - WARN("XML type not supported by the database, skipping the test."); - return; - } - - int id = 1; - xml_type xml; - xml.value = make_long_xml_string(); - - sql << "insert into soci_test (id, x) values (:1, " - << tc_.to_xml(":2") - << ")", - use(id), use(xml); - - xml_type xml2; - - sql << "select " - << tc_.from_xml("x") - << " from soci_test where id = :1", - into(xml2), use(id); - - // The returned value doesn't need to be identical to the original one as - // string, only structurally equal as XML. In particular, extra whitespace - // can be added and this does happen with Oracle, for example, which adds - // an extra new line, so remove it if it's present. - if (!xml2.value.empty() && *xml2.value.rbegin() == '\n') - { - xml2.value.resize(xml2.value.length() - 1); - } - - CHECK(xml.value == xml2.value); - - sql << "update soci_test set x = null where id = :1", use(id); - - indicator ind; - sql << "select " - << tc_.from_xml("x") - << " from soci_test where id = :1", - into(xml2, ind), use(id); - - CHECK(ind == i_null); - - // Inserting malformed XML into an XML column must fail but some backends - // (e.g. Firebird) don't have real XML support, so exclude them from this - // test. - if (tc_.has_real_xml_support()) - { - xml.value = ""; - CHECK_THROWS_AS( - (sql << "insert into soci_test(id, x) values (2, " - + tc_.to_xml(":1") + ")", - use(xml) - ), soci_error - ); - } -} - -} // namespace test_cases - -} // namespace tests - -} // namespace soci - -#endif // SOCI_COMMON_TESTS_H_INCLUDED diff --git a/src/soci/tests/db2/CMakeLists.txt b/src/soci/tests/db2/CMakeLists.txt deleted file mode 100644 index 594eacca1f..0000000000 --- a/src/soci/tests/db2/CMakeLists.txt +++ /dev/null @@ -1,16 +0,0 @@ -############################################################################### -# -# This file is part of CMake configuration for SOCI library -# -# Copyright (C) 2010-2013 Mateusz Loskot -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -# -############################################################################### - -soci_backend_test( - BACKEND DB2 - DEPENDS DB2 - SOURCE test-db2.cpp ${SOCI_TESTS_COMMON} - CONNSTR "DSN=SAMPLE;Uid=db2inst1;Pwd=db2inst1;autocommit=off") diff --git a/src/soci/tests/db2/test-db2.cpp b/src/soci/tests/db2/test-db2.cpp deleted file mode 100644 index 082737fe8b..0000000000 --- a/src/soci/tests/db2/test-db2.cpp +++ /dev/null @@ -1,424 +0,0 @@ -// -// Copyright (C) 2011-2013 Denis Chapligin -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#include "soci/soci.h" -#include "soci/db2/soci-db2.h" -#include "common-tests.h" -#include -#include -#include -#include - -using namespace soci; -using namespace soci::tests; - -std::string connectString; -backend_factory const &backEnd = *soci::factory_db2(); - -// -// Support for soci Common Tests -// - -struct table_creator_one : public table_creator_base -{ - table_creator_one(soci::session & sql) - : table_creator_base(sql) - { - sql << "CREATE TABLE SOCI_TEST(ID INTEGER, VAL SMALLINT, C CHAR, STR VARCHAR(20), SH SMALLINT, UL NUMERIC(20), D DOUBLE, " - "NUM76 NUMERIC(7,6), " - "TM TIMESTAMP, I1 INTEGER, I2 INTEGER, I3 INTEGER, NAME VARCHAR(20))"; - } -}; - -struct table_creator_two : public table_creator_base -{ - table_creator_two(soci::session & sql) - : table_creator_base(sql) - { - sql << "CREATE TABLE SOCI_TEST(NUM_FLOAT DOUBLE, NUM_INT INTEGER, NAME VARCHAR(20), SOMETIME TIMESTAMP, CHR CHAR)"; - } -}; - -struct table_creator_three : public table_creator_base -{ - table_creator_three(soci::session & sql) - : table_creator_base(sql) - { - sql << "CREATE TABLE SOCI_TEST(NAME VARCHAR(100) NOT NULL, PHONE VARCHAR(15))"; - } -}; - -struct table_creator_for_get_affected_rows : table_creator_base -{ - table_creator_for_get_affected_rows(soci::session & sql) - : table_creator_base(sql) - { - sql << "CREATE TABLE SOCI_TEST(VAL INTEGER)"; - } -}; - -class test_context :public test_context_base -{ -public: - test_context(backend_factory const & pi_back_end, std::string const & pi_connect_string) - : test_context_base(pi_back_end, pi_connect_string) {} - - table_creator_base* table_creator_1(soci::session & pr_s) const SOCI_OVERRIDE - { - pr_s << "SET CURRENT SCHEMA = 'DB2INST1'"; - return new table_creator_one(pr_s); - } - - table_creator_base* table_creator_2(soci::session & pr_s) const SOCI_OVERRIDE - { - pr_s << "SET CURRENT SCHEMA = 'DB2INST1'"; - return new table_creator_two(pr_s); - } - - table_creator_base* table_creator_3(soci::session & pr_s) const SOCI_OVERRIDE - { - pr_s << "SET CURRENT SCHEMA = 'DB2INST1'"; - return new table_creator_three(pr_s); - } - - table_creator_base* table_creator_4(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_for_get_affected_rows(s); - } - - std::string to_date_time(std::string const & pi_datdt_string) const SOCI_OVERRIDE - { - return "to_date('" + pi_datdt_string + "', 'YYYY-MM-DD HH24:MI:SS')"; - } - - std::string sql_length(std::string const& s) const SOCI_OVERRIDE - { - return "length(" + s + ")"; - } -}; - - -// -// Additional tests to exercise the DB2 backend -// - -TEST_CASE("DB2 test 1", "[db2]") -{ - soci::session sql(backEnd, connectString); - - sql << "SELECT CURRENT TIMESTAMP FROM SYSIBM.SYSDUMMY1"; - sql << "SELECT " << 123 << " FROM SYSIBM.SYSDUMMY1"; - - std::string query = "CREATE TABLE DB2INST1.SOCI_TEST (ID BIGINT,DATA VARCHAR(8))"; - sql << query; - - { - const int i = 7; - sql << "insert into db2inst1.SOCI_TEST (id) values (:id)", use(i,"id"); - int j = 0; - sql << "select id from db2inst1.SOCI_TEST where id=7", into(j); - CHECK(j == i); - } - - { - const long int li = 9; - sql << "insert into db2inst1.SOCI_TEST (id) values (:id)", use(li,"id"); - long int lj = 0;; - sql << "select id from db2inst1.SOCI_TEST where id=9", into(lj); - CHECK(lj == li); - } - - { - const long long ll = 11; - sql << "insert into db2inst1.SOCI_TEST (id) values (:id)", use(ll,"id"); - long long lj = 0; - sql << "select id from db2inst1.SOCI_TEST where id=11", into(lj); - CHECK(lj == ll); - } - - { - const int i = 13; - indicator i_ind = i_ok; - sql << "insert into db2inst1.SOCI_TEST (id) values (:id)", use(i,i_ind,"id"); - int j = 0; - indicator j_ind = i_null; - sql << "select id from db2inst1.SOCI_TEST where id=13", into(j,j_ind); - CHECK(j == i); - CHECK(j_ind == i_ok); - } - - { - std::vector numbers(100); - for (int i = 0 ; i < 100 ; i++) - { - numbers[i] = i + 1000; - } - sql << "insert into db2inst1.SOCI_TEST (id) values (:id)", use(numbers,"id"); - sql << "select id from db2inst1.SOCI_TEST where id >= 1000 and id < 2000 order by id", into(numbers); - for (int i = 0 ; i < 100 ; i++) - { - CHECK(numbers[i] == i + 1000); - } - } - - { - std::vector numbers(100); - std::vector inds(100); - for (int i = 0 ; i < 100 ; i++) - { - numbers[i] = i + 2000; - inds[i] = i_ok; - } - sql << "insert into db2inst1.SOCI_TEST (id) values (:id)", use(numbers,inds,"id"); - for (int i = 0 ; i < 100 ; i++) - { - numbers[i] = 0; - inds[i] = i_null; - } - sql << "select id from db2inst1.SOCI_TEST where id >= 2000 and id < 3000 order by id", into(numbers,inds); - for (int i = 0 ; i < 100 ; i++) - { - CHECK(numbers[i] == i + 2000); - CHECK(inds[i] == i_ok); - } - } - - { - int i = 0; - statement st = (sql.prepare << "select id from db2inst1.SOCI_TEST where id < 1000", into(i)); - st.execute(); - st.fetch(); - CHECK (i == 7); - st.fetch(); - CHECK (i == 9); - st.fetch(); - CHECK (i == 11); - st.fetch(); - CHECK (i == 13); - } - - { - int i = 0; - indicator i_ind = i_null; - std::string d; - indicator d_ind = i_ok; - statement st = (sql.prepare << "select id, data from db2inst1.SOCI_TEST where id = 13", into(i, i_ind), into(d, d_ind)); - st.execute(); - st.fetch(); - CHECK (i == 13); - CHECK (i_ind == i_ok); - CHECK (d_ind == i_null); - } - - { - std::vector numbers(100); - for (int i = 0 ; i < 100 ; i++) - { - numbers[i] = 0; - } - statement st = (sql.prepare << "select id from db2inst1.SOCI_TEST where id >= 1000 order by id", into(numbers)); - st.execute(); - st.fetch(); - for (int i = 0 ; i < 100 ; i++) - { - CHECK(numbers[i] == i + 1000); - } - st.fetch(); - for (int i = 0 ; i < 100 ; i++) - { - CHECK(numbers[i] == i + 2000); - } - } - - { - std::vector numbers(100); - std::vector inds(100); - for (int i = 0 ; i < 100 ; i++) - { - numbers[i] = 0; - inds[i] = i_null; - } - statement st = (sql.prepare << "select id from db2inst1.SOCI_TEST where id >= 1000 order by id", into(numbers, inds)); - st.execute(); - st.fetch(); - for (int i = 0 ; i < 100 ; i++) - { - CHECK(numbers[i] == i + 1000); - CHECK(inds[i] == i_ok); - } - st.fetch(); - for (int i = 0 ; i < 100 ; i++) - { - CHECK(numbers[i] == i + 2000); - CHECK(inds[i] == i_ok); - } - } - - { - // XXX: what is the purpose of this test?? what is the expected value? - int i = 0; - statement st = (sql.prepare << "select id from db2inst1.SOCI_TEST", use(i)); - } - - { - // XXX: what is the purpose of this test?? what is the expected value? - int i = 0; - indicator ind = i_ok; - statement st = (sql.prepare << "select id from db2inst1.SOCI_TEST", use(i, ind)); - } - - { - // XXX: what is the purpose of this test?? what is the expected value? - std::vector numbers(100); - statement st = (sql.prepare << "select id from db2inst1.SOCI_TEST", use(numbers)); - } - - { - // XXX: what is the purpose of this test?? what is the expected value? - std::vector numbers(100); - std::vector inds(100); - statement st = (sql.prepare << "select id from db2inst1.SOCI_TEST", use(numbers, inds)); - } - - sql<<"DROP TABLE DB2INST1.SOCI_TEST"; - sql.commit(); -} - -TEST_CASE("DB2 test 2", "[db2]") -{ - soci::session sql(backEnd, connectString); - - std::string query = "CREATE TABLE DB2INST1.SOCI_TEST (ID BIGINT,DATA VARCHAR(8),DT TIMESTAMP)"; - sql << query; - - { - int i = 7; - std::string n("test"); - sql << "insert into db2inst1.SOCI_TEST (id,data) values (:id,:name)", use(i,"id"),use(n,"name"); - int j; - std::string m; - sql << "select id,data from db2inst1.SOCI_TEST where id=7", into(j),into(m); - CHECK (j == i); - CHECK (m == n); - } - - { - int i = 8; - sql << "insert into db2inst1.SOCI_TEST (id) values (:id)", use(i,"id"); - int j; - std::string m; - indicator ind = i_ok; - sql << "select id,data from db2inst1.SOCI_TEST where id=8", into(j),into(m,ind); - CHECK(j == i); - CHECK(ind==i_null); - } - - { - std::tm dt; - sql << "select current timestamp from sysibm.sysdummy1",into(dt); - sql << "insert into db2inst1.SOCI_TEST (dt) values (:dt)",use(dt,"dt"); - std::tm dt2; - sql << "select dt from db2inst1.SOCI_TEST where dt is not null", into(dt2); - CHECK(dt2.tm_year == dt.tm_year); - CHECK(dt2.tm_mon == dt.tm_mon); - CHECK(dt2.tm_mday == dt.tm_mday); - CHECK(dt2.tm_hour == dt.tm_hour); - CHECK(dt2.tm_min == dt.tm_min); - CHECK(dt2.tm_sec == dt.tm_sec); - } - - sql<<"DROP TABLE DB2INST1.SOCI_TEST"; - sql.commit(); -} - -TEST_CASE("DB2 test 3", "[db2]") -{ - soci::session sql(backEnd, connectString); - int i; - - std::string query = "CREATE TABLE DB2INST1.SOCI_TEST (ID BIGINT,DATA VARCHAR(8),DT TIMESTAMP)"; - sql << query; - - std::vector ids(100); - std::vector data(100); - std::vector dts(100); - for (int i = 0; i < 100; i++) - { - ids[i] = 1000000000LL + i; - data[i] = "test"; - dts[i].tm_year = 112; - dts[i].tm_mon = 7; - dts[i].tm_mday = 17; - dts[i].tm_hour = 0; - dts[i].tm_min = 0; - dts[i].tm_sec = i % 60; - } - - sql << "insert into db2inst1.SOCI_TEST (id, data, dt) values (:id, :data, :dt)", - use(ids, "id"), use(data,"data"), use(dts, "dt"); - - i = 0; - rowset rs = (sql.prepare<<"SELECT ID, DATA, DT FROM DB2INST1.SOCI_TEST"); - for (rowset::const_iterator it = rs.begin(); it != rs.end(); it++) - { - const row & r = *it; - const long long id = r.get(0); - const std::string data = r.get(1); - const std::tm dt = r.get(2); - - CHECK(id == 1000000000LL + i); - CHECK(data == "test"); - CHECK(dt.tm_year == 112); - CHECK(dt.tm_mon == 7); - CHECK(dt.tm_mday == 17); - CHECK(dt.tm_hour == 0); - CHECK(dt.tm_min == 0); - CHECK(dt.tm_sec == i % 60); - - i += 1; - } - - sql<<"DROP TABLE DB2INST1.SOCI_TEST"; - sql.commit(); -} - - -int main(int argc, char** argv) -{ - -#ifdef _MSC_VER - // Redirect errors, unrecoverable problems, and assert() failures to STDERR, - // instead of debug message window. - // This hack is required to run assert()-driven tests by Buildbot. - // NOTE: Comment this 2 lines for debugging with Visual C++ debugger to catch assertions inside. - _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); - _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); -#endif //_MSC_VER - - if (argc >= 2) - { - connectString = argv[1]; - - argv[1] = argv[0]; - - argc--; - argv++; - } - else - { - std::cout << "usage: " << argv[0] - << " connectstring [test-arguments...]\n" - << "example: " << argv[0] - << " \'DSN=SAMPLE;Uid=db2inst1;Pwd=db2inst1;autocommit=off\'\n"; - std::exit(1); - } - - test_context tc(backEnd, connectString); - - return Catch::Session().run(argc, argv); -} diff --git a/src/soci/tests/empty/CMakeLists.txt b/src/soci/tests/empty/CMakeLists.txt deleted file mode 100644 index 38d95b83ee..0000000000 --- a/src/soci/tests/empty/CMakeLists.txt +++ /dev/null @@ -1,15 +0,0 @@ -############################################################################### -# -# This file is part of CMake configuration for SOCI library -# -# Copyright (C) 2010-2013 Mateusz Loskot -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -# -############################################################################### - -soci_backend_test( - BACKEND Empty - SOURCE test-empty.cpp ${SOCI_TESTS_COMMON} - CONNSTR "dummy") diff --git a/src/soci/tests/empty/test-empty.cpp b/src/soci/tests/empty/test-empty.cpp deleted file mode 100644 index fd1f0b5601..0000000000 --- a/src/soci/tests/empty/test-empty.cpp +++ /dev/null @@ -1,178 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#include "soci/soci.h" -#include "soci/empty/soci-empty.h" - -// Normally the tests would include common-tests.h here, but we can't run any -// of the tests registered there, so instead include CATCH header directly. -#define CATCH_CONFIG_RUNNER -#include - -#include -#include -#include -#include - -using namespace soci; - -std::string connectString; -backend_factory const &backEnd = *soci::factory_empty(); - -// NOTE: -// This file is supposed to serve two purposes: -// 1. To be a starting point for implementing new tests (for new backends). -// 2. To exercise (at least some of) the syntax and try the SOCI library -// against different compilers, even in those environments where there -// is no database. SOCI uses advanced template techniques which are known -// to cause problems on different versions of popular compilers, and this -// test is handy to verify that the code is accepted by as many compilers -// as possible. -// -// Both of these purposes mean that the actual code here is meaningless -// from the database-development point of view. For new tests, you may wish -// to remove this code and keep only the general structure of this file. - -struct Person -{ - int id; - std::string firstName; - std::string lastName; -}; - -namespace soci -{ - template<> struct type_conversion - { - typedef values base_type; - static void from_base(values & /* r */, indicator /* ind */, - Person & /* p */) - { - } - }; -} - -TEST_CASE("Dummy test", "[empty]") -{ - soci::session sql(backEnd, connectString); - - sql << "Do what I want."; - sql << "Do what I want " << 123 << " times."; - - char const* const query = "some query"; - sql << query; - - { - std::string squery = "some query"; - sql << squery; - } - - int i = 7; - sql << "insert", use(i); - sql << "select", into(i); - sql << query, use(i); - sql << query, into(i); - -#if defined (__LP64__) || ( __WORDSIZE == 64 ) - long int li = 9; - sql << "insert", use(li); - sql << "select", into(li); -#endif - - long long ll = 11; - sql << "insert", use(ll); - sql << "select", into(ll); - - indicator ind = i_ok; - sql << "insert", use(i, ind); - sql << "select", into(i, ind); - sql << query, use(i, ind); - sql << query, use(i, ind); - - std::vector numbers(100); - sql << "insert", use(numbers); - sql << "select", into(numbers); - - std::vector inds(100); - sql << "insert", use(numbers, inds); - sql << "select", into(numbers, inds); - - { - statement st = (sql.prepare << "select", into(i)); - st.execute(); - st.fetch(); - } - { - statement st = (sql.prepare << query, into(i)); - st.execute(); - st.fetch(); - } - { - statement st = (sql.prepare << "select", into(i, ind)); - statement sq = (sql.prepare << query, into(i, ind)); - } - { - statement st = (sql.prepare << "select", into(numbers)); - } - { - statement st = (sql.prepare << "select", into(numbers, inds)); - } - { - statement st = (sql.prepare << "insert", use(i)); - statement sq = (sql.prepare << query, use(i)); - } - { - statement st = (sql.prepare << "insert", use(i, ind)); - statement sq = (sql.prepare << query, use(i, ind)); - } - { - statement st = (sql.prepare << "insert", use(numbers)); - } - { - statement st = (sql.prepare << "insert", use(numbers, inds)); - } - { - Person p; - sql << "select person", into(p); - } -} - - -int main(int argc, char** argv) -{ - -#ifdef _MSC_VER - // Redirect errors, unrecoverable problems, and assert() failures to STDERR, - // instead of debug message window. - // This hack is required to run assert()-driven tests by Buildbot. - // NOTE: Comment this 2 lines for debugging with Visual C++ debugger to catch assertions inside. - _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); - _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); -#endif //_MSC_VER - - if (argc >= 2) - { - connectString = argv[1]; - - // Replace the connect string with the process name to ensure that - // CATCH uses the correct name in its messages. - argv[1] = argv[0]; - - argc--; - argv++; - } - else - { - std::cout << "usage: " << argv[0] - << " connectstring [test-arguments...]\n" - << "example: " << argv[0] - << " \'connect_string_for_empty_backend\'\n"; - std::exit(1); - } - - return Catch::Session().run(argc, argv); -} diff --git a/src/soci/tests/firebird/CMakeLists.txt b/src/soci/tests/firebird/CMakeLists.txt deleted file mode 100644 index 4389d259d2..0000000000 --- a/src/soci/tests/firebird/CMakeLists.txt +++ /dev/null @@ -1,16 +0,0 @@ -############################################################################### -# -# This file is part of CMake configuration for SOCI library -# -# Copyright (C) 2010-2013 Mateusz Loskot -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -# -############################################################################### - -soci_backend_test( - BACKEND Firebird - DEPENDS Firebird - SOURCE test-firebird.cpp ${SOCI_TESTS_COMMON} - CONNSTR "service=/tmp/test.fdb user=SYSDBA password=masterkey") diff --git a/src/soci/tests/firebird/test-firebird.cpp b/src/soci/tests/firebird/test-firebird.cpp deleted file mode 100644 index 3a39869adc..0000000000 --- a/src/soci/tests/firebird/test-firebird.cpp +++ /dev/null @@ -1,1389 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, Rafal Bobrowski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -// - -#include "soci/soci.h" -#include "soci/firebird/soci-firebird.h" -#include "soci-compiler.h" -#include "firebird/error-firebird.h" // soci::details::Firebird::throw_iscerror() -#include "firebird/common.h" -#include "common-tests.h" -#include -#include -#include -#include -#include - -using namespace soci; - -std::string connectString; -soci::backend_factory const &backEnd = *factory_firebird(); - -// fundamental tests - transactions in Firebird -TEST_CASE("Firebird transactions", "[firebird][transaction]") -{ - soci::session sql(backEnd, connectString); - - // In Firebird transaction is always required and is started - // automatically when session is opened. There is no need to - // call session::begin(); it will do nothing if there is active - // transaction. - - // sql.begin(); - - try - { - sql << "drop table test1"; - } - catch (soci_error const &) - {} // ignore if error - - sql << "create table test1 (id integer)"; - - // After DDL statement transaction must be commited or changes - // won't be visible to active transaction. - sql.commit(); - - // After commit or rollback, transaction must be started manually. - sql.begin(); - - sql << "insert into test1(id) values(5)"; - sql << "drop table test1"; - - // Transaction is automatically commited in session's destructor -} - -// character types -TEST_CASE("Firebird char types", "[firebird][string]") -{ - soci::session sql(backEnd, connectString); - - try - { - sql << "drop table test2"; - } - catch (soci_error const &) - {} // ignore if error - - sql << "create table test2 (p1 char(10) character set none, p2 varchar(10) character set none)"; - sql.commit(); - - sql.begin(); - - { - char a('a'), b('b'), c1, c2; - - sql << "insert into test2(p1,p2) values(?,?)", use(a), use(b); - - sql << "select p1,p2 from test2", into(c1), into(c2); - CHECK(c1 == 'a'); - CHECK(c2 == 'b'); - - sql << "delete from test2"; - } - -#if 0 // SOCI doesn't support binding into(char *, ...) anymore, use std::string - { - char msg[] = "Hello, Firebird!"; - char buf1[100], buf2[100], buf3[100]; - char *b1 = buf1, *b2 = buf2, *b3 = buf3; - - strcpy(b1, msg); - - sql << "insert into test2(p1, p2) values (?,?)", use(b1, 100), use(b1, 100); - sql << "select p1, p2 from test2", into(b2, 100), into(b3, 100); - - CHECK(!std::strcmp(buf2, buf3)); - CHECK(!std::strcmp(buf2, "Hello, Fir")); - - sql << "delete from test2"; - } - - { - char msg[] = "Hello, Firebird!"; - char buf1[100], buf2[100], buf3[100]; - strcpy(buf1, msg); - - sql << "insert into test2(p1, p2) values (?,?)", - use(buf1), use(buf1); - sql << "select p1, p2 from test2", into(buf2), into(buf3); - - CHECK(!std::strcmp(buf2, buf3)); - CHECK(!std::strcmp(buf2, "Hello, Fir")); - - sql << "delete from test2"; - } -#endif - - { - // The test string is exactly 10 bytes long, i.e. same as column length. - std::string b1("Hello, FB!"), b2, b3; - - sql << "insert into test2(p1, p2) values (?,?)", use(b1), use(b1); - sql << "select p1, p2 from test2", into(b2), into(b3); - - CHECK(b2 == b3); - CHECK(b2 == "Hello, FB!"); - - sql << "delete from test2"; - } - - { - // verify blank padding in CHAR fields - // In Firebird, CHAR fields are always padded with whitespaces. - char msg[] = "Hello"; - sql << "insert into test2(p1) values(\'" << msg << "\')"; - - char buf[20]; - std::string buf_str; - sql << "select p1 from test2", into(buf_str); - std::strcpy(buf, buf_str.c_str()); - - CHECK(std::strncmp(buf, msg, 5) == 0); - // This test works only for charset none - CHECK(std::strncmp(buf+5, " ", 5) == 0); - - sql << "delete from test2"; - } - - sql << "drop table test2"; -} - -// date and time -TEST_CASE("Firebird date and time", "[firebird][datetime]") -{ - soci::session sql(backEnd, connectString); - - try - { - sql << "drop table test3"; - } - catch (soci_error const &) - {} // ignore if error - - sql << "create table test3 (p1 timestamp, p2 date, p3 time)"; - sql.commit(); - - sql.begin(); - - std::tm t1 = std::tm(); - std::tm t2 = std::tm(); - std::tm t3 = std::tm(); - std::time_t now = std::time(NULL); - std::tm t = *std::localtime(&now); - sql << "insert into test3(p1, p2, p3) " - << "values (?,?,?)", use(t), use(t), use(t); - - sql << "select p1, p2, p3 from test3", into(t1), into(t2), into(t3); - - // timestamp - CHECK(t1.tm_year == t.tm_year); - CHECK(t1.tm_mon == t.tm_mon); - CHECK(t1.tm_mday == t.tm_mday); - CHECK(t1.tm_hour == t.tm_hour); - CHECK(t1.tm_min == t.tm_min); - CHECK(t1.tm_sec == t.tm_sec); - - // date - CHECK(t2.tm_year == t.tm_year); - CHECK(t2.tm_mon == t.tm_mon); - CHECK(t2.tm_mday == t.tm_mday); - CHECK(t2.tm_hour == 0); - CHECK(t2.tm_min == 0); - CHECK(t2.tm_sec == 0); - - // time - CHECK(t3.tm_year == 0); - CHECK(t3.tm_mon == 0); - CHECK(t3.tm_mday == 0); - CHECK(t3.tm_hour == t.tm_hour); - CHECK(t3.tm_min == t.tm_min); - CHECK(t3.tm_sec == t.tm_sec); - - sql << "drop table test3"; -} - -// floating points -TEST_CASE("Firebird floating point", "[firebird][float]") -{ - soci::session sql(backEnd, connectString); - - try - { - sql << "drop table test4"; - } - catch (soci_error const &) - {} // ignore if error - - sql << "create table test4 (p1 numeric(8,2), " - << "p2 decimal(14,8), p3 double precision, p4 integer)"; - sql.commit(); - - sql.begin(); - - double d1 = 1234.23, d2 = 1e8, d3 = 1.0/1440.0, - d4, d5, d6; - - sql << "insert into test4(p1, p2, p3) values (?,?,?)", - use(d1), use(d2), use(d3); - - sql << "select p1, p2, p3 from test4", - into(d4), into(d5), into(d6); - - // The doubles should make the round trip unchanged, so use the exact - // comparisons here. - CHECK(tests::are_doubles_exactly_equal(d1, d4)); - CHECK(tests::are_doubles_exactly_equal(d2, d5)); - CHECK(tests::are_doubles_exactly_equal(d3, d6)); - - // test negative doubles too - sql << "delete from test4"; - d1 = -d1; - d2 = -d2; - d3 = -d3; - - sql << "insert into test4(p1, p2, p3) values (?,?,?)", - use(d1), use(d2), use(d3); - - sql << "select p1, p2, p3 from test4", - into(d4), into(d5), into(d6); - - CHECK(tests::are_doubles_exactly_equal(d1, d4)); - CHECK(tests::are_doubles_exactly_equal(d2, d5)); - CHECK(tests::are_doubles_exactly_equal(d3, d6)); - - // verify an exception is thrown when fetching non-integral value - // to integral variable - try - { - int i; - sql << "select p1 from test4", into(i); - - // expecting error - CHECK(false); - } - catch (soci_error const &e) - { - CHECK(e.get_error_message() == - "Can't convert value with scale 2 to integral type"); - } - - // verify an exception is thrown when inserting non-integral value - // to integral column - try - { - sql << "insert into test4(p4) values(?)", use(d1); - - // expecting error - CHECK(false); - } - catch (soci_error const &e) - { - CHECK(e.get_error_message() == - "Can't convert non-integral value to integral column type"); - } - - sql << "drop table test4"; -} - -// integer types and indicators -TEST_CASE("Firebird integers", "[firebird][int]") -{ - soci::session sql(backEnd, connectString); - - { - short sh(0); - sql << "select 3 from rdb$database", into(sh); - CHECK(sh == 3); - } - - { - int i(0); - sql << "select 5 from rdb$database", into(i); - CHECK(i == 5); - } - - { - unsigned long ul(0); - sql << "select 7 from rdb$database", into(ul); - CHECK(ul == 7); - } - - { - // test indicators - indicator ind; - int i; - - sql << "select 2 from rdb$database", into(i, ind); - CHECK(ind == i_ok); - - sql << "select NULL from rdb$database", into(i, ind); - CHECK(ind == i_null); - -#if 0 // SOCI doesn't support binding into(char *, ...) anymore, use std::string - char buf[4]; - sql << "select \'Hello\' from rdb$database", into(buf, ind); - CHECK(ind == i_truncated); -#endif - - sql << "select 5 from rdb$database where 0 = 1", into(i, ind); - CHECK(sql.got_data() == false); - - try - { - // expect error - sql << "select NULL from rdb$database", into(i); - CHECK(false); - } - catch (soci_error const &e) - { - CHECK(e.get_error_message() == - "Null value fetched and no indicator defined."); - } - - // expect no data - sql << "select 5 from rdb$database where 0 = 1", into(i); - CHECK(!sql.got_data()); - } -} - -// repeated fetch and bulk operations for character types -TEST_CASE("Firebird bulk operations", "[firebird][bulk]") -{ - soci::session sql(backEnd, connectString); - - try - { - sql << "drop table test6"; - } - catch (soci_error const &) - {} // ignore if error - - sql << "create table test6 (p1 char(10) character set none, p2 varchar(10) character set none)"; - sql.commit(); - - sql.begin(); - - for (char c = 'a'; c <= 'z'; ++c) - { - sql << "insert into test6(p1, p2) values(?,?)", use(c), use(c); - } - - { - char c, c1, c2; - - statement st = (sql.prepare << - "select p1,p2 from test6 order by p1", into(c1), into(c2)); - - // Verify that fetch after re-executing the same statement works. - for (int n = 0; n < 2; ++n) - { - st.execute(); - - c='a'; - while (st.fetch()) - { - CHECK(c == c1); - CHECK(c == c2); - ++c; - } - CHECK(c == 'z'+1); - } - } - - { - char c='a'; - - std::vector c1(10), c2(10); - - statement st = (sql.prepare << - "select p1,p2 from test6 order by p1", into(c1), into(c2)); - - st.execute(); - while (st.fetch()) - { - for (std::size_t i = 0; i != c1.size(); ++i) - { - CHECK(c == c1[i]); - CHECK(c == c2[i]); - ++c; - } - } - CHECK(c == 'z' + 1); - } - - { - // verify an exception is thrown when empty vector is used - std::vector vec; - try - { - sql << "select p1 from test6", into(vec); - CHECK(false); - } - catch (soci_error const &e) - { - CHECK(e.get_error_message() == - "Vectors of size 0 are not allowed."); - } - } - - sql << "delete from test6"; - - // verifying std::string - int const rowsToTest = 10; - for (int i = 0; i != rowsToTest; ++i) - { - std::ostringstream ss; - ss << "Hello_" << i; - - std::string const &x = ss.str(); - - sql << "insert into test6(p1, p2) values(\'" - << x << "\', \'" << x << "\')"; - } - - int count; - sql << "select count(*) from test6", into(count); - CHECK(count == rowsToTest); - - { - int i = 0; - std::string s1, s2; - statement st = (sql.prepare << - "select p1, p2 from test6 order by p1", into(s1), into(s2)); - - st.execute(); - while (st.fetch()) - { - std::ostringstream ss; - ss << "Hello_" << i; - std::string const &x = ss.str(); - - // Note: CHAR fields are always padded with whitespaces - ss << " "; - CHECK(s1 == ss.str()); - CHECK(s2 == x); - ++i; - } - CHECK(i == rowsToTest); - } - - { - int i = 0; - - std::vector s1(4), s2(4); - statement st = (sql.prepare << - "select p1, p2 from test6 order by p1", into(s1), into(s2)); - st.execute(); - while (st.fetch()) - { - for (std::size_t j = 0; j != s1.size(); ++j) - { - std::ostringstream ss; - ss << "Hello_" << i; - std::string const &x = ss.str(); - - // Note: CHAR fields are always padded with whitespaces - ss << " "; - CHECK(ss.str() == s1[j]); - CHECK(x == s2[j]); - ++i; - } - } - CHECK(i == rowsToTest); - } - - sql << "drop table test6"; -} - -// blob test -TEST_CASE("Firebird blobs", "[firebird][blob]") -{ - soci::session sql(backEnd, connectString); - - try - { - sql << "drop table test7"; - } - catch (std::runtime_error &) - {} // ignore if error - - sql << "create table test7(id integer, img blob)"; - sql.commit(); - - sql.begin(); - { - // verify empty blob - blob b(sql); - indicator ind; - - sql << "insert into test7(id, img) values(1,?)", use(b); - sql << "select img from test7 where id = 1", into(b, ind); - - CHECK(ind == i_ok); - CHECK(b.get_len() == 0); - - sql << "delete from test7"; - } - - { - // create a new blob - blob b(sql); - - char str1[] = "Hello"; - b.write(0, str1, strlen(str1)); - - char str2[20]; - std::size_t i = b.read(3, str2, 2); - str2[i] = '\0'; - CHECK(str2[0] == 'l'); - CHECK(str2[1] == 'o'); - CHECK(str2[2] == '\0'); - - char str3[] = ", Firebird!"; - b.append(str3, strlen(str3)); - - sql << "insert into test7(id, img) values(1,?)", use(b); - } - - { - // read & update blob - blob b(sql); - - sql << "select img from test7 where id = 1", into(b); - - std::vector text(b.get_len()); - b.read(0, &text[0], b.get_len()); - CHECK(strncmp(&text[0], "Hello, Firebird!", b.get_len()) == 0); - - char str1[] = "FIREBIRD"; - b.write(7, str1, strlen(str1)); - - // after modification blob must be written to database - sql << "update test7 set img=? where id=1", use(b); - } - - { - // read blob from database, modify and write to another record - blob b(sql); - - sql << "select img from test7 where id = 1", into(b); - - std::vector text(b.get_len()); - b.read(0, &text[0], b.get_len()); - - char str1[] = "HELLO"; - b.write(0, str1, strlen(str1)); - - b.read(0, &text[0], b.get_len()); - CHECK(strncmp(&text[0], "HELLO, FIREBIRD!", b.get_len()) == 0); - - b.trim(5); - sql << "insert into test7(id, img) values(2,?)", use(b); - } - - { - blob b(sql); - statement st = (sql.prepare << "select img from test7", into(b)); - - st.execute(); - - st.fetch(); - std::vector text(b.get_len()); - b.read(0, &text[0], b.get_len()); - CHECK(strncmp(&text[0], "Hello, FIREBIRD!", b.get_len()) == 0); - - st.fetch(); - text.resize(b.get_len()); - b.read(0, &text[0], b.get_len()); - CHECK(strncmp(&text[0], "HELLO", b.get_len()) == 0); - } - - { - // delete blob - blob b(sql); - indicator ind=i_null; - sql << "update test7 set img=? where id = 1", use(b, ind); - - sql << "select img from test7 where id = 2", into(b, ind); - CHECK(ind==i_ok); - - sql << "select img from test7 where id = 1", into(b, ind); - CHECK(ind==i_null); - } - - { - //create large blob - const int blobSize = 65536; //max segment size is 65535(unsigned short) - std::vector data(blobSize); - blob b(sql); - b.write(0, data.data(), blobSize); - sql << "insert into test7(id, img) values(3,?)", use(b); - - //now read blob back from database and make sure it has correct content and size - blob br(sql); - sql << "select img from test7 where id = 3", into(br); - std::vector data2(br.get_len()); - if(br.get_len()>0) - br.read(0, data2.data(), br.get_len()); - CHECK(data == data2); - } - - sql << "drop table test7"; -} - -// named parameters -TEST_CASE("Firebird named parameters", "[firebird][named-params]") -{ - soci::session sql(backEnd, connectString); - - try - { - sql << "drop table test8"; - } - catch (std::runtime_error &) - {} // ignore if error - - sql << "create table test8(id1 integer, id2 integer)"; - sql.commit(); - - sql.begin(); - - int j = 13, k = 4, i, m; - sql << "insert into test8(id1, id2) values(:id1, :id2)", - use(k, "id2"), use(j, "id1"); - sql << "select id1, id2 from test8", into(i), into(m); - CHECK(i == j); - CHECK(m == k); - - sql << "delete from test8"; - - std::vector in1(3), in2(3); - in1[0] = 3; - in1[1] = 2; - in1[2] = 1; - in2[0] = 4; - in2[1] = 5; - in2[2] = 6; - - { - statement st = (sql.prepare << - "insert into test8(id1, id2) values(:id1, :id2)", - use(k, "id2"), use(j, "id1")); - - std::size_t s = in1.size(); - for (std::size_t x = 0; x < s; ++x) - { - j = in1[x]; - k = in2[x]; - st.execute(); - } - } - - { - statement st = ( - sql.prepare << "select id1, id2 from test8", into(i), into(m)); - st.execute(); - - std::size_t x(0); - while (st.fetch()) - { - CHECK(i == in1[x]); - CHECK(m == in2[x]); - ++x; - } - } - - sql << "delete from test8"; - - // test vectors - sql << "insert into test8(id1, id2) values(:id1, :id2)", - use(in1, "id1"), use(in2, "id2"); - - std::vector out1(3), out2(3); - - sql << "select id1, id2 from test8", into(out1), into(out2); - std::size_t s = out1.size(); - CHECK(s == 3); - - for (std::size_t x = 0; x(0) == 1); - CHECK(r.get(1) == "Hello"); - CHECK(tests::are_doubles_exactly_equal(r.get(2), d)); - - // get values by name - CHECK(r.get("ID") == 1); - CHECK(r.get("MSG") == "Hello"); - CHECK(tests::are_doubles_exactly_equal(r.get("NTEST"), d)); - - st.fetch(); - CHECK(r.get(0) == 2); - CHECK(r.get("MSG") == "Firebird"); - CHECK(r.get_indicator(2) == i_null); - - // verify default values - CHECK(tests::are_doubles_exactly_equal(r.get("NTEST", 2), 2)); - - CHECK_THROWS_AS(r.get("NTEST"), soci_error); - - // verify exception thrown on invalid get<> - CHECK_THROWS_AS(r.get(0), std::bad_cast); - - sql << "drop table test9"; -} - -// stored procedures -TEST_CASE("Firebird stored procedures", "[firebird][procedure]") -{ - soci::session sql(backEnd, connectString); - - try - { - sql << "drop procedure sp_test10"; - } - catch (std::runtime_error &) - {} // ignore if error - - try - { - sql << "drop procedure sp_test10a"; - } - catch (std::runtime_error &) - {} // ignore if error - - try - { - sql << "drop table test10"; - } - catch (std::runtime_error &) - {} // ignore if error - - sql << "create table test10(id integer, id2 integer)"; - - sql << "create procedure sp_test10\n" - << "returns (rid integer, rid2 integer)\n" - << "as begin\n" - << "for select id, id2 from test10 into rid, rid2 do begin\n" - << "suspend;\n" - << "end\n" - << "end;\n"; - - sql << "create procedure sp_test10a (pid integer, pid2 integer)\n" - << "as begin\n" - << "insert into test10(id, id2) values (:pid, :pid2);\n" - << "end;\n"; - - sql.commit(); - - sql.begin(); - - row r; - int p1 = 3, p2 = 4; - - // calling procedures that do not return values requires - // 'execute procedure ...' statement - sql << "execute procedure sp_test10a ?, ?", use(p1), use(p2); - - // calling procedures that return values requires - // 'select ... from ...' statement - sql << "select * from sp_test10", into(r); - - CHECK(r.get(0) == p1); - CHECK(r.get(1) == p2); - - sql << "delete from test10"; - - p1 = 5; - p2 = 6; - { - procedure proc = ( - sql.prepare << "sp_test10a :p1, :p2", - use(p2, "p2"), use(p1, "p1")); - proc.execute(1); - } - - { - row rw; - procedure proc = (sql.prepare << "sp_test10", into(rw)); - proc.execute(1); - - CHECK(rw.get(0) == p1); - CHECK(rw.get(1) == p2); - } - - sql << "delete from test10"; - - // test vectors - std::vector in1(3), in2(3); - in1[0] = 3; - in1[1] = 2; - in1[2] = 1; - in2[0] = 4; - in2[1] = 5; - in2[2] = 6; - - { - procedure proc = ( - sql.prepare << "sp_test10a :p1, :p2", - use(in2, "p2"), use(in1, "p1")); - proc.execute(1); - } - - { - row rw; - procedure proc = (sql.prepare << "sp_test10", into(rw)); - - proc.execute(1); - CHECK(rw.get(0) == in1[0]); - CHECK(rw.get(1) == in2[0]); - proc.fetch(); - CHECK(rw.get(0) == in1[1]); - CHECK(rw.get(1) == in2[1]); - proc.fetch(); - CHECK(rw.get(0) == in1[2]); - CHECK(rw.get(1) == in2[2]); - CHECK(proc.fetch() == false); - } - - { - std::vector out1(3), out2(3); - procedure proc = (sql.prepare << "sp_test10", into(out1), into(out2)); - proc.execute(1); - - std::size_t s = out1.size(); - CHECK(s == 3); - - for (std::size_t x = 0; x < s; ++x) - { - CHECK(out1[x] == in1[x]); - CHECK(out2[x] == in2[x]); - } - } - - sql.rollback(); - - sql.begin(); - sql << "drop procedure sp_test10"; - sql << "drop procedure sp_test10a"; - sql << "drop table test10"; -} - -// direct access to Firebird using handles exposed by -// soci::FirebirdStatmentBackend -namespace soci -{ - enum eRowCountType - { - eRowsSelected = isc_info_req_select_count, - eRowsInserted = isc_info_req_insert_count, - eRowsUpdated = isc_info_req_update_count, - eRowsDeleted = isc_info_req_delete_count - }; - - // Returns number of rows afected by last statement - // or -1 if there is no such counter available. - long getRowCount(soci::statement & statement, eRowCountType type) - { - ISC_STATUS stat[20]; - char cnt_req[2], cnt_info[128]; - - cnt_req[0]=isc_info_sql_records; - cnt_req[1]=isc_info_end; - - firebird_statement_backend* statementBackEnd - = static_cast(statement.get_backend()); - - // Note: This is very poorly documented function. - // It can extract number of rows returned by select statement, - // but it appears that this is only number of rows prefetched by - // client library, not total number of selected rows. - if (isc_dsql_sql_info(stat, &statementBackEnd->stmtp_, sizeof(cnt_req), - cnt_req, sizeof(cnt_info), cnt_info)) - { - soci::details::firebird::throw_iscerror(stat); - } - - long count = -1; - char type_ = static_cast(type); - for (char *ptr = cnt_info + 3; *ptr != isc_info_end;) - { - char count_type = *ptr++; - int m = isc_vax_integer(ptr, 2); - ptr += 2; - count = isc_vax_integer(ptr, static_cast(m)); - - if (count_type == type_) - { - // this is requested number - break; - } - ptr += m; - } - - return count; - } - -} // namespace soci - -TEST_CASE("Firebird direct API use", "[firebird][native]") -{ - soci::session sql(backEnd, connectString); - - try - { - sql << "drop table test11"; - } - catch (std::runtime_error &) - {} // ignore if error - - sql << "create table test11(id integer)"; - sql.commit(); - - sql.begin(); - - { - std::vector in(3); - in[0] = 3; - in[1] = 2; - in[2] = 1; - - statement st = (sql.prepare << "insert into test11(id) values(?)", - use(in)); - st.execute(1); - - // Note: Firebird backend inserts every row with separate insert - // statement to achieve the effect of inserting vectors of values. - // Since getRowCount() returns number of rows affected by the *last* - // statement, it will return 1 here. - CHECK(getRowCount(st, eRowsInserted) == 1); - } - - { - int i = 5; - statement st = (sql.prepare << "update test11 set id = ? where id<3", - use(i)); - st.execute(1); - CHECK(getRowCount(st, eRowsUpdated) == 2); - - // verify that no rows were deleted - CHECK(getRowCount(st, eRowsDeleted) == 0); - } - - { - std::vector out(3); - statement st = (sql.prepare << "select id from test11", into(out)); - st.execute(1); - - CHECK(getRowCount(st, eRowsSelected) == 3); - } - - { - statement st = (sql.prepare << "delete from test11 where id=10"); - st.execute(1); - CHECK(getRowCount(st, eRowsDeleted) == 0); - } - - { - statement st = (sql.prepare << "delete from test11"); - st.execute(1); - CHECK(getRowCount(st, eRowsDeleted) == 3); - } - - sql << "drop table test11"; -} - -TEST_CASE("Firebird string coercions", "[firebird][string]") -{ - soci::session sql(backEnd, connectString); - - try - { - sql << "drop table test12"; - } - catch (std::runtime_error &) - {} // ignore if error - - sql << "create table test12(a decimal(10,3), b timestamp, c date, d time)"; - sql.commit(); - sql.begin(); - - // Check if passing input parameters as strings works - // for different column types. - { - std::string a = "-3.14150", b = "2013-02-28 23:36:01", - c = "2013-02-28", d = "23:36:01"; - statement st = (sql.prepare << - "insert into test12(a, b, c, d) values (?, ?, ?, ?)", - use(a), use(b), use(c), use(d)); - st.execute(1); - CHECK(getRowCount(st, eRowsInserted) == 1); - } - - { - double a; - std::tm b = std::tm(), c = std::tm(), d = std::tm(); - sql << "select a, b, c, d from test12", - into(a), into(b), into(c), into(d); - CHECK(std::fabs(a - (-3.141)) < 0.000001); - CHECK(b.tm_year == 2013 - 1900); - CHECK(b.tm_mon == 2 - 1); - CHECK(b.tm_mday == 28); - CHECK(b.tm_hour == 23); - CHECK(b.tm_min == 36); - CHECK(b.tm_sec == 1); - CHECK(c.tm_year == 2013 - 1900); - CHECK(c.tm_mon == 2 - 1); - CHECK(c.tm_mday == 28); - CHECK(c.tm_hour == 0); - CHECK(c.tm_min == 0); - CHECK(c.tm_sec == 0); - CHECK(d.tm_hour == 23); - CHECK(d.tm_min == 36); - CHECK(d.tm_sec == 1); - } - - sql << "drop table test12"; -} - -// Dynamic binding to row objects: decimals_as_strings -TEST_CASE("Firebird decimals as strings", "[firebird][decimal][string]") -{ - using namespace soci::details::firebird; - - int a = -12345678; - CHECK(format_decimal(&a, 1) == "-123456780"); - CHECK(format_decimal(&a, 0) == "-12345678"); - CHECK(format_decimal(&a, -3) == "-12345.678"); - CHECK(format_decimal(&a, -8) == "-0.12345678"); - CHECK(format_decimal(&a, -9) == "-0.012345678"); - - a = 12345678; - CHECK(format_decimal(&a, 1) == "123456780"); - CHECK(format_decimal(&a, 0) == "12345678"); - CHECK(format_decimal(&a, -3) == "12345.678"); - CHECK(format_decimal(&a, -8) == "0.12345678"); - CHECK(format_decimal(&a, -9) == "0.012345678"); - - soci::session sql(backEnd, connectString + " decimals_as_strings=1"); - - try - { - sql << "drop table test13"; - } - catch (std::runtime_error &) - {} // ignore if error - - sql << "create table test13(ntest1 decimal(10,2), " - << "ntest2 decimal(4,4), ntest3 decimal(3,1))"; - sql.commit(); - - sql.begin(); - - { - row r; - sql << "select * from test13", into(r); - CHECK(sql.got_data() == false); - } - - std::string d_str0("+03.140"), d_str1("3.14"), - d_str2("3.1400"), d_str3("3.1"); - indicator ind(i_ok); - - { - statement st((sql.prepare << - "insert into test13(ntest1, ntest2, ntest3) " - "values(:ntest1, :ntest2, :ntest3)", - use(d_str0, ind, "ntest1"), use(d_str0, "ntest2"), - use(d_str0, "ntest3"))); - - st.execute(1); - - ind = i_null; - st.execute(1); - } - - row r; - statement st = (sql.prepare << "select * from test13", into(r)); - st.execute(1); - - CHECK(r.size() == 3); - - // get properties by position - CHECK(r.get_properties(0).get_name() == "NTEST1"); - CHECK(r.get_properties(0).get_data_type() == dt_string); - CHECK(r.get_properties(1).get_name() == "NTEST2"); - CHECK(r.get_properties(1).get_data_type() == dt_string); - CHECK(r.get_properties(2).get_name() == "NTEST3"); - CHECK(r.get_properties(2).get_data_type() == dt_string); - - // get properties by name - CHECK(r.get_properties("NTEST1").get_name() == "NTEST1"); - CHECK(r.get_properties("NTEST1").get_data_type() == dt_string); - CHECK(r.get_properties("NTEST2").get_name() == "NTEST2"); - CHECK(r.get_properties("NTEST2").get_data_type() == dt_string); - CHECK(r.get_properties("NTEST3").get_name() == "NTEST3"); - CHECK(r.get_properties("NTEST3").get_data_type() == dt_string); - - // get values by position - CHECK(r.get(0) == d_str1); - CHECK(r.get(1) == d_str2); - CHECK(r.get(2) == d_str3); - - // get values by name - CHECK(r.get("NTEST1") == d_str1); - CHECK(r.get("NTEST2") == d_str2); - CHECK(r.get("NTEST3") == d_str3); - - st.fetch(); - CHECK(r.get_indicator(0) == i_null); - CHECK(r.get_indicator(1) == i_ok); - CHECK(r.get_indicator(2) == i_ok); - - sql << "drop table test13"; -} - -// -// Support for soci Common Tests -// - -struct TableCreator1 : public tests::table_creator_base -{ - TableCreator1(soci::session & sql) - : tests::table_creator_base(sql) - { - sql << "create table soci_test(id integer, val integer, c char, " - "str varchar(20), sh smallint, ul bigint, d double precision, " - "num76 numeric(7,6), " - "tm timestamp, i1 integer, i2 integer, i3 integer, name varchar(20))"; - sql.commit(); - sql.begin(); - } -}; - -struct TableCreator2 : public tests::table_creator_base -{ - TableCreator2(soci::session & sql) - : tests::table_creator_base(sql) - { - sql << "create table soci_test(num_float float, num_int integer, " - "name varchar(20), sometime timestamp, chr char)"; - sql.commit(); - sql.begin(); - } -}; - -struct TableCreator3 : public tests::table_creator_base -{ - TableCreator3(soci::session & sql) - : tests::table_creator_base(sql) - { - sql << "create table soci_test(name varchar(100) not null, " - "phone varchar(15))"; - sql.commit(); - sql.begin(); - } -}; - -struct TableCreator4 : public tests::table_creator_base -{ - TableCreator4(soci::session & sql) - : tests::table_creator_base(sql) - { - sql << "create table soci_test(val integer)"; - sql.commit(); - sql.begin(); - } -}; - -struct TableCreatorCLOB : public tests::table_creator_base -{ - TableCreatorCLOB(soci::session & sql) - : tests::table_creator_base(sql) - { - sql << "create table soci_test(id integer, s blob sub_type text)"; - sql.commit(); - sql.begin(); - } -}; - -struct TableCreatorXML : public tests::table_creator_base -{ - TableCreatorXML(soci::session & sql) - : tests::table_creator_base(sql) - { - sql << "create table soci_test(id integer, x blob sub_type text)"; - sql.commit(); - sql.begin(); - } -}; - -class test_context : public tests::test_context_base -{ - public: - test_context(backend_factory const &backEnd, - std::string const &connectString) - : test_context_base(backEnd, connectString) - {} - - tests::table_creator_base* table_creator_1(soci::session& s) const SOCI_OVERRIDE - { - return new TableCreator1(s); - } - - tests::table_creator_base* table_creator_2(soci::session& s) const SOCI_OVERRIDE - { - return new TableCreator2(s); - } - - tests::table_creator_base* table_creator_3(soci::session& s) const SOCI_OVERRIDE - { - return new TableCreator3(s); - } - - tests::table_creator_base* table_creator_4(soci::session& s) const SOCI_OVERRIDE - { - return new TableCreator4(s); - } - - tests::table_creator_base* table_creator_clob(soci::session& s) const SOCI_OVERRIDE - { - return new TableCreatorCLOB(s); - } - - tests::table_creator_base* table_creator_xml(soci::session& s) const SOCI_OVERRIDE - { - return new TableCreatorXML(s); - } - - std::string to_date_time(std::string const &datdt_string) const SOCI_OVERRIDE - { - return "'" + datdt_string + "'"; - } - - void on_after_ddl(soci::session& sql) const SOCI_OVERRIDE - { - sql.commit(); - } - - std::string sql_length(std::string const& s) const SOCI_OVERRIDE - { - return "char_length(" + s + ")"; - } -}; - - -int main(int argc, char** argv) -{ - -#ifdef _MSC_VER - // Redirect errors, unrecoverable problems, and assert() failures to STDERR, - // instead of debug message window. - // This hack is required to run assert()-driven tests by Buildbot. - // NOTE: Comment this 2 lines for debugging with Visual C++ debugger to catch assertions inside. - _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); - _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); -#endif //_MSC_VER - - if (argc >= 2) - { - connectString = argv[1]; - - // Replace the connect string with the process name to ensure that - // CATCH uses the correct name in its messages. - argv[1] = argv[0]; - - argc--; - argv++; - } - else - { - std::cout << "usage: " << argv[0] - << " connectstring [test-arguments...]\n" - << "example: " << argv[0] - << " \"service=/usr/local/firebird/db/test.fdb user=SYSDBA password=masterkey\"\n"; - return EXIT_FAILURE; - } - - test_context tc(backEnd, connectString); - - return Catch::Session().run(argc, argv); -} diff --git a/src/soci/tests/mysql/CMakeLists.txt b/src/soci/tests/mysql/CMakeLists.txt deleted file mode 100644 index 533b61f68b..0000000000 --- a/src/soci/tests/mysql/CMakeLists.txt +++ /dev/null @@ -1,16 +0,0 @@ -############################################################################### -# -# This file is part of CMake configuration for SOCI library -# -# Copyright (C) 2010-2013 Mateusz Loskot -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -# -############################################################################### - -soci_backend_test( - BACKEND MySQL - DEPENDS MySQL - SOURCE test-mysql.cpp ${SOCI_TESTS_COMMON} - CONNSTR "db=soci_test") diff --git a/src/soci/tests/mysql/test-mysql.cpp b/src/soci/tests/mysql/test-mysql.cpp deleted file mode 100644 index 8c73b52a1a..0000000000 --- a/src/soci/tests/mysql/test-mysql.cpp +++ /dev/null @@ -1,867 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton -// MySQL backend copyright (C) 2006 Pawel Aleksander Fedorynski -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#include "soci/soci.h" -#include "soci/mysql/soci-mysql.h" -#include "mysql/test-mysql.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -std::string connectString; -backend_factory const &backEnd = *soci::factory_mysql(); - -// procedure call test -TEST_CASE("MySQL stored procedures", "[mysql][stored-procedure]") -{ - soci::session sql(backEnd, connectString); - - mysql_session_backend *sessionBackEnd - = static_cast(sql.get_backend()); - std::string version = mysql_get_server_info(sessionBackEnd->conn_); - int v; - std::istringstream iss(version); - if ((iss >> v) && v < 5) - { - WARN("MySQL server version " << v - << " does not support stored procedures, skipping test."); - return; - } - - try { sql << "drop function myecho"; } - catch (soci_error const &) {} - - sql << - "create function myecho(msg text) " - "returns text deterministic " - " return msg; "; - - std::string in("my message"); - std::string out; - - statement st = (sql.prepare << - "select myecho(:input)", - into(out), - use(in, "input")); - - st.execute(1); - CHECK(out == in); - - // explicit procedure syntax - { - std::string in("my message2"); - std::string out; - - procedure proc = (sql.prepare << - "myecho(:input)", - into(out), use(in, "input")); - - proc.execute(1); - CHECK(out == in); - } - - sql << "drop function myecho"; -} - -// MySQL error reporting test. -TEST_CASE("MySQL error reporting", "[mysql][exception]") -{ - { - try - { - soci::session sql(backEnd, "host=test.soci.invalid"); - } - catch (mysql_soci_error const &e) - { - if (e.err_num_ != CR_UNKNOWN_HOST && - e.err_num_ != CR_CONN_HOST_ERROR) - { - CAPTURE(e.err_num_); - FAIL("Unexpected error trying to connect to invalid host."); - } - } - } - - { - soci::session sql(backEnd, connectString); - sql << "create table soci_test (id integer)"; - try - { - int n; - sql << "select id from soci_test_nosuchtable", into(n); - } - catch (mysql_soci_error const &e) - { - CHECK(e.err_num_ == ER_NO_SUCH_TABLE); - } - try - { - sql << "insert into soci_test (invalid) values (256)"; - } - catch (mysql_soci_error const &e) - { - CHECK(e.err_num_ == ER_BAD_FIELD_ERROR); - } - // A bulk operation. - try - { - std::vector v(3, 5); - sql << "insert into soci_test_nosuchtable values (:n)", use(v); - } - catch (mysql_soci_error const &e) - { - CHECK(e.err_num_ == ER_NO_SUCH_TABLE); - } - sql << "drop table soci_test"; - } -} - -struct bigint_table_creator : table_creator_base -{ - bigint_table_creator(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(val bigint)"; - } -}; - -struct bigint_unsigned_table_creator : table_creator_base -{ - bigint_unsigned_table_creator(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(val bigint unsigned)"; - } -}; - -TEST_CASE("MySQL long long", "[mysql][longlong]") -{ - { - soci::session sql(backEnd, connectString); - - bigint_table_creator tableCreator(sql); - - long long v1 = 1000000000000LL; - sql << "insert into soci_test(val) values(:val)", use(v1); - - long long v2 = 0LL; - sql << "select val from soci_test", into(v2); - - CHECK(v2 == v1); - } - - // vector - { - soci::session sql(backEnd, connectString); - - bigint_table_creator tableCreator(sql); - - std::vector v1; - v1.push_back(1000000000000LL); - v1.push_back(1000000000001LL); - v1.push_back(1000000000002LL); - v1.push_back(1000000000003LL); - v1.push_back(1000000000004LL); - - sql << "insert into soci_test(val) values(:val)", use(v1); - - std::vector v2(10); - sql << "select val from soci_test order by val desc", into(v2); - - REQUIRE(v2.size() == 5); - CHECK(v2[0] == 1000000000004LL); - CHECK(v2[1] == 1000000000003LL); - CHECK(v2[2] == 1000000000002LL); - CHECK(v2[3] == 1000000000001LL); - CHECK(v2[4] == 1000000000000LL); - } - - { - soci::session sql(backEnd, connectString); - - bigint_unsigned_table_creator tableCreator(sql); - - sql << "insert into soci_test set val = 18446744073709551615"; - row v; - sql << "select * from soci_test", into(v); - } - - { - soci::session sql(backEnd, connectString); - - bigint_unsigned_table_creator tableCreator(sql); - - const char* source = "18446744073709551615"; - sql << "insert into soci_test set val = " << source; - unsigned long long vv = 0; - sql << "select val from soci_test", into(vv); - std::stringstream buf; - buf << vv; - CHECK(buf.str() == source); - } - - { - soci::session sql(backEnd, connectString); - - bigint_unsigned_table_creator tableCreator(sql); - - const char* source = "18446744073709551615"; - sql << "insert into soci_test set val = " << source; - std::vector v(1); - sql << "select val from soci_test", into(v); - std::stringstream buf; - buf << v.at(0); - CHECK(buf.str() == source); - } - - { - soci::session sql(backEnd, connectString); - - bigint_unsigned_table_creator tableCreator(sql); - - unsigned long long n = 18446744073709551615ULL; - sql << "insert into soci_test(val) values (:n)", use(n); - unsigned long long m = 0; - sql << "select val from soci_test", into(m); - CHECK(n == m); - } - - { - soci::session sql(backEnd, connectString); - - bigint_unsigned_table_creator tableCreator(sql); - - std::vector v1; - v1.push_back(18446744073709551615ULL); - v1.push_back(18446744073709551614ULL); - v1.push_back(18446744073709551613ULL); - sql << "insert into soci_test(val) values(:val)", use(v1); - - std::vector v2(10); - sql << "select val from soci_test order by val", into(v2); - - REQUIRE(v2.size() == 3); - CHECK(v2[0] == 18446744073709551613ULL); - CHECK(v2[1] == 18446744073709551614ULL); - CHECK(v2[2] == 18446744073709551615ULL); - } -} - -template -void test_num(const char* s, bool valid, T value) -{ - try - { - soci::session sql(backEnd, connectString); - T val; - sql << "select \'" << s << "\'", into(val); - if (valid) - { - double v1 = static_cast(value); - double v2 = static_cast(val); - double d = std::fabs(v1 - v2); - double epsilon = 0.001; - if (d >= epsilon && - d >= epsilon * (std::fabs(v1) + std::fabs(v2))) - { - FAIL("Difference between " << value - << " and " << val << " is too big."); - } - } - else - { - FAIL("string \"" << s << "\" parsed as " << val - << " but should have failed."); - } - } - catch (soci_error const& e) - { - if (valid) - { - FAIL("couldn't parse number: \"" << s << "\""); - } - else - { - char const * expectedPrefix = "Cannot convert data"; - CAPTURE(e.what()); - CHECK(strncmp(e.what(), expectedPrefix, strlen(expectedPrefix)) == 0); - } - } -} - -// Number conversion test. -TEST_CASE("MySQL number conversion", "[mysql][float][int]") -{ - test_num("", false, 0); - test_num("foo", false, 0); - test_num("1", true, 1); - test_num("12", true, 12); - test_num("123", true, 123); - test_num("12345", true, 12345); - test_num("12341234123412341234123412341234123412341234123412341", - true, 1.23412e+52); - test_num("99999999999999999999999912222222222222222222222222223" - "9999999999999999999999991222222222222222222222222222333333333333" - "9999999999999999999999991222222222222222222222222222333333333333" - "9999999999999999999999991222222222222222222222222222333333333333" - "9999999999999999999999991222222222222222222222222222333333333333" - "9999999999999999999999991222222222222222222222222222333333333333" - "9999999999999999999999991222222222222222222222222222333333333333" - "9999999999999999999999991222222222222222222222222222333333333333" - "9999999999999999999999991222222222222222222222222222333333333333" - "9999999999999999999999991222222222222222222222222222333333333333" - "9999999999999999999999991222222222222222222222222222333333333333" - "9999999999999999999999991222222222222222222222222222333333333333" - "9999999999999999999999991222222222222222222222222222333333333333" - "9999999999999999999999991222222222222222222222222222333333333333" - "9999999999999999999999991222222222222222222222222222333333333333", - false, 0); - test_num("1e3", true, 1000); - test_num("1.2", true, 1.2); - test_num("1.2345e2", true, 123.45); - test_num("1 ", false, 0); - test_num(" 123", true, 123); - test_num("1,2", false, 0); - test_num("123abc", false, 0); - test_num("-0", true, 0); - - test_num("123", true, 123); - test_num("100000", false, 0); - - test_num("123", true, 123); - test_num("2147483647", true, 2147483647); - test_num("2147483647a", false, 0); - test_num("2147483648", false, 0); - // -2147483648 causes a warning because it is interpreted as - // 2147483648 (which doesn't fit in an integer) to which a negation - // is applied. - test_num("-2147483648", true, -2147483647 - 1); - test_num("-2147483649", false, 0); - test_num("-0", true, 0); - test_num("1.1", false, 0); - - test_num("123", true, 123); - test_num("9223372036854775807", true, 9223372036854775807LL); - test_num("9223372036854775808", false, 0); -} - -TEST_CASE("MySQL datetime", "[mysql][datetime]") -{ - soci::session sql(backEnd, connectString); - std::tm t = std::tm(); - sql << "select maketime(19, 54, 52)", into(t); - CHECK(t.tm_year == 0); - CHECK(t.tm_mon == 0); - CHECK(t.tm_mday == 1); - CHECK(t.tm_hour == 19); - CHECK(t.tm_min == 54); - CHECK(t.tm_sec == 52); -} - -// TEXT and BLOB types support test. -TEST_CASE("MySQL text and blob", "[mysql][text][blob]") -{ - soci::session sql(backEnd, connectString); - std::string a("asdfg\0hjkl", 10); - std::string b("lkjhg\0fd\0\0sa\0", 13); - std::string c("\\0aa\\0bb\\0cc\\0", 10); - // The maximum length for TEXT and BLOB is 65536. - std::string x(60000, 'X'); - std::string y(60000, 'Y'); - // The default max_allowed_packet value for a MySQL server is 1M, - // so let's limit ourselves to 800k, even though the maximum length - // for LONGBLOB is 4G. - std::string z(800000, 'Z'); - - sql << "create table soci_test (id int, text_value text, " - "blob_value blob, longblob_value longblob)"; - sql << "insert into soci_test values (1, \'foo\', \'bar\', \'baz\')"; - sql << "insert into soci_test " - << "values (2, \'qwerty\\0uiop\', \'zxcv\\0bnm\', " - << "\'qwerty\\0uiop\\0zxcvbnm\\0\')"; - sql << "insert into soci_test values (3, :a, :b, :c)", - use(a), use(b), use(c); - sql << "insert into soci_test values (4, :x, :y, :z)", - use(x), use(y), use(z); - - std::vector text_vec(100); - std::vector blob_vec(100); - std::vector longblob_vec(100); - sql << "select text_value, blob_value, longblob_value " - << "from soci_test order by id", - into(text_vec), into(blob_vec), into(longblob_vec); - REQUIRE(text_vec.size() == 4); - REQUIRE(blob_vec.size() == 4); - REQUIRE(longblob_vec.size() == 4); - CHECK(text_vec[0] == "foo"); - CHECK(blob_vec[0] == "bar"); - CHECK(longblob_vec[0] == "baz"); - CHECK(text_vec[1] == std::string("qwerty\0uiop", 11)); - CHECK(blob_vec[1] == std::string("zxcv\0bnm", 8)); - CHECK(longblob_vec[1] == std::string("qwerty\0uiop\0zxcvbnm\0", 20)); - CHECK(text_vec[2] == a); - CHECK(blob_vec[2] == b); - CHECK(longblob_vec[2] == c); - CHECK(text_vec[3] == x); - CHECK(blob_vec[3] == y); - CHECK(longblob_vec[3] == z); - - std::string text, blob, longblob; - sql << "select text_value, blob_value, longblob_value " - << "from soci_test where id = 1", - into(text), into(blob), into(longblob); - CHECK(text == "foo"); - CHECK(blob == "bar"); - CHECK(longblob == "baz"); - sql << "select text_value, blob_value, longblob_value " - << "from soci_test where id = 2", - into(text), into(blob), into(longblob); - CHECK(text == std::string("qwerty\0uiop", 11)); - CHECK(blob == std::string("zxcv\0bnm", 8)); - CHECK(longblob == std::string("qwerty\0uiop\0zxcvbnm\0", 20)); - sql << "select text_value, blob_value, longblob_value " - << "from soci_test where id = 3", - into(text), into(blob), into(longblob); - CHECK(text == a); - CHECK(blob == b); - CHECK(longblob == c); - sql << "select text_value, blob_value, longblob_value " - << "from soci_test where id = 4", - into(text), into(blob), into(longblob); - CHECK(text == x); - CHECK(blob == y); - CHECK(longblob == z); - - rowset rs = - (sql.prepare << "select text_value, blob_value, longblob_value " - "from soci_test order by id"); - rowset::const_iterator r = rs.begin(); - CHECK(r->get_properties(0).get_data_type() == dt_string); - CHECK(r->get(0) == "foo"); - CHECK(r->get_properties(1).get_data_type() == dt_string); - CHECK(r->get(1) == "bar"); - CHECK(r->get_properties(2).get_data_type() == dt_string); - CHECK(r->get(2) == "baz"); - ++r; - CHECK(r->get_properties(0).get_data_type() == dt_string); - CHECK(r->get(0) == std::string("qwerty\0uiop", 11)); - CHECK(r->get_properties(1).get_data_type() == dt_string); - CHECK(r->get(1) == std::string("zxcv\0bnm", 8)); - CHECK(r->get_properties(2).get_data_type() == dt_string); - CHECK(r->get(2) == - std::string("qwerty\0uiop\0zxcvbnm\0", 20)); - ++r; - CHECK(r->get_properties(0).get_data_type() == dt_string); - CHECK(r->get(0) == a); - CHECK(r->get_properties(1).get_data_type() == dt_string); - CHECK(r->get(1) == b); - CHECK(r->get_properties(2).get_data_type() == dt_string); - CHECK(r->get(2) == c); - ++r; - CHECK(r->get_properties(0).get_data_type() == dt_string); - CHECK(r->get(0) == x); - CHECK(r->get_properties(1).get_data_type() == dt_string); - CHECK(r->get(1) == y); - CHECK(r->get_properties(2).get_data_type() == dt_string); - CHECK(r->get(2) == z); - ++r; - CHECK(r == rs.end()); - - sql << "drop table soci_test"; -} - -// test for number of affected rows - -struct integer_value_table_creator : table_creator_base -{ - integer_value_table_creator(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(val integer)"; - } -}; - -TEST_CASE("MySQL get affected rows", "[mysql][affected-rows]") -{ - soci::session sql(backEnd, connectString); - - integer_value_table_creator tableCreator(sql); - - for (int i = 0; i != 10; i++) - { - sql << "insert into soci_test(val) values(:val)", use(i); - } - - statement st1 = (sql.prepare << - "update soci_test set val = val + 1"); - st1.execute(false); - - CHECK(st1.get_affected_rows() == 10); - - statement st2 = (sql.prepare << - "delete from soci_test where val <= 5"); - st2.execute(false); - - CHECK(st2.get_affected_rows() == 5); -} - - -// The prepared statements should survive session::reconnect(). -// However currently it doesn't and attempting to use it results in crashes due -// to accessing the already destroyed session backend, so disable this test. -TEST_CASE("MySQL statements after reconnect", "[mysql][connect][.]") -{ - soci::session sql(backEnd, connectString); - - integer_value_table_creator tableCreator(sql); - - int i; - statement st = (sql.prepare - << "insert into soci_test(val) values(:val)", use(i)); - i = 5; - st.execute(true); - - sql.reconnect(); - - i = 6; - st.execute(true); - - sql.close(); - sql.reconnect(); - - i = 7; - st.execute(true); - - std::vector v(5); - sql << "select val from soci_test order by val", into(v); - REQUIRE(v.size() == 3); - CHECK(v[0] == 5); - CHECK(v[1] == 6); - CHECK(v[2] == 7); -} - -struct unsigned_value_table_creator : table_creator_base -{ - unsigned_value_table_creator(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(val int unsigned)"; - } -}; - -// rowset<> should be able to take INT UNSIGNED. -TEST_CASE("MySQL unsigned int", "[mysql][int]") -{ - soci::session sql(backEnd, connectString); - - unsigned_value_table_creator tableCreator(sql); - - unsigned int mask = 0xffffff00; - sql << "insert into soci_test set val = " << mask; - soci::rowset<> rows(sql.prepare << "select val from soci_test"); - int cnt = 0; - for (soci::rowset<>::iterator it = rows.begin(), end = rows.end(); - it != end; ++it) - { - cnt++; - } - CHECK(cnt == 1); -} - -TEST_CASE("MySQL function call", "[mysql][function]") -{ - soci::session sql(backEnd, connectString); - - row r; - - sql << "set @day = '5'"; - sql << "set @mm = 'december'"; - sql << "set @year = '2012'"; - sql << "select concat(@day,' ',@mm,' ',@year)", into(r); -} - -struct double_value_table_creator : table_creator_base -{ - double_value_table_creator(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(val double)"; - } -}; - -TEST_CASE("MySQL special floating point values", "[mysql][float]") -{ - static bool is_iec559 = std::numeric_limits::is_iec559; - if (!is_iec559) - { - WARN("C++ double type is not IEC-559, skipping test."); - return; - } - - const std::string expectedError = - "Use element used with infinity or NaN, which are " - "not supported by the MySQL server."; - { - soci::session sql(backEnd, connectString); - - double x = std::numeric_limits::quiet_NaN(); - statement st = (sql.prepare << "SELECT :x", use(x, "x")); - try { - st.execute(true); - } catch (soci_error const &e) { - CHECK(e.get_error_message() == expectedError); - } - } - { - soci::session sql(backEnd, connectString); - - double x = std::numeric_limits::infinity(); - statement st = (sql.prepare << "SELECT :x", use(x, "x")); - try { - st.execute(true); - } catch (soci_error const &e) { - CHECK(e.get_error_message() == expectedError); - } - } - { - soci::session sql(backEnd, connectString); - double_value_table_creator tableCreator(sql); - - std::vector v(1, std::numeric_limits::quiet_NaN()); - try { - sql << "insert into soci_test (val) values (:val)", use(v); - } catch (soci_error const &e) { - CHECK(e.get_error_message() == expectedError); - } - } - { - soci::session sql(backEnd, connectString); - double_value_table_creator tableCreator(sql); - - std::vector v(1, std::numeric_limits::infinity()); - try { - sql << "insert into soci_test (val) values (:val)", use(v); - } catch (soci_error const &e) { - CHECK(e.get_error_message() == expectedError); - } - } -} - -struct tinyint_value_table_creator : table_creator_base -{ - tinyint_value_table_creator(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(val tinyint)"; - } -}; - -struct tinyint_unsigned_value_table_creator : table_creator_base -{ - tinyint_unsigned_value_table_creator(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(val tinyint unsigned)"; - } -}; - -TEST_CASE("MySQL tinyint", "[mysql][int][tinyint]") -{ - { - soci::session sql(backEnd, connectString); - unsigned_value_table_creator tableCreator(sql); - unsigned int mask = 0xffffff00; - sql << "insert into soci_test set val = " << mask; - row r; - sql << "select val from soci_test", into(r); - REQUIRE(r.size() == 1); - CHECK(r.get_properties("val").get_data_type() == dt_long_long); - CHECK(r.get("val") == 0xffffff00); - CHECK(r.get("val") == 0xffffff00); - } - { - soci::session sql(backEnd, connectString); - tinyint_value_table_creator tableCreator(sql); - sql << "insert into soci_test set val = -123"; - row r; - sql << "select val from soci_test", into(r); - REQUIRE(r.size() == 1); - CHECK(r.get_properties("val").get_data_type() == dt_integer); - CHECK(r.get("val") == -123); - } - { - soci::session sql(backEnd, connectString); - tinyint_unsigned_value_table_creator tableCreator(sql); - sql << "insert into soci_test set val = 123"; - row r; - sql << "select val from soci_test", into(r); - REQUIRE(r.size() == 1); - CHECK(r.get_properties("val").get_data_type() == dt_integer); - CHECK(r.get("val") == 123); - } - { - soci::session sql(backEnd, connectString); - bigint_unsigned_table_creator tableCreator(sql); - sql << "insert into soci_test set val = 123456789012345"; - row r; - sql << "select val from soci_test", into(r); - REQUIRE(r.size() == 1); - CHECK(r.get_properties("val").get_data_type() == dt_unsigned_long_long); - CHECK(r.get("val") == 123456789012345ULL); - } - { - soci::session sql(backEnd, connectString); - bigint_table_creator tableCreator(sql); - sql << "insert into soci_test set val = -123456789012345"; - row r; - sql << "select val from soci_test", into(r); - REQUIRE(r.size() == 1); - CHECK(r.get_properties("val").get_data_type() == dt_long_long); - CHECK(r.get("val") == -123456789012345LL); - } -} - -struct strings_table_creator : table_creator_base -{ - strings_table_creator(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(s1 char(20), s2 varchar(20), " - "s3 tinytext, s4 mediumtext, s5 text, s6 longtext, " - "b1 binary(20), b2 varbinary(20), b3 tinyblob, b4 mediumblob, " - "b5 blob, b6 longblob, e1 enum ('foo', 'bar', 'baz'))"; - } -}; - -TEST_CASE("MySQL strings", "[mysql][string]") -{ - soci::session sql(backEnd, connectString); - strings_table_creator tableCreator(sql); - std::string text = "Ala ma kota."; - std::string binary("Ala\0ma\0kota.........", 20); - sql << "insert into soci_test " - "(s1, s2, s3, s4, s5, s6, b1, b2, b3, b4, b5, b6, e1) values " - "(:s1, :s2, :s3, :s4, :d5, :s6, :b1, :b2, :b3, :b4, :b5, :b6, " - "\'foo\')", - use(text), use(text), use(text), use(text), use(text), use(text), - use(binary), use(binary), use(binary), use(binary), use(binary), - use(binary); - row r; - sql << "select s1, s2, s3, s4, s5, s6, b1, b2, b3, b4, b5, b6, e1 " - "from soci_test", into(r); - REQUIRE(r.size() == 13); - for (int i = 0; i < 13; i++) { - CHECK(r.get_properties(i).get_data_type() == dt_string); - if (i < 6) { - CHECK(r.get(i) == text); - } else if (i < 12) { - CHECK(r.get(i) == binary); - } else { - CHECK(r.get(i) == "foo"); - } - } -} - -struct table_creator_for_get_last_insert_id : table_creator_base -{ - table_creator_for_get_last_insert_id(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(id integer not null auto_increment, " - "primary key (id))"; - sql << "alter table soci_test auto_increment = 42"; - } -}; - -TEST_CASE("MySQL last insert id", "[mysql][last-insert-id]") -{ - soci::session sql(backEnd, connectString); - table_creator_for_get_last_insert_id tableCreator(sql); - sql << "insert into soci_test () values ()"; - long id; - bool result = sql.get_last_insert_id("soci_test", id); - CHECK(result == true); - CHECK(id == 42); -} - -std::string escape_string(soci::session& sql, const std::string& s) -{ - mysql_session_backend* backend = static_cast( - sql.get_backend()); - char* escaped = new char[2 * s.size() + 1]; - mysql_real_escape_string(backend->conn_, escaped, s.data(), static_cast(s.size())); - std::string retv = escaped; - delete [] escaped; - return retv; -} - -void test14() -{ - { - soci::session sql(backEnd, connectString); - strings_table_creator tableCreator(sql); - std::string s = "word1'word2:word3"; - std::string escaped = escape_string(sql, s); - std::string query = "insert into soci_test (s5) values ('"; - query.append(escaped); - query.append("')"); - sql << query; - std::string s2; - sql << "select s5 from soci_test", into(s2); - CHECK(s == s2); - } - - std::cout << "test 14 passed" << std::endl; -} - -void test15() -{ - { - soci::session sql(backEnd, connectString); - int n; - sql << "select @a := 123", into(n); - CHECK(n == 123); - } - - std::cout << "test 15 passed" << std::endl; -} - -int main(int argc, char** argv) -{ - if (argc >= 2) - { - connectString = argv[1]; - - // Replace the connect string with the process name to ensure that - // CATCH uses the correct name in its messages. - argv[1] = argv[0]; - - argc--; - argv++; - } - else - { - std::cout << "usage: " << argv[0] - << " connectstring [test-arguments...]\n" - << "example: " << argv[0] - << " \"dbname=test user=root password=\'Ala ma kota\'\"\n"; - std::exit(1); - } - - test_context tc(backEnd, connectString); - - return Catch::Session().run(argc, argv); -} diff --git a/src/soci/tests/mysql/test-mysql.h b/src/soci/tests/mysql/test-mysql.h deleted file mode 100644 index 6cca072777..0000000000 --- a/src/soci/tests/mysql/test-mysql.h +++ /dev/null @@ -1,137 +0,0 @@ -#ifndef SOCI_TESTS_MYSQL_H_INCLUDED -#define SOCI_TESTS_MYSQL_H_INCLUDED - -#include "common-tests.h" - -using namespace soci; -using namespace soci::tests; - -// DDL Creation objects for common tests -struct table_creator_one : public table_creator_base -{ - table_creator_one(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(id integer, val integer, c char, " - "str varchar(20), sh int2, ul numeric(20), d float8, " - "num76 numeric(7,6), " - "tm datetime, i1 integer, i2 integer, i3 integer, " - "name varchar(20)) engine=InnoDB"; - } -}; - -struct table_creator_two : public table_creator_base -{ - table_creator_two(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(num_float float8, num_int integer," - " name varchar(20), sometime datetime, chr char)"; - } -}; - -struct table_creator_three : public table_creator_base -{ - table_creator_three(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(name varchar(100) not null, " - "phone varchar(15))"; - } -}; - -struct table_creator_for_get_affected_rows : table_creator_base -{ - table_creator_for_get_affected_rows(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(val integer)"; - } -}; - -// -// Support for SOCI Common Tests -// - -class test_context : public test_context_base -{ -public: - test_context(backend_factory const &backEnd, - std::string const &connectString) - : test_context_base(backEnd, connectString) {} - - table_creator_base* table_creator_1(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_one(s); - } - - table_creator_base* table_creator_2(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_two(s); - } - - table_creator_base* table_creator_3(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_three(s); - } - - table_creator_base* table_creator_4(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_for_get_affected_rows(s); - } - - std::string to_date_time(std::string const &datdt_string) const SOCI_OVERRIDE - { - return "\'" + datdt_string + "\'"; - } - - bool has_fp_bug() const SOCI_OVERRIDE - { - // MySQL fails in the common test3() with "1.8000000000000000 != - // 1.7999999999999998", so don't use exact doubles comparisons for it. - return true; - } - - bool has_transactions_support(soci::session& sql) const SOCI_OVERRIDE - { - sql << "drop table if exists soci_test"; - sql << "create table soci_test (id int) engine=InnoDB"; - row r; - sql << "show table status like \'soci_test\'", into(r); - bool retv = (r.get(1) == "InnoDB"); - sql << "drop table soci_test"; - return retv; - } - - bool has_silent_truncate_bug(soci::session& sql) const SOCI_OVERRIDE - { - std::string sql_mode; - sql << "select @@session.sql_mode", into(sql_mode); - - // The database must be configured to use STRICT_{ALL,TRANS}_TABLES in - // SQL mode to avoid silent truncation of too long values. - return sql_mode.find("STRICT_") == std::string::npos; - } - - bool enable_std_char_padding(soci::session& sql) const SOCI_OVERRIDE - { - // turn on standard right padding on mysql. This options is supported as of version 5.1.20 - try - { - sql << "SET @@session.sql_mode = 'PAD_CHAR_TO_FULL_LENGTH'"; - return true; - } - catch(const soci_error&) - { - // Padding cannot be enabled - test will not be performed - return false; - } - } - - std::string sql_length(std::string const& s) const SOCI_OVERRIDE - { - return "char_length(" + s + ")"; - } -}; - -#endif // SOCI_TESTS_MYSQL_H_INCLUDED diff --git a/src/soci/tests/odbc/CMakeLists.txt b/src/soci/tests/odbc/CMakeLists.txt deleted file mode 100644 index 2e87069817..0000000000 --- a/src/soci/tests/odbc/CMakeLists.txt +++ /dev/null @@ -1,58 +0,0 @@ -############################################################################### -# -# This file is part of CMake configuration for SOCI library -# -# Copyright (C) 2010-2013 Mateusz Loskot -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -# -############################################################################### - -if (WIN32) - # MDBTools driver seems unreliable - soci_backend_test( - NAME access - BACKEND ODBC - DEPENDS ODBC - SOURCE test-odbc-access.cpp ${SOCI_TESTS_COMMON} - CONNSTR "test-access.dsn") -else() - message(STATUS "MS Access test disabled on non-Windows platform") -endif() - -soci_backend_test( - NAME mssql - BACKEND ODBC - DEPENDS ODBC - SOURCE test-odbc-mssql.cpp ${SOCI_TESTS_COMMON} - CONNSTR "test-mssql.dsn") - -soci_backend_test( - NAME mysql - BACKEND ODBC - DEPENDS ODBC - SOURCE test-odbc-mysql.cpp ${SOCI_TESTS_COMMON} - CONNSTR "test-mysql.dsn") - -if(WIN32) - set(TEST_PGSQL_DSN "test-postgresql-win64.dsn") -else() - set(TEST_PGSQL_DSN "test-postgresql.dsn") -endif() -soci_backend_test( - NAME postgresql - BACKEND ODBC - DEPENDS ODBC - SOURCE test-odbc-postgresql.cpp ${SOCI_TESTS_COMMON} - CONNSTR ${TEST_PGSQL_DSN}) - -# TODO: DB2 backend is tested by Travis CI on dedicated VM, separate from ODBC, -# in order to test DB2 with ODBC, it would be best to install DB2 driver only. -if (NOT $ENV{TRAVIS}) -soci_backend_test( - NAME db2 - BACKEND ODBC - SOURCE test-odbc-db2.cpp - CONNSTR "test-db2.dsn") -endif() diff --git a/src/soci/tests/odbc/soci_test.mdb b/src/soci/tests/odbc/soci_test.mdb deleted file mode 100644 index cf52bd9755f88dcf4284cfe31a27e6a5c3c07ae2..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 77824 zcmeI5U2Ggz701t=9k2IuX4k2rs!CN0m4XlraT=vnLBdVk2rN6U<3uQ`6yo*TvFq4Q zH*QF1g>9e`^npe~NKh43ZIMvlC{Q6m9}pDs01^>GqVPaKt&j>0Pk<^ay!_9dnVtQz zYh2&&MC*FGL zOr`&m^6VF$yIg(pnZ93K`tkLBuU`B0w4{!!tHkG%NjC%%=sSP`|9uO;mA+?3x3e%l>|tD1W14cNPq-LfCNZ@ z1W14cNMJh=c&ECV!!du#sx`N{A}5h^PlcvMF@ea^v7%(9h!BB>32?6FAdE-Dzk?bq^yocK}u)1w)Q{;yX@!;lv_bplb{CzS7&tBR0T6`gN}>}GH5g| zzH01@U?1@sx@uNu1qEZC7kEc zdrR0eiIEk&R%w0j2{|X_us0(|^v_|YE1$-ASBB&QR@du; zauGT!kQeOhVazMbW6(4yIotCPqzhOlRnwA@5&4|mbp^8?!d%_kJoKpc-Es_TX?tF# zFmnj!Ja%zwQ~#JuLsG%WlpL2!SYcAWgm(eLfsUAJRoeb5fTg}w^jNW1or76zM+con z%!&R`f;oCe^yb0F)ZStafK4n&_TLelho&IlKDK6+cP$yoT{a}n-kfYTB5oS z5rrrcFZw& z{!`Zb*YfoVw8{2Li*tXpPr72;Qty zEs?;S=-VRVIrt#MI&)miiAqd@IZ@EazTx8dh24Y7^j_;(7u%@GY@?0r|6#pxij0rc zc(XwQBtQZrKmsH{0wh2JB(M_+81v7l;vJvT*YE%9^WXNq>y^CQz1QY&(hq>7H!`Zw22rNB~JuQt4&J7L?&W_IN ze_=%vbk2;P8k{>>F3o=Cx} z$4wP_`J}VZqGfYRTyr_UR&uwN|F1Q+z-Fp=UkQZy{~n1Nd2Qg1 z_ZV&9&C}yVjjT3M5zv!}8aZ3MkDj2oAB~{+9}Ulz?xT^?hAOm`{@Snw1={e#@`0Xo z)Tn*e#QO??i;(~ckN^pg011!)36KB@kN^pYF;7R|`wrJH{{BCrApsH~0TLhq5+DH* zAOR8}0TLjA8%7}d<**yJfzDglHND>EDhN7{2`wT45+DH*AOR8}0TLhq5+DH*Ac0OJ z!2Exw-BH>@0wh2JBtQZrKmsH{0wh2Joj_pQ`~qixC(u+IH2;r}eDfdy5+DH*AOR8} z0TLhq5+DH*AORBSU;_02JNV|(G!h^I5+DH*AOR8}0TLhq5+DH*2no>t=UagUNPq-L zfCNZ@1W14cNPq-LfCM_9fH9xSJE55=dBrdLS^uZrthdLzlAp?VzWub21W14cNPq-L zfCNZ@1W14cww6Fqe^y)Y>2=@82eXfU{|DcBvp;%IVQ_F`4oK@`f2>d`uC4Gm6qWEs3RJb4yjN;Q z8}ovvcUg~uT=)OzU-5tFKkt9df83w;Pxy!YkNJE2wEu7K4ex60mjZ+FypjM3kN^pg z011!)36KB@kN^pgz>Ol{iaPPtsxK>jImsa0;JY^FP+e{4(on=LIHOVBt_{&Nb!kwg zsS7;?^@Hms23<+S7lIX`D{%N5x^!PgTDn%@$gdn|*lN=#_4S)Z1>e}`)vu^ql@|5Q KU21m2sQ&@2FZaCw diff --git a/src/soci/tests/odbc/test-mssql.dsn b/src/soci/tests/odbc/test-mssql.dsn deleted file mode 100644 index 5db0e2cf08..0000000000 --- a/src/soci/tests/odbc/test-mssql.dsn +++ /dev/null @@ -1,10 +0,0 @@ -[ODBC] -DRIVER=SQL Server Native Client 11.0 -UID=sa -PWD=Password12! -WSID=SOLARWIND -APP=SOCI Test Application -SERVER=(local)\SQL2014 -DATABASE=soci_test -Description=SQL on AppVeyor - diff --git a/src/soci/tests/odbc/test-odbc-access.cpp b/src/soci/tests/odbc/test-odbc-access.cpp deleted file mode 100644 index 2903996f79..0000000000 --- a/src/soci/tests/odbc/test-odbc-access.cpp +++ /dev/null @@ -1,148 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#include "soci/soci.h" -#include "soci/odbc/soci-odbc.h" -#include "common-tests.h" -#include -#include -#include -#include - -using namespace soci; -using namespace soci::tests; - -std::string connectString; -backend_factory const &backEnd = *soci::factory_odbc(); - -// DDL Creation objects for common tests -struct table_creator_one : public table_creator_base -{ - table_creator_one(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(id integer, val integer, c char, " - "str varchar(20), sh integer, ul number, d float, " - "num76 numeric(7,6), " - "tm timestamp, i1 integer, i2 integer, i3 integer, " - "name varchar(20))"; - } -}; - -struct table_creator_two : public table_creator_base -{ - table_creator_two(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(num_float float, num_int integer," - " name varchar(20), sometime datetime, chr char)"; - } -}; - -struct table_creator_three : public table_creator_base -{ - table_creator_three(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(name varchar(100) not null, " - "phone varchar(15))"; - } -}; - -struct table_creator_for_get_affected_rows : table_creator_base -{ - table_creator_for_get_affected_rows(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(val integer)"; - } -}; - -// -// Support for SOCI Common Tests -// - -class test_context : public test_context_base -{ -public: - -test_context(backend_factory const &backEnd, std::string const &connectString) - : test_context_base(backEnd, connectString) {} - - table_creator_base * table_creator_1(soci::session& s) const - { - return new table_creator_one(s); - } - - table_creator_base * table_creator_2(soci::session& s) const - { - return new table_creator_two(s); - } - - table_creator_base * table_creator_3(soci::session& s) const - { - return new table_creator_three(s); - } - - table_creator_base * table_creator_4(soci::session& s) const - { - return new table_creator_for_get_affected_rows(s); - } - - std::string fromDual(std::string const &sql) const - { - return sql; - } - - std::string toDate(std::string const &datdt_string) const - { - return "#" + datdt_string + "#"; - } - - std::string to_date_time(std::string const &datdt_string) const - { - return "#" + datdt_string + "#"; - } - - virtual std::string sql_length(std::string const& s) const - { - return "len(" + s + ")"; - } -}; - -int main(int argc, char** argv) -{ - -#ifdef _MSC_VER - // Redirect errors, unrecoverable problems, and assert() failures to STDERR, - // instead of debug message window. - // This hack is required to run assert()-driven tests by Buildbot. - // NOTE: Comment this 2 lines for debugging with Visual C++ debugger to catch assertions inside. - _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); - _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); -#endif //_MSC_VER - - if (argc >= 2 && argv[1][0] != '-') - { - connectString = argv[1]; - - // Replace the connect string with the process name to ensure that - // CATCH uses the correct name in its messages. - argv[1] = argv[0]; - - argc--; - argv++; - } - else - { - connectString = "FILEDSN=./test-access.dsn"; - } - - test_context tc(backEnd, connectString); - - return Catch::Session().run(argc, argv); -} diff --git a/src/soci/tests/odbc/test-odbc-db2.cpp b/src/soci/tests/odbc/test-odbc-db2.cpp deleted file mode 100644 index bcd771d9ba..0000000000 --- a/src/soci/tests/odbc/test-odbc-db2.cpp +++ /dev/null @@ -1,287 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#include "soci/soci.h" -#include "soci/odbc/soci-odbc.h" -#include "common-tests.h" -#include -#include -#include -#include - -using namespace soci; -using namespace soci::tests; - -std::string connectString; -backend_factory const &backEnd = *soci::factory_odbc(); - -// DDL Creation objects for common tests -struct table_creator_one : public table_creator_base -{ - table_creator_one(soci::session & sql) - : table_creator_base(sql) - { - sql << "CREATE TABLE SOCI_TEST(ID INTEGER, VAL SMALLINT, C CHAR, STR VARCHAR(20), SH SMALLINT, UL NUMERIC(20), D DOUBLE, " - "NUM76 NUMERIC(7,6), " - "TM TIMESTAMP(9), I1 INTEGER, I2 INTEGER, I3 INTEGER, NAME VARCHAR(20))"; - } -}; - -struct table_creator_two : public table_creator_base -{ - table_creator_two(soci::session & sql) - : table_creator_base(sql) - { - sql << "CREATE TABLE SOCI_TEST(NUM_FLOAT DOUBLE, NUM_INT INTEGER, NAME VARCHAR(20), SOMETIME TIMESTAMP, CHR CHAR)"; - } -}; - -struct table_creator_three : public table_creator_base -{ - table_creator_three(soci::session & sql) - : table_creator_base(sql) - { - sql << "CREATE TABLE SOCI_TEST(NAME VARCHAR(100) NOT NULL, PHONE VARCHAR(15))"; - } -}; - -struct table_creator_for_get_affected_rows : table_creator_base -{ - table_creator_for_get_affected_rows(soci::session & sql) - : table_creator_base(sql) - { - sql << "CREATE TABLE SOCI_TEST(VAL INTEGER)"; - } -}; - -// -// Support for SOCI Common Tests -// - -class test_context : public test_context_base -{ -public: - test_context(backend_factory const &backEnd, - std::string const &connectString) - : test_context_base(backEnd, connectString) {} - - table_creator_base * table_creator_1(soci::session& s) const - { - return new table_creator_one(s); - } - - table_creator_base * table_creator_2(soci::session& s) const - { - return new table_creator_two(s); - } - - table_creator_base * table_creator_3(soci::session& s) const - { - return new table_creator_three(s); - } - - table_creator_base * table_creator_4(soci::session& s) const - { - return new table_creator_for_get_affected_rows(s); - } - - std::string to_date_time(std::string const &datdt_string) const - { - return "\'" + datdt_string + "\'"; - } - - virtual std::string sql_length(std::string const& s) const - { - return "length(" + s + ")"; - } -}; - -struct table_creator_bigint : table_creator_base -{ - table_creator_bigint(soci::session & sql) - : table_creator_base(sql) - { - sql << "CREATE TABLE SOCI_TEST (VAL BIGINT)"; - } -}; - -TEST_CASE("ODBC/DB2 long long", "[odbc][db2][longlong]") -{ - const int num_recs = 100; - soci::session sql(backEnd, connectString); - table_creator_bigint table(sql); - - { - long long n; - statement st = (sql.prepare << - "INSERT INTO SOCI_TEST (VAL) VALUES (:val)", use(n)); - for (int i = 0; i < num_recs; i++) - { - n = 1000000000LL + i; - st.execute(); - } - } - { - long long n2; - statement st = (sql.prepare << - "SELECT VAL FROM SOCI_TEST ORDER BY VAL", into(n2)); - st.execute(); - for (int i = 0; i < num_recs; i++) - { - st.fetch(); - CHECK(n2 == 1000000000LL + i); - } - } -} - -TEST_CASE("ODBC/DB2 unsigned long long", "[odbc][db2][unsigned][longlong]") -{ - const int num_recs = 100; - soci::session sql(backEnd, connectString); - table_creator_bigint table(sql); - - { - unsigned long long n; - statement st = (sql.prepare << - "INSERT INTO SOCI_TEST (VAL) VALUES (:val)", use(n)); - for (int i = 0; i < num_recs; i++) - { - n = 1000000000LL + i; - st.execute(); - } - } - { - unsigned long long n2; - statement st = (sql.prepare << - "SELECT VAL FROM SOCI_TEST ORDER BY VAL", into(n2)); - st.execute(); - for (int i = 0; i < num_recs; i++) - { - st.fetch(); - CHECK(n2 == 1000000000LL + i); - } - } -} - -TEST_CASE("ODBC/DB2 vector long long", "[odbc][db2][vector][longlong]") -{ - const std::size_t num_recs = 100; - soci::session sql(backEnd, connectString); - table_creator_bigint table(sql); - - { - std::vector v(num_recs); - for (std::size_t i = 0; i < num_recs; i++) - { - v[i] = 1000000000LL + i; - } - - sql << "INSERT INTO SOCI_TEST (VAL) VALUES (:bi)", use(v); - } - { - std::size_t recs = 0; - - std::vector v(num_recs / 2 + 1); - statement st = (sql.prepare << - "SELECT VAL FROM SOCI_TEST ORDER BY VAL", into(v)); - st.execute(); - while (true) - { - if (!st.fetch()) - { - break; - } - - const std::size_t vsize = v.size(); - for (std::size_t i = 0; i < vsize; i++) - { - CHECK(v[i] == 1000000000LL + - static_cast(recs)); - recs++; - } - } - CHECK(recs == num_recs); - } -} - -TEST_CASE("ODBC/DB2 vector unsigned long long", "[odbc][db2][vector][unsigned][longlong]") -{ - const std::size_t num_recs = 100; - soci::session sql(backEnd, connectString); - table_creator_bigint table(sql); - - { - std::vector v(num_recs); - for (std::size_t i = 0; i < num_recs; i++) - { - v[i] = 1000000000LL + i; - } - - sql << "INSERT INTO SOCI_TEST (VAL) VALUES (:bi)", use(v); - } - { - std::size_t recs = 0; - - std::vector v(num_recs / 2 + 1); - statement st = (sql.prepare << - "SELECT VAL FROM SOCI_TEST ORDER BY VAL", into(v)); - st.execute(); - while (true) - { - if (!st.fetch()) - { - break; - } - - const std::size_t vsize = v.size(); - for (std::size_t i = 0; i < vsize; i++) - { - CHECK(v[i] == 1000000000LL + - static_cast(recs)); - recs++; - } - } - CHECK(recs == num_recs); - } - - std::cout << "test odbc_db2_unsigned_long_long_vector passed" << std::endl; -} - -int main(int argc, char** argv) -{ -#ifdef _MSC_VER - // Redirect errors, unrecoverable problems, and assert() failures to STDERR, - // instead of debug message window. - // This hack is required to run assert()-driven tests by Buildbot. - // NOTE: Comment this 2 lines for debugging with Visual C++ debugger to catch assertions inside. - _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); - _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); -#endif //_MSC_VER - - if (argc >= 2) - { - connectString = argv[1]; - - // Replace the connect string with the process name to ensure that - // CATCH uses the correct name in its messages. - argv[1] = argv[0]; - - argc--; - argv++; - } - else - { - std::cerr << std::endl << - "usage: test-odbc-db2 \"DSN=;Uid=;Pwd=\"" << - std::endl << std::endl; - return EXIT_FAILURE; - } - - test_context tc(backEnd, connectString); - - return Catch::Session().run(argc, argv); -} diff --git a/src/soci/tests/odbc/test-odbc-mssql.cpp b/src/soci/tests/odbc/test-odbc-mssql.cpp deleted file mode 100644 index 6192605895..0000000000 --- a/src/soci/tests/odbc/test-odbc-mssql.cpp +++ /dev/null @@ -1,233 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#include "soci/soci.h" -#include "soci/odbc/soci-odbc.h" -#include "common-tests.h" -#include -#include -#include -#include - -using namespace soci; -using namespace soci::tests; - -std::string connectString; -backend_factory const &backEnd = *soci::factory_odbc(); - -// MS SQL-specific tests -TEST_CASE("MS SQL long string", "[odbc][mssql][long]") -{ - session sql(backEnd, connectString); - - struct long_text_table_creator : public table_creator_base - { - explicit long_text_table_creator(session& sql) - : table_creator_base(sql) - { - // Notice that 4000 is the maximal length of an nvarchar() column, - // at least when using FreeTDS ODBC driver. - sql << "create table soci_test (" - "long_text nvarchar(max) null, " - "fixed_text nvarchar(4000) null" - ")"; - } - } long_text_table_creator(sql); - - // Build a string at least 8000 characters long to test that it survives - // the round trip unscathed. - std::ostringstream os; - for ( int n = 0; n < 1000; ++n ) - { - os << "Line #" << n << "\n"; - } - - std::string const str_in = os.str(); - sql << "insert into soci_test(long_text) values(:str)", use(str_in); - - std::string str_out; - sql << "select long_text from soci_test", into(str_out); - - // Don't just compare the strings because the error message in case they - // differ is completely unreadable due to their size, so give a better - // error in the common failure case. - if (str_out.length() != str_in.length()) - { - FAIL("Read back string of length " << str_out.length() << - " instead of expected " << str_in.length()); - } - else - { - CHECK(str_out == str_in); - } - - // The long string should be truncated when inserting it into a fixed size - // column. - CHECK_THROWS_AS( - (sql << "insert into soci_test(fixed_text) values(:str)", use(str_in)), - soci_error - ); -} - -// DDL Creation objects for common tests -struct table_creator_one : public table_creator_base -{ - table_creator_one(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(id integer, val integer, c char, " - "str varchar(20), sh smallint, ul numeric(20), d float, " - "num76 numeric(7,6), " - "tm datetime, i1 integer, i2 integer, i3 integer, " - "name varchar(20))"; - } -}; - -struct table_creator_two : public table_creator_base -{ - table_creator_two(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(num_float float, num_int integer," - " name varchar(20), sometime datetime, chr char)"; - } -}; - -struct table_creator_three : public table_creator_base -{ - table_creator_three(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(name varchar(100) not null, " - "phone varchar(15))"; - } -}; - -struct table_creator_for_get_affected_rows : table_creator_base -{ - table_creator_for_get_affected_rows(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(val integer)"; - } -}; - -struct table_creator_for_clob : table_creator_base -{ - table_creator_for_clob(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(id integer, s text)"; - } -}; - -struct table_creator_for_xml : table_creator_base -{ - table_creator_for_xml(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(id integer, x xml)"; - } -}; - -// -// Support for SOCI Common Tests -// - -class test_context : public test_context_base -{ -public: - test_context(backend_factory const &backEnd, - std::string const &connectString) - : test_context_base(backEnd, connectString) {} - - table_creator_base* table_creator_1(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_one(s); - } - - table_creator_base* table_creator_2(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_two(s); - } - - table_creator_base* table_creator_3(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_three(s); - } - - table_creator_base * table_creator_4(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_for_get_affected_rows(s); - } - - tests::table_creator_base* table_creator_clob(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_for_clob(s); - } - - tests::table_creator_base* table_creator_xml(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_for_xml(s); - } - - bool has_real_xml_support() const SOCI_OVERRIDE - { - return true; - } - - std::string to_date_time(std::string const &datdt_string) const SOCI_OVERRIDE - { - return "convert(datetime, \'" + datdt_string + "\', 120)"; - } - - bool has_multiple_select_bug() const SOCI_OVERRIDE - { - // MS SQL does support MARS (multiple active result sets) since 2005 - // version, but this support needs to be explicitly enabled and is not - // implemented in FreeTDS ODBC driver used under Unix currently, so err - // on the side of caution and suppose that it's not supported. - return true; - } - - std::string sql_length(std::string const& s) const SOCI_OVERRIDE - { - return "len(" + s + ")"; - } -}; - -int main(int argc, char** argv) -{ -#ifdef _MSC_VER - // Redirect errors, unrecoverable problems, and assert() failures to STDERR, - // instead of debug message window. - // This hack is required to run assert()-driven tests by Buildbot. - // NOTE: Comment this 2 lines for debugging with Visual C++ debugger to catch assertions inside. - _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); - _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); -#endif //_MSC_VER - - if (argc >= 2 && argv[1][0] != '-') - { - connectString = argv[1]; - - // Replace the connect string with the process name to ensure that - // CATCH uses the correct name in its messages. - argv[1] = argv[0]; - - argc--; - argv++; - } - else - { - connectString = "FILEDSN=./test-mssql.dsn"; - } - - test_context tc(backEnd, connectString); - - return Catch::Session().run(argc, argv); -} diff --git a/src/soci/tests/odbc/test-odbc-mysql.cpp b/src/soci/tests/odbc/test-odbc-mysql.cpp deleted file mode 100644 index 9ea70adf6e..0000000000 --- a/src/soci/tests/odbc/test-odbc-mysql.cpp +++ /dev/null @@ -1,49 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#include "soci/soci.h" -#include "soci/odbc/soci-odbc.h" -#include "mysql/test-mysql.h" -#include -#include -#include -#include - -std::string connectString; -backend_factory const &backEnd = *soci::factory_odbc(); - -int main(int argc, char** argv) -{ -#ifdef _MSC_VER - // Redirect errors, unrecoverable problems, and assert() failures to STDERR, - // instead of debug message window. - // This hack is required to run assert()-driven tests by Buildbot. - // NOTE: Comment this 2 lines for debugging with Visual C++ debugger to catch assertions inside. - _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); - _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); -#endif //_MSC_VER - - if (argc >= 2 && argv[1][0] != '-') - { - connectString = argv[1]; - - // Replace the connect string with the process name to ensure that - // CATCH uses the correct name in its messages. - argv[1] = argv[0]; - - argc--; - argv++; - } - else - { - connectString = "FILEDSN=./test-mysql.dsn"; - } - - test_context tc(backEnd, connectString); - - return Catch::Session().run(argc, argv); -} diff --git a/src/soci/tests/odbc/test-odbc-postgresql.cpp b/src/soci/tests/odbc/test-odbc-postgresql.cpp deleted file mode 100644 index af52648ffd..0000000000 --- a/src/soci/tests/odbc/test-odbc-postgresql.cpp +++ /dev/null @@ -1,295 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#include "soci/soci.h" -#include "soci/odbc/soci-odbc.h" -#include "common-tests.h" -#include -#include -#include -#include -#include - -using namespace soci; -using namespace soci::tests; - -// A generic version class: we might want to factor it out later if it is -// needed elsewhere (it would probably also need to be renamed to something -// less generic then). -class odbc_version -{ -public: - odbc_version() - { - initialized_ = false; - } - - odbc_version(unsigned major, unsigned minor, unsigned release) - : major_(major), minor_(minor), release_(release) - { - initialized_ = true; - } - - bool init_from_string(char const* s) - { - initialized_ = std::sscanf(s, "%u.%u.%u", - &major_, &minor_, &release_) == 3; - return initialized_; - } - - bool is_initialized() const { return initialized_; } - - std::string as_string() const - { - if (initialized_) - { - char buf[128]; - // This uses the ODBC convention of padding the minor and release - // versions with 0 and might be not appropriate in general. - std::sprintf(buf, "%u.%02u.%04u", major_, minor_, release_); - return buf; - } - else - { - return "(uninitialized)"; - } - } - - // Compare versions using the lexicographical sort order, with - // uninitialized version considered less than any initialized one. - bool operator<(odbc_version const& v) const - { - if (!initialized_) - return v.initialized_; - - return major_ < v.major_ || - (major_ == v.major_ && (minor_ < v.minor_ || - (minor_ == v.minor_ && release_ < v.release_))); - } - -private: - unsigned major_, minor_, release_; - bool initialized_; -}; - -std::ostream& operator<<(std::ostream& os, odbc_version const& v) -{ - os << v.as_string(); - return os; -} - -std::string connectString; -backend_factory const &backEnd = *soci::factory_odbc(); - -// DDL Creation objects for common tests -struct table_creator_one : public table_creator_base -{ - table_creator_one(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(id integer, val integer, c char, " - "str varchar(20), sh int2, ul numeric(20), d float8, " - "num76 numeric(7,6), " - "tm timestamp, i1 integer, i2 integer, i3 integer, " - "name varchar(20))"; - } -}; - -struct table_creator_two : public table_creator_base -{ - table_creator_two(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(num_float float8, num_int integer," - " name varchar(20), sometime timestamp, chr char)"; - } -}; - -struct table_creator_three : public table_creator_base -{ - table_creator_three(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(name varchar(100) not null, " - "phone varchar(15))"; - } -}; - -struct table_creator_for_get_affected_rows : table_creator_base -{ - table_creator_for_get_affected_rows(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(val integer)"; - } -}; - -struct table_creator_for_xml : table_creator_base -{ - table_creator_for_xml(soci::session& sql) - : table_creator_base(sql) - { - sql << "create table soci_test(id integer, x xml)"; - } -}; - -struct table_creator_for_clob : table_creator_base -{ - table_creator_for_clob(soci::session& sql) - : table_creator_base(sql) - { - sql << "create table soci_test(id integer, s text)"; - } -}; - -// -// Support for SOCI Common Tests -// - -class test_context : public test_context_base -{ -public: - test_context(backend_factory const &backEnd, - std::string const &connectString) - : test_context_base(backEnd, connectString), - m_verDriver(get_driver_version()) - { - std::cout << "Using ODBC driver version " << m_verDriver << "\n"; - } - - table_creator_base * table_creator_1(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_one(s); - } - - table_creator_base * table_creator_2(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_two(s); - } - - table_creator_base * table_creator_3(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_three(s); - } - - table_creator_base * table_creator_4(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_for_get_affected_rows(s); - } - - table_creator_base* table_creator_xml(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_for_xml(s); - } - - table_creator_base* table_creator_clob(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_for_clob(s); - } - - bool has_real_xml_support() const SOCI_OVERRIDE - { - return true; - } - - std::string to_date_time(std::string const &datdt_string) const SOCI_OVERRIDE - { - return "timestamptz(\'" + datdt_string + "\')"; - } - - bool has_fp_bug() const SOCI_OVERRIDE - { - // The bug with using insufficiently many digits for double values was - // only fixed in 9.03.0400 version of the ODBC driver (see commit - // a5fed2338b59ae16a2d3a8d2744b084949684775 in its repository), so we - // need to check for its version here. - // - // Be pessimistic if we failed to retrieve the version at all. - return !m_verDriver.is_initialized() || m_verDriver < odbc_version(9, 3, 400); - } - - std::string sql_length(std::string const& s) const SOCI_OVERRIDE - { - return "char_length(" + s + ")"; - } - -private: - odbc_version get_driver_version() const - { - try - { - soci::session sql(get_backend_factory(), get_connect_string()); - odbc_session_backend* const - odbc_session = static_cast(sql.get_backend()); - if (!odbc_session) - { - std::cerr << "Failed to get odbc_session_backend?\n"; - return odbc_version(); - } - - char driver_ver[1024]; - SQLSMALLINT len = sizeof(driver_ver); - SQLRETURN rc = SQLGetInfo(odbc_session->hdbc_, SQL_DRIVER_VER, - driver_ver, len, &len); - if (soci::is_odbc_error(rc)) - { - std::cerr << "Retrieving ODBC driver version failed: " - << rc << "\n"; - return odbc_version(); - } - - odbc_version v; - if (!v.init_from_string(driver_ver)) - { - std::cerr << "Unknown ODBC driver version format: \"" - << driver_ver << "\"\n"; - } - - return v; - } - catch ( ... ) - { - // Failure getting the version is not fatal. - return odbc_version(); - } - } - - odbc_version const m_verDriver; -}; - -int main(int argc, char** argv) -{ - -#ifdef _MSC_VER - // Redirect errors, unrecoverable problems, and assert() failures to STDERR, - // instead of debug message window. - // This hack is required to run assert()-driven tests by Buildbot. - // NOTE: Comment this 2 lines for debugging with Visual C++ debugger to catch assertions inside. - _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); - _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); -#endif //_MSC_VER - - if (argc >= 2 && argv[1][0] != '-') - { - connectString = argv[1]; - - // Replace the connect string with the process name to ensure that - // CATCH uses the correct name in its messages. - argv[1] = argv[0]; - - argc--; - argv++; - } - else - { - connectString = "FILEDSN=./test-postgresql.dsn"; - } - - test_context tc(backEnd, connectString); - - return Catch::Session().run(argc, argv); -} diff --git a/src/soci/tests/odbc/test-postgresql-win64.dsn b/src/soci/tests/odbc/test-postgresql-win64.dsn deleted file mode 100644 index 334ff1d9b8..0000000000 --- a/src/soci/tests/odbc/test-postgresql-win64.dsn +++ /dev/null @@ -1,9 +0,0 @@ -[ODBC] -Description=DSN for SOCI ODBC connection to PostgreSQL(AppVeyor) -Driver=PostgreSQL ANSI(x64) -Server=localhost -Port=5432 -Database=soci_test -UID=postgres -PWD=Password12! -UnknownsAsLongVarchar=1 diff --git a/src/soci/tests/odbc/test-postgresql.dsn b/src/soci/tests/odbc/test-postgresql.dsn deleted file mode 100644 index 9af148d2a7..0000000000 --- a/src/soci/tests/odbc/test-postgresql.dsn +++ /dev/null @@ -1,9 +0,0 @@ -[ODBC] -Description=DSN for SOCI ODBC connection to PostgreSQL(Travis-CI) -Driver=PostgreSQL ANSI -Server=localhost -Port=5432 -Database=soci_test -UID=postgres -PWD=Password12! -UnknownsAsLongVarchar=1 diff --git a/src/soci/tests/oracle/CMakeLists.txt b/src/soci/tests/oracle/CMakeLists.txt deleted file mode 100644 index da6767ba93..0000000000 --- a/src/soci/tests/oracle/CMakeLists.txt +++ /dev/null @@ -1,16 +0,0 @@ -############################################################################### -# -# This file is part of CMake configuration for SOCI library -# -# Copyright (C) 2010-2013 Mateusz Loskot -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -# -############################################################################### - -soci_backend_test( - BACKEND Oracle - DEPENDS Oracle - SOURCE test-oracle.cpp ${SOCI_TESTS_COMMON} - CONNSTR "service=orcl user=scott password=tiger") diff --git a/src/soci/tests/oracle/Makefile.basic b/src/soci/tests/oracle/Makefile.basic deleted file mode 100644 index 11c3e24cd6..0000000000 --- a/src/soci/tests/oracle/Makefile.basic +++ /dev/null @@ -1,13 +0,0 @@ -COMPILER = g++ -CXXFLAGS = -Wall -pedantic -Wno-long-long -INCLUDEDIRS = -I../../include -I../../include/private -I.. \ - -I${ORACLE_HOME}/rdbms/public -LIBDIRS = -L../../src/core -L../../src/backends/oracle -L${ORACLE_HOME}/lib -LIBS = -lsoci_core -lsoci_oracle -ldl -lclntsh -locci -lnnz11 - -test-oracle : test-oracle.cpp - ${COMPILER} $? -o $@ ${INCLUDEDIRS} ${LIBDIRS} ${LIBS} - - -clean : - rm -f test-oracle diff --git a/src/soci/tests/oracle/test-oracle.cpp b/src/soci/tests/oracle/test-oracle.cpp deleted file mode 100644 index b699b22f91..0000000000 --- a/src/soci/tests/oracle/test-oracle.cpp +++ /dev/null @@ -1,1589 +0,0 @@ -// -// // Copyright (C) 2004-2007 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#include "common-tests.h" -#include "soci/soci.h" -#include "soci/oracle/soci-oracle.h" -#include -#include -#include -#include - -using namespace soci; -using namespace soci::tests; - -std::string connectString; -backend_factory const &backEnd = *soci::factory_oracle(); - -// Extra tests for date/time -TEST_CASE("Oracle datetime", "[oracle][datetime]") -{ - soci::session sql(backEnd, connectString); - - { - std::time_t now = std::time(NULL); - std::tm t1, t2; - t2 = *std::localtime(&now); - - sql << "select t from (select :t as t from dual)", - into(t1), use(t2); - - CHECK(t1.tm_sec == t2.tm_sec); - CHECK(t1.tm_min == t2.tm_min); - CHECK(t1.tm_hour == t2.tm_hour); - CHECK(t1.tm_mday == t2.tm_mday); - CHECK(t1.tm_mon == t2.tm_mon); - CHECK(t1.tm_year == t2.tm_year); - CHECK(t1.tm_wday == t2.tm_wday); - CHECK(t1.tm_yday == t2.tm_yday); - CHECK(t1.tm_isdst == t2.tm_isdst); - - // make sure the date is stored properly in Oracle - char buf[25]; - strftime(buf, sizeof(buf), "%m-%d-%Y %H:%M:%S", &t2); - - std::string t_out; - std::string format("MM-DD-YYYY HH24:MI:SS"); - sql << "select to_char(t, :format) from (select :t as t from dual)", - into(t_out), use(format), use(t2); - - CHECK(t_out == std::string(buf)); - } - - { - // date and time - before year 2000 - std::time_t then = std::time(NULL) - 17*365*24*60*60; - std::tm t1, t2; - t2 = *std::localtime(&then); - - sql << "select t from (select :t as t from dual)", - into(t1), use(t2); - - CHECK(t1.tm_sec == t2.tm_sec); - CHECK(t1.tm_min == t2.tm_min); - CHECK(t1.tm_hour == t2.tm_hour); - CHECK(t1.tm_mday == t2.tm_mday); - CHECK(t1.tm_mon == t2.tm_mon); - CHECK(t1.tm_year == t2.tm_year); - CHECK(t1.tm_wday == t2.tm_wday); - CHECK(t1.tm_yday == t2.tm_yday); - CHECK(t1.tm_isdst == t2.tm_isdst); - - // make sure the date is stored properly in Oracle - char buf[25]; - strftime(buf, sizeof(buf), "%m-%d-%Y %H:%M:%S", &t2); - - std::string t_out; - std::string format("MM-DD-YYYY HH24:MI:SS"); - sql << "select to_char(t, :format) from (select :t as t from dual)", - into(t_out), use(format), use(t2); - - CHECK(t_out == std::string(buf)); - } -} - -// explicit calls test -TEST_CASE("Oracle explicit calls", "[oracle]") -{ - soci::session sql(backEnd, connectString); - - statement st(sql); - st.alloc(); - int i = 0; - st.exchange(into(i)); - st.prepare("select 7 from dual"); - st.define_and_bind(); - st.execute(1); - CHECK(i == 7); -} - -// DDL + blob test - -struct blob_table_creator : public table_creator_base -{ - blob_table_creator(soci::session & sql) - : table_creator_base(sql) - { - sql << - "create table soci_test (" - " id number(10) not null," - " img blob" - ")"; - } -}; - -TEST_CASE("Oracle blob", "[oracle][blob]") -{ - { - session sql(backEnd, connectString); - - blob_table_creator tableCreator(sql); - - char buf[] = "abcdefghijklmnopqrstuvwxyz"; - sql << "insert into soci_test (id, img) values (7, empty_blob())"; - - { - blob b(sql); - - oracle_session_backend *sessionBackEnd - = static_cast(sql.get_backend()); - - oracle_blob_backend *blobBackEnd - = static_cast(b.get_backend()); - - OCILobDisableBuffering(sessionBackEnd->svchp_, - sessionBackEnd->errhp_, blobBackEnd->lobp_); - - sql << "select img from soci_test where id = 7", into(b); - CHECK(b.get_len() == 0); - - // note: blob offsets start from 1 - b.write(1, buf, sizeof(buf)); - CHECK(b.get_len() == sizeof(buf)); - b.trim(10); - CHECK(b.get_len() == 10); - - // append does not work (Oracle bug #886191 ?) - //b.append(buf, sizeof(buf)); - //assert(b.get_len() == sizeof(buf) + 10); - sql.commit(); - } - - { - blob b(sql); - sql << "select img from soci_test where id = 7", into(b); - //assert(b.get_len() == sizeof(buf) + 10); - CHECK(b.get_len() == 10); - char buf2[100]; - b.read(1, buf2, 10); - CHECK(strncmp(buf2, "abcdefghij", 10) == 0); - } - } - - // additional sibling test for read_from_start and write_from_start - { - session sql(backEnd, connectString); - - blob_table_creator tableCreator(sql); - - char buf[] = "abcdefghijklmnopqrstuvwxyz"; - sql << "insert into soci_test (id, img) values (7, empty_blob())"; - - { - blob b(sql); - - oracle_session_backend *sessionBackEnd - = static_cast(sql.get_backend()); - - oracle_blob_backend *blobBackEnd - = static_cast(b.get_backend()); - - OCILobDisableBuffering(sessionBackEnd->svchp_, - sessionBackEnd->errhp_, blobBackEnd->lobp_); - - sql << "select img from soci_test where id = 7", into(b); - CHECK(b.get_len() == 0); - - // note: blob offsets start from 1 - b.write_from_start(buf, sizeof(buf)); - CHECK(b.get_len() == sizeof(buf)); - b.trim(10); - CHECK(b.get_len() == 10); - - // append does not work (Oracle bug #886191 ?) - //b.append(buf, sizeof(buf)); - //assert(b.get_len() == sizeof(buf) + 10); - sql.commit(); - } - - { - blob b(sql); - sql << "select img from soci_test where id = 7", into(b); - //assert(b.get_len() == sizeof(buf) + 10); - CHECK(b.get_len() == 10); - char buf2[100]; - b.read_from_start(buf2, 10); - CHECK(strncmp(buf2, "abcdefghij", 10) == 0); - } - } -} - -// nested statement test -// (the same syntax is used for output cursors in PL/SQL) - -struct basic_table_creator : public table_creator_base -{ - basic_table_creator(soci::session & sql) - : table_creator_base(sql) - { - sql << - "create table soci_test (" - " id number(5) not null," - " name varchar2(100)," - " code number(5)" - ")"; - } -}; - -TEST_CASE("Oracle nested statement", "[oracle][blob]") -{ - soci::session sql(backEnd, connectString); - basic_table_creator tableCreator(sql); - - int id; - std::string name; - { - statement st1 = (sql.prepare << - "insert into soci_test (id, name) values (:id, :name)", - use(id), use(name)); - - id = 1; name = "John"; st1.execute(1); - id = 2; name = "Anna"; st1.execute(1); - id = 3; name = "Mike"; st1.execute(1); - } - - statement stInner(sql); - statement stOuter = (sql.prepare << - "select cursor(select name from soci_test order by id)" - " from soci_test where id = 1", - into(stInner)); - stInner.exchange(into(name)); - stOuter.execute(); - stOuter.fetch(); - - std::vector names; - while (stInner.fetch()) { names.push_back(name); } - - REQUIRE(names.size() == 3); - CHECK(names[0] == "John"); - CHECK(names[1] == "Anna"); - CHECK(names[2] == "Mike"); -} - - -// ROWID test -TEST_CASE("Oracle rowid", "[oracle][rowid]") -{ - soci::session sql(backEnd, connectString); - basic_table_creator tableCreator(sql); - - sql << "insert into soci_test(id, name) values(7, \'John\')"; - - rowid rid(sql); - sql << "select rowid from soci_test where id = 7", into(rid); - - int id; - std::string name; - sql << "select id, name from soci_test where rowid = :rid", - into(id), into(name), use(rid); - - CHECK(id == 7); - CHECK(name == "John"); -} - -// Stored procedures -struct procedure_creator : procedure_creator_base -{ - procedure_creator(soci::session & sql) - : procedure_creator_base(sql) - { - sql << - "create or replace procedure soci_test(output out varchar2," - "input in varchar2) as " - "begin output := input; end;"; - } -}; - -TEST_CASE("Oracle stored procedure", "[oracle][stored-procedure]") -{ - soci::session sql(backEnd, connectString); - procedure_creator procedure_creator(sql); - - std::string in("my message"); - std::string out; - statement st = (sql.prepare << - "begin soci_test(:output, :input); end;", - use(out, "output"), - use(in, "input")); - st.execute(1); - CHECK(out == in); - - // explicit procedure syntax - { - std::string in("my message2"); - std::string out; - procedure proc = (sql.prepare << - "soci_test(:output, :input)", - use(out, "output"), use(in, "input")); - proc.execute(1); - CHECK(out == in); - } -} - -// bind into user-defined objects -struct string_holder -{ - string_holder() {} - string_holder(const char* s) : s_(s) {} - string_holder(std::string s) : s_(s) {} - std::string get() const { return s_; } -private: - std::string s_; -}; - -namespace soci -{ - template <> - struct type_conversion - { - typedef std::string base_type; - static void from_base(const std::string &s, indicator /* ind */, - string_holder &sh) - { - sh = string_holder(s); - } - - static void to_base(const string_holder &sh, std::string &s, indicator &ind) - { - s = sh.get(); - ind = i_ok; - } - }; -} - -struct in_out_procedure_creator : public procedure_creator_base -{ - in_out_procedure_creator(soci::session & sql) - : procedure_creator_base(sql) - { - sql << "create or replace procedure soci_test(s in out varchar2)" - " as begin s := s || s; end;"; - } -}; - -struct returns_null_procedure_creator : public procedure_creator_base -{ - returns_null_procedure_creator(soci::session & sql) - : procedure_creator_base(sql) - { - sql << "create or replace procedure soci_test(s in out varchar2)" - " as begin s := NULL; end;"; - } -}; - -TEST_CASE("Oracle user-defined objects", "[oracle][type_conversion]") -{ - soci::session sql(backEnd, connectString); - { - basic_table_creator tableCreator(sql); - - int id(1); - string_holder in("my string"); - sql << "insert into soci_test(id, name) values(:id, :name)", use(id), use(in); - - string_holder out; - sql << "select name from soci_test", into(out); - CHECK(out.get() == "my string"); - - row r; - sql << "select * from soci_test", into(r); - string_holder dynamicOut = r.get(1); - CHECK(dynamicOut.get() == "my string"); - } -} - -TEST_CASE("Oracle user-defined objects in/out", "[oracle][type_conversion]") -{ - soci::session sql(backEnd, connectString); - - // test procedure with user-defined type as in-out parameter - { - in_out_procedure_creator procedureCreator(sql); - - std::string sh("test"); - procedure proc = (sql.prepare << "soci_test(:s)", use(sh)); - proc.execute(1); - CHECK(sh == "testtest"); - } - - // test procedure with user-defined type as in-out parameter - { - in_out_procedure_creator procedureCreator(sql); - - string_holder sh("test"); - procedure proc = (sql.prepare << "soci_test(:s)", use(sh)); - proc.execute(1); - CHECK(sh.get() == "testtest"); - } -} - -TEST_CASE("Oracle null user-defined objects in/out", "[oracle][null][type_conversion]") -{ - soci::session sql(backEnd, connectString); - - // test procedure which returns null - returns_null_procedure_creator procedureCreator(sql); - - string_holder sh; - indicator ind = i_ok; - procedure proc = (sql.prepare << "soci_test(:s)", use(sh, ind)); - proc.execute(1); - CHECK(ind == i_null); -} - -// test bulk insert features -TEST_CASE("Oracle bulk insert", "[oracle][insert][bulk]") -{ - soci::session sql(backEnd, connectString); - - basic_table_creator tableCreator(sql); - - // verify exception is thrown if vectors of unequal size are passed in - { - std::vector ids; - ids.push_back(1); - ids.push_back(2); - std::vector codes; - codes.push_back(1); - - try - { - sql << "insert into soci_test(id,code) values(:id,:code)", - use(ids), use(codes); - FAIL("expected exception not thrown"); - } - catch (soci_error const &e) - { - std::string const error = e.what(); - CAPTURE(error); - CHECK(error.find("Bind variable size mismatch") - != std::string::npos); - } - - try - { - sql << "select from soci_test", into(ids), into(codes); - FAIL("expected exception not thrown"); - } - catch (std::exception const &e) - { - std::string const error = e.what(); - CAPTURE(error); - CHECK(error.find("Bind variable size mismatch") - != std::string::npos); - } - } - - // verify partial insert occurs when one of the records is bad - { - std::vector ids; - ids.push_back(100); - ids.push_back(1000000); // too big for column - - try - { - sql << "insert into soci_test (id) values(:id)", use(ids, "id"); - FAIL("expected exception not thrown"); - } - catch (soci_error const &e) - { - std::string const error = e.what(); - //TODO e could be made to tell which row(s) failed - CAPTURE(error); - CHECK(error.find("ORA-01438") != std::string::npos); - } - sql.commit(); - int count(7); - sql << "select count(*) from soci_test", into(count); - CHECK(count == 1); - sql << "delete from soci_test"; - } - - // test insert - { - std::vector ids; - for (int i = 0; i != 3; ++i) - { - ids.push_back(i+10); - } - - statement st = (sql.prepare << "insert into soci_test(id) values(:id)", - use(ids)); - st.execute(1); - int count; - sql << "select count(*) from soci_test", into(count); - CHECK(count == 3); - } - - //verify an exception is thrown if into vector is zero length - { - std::vector ids; - CHECK_THROWS_AS((sql << "select id from soci_test", into(ids)), soci_error); - } - - // verify an exception is thrown if use vector is zero length - { - std::vector ids; - CHECK_THROWS_AS((sql << "insert into soci_test(id) values(:id)", use(ids)), soci_error); - } - - // test "no data" condition - { - std::vector inds(3); - std::vector ids_out(3); - statement st = (sql.prepare << "select id from soci_test where 1=0", - into(ids_out, inds)); - - // false return value means "no data" - CHECK(st.execute(1) == false); - - // that's it - nothing else is guaranteed - // and nothing else is to be tested here - } - - // test NULL indicators - { - std::vector ids(3); - sql << "select id from soci_test", into(ids); - - std::vector inds_in; - inds_in.push_back(i_ok); - inds_in.push_back(i_null); - inds_in.push_back(i_ok); - - std::vector new_codes; - new_codes.push_back(10); - new_codes.push_back(11); - new_codes.push_back(10); - - sql << "update soci_test set code = :code where id = :id", - use(new_codes, inds_in), use(ids); - - std::vector inds_out(3); - std::vector codes(3); - - sql << "select code from soci_test", into(codes, inds_out); - REQUIRE(codes.size() == 3); - REQUIRE(inds_out.size() == 3); - CHECK(codes[0] == 10); - CHECK(codes[2] == 10); - CHECK(inds_out[0] == i_ok); - CHECK(inds_out[1] == i_null); - CHECK(inds_out[2] == i_ok); - } - - // verify an exception is thrown if null is selected - // and no indicator was provided - { - std::string msg; - std::vector intos(3); - try - { - sql << "select code from soci_test", into(intos); - FAIL("expected exception not thrown"); - } - catch (soci_error const &e) - { - CHECK(e.get_error_message() == - "Null value fetched and no indicator defined." ); - } - } - - // test basic select - { - const size_t sz = 3; - std::vector inds(sz); - std::vector ids_out(sz); - statement st = (sql.prepare << "select id from soci_test", - into(ids_out, inds)); - const bool gotData = st.execute(true); - CHECK(gotData); - REQUIRE(ids_out.size() == sz); - CHECK(ids_out[0] == 10); - CHECK(ids_out[2] == 12); - REQUIRE(inds.size() == 3); - CHECK(inds[0] == i_ok); - CHECK(inds[1] == i_ok); - CHECK(inds[2] == i_ok); - } - - // verify execute(0) - { - std::vector ids_out(2); - statement st = (sql.prepare << "select id from soci_test", - into(ids_out)); - - st.execute(); - REQUIRE(ids_out.size() == 2); - bool gotData = st.fetch(); - CHECK(gotData); - REQUIRE(ids_out.size() == 2); - CHECK(ids_out[0] == 10); - CHECK(ids_out[1] == 11); - gotData = st.fetch(); - CHECK(gotData); - REQUIRE(ids_out.size() == 1); - CHECK(ids_out[0] == 12); - gotData = st.fetch(); - CHECK(gotData == false); - } - - // verify resizing happens if vector is larger - // than number of rows returned - { - std::vector ids_out(4); // one too many - statement st2 = (sql.prepare << "select id from soci_test", - into(ids_out)); - bool gotData = st2.execute(true); - CHECK(gotData); - REQUIRE(ids_out.size() == 3); - CHECK(ids_out[0] == 10); - CHECK(ids_out[2] == 12); - } - - // verify resizing happens properly during fetch() - { - std::vector more; - more.push_back(13); - more.push_back(14); - sql << "insert into soci_test(id) values(:id)", use(more); - - std::vector ids(2); - statement st3 = (sql.prepare << "select id from soci_test", into(ids)); - bool gotData = st3.execute(true); - CHECK(gotData); - CHECK(ids[0] == 10); - CHECK(ids[1] == 11); - - gotData = st3.fetch(); - CHECK(gotData); - CHECK(ids[0] == 12); - CHECK(ids[1] == 13); - - gotData = st3.fetch(); - CHECK(gotData); - REQUIRE(ids.size() == 1); - CHECK(ids[0] == 14); - - gotData = st3.fetch(); - CHECK(gotData == false); - } -} - -// more tests for bulk fetch -TEST_CASE("Oracle bulk fetch", "[oracle][fetch][bulk]") -{ - soci::session sql(backEnd, connectString); - - basic_table_creator tableCreator(sql); - - std::vector in; - for (int i = 1; i <= 10; ++i) - { - in.push_back(i); - } - - sql << "insert into soci_test (id) values(:id)", use(in); - - int count(0); - sql << "select count(*) from soci_test", into(count); - CHECK(count == 10); - - // verify that the exception is thrown when trying to resize - // the output vector to the size that is bigger than that - // at the time of binding - { - std::vector out(4); - statement st = (sql.prepare << - "select id from soci_test", into(out)); - - st.execute(); - - st.fetch(); - REQUIRE(out.size() == 4); - CHECK(out[0] == 1); - CHECK(out[1] == 2); - CHECK(out[2] == 3); - CHECK(out[3] == 4); - out.resize(5); // this should be detected as error - try - { - st.fetch(); - FAIL("expected exception not thrown"); - } - catch (soci_error const &e) - { - CHECK(e.get_error_message() == - "Increasing the size of the output vector is not supported."); - } - } - - // on the other hand, downsizing is OK - { - std::vector out(4); - statement st = (sql.prepare << - "select id from soci_test", into(out)); - - st.execute(); - - st.fetch(); - REQUIRE(out.size() == 4); - CHECK(out[0] == 1); - CHECK(out[1] == 2); - CHECK(out[2] == 3); - CHECK(out[3] == 4); - out.resize(3); // ok - st.fetch(); - REQUIRE(out.size() == 3); - CHECK(out[0] == 5); - CHECK(out[1] == 6); - CHECK(out[2] == 7); - out.resize(4); // ok, not bigger than initially - st.fetch(); - REQUIRE(out.size() == 3); // downsized because of end of data - CHECK(out[0] == 8); - CHECK(out[1] == 9); - CHECK(out[2] == 10); - bool gotData = st.fetch(); - CHECK(gotData == false); // end of data - } -} - -struct person -{ - int id; - std::string firstName; - string_holder lastName; //test mapping of type_conversion-based types - std::string gender; -}; - -// Object-Relational Mapping -// Note: Use the values class as shown below in type_conversions -// to achieve object relational mapping. The values class should -// not be used directly in any other fashion. -namespace soci -{ - // name-based conversion - template<> struct type_conversion - { - typedef values base_type; - - static void from_base(values const &v, indicator /* ind */, person &p) - { - // ignoring possibility that the whole object might be NULL - - p.id = v.get("ID"); - p.firstName = v.get("FIRST_NAME"); - p.lastName = v.get("LAST_NAME"); - p.gender = v.get("GENDER", "unknown"); - } - - static void to_base(person const & p, values & v, indicator & ind) - { - v.set("ID", p.id); - v.set("FIRST_NAME", p.firstName); - v.set("LAST_NAME", p.lastName); - v.set("GENDER", p.gender, p.gender.empty() ? i_null : i_ok); - ind = i_ok; - } - }; -} - -struct person_table_creator : public table_creator_base -{ - person_table_creator(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(id numeric(5,0) NOT NULL," - << " last_name varchar2(20), first_name varchar2(20), " - " gender varchar2(10))"; - } -}; - -struct times100_procedure_creator : public procedure_creator_base -{ - times100_procedure_creator(soci::session & sql) - : procedure_creator_base(sql) - { - sql << "create or replace procedure soci_test(id in out number)" - " as begin id := id * 100; end;"; - } -}; - -TEST_CASE("Oracle ORM", "[oracle][orm]") -{ - soci::session sql(backEnd, connectString); - - { - person_table_creator tableCreator(sql); - - person p; - p.id = 1; - p.lastName = "Smith"; - p.firstName = "Pat"; - sql << "insert into soci_test(id, first_name, last_name, gender) " - << "values(:ID, :FIRST_NAME, :LAST_NAME, :GENDER)", use(p); - - // p should be unchanged - CHECK(p.id == 1); - CHECK(p.firstName == "Pat"); - CHECK(p.lastName.get() == "Smith"); - - person p1; - sql << "select * from soci_test", into(p1); - CHECK(p1.id == 1); - CHECK(p1.firstName == "Pat"); - CHECK(p1.lastName.get() == "Smith"); - CHECK(p1.gender == "unknown"); - - p.firstName = "Patricia"; - sql << "update soci_test set first_name = :FIRST_NAME " - "where id = :ID", use(p); - - // p should be unchanged - CHECK(p.id == 1); - CHECK(p.firstName == "Patricia"); - CHECK(p.lastName.get() == "Smith"); - // Note: gender is now "unknown" because of the mapping, not "" - CHECK(p.gender == "unknown"); - - person p2; - sql << "select * from soci_test", into(p2); - CHECK(p2.id == 1); - CHECK(p2.firstName == "Patricia"); - CHECK(p2.lastName.get() == "Smith"); - - // insert a second row so we can test fetching - person p3; - p3.id = 2; - p3.firstName = "Joe"; - p3.lastName = "Smith"; - sql << "insert into soci_test(id, first_name, last_name, gender) " - << "values(:ID, :FIRST_NAME, :LAST_NAME, :GENDER)", use(p3); - - person p4; - statement st = (sql.prepare << "select * from soci_test order by id", - into(p4)); - - st.execute(); - bool gotData = st.fetch(); - CHECK(gotData); - CHECK(p4.id == 1); - CHECK(p4.firstName == "Patricia"); - - gotData = st.fetch(); - CHECK(gotData); - CHECK(p4.id == 2); - CHECK(p4.firstName == "Joe"); - gotData = st.fetch(); - CHECK(gotData == false); - } - - // test with stored procedure - { - times100_procedure_creator procedureCreator(sql); - - person p; - p.id = 1; - p.firstName = "Pat"; - p.lastName = "Smith"; - procedure proc = (sql.prepare << "soci_test(:ID)", use(p)); - proc.execute(1); - CHECK(p.id == 100); - CHECK(p.firstName == "Pat"); - CHECK(p.lastName.get() == "Smith"); - } - - // test with stored procedure which returns null - { - returns_null_procedure_creator procedureCreator(sql); - - person p; - try - { - procedure proc = (sql.prepare << "soci_test(:FIRST_NAME)", - use(p)); - proc.execute(1); - FAIL("expected exception not thrown"); - } - catch (soci_error& e) - { - CHECK(e.get_error_message() == - "Null value not allowed for this type"); - } - - procedure proc = (sql.prepare << "soci_test(:GENDER)", - use(p)); - proc.execute(1); - CHECK(p.gender == "unknown"); - - } -} - -// Experimental support for position based O/R Mapping - -// additional type for position-based test -struct person2 -{ - int id; - std::string firstName; - std::string lastName; - std::string gender; -}; - -// additional type for stream-like test -struct person3 : person2 {}; - -namespace soci -{ - // position-based conversion - template<> struct type_conversion - { - typedef values base_type; - - static void from_base(values const &v, indicator /* ind */, person2 &p) - { - p.id = v.get(0); - p.firstName = v.get(1); - p.lastName = v.get(2); - p.gender = v.get(3, "whoknows"); - } - - // What about the "to" part? Does it make any sense to have it? - }; - - // stream-like conversion - template<> struct type_conversion - { - typedef values base_type; - - static void from_base(values const &v, indicator /* ind */, person3 &p) - { - v >> p.id >> p.firstName >> p.lastName >> p.gender; - } - // TODO: The "to" part is certainly needed. - }; -} - -TEST_CASE("Oracle ORM by index", "[oracle][orm]") -{ - soci::session sql(backEnd, connectString); - - person_table_creator tableCreator(sql); - - person p; - p.id = 1; - p.lastName = "Smith"; - p.firstName = "Patricia"; - sql << "insert into soci_test(id, first_name, last_name, gender) " - << "values(:ID, :FIRST_NAME, :LAST_NAME, :GENDER)", use(p); - - // test position-based conversion - person2 p3; - sql << "select id, first_name, last_name, gender from soci_test", into(p3); - CHECK(p3.id == 1); - CHECK(p3.firstName == "Patricia"); - CHECK(p3.lastName == "Smith"); - CHECK(p3.gender == "whoknows"); - - sql << "update soci_test set gender = 'F' where id = 1"; - - // additional test for stream-like conversion - person3 p4; - sql << "select id, first_name, last_name, gender from soci_test", into(p4); - CHECK(p4.id == 1); - CHECK(p4.firstName == "Patricia"); - CHECK(p4.lastName == "Smith"); - CHECK(p4.gender == "F"); -} - -// -// Backwards compatibility - support use of large strings with -// columns of type LONG -/// -struct long_table_creator : public table_creator_base -{ - long_table_creator(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(l long)"; - } -}; - -TEST_CASE("Oracle large strings as long", "[oracle][compatibility]") -{ - soci::session sql(backEnd, connectString); - long_table_creator creator(sql); - - const std::string::size_type max = 32768; - std::string in(max, 'X'); - - sql << "insert into soci_test values(:l)", use(in); - - std::string out; - sql << "select l from soci_test", into(out); - - CHECK(out.size() == max); - CHECK(in == out); -} - -// test for modifiable and const use elements -TEST_CASE("Oracle const and modifiable parameters", "[oracle][use]") -{ - soci::session sql(backEnd, connectString); - - int i = 7; - sql << "begin " - "select 2 * :i into :i from dual; " - "end;", use(i); - CHECK(i == 14); - - const int j = 7; - try - { - sql << "begin " - "select 2 * :i into :i from dual;" - " end;", use(j); - - FAIL("expected exception not thrown"); - } - catch (soci_error const & e) - { - CHECK(e.get_error_message() == - "Attempted modification of const use element"); - } -} - -struct longlong_table_creator : table_creator_base -{ - longlong_table_creator(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(val number(20))"; - } -}; - -// long long test -TEST_CASE("Oracle long long", "[oracle][longlong]") -{ - { - soci::session sql(backEnd, connectString); - - longlong_table_creator tableCreator(sql); - - long long v1 = 1000000000000LL; - sql << "insert into soci_test(val) values(:val)", use(v1); - - long long v2 = 0LL; - sql << "select val from soci_test", into(v2); - - CHECK(v2 == v1); - } - - // vector - { - soci::session sql(backEnd, connectString); - - longlong_table_creator tableCreator(sql); - - std::vector v1; - v1.push_back(1000000000000LL); - v1.push_back(1000000000001LL); - v1.push_back(1000000000002LL); - v1.push_back(1000000000003LL); - v1.push_back(1000000000004LL); - - sql << "insert into soci_test(val) values(:val)", use(v1); - - std::vector v2(10); - sql << "select val from soci_test order by val desc", into(v2); - - REQUIRE(v2.size() == 5); - CHECK(v2[0] == 1000000000004LL); - CHECK(v2[1] == 1000000000003LL); - CHECK(v2[2] == 1000000000002LL); - CHECK(v2[3] == 1000000000001LL); - CHECK(v2[4] == 1000000000000LL); - } -} - -// Test the DDL and metadata functionality -TEST_CASE("Oracle DDL with metadata", "[oracle][ddl]") -{ - soci::session sql(backEnd, connectString); - - // note: prepare_column_descriptions expects l-value - std::string ddl_t1 = "DDL_T1"; - std::string ddl_t2 = "DDL_T2"; - std::string ddl_t3 = "DDL_T3"; - - // single-expression variant: - sql.create_table(ddl_t1).column("I", soci::dt_integer).column("J", soci::dt_integer); - - // check whether this table was created: - - bool ddl_t1_found = false; - bool ddl_t2_found = false; - bool ddl_t3_found = false; - std::string table_name; - soci::statement st = (sql.prepare_table_names(), into(table_name)); - st.execute(); - while (st.fetch()) - { - if (table_name == ddl_t1) { ddl_t1_found = true; } - if (table_name == ddl_t2) { ddl_t2_found = true; } - if (table_name == ddl_t3) { ddl_t3_found = true; } - } - - CHECK(ddl_t1_found); - CHECK(ddl_t2_found == false); - CHECK(ddl_t3_found == false); - - // check whether ddl_t1 has the right structure: - - bool i_found = false; - bool j_found = false; - bool other_found = false; - soci::column_info ci; - soci::statement st1 = (sql.prepare_column_descriptions(ddl_t1), into(ci)); - st1.execute(); - while (st1.fetch()) - { - if (ci.name == "I") - { - CHECK(ci.type == soci::dt_integer); - CHECK(ci.nullable); - i_found = true; - } - else if (ci.name == "J") - { - CHECK(ci.type == soci::dt_integer); - CHECK(ci.nullable); - j_found = true; - } - else - { - other_found = true; - } - } - - CHECK(i_found); - CHECK(j_found); - CHECK(other_found == false); - - // two more tables: - - // separately defined columns: - // (note: statement is executed when ddl object goes out of scope) - { - soci::ddl_type ddl = sql.create_table(ddl_t2); - ddl.column("I", soci::dt_integer); - ddl.column("J", soci::dt_integer); - ddl.column("K", soci::dt_integer)("not null"); - ddl.primary_key("t2_pk", "J"); - } - - sql.add_column(ddl_t1, "K", soci::dt_integer); - sql.add_column(ddl_t1, "BIG", soci::dt_string, 0); // "unlimited" length -> CLOB - sql.drop_column(ddl_t1, "I"); - - // or with constraint as in t2: - sql.add_column(ddl_t2, "M", soci::dt_integer)("not null"); - - // third table with a foreign key to the second one - { - soci::ddl_type ddl = sql.create_table(ddl_t3); - ddl.column("X", soci::dt_integer); - ddl.column("Y", soci::dt_integer); - ddl.foreign_key("t3_fk", "X", ddl_t2, "J"); - } - - // check if all tables were created: - - ddl_t1_found = false; - ddl_t2_found = false; - ddl_t3_found = false; - soci::statement st2 = (sql.prepare_table_names(), into(table_name)); - st2.execute(); - while (st2.fetch()) - { - if (table_name == ddl_t1) { ddl_t1_found = true; } - if (table_name == ddl_t2) { ddl_t2_found = true; } - if (table_name == ddl_t3) { ddl_t3_found = true; } - } - - CHECK(ddl_t1_found); - CHECK(ddl_t2_found); - CHECK(ddl_t3_found); - - // check if ddl_t1 has the right structure (it was altered): - - i_found = false; - j_found = false; - bool k_found = false; - bool big_found = false; - other_found = false; - soci::statement st3 = (sql.prepare_column_descriptions(ddl_t1), into(ci)); - st3.execute(); - while (st3.fetch()) - { - if (ci.name == "J") - { - CHECK(ci.type == soci::dt_integer); - CHECK(ci.nullable); - j_found = true; - } - else if (ci.name == "K") - { - CHECK(ci.type == soci::dt_integer); - CHECK(ci.nullable); - k_found = true; - } - else if (ci.name == "BIG") - { - CHECK(ci.type == soci::dt_string); - CHECK(ci.precision == 0); // "unlimited" for strings - big_found = true; - } - else - { - other_found = true; - } - } - - CHECK(i_found == false); - CHECK(j_found); - CHECK(k_found); - CHECK(big_found); - CHECK(other_found == false); - - // check if ddl_t2 has the right structure: - - i_found = false; - j_found = false; - k_found = false; - bool m_found = false; - other_found = false; - soci::statement st4 = (sql.prepare_column_descriptions(ddl_t2), into(ci)); - st4.execute(); - while (st4.fetch()) - { - if (ci.name == "I") - { - CHECK(ci.type == soci::dt_integer); - CHECK(ci.nullable); - i_found = true; - } - else if (ci.name == "J") - { - CHECK(ci.type == soci::dt_integer); - CHECK(ci.nullable == false); // primary key - j_found = true; - } - else if (ci.name == "K") - { - CHECK(ci.type == soci::dt_integer); - CHECK(ci.nullable == false); - k_found = true; - } - else if (ci.name == "M") - { - CHECK(ci.type == soci::dt_integer); - CHECK(ci.nullable == false); - m_found = true; - } - else - { - other_found = true; - } - } - - CHECK(i_found); - CHECK(j_found); - CHECK(k_found); - CHECK(m_found); - CHECK(other_found == false); - - sql.drop_table(ddl_t1); - sql.drop_table(ddl_t3); // note: this must be dropped before ddl_t2 - sql.drop_table(ddl_t2); - - // check if all tables were dropped: - - ddl_t1_found = false; - ddl_t2_found = false; - ddl_t3_found = false; - st2 = (sql.prepare_table_names(), into(table_name)); - st2.execute(); - while (st2.fetch()) - { - if (table_name == ddl_t1) { ddl_t1_found = true; } - if (table_name == ddl_t2) { ddl_t2_found = true; } - if (table_name == ddl_t3) { ddl_t3_found = true; } - } - - CHECK(ddl_t1_found == false); - CHECK(ddl_t2_found == false); - CHECK(ddl_t3_found == false); - - int i = -1; - sql << "select length(" + sql.empty_blob() + ") from dual", into(i); - CHECK(i == 0); - sql << "select " + sql.nvl() + "(1, 2) from dual", into(i); - CHECK(i == 1); - sql << "select " + sql.nvl() + "(NULL, 2) from dual", into(i); - CHECK(i == 2); -} - -// Test the bulk iterators functionality -TEST_CASE("Bulk iterators", "[oracle][bulkiters]") -{ - soci::session sql(backEnd, connectString); - - sql << "create table t (i integer)"; - - // test bulk iterators with basic types - { - std::vector v; - v.push_back(10); - v.push_back(20); - v.push_back(30); - v.push_back(40); - v.push_back(50); - - std::size_t begin = 2; - std::size_t end = 5; - sql << "insert into t (i) values (:v)", soci::use(v, begin, end); - - v.clear(); - v.resize(20); - begin = 5; - end = 20; - sql << "select i from t", soci::into(v, begin, end); - - CHECK(end == 8); - for (std::size_t i = 0; i != 5; ++i) - { - CHECK(v[i] == 0); - } - CHECK(v[5] == 30); - CHECK(v[6] == 40); - CHECK(v[7] == 50); - for (std::size_t i = end; i != 20; ++i) - { - CHECK(v[i] == 0); - } - } - - sql << "delete from t"; - - // test bulk iterators with user types - { - std::vector v; - v.push_back(MyInt(10)); - v.push_back(MyInt(20)); - v.push_back(MyInt(30)); - v.push_back(MyInt(40)); - v.push_back(MyInt(50)); - - std::size_t begin = 2; - std::size_t end = 5; - sql << "insert into t (i) values (:v)", soci::use(v, begin, end); - - v.clear(); - for (std::size_t i = 0; i != 20; ++i) - { - v.push_back(MyInt(-1)); - } - - begin = 5; - end = 20; - sql << "select i from t", soci::into(v, begin, end); - - CHECK(end == 8); - for (std::size_t i = 0; i != 5; ++i) - { - CHECK(v[i].get() == -1); - } - CHECK(v[5].get() == 30); - CHECK(v[6].get() == 40); - CHECK(v[7].get() == 50); - for (std::size_t i = end; i != 20; ++i) - { - CHECK(v[i].get() == -1); - } - } - - sql << "drop table t"; -} - -// -// Support for soci Common Tests -// - -struct table_creator_one : public table_creator_base -{ - table_creator_one(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(id number(10,0), val number(4,0), c char, " - "str varchar2(20), sh number, ul number, d number, " - "num76 numeric(7,6), " - "tm date, i1 number, i2 number, i3 number, name varchar2(20))"; - } -}; - -struct table_creator_two : public table_creator_base -{ - table_creator_two(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(num_float number, num_int numeric(4,0)," - " name varchar2(20), sometime date, chr char)"; - } -}; - -struct table_creator_three : public table_creator_base -{ - table_creator_three(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(name varchar2(100) not null, " - "phone varchar2(15))"; - } -}; - -struct table_creator_four : public table_creator_base -{ - table_creator_four(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(val number)"; - } -}; - -struct table_creator_for_xml : table_creator_base -{ - table_creator_for_xml(soci::session& sql) - : table_creator_base(sql) - { - sql << "create table soci_test(id integer, x xmltype)"; - } -}; - -struct table_creator_for_clob : table_creator_base -{ - table_creator_for_clob(soci::session& sql) - : table_creator_base(sql) - { - sql << "create table soci_test(id integer, s clob)"; - } -}; - -class test_context :public test_context_base -{ -public: - test_context(backend_factory const &backEnd, - std::string const &connectString) - : test_context_base(backEnd, connectString) {} - - table_creator_base* table_creator_1(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_one(s); - } - - table_creator_base* table_creator_2(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_two(s); - } - - table_creator_base* table_creator_3(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_three(s); - } - - table_creator_base* table_creator_4(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_four(s); - } - - table_creator_base* table_creator_clob(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_for_clob(s); - } - - table_creator_base* table_creator_xml(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_for_xml(s); - } - - std::string to_xml(std::string const& x) const SOCI_OVERRIDE - { - return "xmltype(" + x + ")"; - } - - std::string from_xml(std::string const& x) const SOCI_OVERRIDE - { - // Notice that using just x.getCLOBVal() doesn't work, only - // table.x.getCLOBVal() or (x).getCLOBVal(), as used here, does. - return "(" + x + ").getCLOBVal()"; - } - - bool has_real_xml_support() const SOCI_OVERRIDE - { - return true; - } - - std::string to_date_time(std::string const &datdt_string) const SOCI_OVERRIDE - { - return "to_date('" + datdt_string + "', 'YYYY-MM-DD HH24:MI:SS')"; - } - - std::string sql_length(std::string const& s) const SOCI_OVERRIDE - { - // Oracle treats empty strings as NULLs, but we want to return the - // length of 0 for them for consistency with the other backends, so use - // nvl() explicitly to achieve this. - return "nvl(length(" + s + "), 0)"; - } -}; - -int main(int argc, char** argv) -{ -#ifdef _MSC_VER - // Redirect errors, unrecoverable problems, and assert() failures to STDERR, - // instead of debug message window. - // This hack is required to run assert()-driven tests by Buildbot. - // NOTE: Comment this 2 lines for debugging with Visual C++ debugger to catch assertions inside. - _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); - _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); -#endif //_MSC_VER - - if (argc >= 2) - { - connectString = argv[1]; - - // Replace the connect string with the process name to ensure that - // CATCH uses the correct name in its messages. - argv[1] = argv[0]; - - argc--; - argv++; - } - else - { - std::cout << "usage: " << argv[0] - << " connectstring [test-arguments...]\n" - << "example: " << argv[0] - << " \'service=orcl user=scott password=tiger\'\n"; - std::exit(1); - } - - test_context tc(backEnd, connectString); - - return Catch::Session().run(argc, argv); -} diff --git a/src/soci/tests/postgresql/CMakeLists.txt b/src/soci/tests/postgresql/CMakeLists.txt deleted file mode 100644 index 0fac5737b9..0000000000 --- a/src/soci/tests/postgresql/CMakeLists.txt +++ /dev/null @@ -1,16 +0,0 @@ -############################################################################### -# -# This file is part of CMake configuration for SOCI library -# -# Copyright (C) 2010-2013 Mateusz Loskot -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -# -############################################################################### - -soci_backend_test( - BACKEND PostgreSQL - DEPENDS PostgreSQL - SOURCE test-postgresql.cpp ${SOCI_TESTS_COMMON} - CONNSTR "dbname=soci_test") diff --git a/src/soci/tests/postgresql/Makefile.basic b/src/soci/tests/postgresql/Makefile.basic deleted file mode 100644 index 145347c358..0000000000 --- a/src/soci/tests/postgresql/Makefile.basic +++ /dev/null @@ -1,12 +0,0 @@ -COMPILER = g++ -CXXFLAGS = -Wall -pedantic -Wno-long-long -INCLUDEDIRS = -I../../include -I../../include/private -I.. -I/usr/include/postgresql -LIBDIRS = -L../../src/core -L../../src/backends/postgresql -L/usr/lib/x86_64-linux-gnu -LIBS = -lsoci_postgresql -lsoci_core -ldl -lpq - -test-postgresql : test-postgresql.cpp - ${COMPILER} $? -o $@ ${INCLUDEDIRS} ${LIBDIRS} ${LIBS} - - -clean : - rm -f test-postgresql diff --git a/src/soci/tests/postgresql/test-postgresql.cpp b/src/soci/tests/postgresql/test-postgresql.cpp deleted file mode 100644 index 9b0b4c86ec..0000000000 --- a/src/soci/tests/postgresql/test-postgresql.cpp +++ /dev/null @@ -1,1200 +0,0 @@ -// -// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#include "soci/soci.h" -#include "soci/postgresql/soci-postgresql.h" -#include "common-tests.h" -#include -#include -#include -#include -#include -#include -#include - -using namespace soci; -using namespace soci::tests; - -std::string connectString; -backend_factory const &backEnd = *soci::factory_postgresql(); - -// Postgres-specific tests - -struct oid_table_creator : public table_creator_base -{ - oid_table_creator(soci::session& sql) - : table_creator_base(sql) - { - sql << "create table soci_test (" - " id integer," - " name varchar(100)" - ") with oids"; - } -}; - -// ROWID test -// Note: in PostgreSQL, there is no ROWID, there is OID. -// It is still provided as a separate type for "portability", -// whatever that means. -TEST_CASE("PostgreSQL ROWID", "[postgresql][rowid][oid]") -{ - soci::session sql(backEnd, connectString); - - oid_table_creator tableCreator(sql); - - sql << "insert into soci_test(id, name) values(7, \'John\')"; - - rowid rid(sql); - sql << "select oid from soci_test where id = 7", into(rid); - - int id; - std::string name; - -#ifndef SOCI_POSTGRESQL_NOPARAMS - - sql << "select id, name from soci_test where oid = :rid", - into(id), into(name), use(rid); - -#else - // Older PostgreSQL does not support use elements. - - postgresql_rowid_backend *rbe - = static_cast(rid.get_backend()); - - unsigned long oid = rbe->value_; - - sql << "select id, name from soci_test where oid = " << oid, - into(id), into(name); - -#endif // SOCI_POSTGRESQL_NOPARAMS - - CHECK(id == 7); - CHECK(name == "John"); -} - -TEST_CASE("PostgreSQL prepare error", "[postgresql][exception]") -{ - soci::session sql(backEnd, connectString); - - // Must not cause the application to crash. - statement st(sql); - st.prepare(""); // Throws an exception in some versions. -} - -// function call test -class function_creator : function_creator_base -{ -public: - - function_creator(soci::session & sql) - : function_creator_base(sql) - { - // before a language can be used it must be defined - // if it has already been defined then an error will occur - try { sql << "create language plpgsql"; } - catch (soci_error const &) {} // ignore if error - -#ifndef SOCI_POSTGRESQL_NOPARAMS - - sql << - "create or replace function soci_test(msg varchar) " - "returns varchar as $$ " - "declare x int := 1;" - "begin " - " return msg; " - "end $$ language plpgsql"; -#else - - sql << - "create or replace function soci_test(varchar) " - "returns varchar as \' " - "declare x int := 1;" - "begin " - " return $1; " - "end \' language plpgsql"; -#endif - } - -protected: - - std::string drop_statement() - { - return "drop function soci_test(varchar)"; - } -}; - -TEST_CASE("PostgreSQL function call", "[postgresql][function]") -{ - soci::session sql(backEnd, connectString); - - function_creator functionCreator(sql); - - std::string in("my message"); - std::string out; - -#ifndef SOCI_POSTGRESQL_NOPARAMS - - statement st = (sql.prepare << - "select soci_test(:input)", - into(out), - use(in, "input")); - -#else - // Older PostgreSQL does not support use elements. - - statement st = (sql.prepare << - "select soci_test(\'" << in << "\')", - into(out)); - -#endif // SOCI_POSTGRESQL_NOPARAMS - - st.execute(true); - CHECK(out == in); - - // explicit procedure syntax - { - std::string in("my message2"); - std::string out; - -#ifndef SOCI_POSTGRESQL_NOPARAMS - - procedure proc = (sql.prepare << - "soci_test(:input)", - into(out), use(in, "input")); - -#else - // Older PostgreSQL does not support use elements. - - procedure proc = (sql.prepare << - "soci_test(\'" << in << "\')", into(out)); - -#endif // SOCI_POSTGRESQL_NOPARAMS - - proc.execute(true); - CHECK(out == in); - } -} - -// BLOB test -struct blob_table_creator : public table_creator_base -{ - blob_table_creator(soci::session & sql) - : table_creator_base(sql) - { - sql << - "create table soci_test (" - " id integer," - " img oid" - ")"; - } -}; - -TEST_CASE("PostgreSQL blob", "[postgresql][blob]") -{ - { - soci::session sql(backEnd, connectString); - - blob_table_creator tableCreator(sql); - - char buf[] = "abcdefghijklmnopqrstuvwxyz"; - - sql << "insert into soci_test(id, img) values(7, lo_creat(-1))"; - - // in PostgreSQL, BLOB operations must be within transaction block - transaction tr(sql); - - { - blob b(sql); - - sql << "select img from soci_test where id = 7", into(b); - CHECK(b.get_len() == 0); - - b.write(0, buf, sizeof(buf)); - CHECK(b.get_len() == sizeof(buf)); - - b.append(buf, sizeof(buf)); - CHECK(b.get_len() == 2 * sizeof(buf)); - } - { - blob b(sql); - sql << "select img from soci_test where id = 7", into(b); - CHECK(b.get_len() == 2 * sizeof(buf)); - char buf2[100]; - b.read(0, buf2, 10); - CHECK(std::strncmp(buf2, "abcdefghij", 10) == 0); - } - - unsigned long oid; - sql << "select img from soci_test where id = 7", into(oid); - sql << "select lo_unlink(" << oid << ")"; - } - - // additional sibling test for read_from_start and write_from_start - { - soci::session sql(backEnd, connectString); - - blob_table_creator tableCreator(sql); - - char buf[] = "abcdefghijklmnopqrstuvwxyz"; - - sql << "insert into soci_test(id, img) values(7, lo_creat(-1))"; - - // in PostgreSQL, BLOB operations must be within transaction block - transaction tr(sql); - - { - blob b(sql); - - sql << "select img from soci_test where id = 7", into(b); - CHECK(b.get_len() == 0); - - b.write_from_start(buf, sizeof(buf)); - CHECK(b.get_len() == sizeof(buf)); - - b.append(buf, sizeof(buf)); - CHECK(b.get_len() == 2 * sizeof(buf)); - } - { - blob b(sql); - sql << "select img from soci_test where id = 7", into(b); - CHECK(b.get_len() == 2 * sizeof(buf)); - char buf2[100]; - b.read_from_start(buf2, 10); - CHECK(std::strncmp(buf2, "abcdefghij", 10) == 0); - } - - unsigned long oid; - sql << "select img from soci_test where id = 7", into(oid); - sql << "select lo_unlink(" << oid << ")"; - } -} - -struct longlong_table_creator : table_creator_base -{ - longlong_table_creator(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(val int8)"; - } -}; - -// long long test -TEST_CASE("PostgreSQL long long", "[postgresql][longlong]") -{ - soci::session sql(backEnd, connectString); - - longlong_table_creator tableCreator(sql); - - long long v1 = 1000000000000LL; - sql << "insert into soci_test(val) values(:val)", use(v1); - - long long v2 = 0LL; - sql << "select val from soci_test", into(v2); - - CHECK(v2 == v1); -} - -// vector -TEST_CASE("PostgreSQL vector long long", "[postgresql][vector][longlong]") -{ - soci::session sql(backEnd, connectString); - - longlong_table_creator tableCreator(sql); - - std::vector v1; - v1.push_back(1000000000000LL); - v1.push_back(1000000000001LL); - v1.push_back(1000000000002LL); - v1.push_back(1000000000003LL); - v1.push_back(1000000000004LL); - - sql << "insert into soci_test(val) values(:val)", use(v1); - - std::vector v2(10); - sql << "select val from soci_test order by val desc", into(v2); - - REQUIRE(v2.size() == 5); - CHECK(v2[0] == 1000000000004LL); - CHECK(v2[1] == 1000000000003LL); - CHECK(v2[2] == 1000000000002LL); - CHECK(v2[3] == 1000000000001LL); - CHECK(v2[4] == 1000000000000LL); -} - -// unsigned long long test -TEST_CASE("PostgreSQL unsigned long long", "[postgresql][unsigned][longlong]") -{ - soci::session sql(backEnd, connectString); - - longlong_table_creator tableCreator(sql); - - unsigned long long v1 = 1000000000000ULL; - sql << "insert into soci_test(val) values(:val)", use(v1); - - unsigned long long v2 = 0ULL; - sql << "select val from soci_test", into(v2); - - CHECK(v2 == v1); -} - -struct boolean_table_creator : table_creator_base -{ - boolean_table_creator(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(val boolean)"; - } -}; - -TEST_CASE("PostgreSQL boolean", "[postgresql][boolean]") -{ - soci::session sql(backEnd, connectString); - - boolean_table_creator tableCreator(sql); - - int i1 = 0; - - sql << "insert into soci_test(val) values(:val)", use(i1); - - int i2 = 7; - sql << "select val from soci_test", into(i2); - - CHECK(i2 == i1); - - sql << "update soci_test set val = true"; - sql << "select val from soci_test", into(i2); - CHECK(i2 == 1); -} - -struct uuid_table_creator : table_creator_base -{ - uuid_table_creator(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(val uuid)"; - } -}; - -// uuid test -TEST_CASE("PostgreSQL uuid", "[postgresql][uuid]") -{ - soci::session sql(backEnd, connectString); - - uuid_table_creator tableCreator(sql); - - std::string v1("cd2dcb78-3817-442e-b12a-17c7e42669a0"); - sql << "insert into soci_test(val) values(:val)", use(v1); - - std::string v2; - sql << "select val from soci_test", into(v2); - - CHECK(v2 == v1); -} - -// dynamic backend test -- currently skipped by default -TEST_CASE("PostgreSQL dynamic backend", "[postgresql][backend][.]") -{ - try - { - soci::session sql("nosuchbackend://" + connectString); - FAIL("expected exception not thrown"); - } - catch (soci_error const & e) - { - CHECK(e.get_error_message() == - "Failed to open: libsoci_nosuchbackend.so"); - } - - { - dynamic_backends::register_backend("pgsql", backEnd); - - std::vector backends = dynamic_backends::list_all(); - REQUIRE(backends.size() == 1); - CHECK(backends[0] == "pgsql"); - - { - soci::session sql("pgsql://" + connectString); - } - - dynamic_backends::unload("pgsql"); - - backends = dynamic_backends::list_all(); - CHECK(backends.empty()); - } - - { - soci::session sql("postgresql://" + connectString); - } -} - -TEST_CASE("PostgreSQL literals", "[postgresql][into]") -{ - soci::session sql(backEnd, connectString); - - int i; - sql << "select 123", into(i); - CHECK(i == 123); - - try - { - sql << "select 'ABC'", into (i); - FAIL("expected exception not thrown"); - } - catch (soci_error const & e) - { - char const * expectedPrefix = "Cannot convert data"; - CAPTURE(e.what()); - CHECK(strncmp(e.what(), expectedPrefix, strlen(expectedPrefix)) == 0); - } -} - -TEST_CASE("PostgreSQL backend name", "[postgresql][backend]") -{ - soci::session sql(backEnd, connectString); - - CHECK(sql.get_backend_name() == "postgresql"); -} - -// test for double-colon cast in SQL expressions -TEST_CASE("PostgreSQL double colon cast", "[postgresql][cast]") -{ - soci::session sql(backEnd, connectString); - - int a = 123; - int b = 0; - sql << "select :a::integer", use(a), into(b); - CHECK(b == a); -} - -// test for date, time and timestamp parsing -TEST_CASE("PostgreSQL datetime", "[postgresql][datetime]") -{ - soci::session sql(backEnd, connectString); - - std::string someDate = "2009-06-17 22:51:03.123"; - std::tm t1 = std::tm(), t2 = std::tm(), t3 = std::tm(); - - sql << "select :sd::date, :sd::time, :sd::timestamp", - use(someDate, "sd"), into(t1), into(t2), into(t3); - - // t1 should contain only the date part - CHECK(t1.tm_year == 2009 - 1900); - CHECK(t1.tm_mon == 6 - 1); - CHECK(t1.tm_mday == 17); - CHECK(t1.tm_hour == 0); - CHECK(t1.tm_min == 0); - CHECK(t1.tm_sec == 0); - - // t2 should contain only the time of day part - CHECK(t2.tm_year == 0); - CHECK(t2.tm_mon == 0); - CHECK(t2.tm_mday == 1); - CHECK(t2.tm_hour == 22); - CHECK(t2.tm_min == 51); - CHECK(t2.tm_sec == 3); - - // t3 should contain all information - CHECK(t3.tm_year == 2009 - 1900); - CHECK(t3.tm_mon == 6 - 1); - CHECK(t3.tm_mday == 17); - CHECK(t3.tm_hour == 22); - CHECK(t3.tm_min == 51); - CHECK(t3.tm_sec == 3); -} - -// test for number of affected rows - -struct table_creator_for_test11 : table_creator_base -{ - table_creator_for_test11(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(val integer)"; - } -}; - -TEST_CASE("PostgreSQL get affected rows", "[postgresql][affected-rows]") -{ - soci::session sql(backEnd, connectString); - - table_creator_for_test11 tableCreator(sql); - - for (int i = 0; i != 10; i++) - { - sql << "insert into soci_test(val) values(:val)", use(i); - } - - statement st1 = (sql.prepare << - "update soci_test set val = val + 1"); - st1.execute(false); - - CHECK(st1.get_affected_rows() == 10); - - statement st2 = (sql.prepare << - "delete from soci_test where val <= 5"); - st2.execute(false); - - CHECK(st2.get_affected_rows() == 5); -} - -// test INSERT INTO ... RETURNING syntax - -struct table_creator_for_test12 : table_creator_base -{ - table_creator_for_test12(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(sid serial, txt text)"; - } -}; - -TEST_CASE("PostgreSQL insert into ... returning", "[postgresql]") -{ - soci::session sql(backEnd, connectString); - - table_creator_for_test12 tableCreator(sql); - - std::vector ids(10); - for (std::size_t i = 0; i != ids.size(); i++) - { - long sid(0); - std::string txt("abc"); - sql << "insert into soci_test(txt) values(:txt) returning sid", use(txt, "txt"), into(sid); - ids[i] = sid; - } - - std::vector ids2(ids.size()); - sql << "select sid from soci_test order by sid", into(ids2); - CHECK(std::equal(ids.begin(), ids.end(), ids2.begin())); -} - -struct bytea_table_creator : public table_creator_base -{ - bytea_table_creator(soci::session& sql) - : table_creator_base(sql) - { - sql << "drop table if exists soci_test;"; - sql << "create table soci_test ( val bytea null )"; - } -}; - -TEST_CASE("PostgreSQL bytea", "[postgresql][bytea]") -{ - soci::session sql(backEnd, connectString); - - // PostgreSQL supports two different output formats for bytea values: - // historical "escape" format, which is the only one supported until - // PostgreSQL 9.0, and "hex" format used by default since 9.0, we need - // to determine which one is actually in use. - std::string bytea_output_format; - sql << "select setting from pg_settings where name='bytea_output'", - into(bytea_output_format); - char const* expectedBytea; - if (bytea_output_format.empty() || bytea_output_format == "escape") - expectedBytea = "\\015\\014\\013\\012"; - else if (bytea_output_format == "hex") - expectedBytea = "\\x0d0c0b0a"; - else - throw std::runtime_error("Unknown PostgreSQL bytea_output \"" + - bytea_output_format + "\""); - - bytea_table_creator tableCreator(sql); - - int v = 0x0A0B0C0D; - unsigned char* b = reinterpret_cast(&v); - std::string data; - std::copy(b, b + sizeof(v), std::back_inserter(data)); - { - - sql << "insert into soci_test(val) values(:val)", use(data); - - // 1) into string, no Oid mapping - std::string bin1; - sql << "select val from soci_test", into(bin1); - CHECK(bin1 == expectedBytea); - - // 2) Oid-to-dt_string mapped - row r; - sql << "select * from soci_test", into(r); - - REQUIRE(r.size() == 1); - column_properties const& props = r.get_properties(0); - CHECK(props.get_data_type() == soci::dt_string); - std::string bin2 = r.get(0); - CHECK(bin2 == expectedBytea); - } -} - -// json -struct table_creator_json : public table_creator_base -{ - table_creator_json(soci::session& sql) - : table_creator_base(sql) - { - sql << "drop table if exists soci_json_test;"; - sql << "create table soci_json_test(data json)"; - } -}; - -// Return 9,2 for 9.2.3 -typedef std::pair server_version; - -server_version get_postgresql_version(soci::session& sql) -{ - std::string version; - std::pair result; - sql << "select version()",into(version); - if (sscanf(version.c_str(),"PostgreSQL %i.%i", &result.first, &result.second) < 2) - { - throw std::runtime_error("Failed to retrieve PostgreSQL version number"); - } - return result; -} - -// Test JSON. Only valid for PostgreSQL Server 9.2++ -TEST_CASE("PostgreSQL JSON", "[postgresql][json]") -{ - soci::session sql(backEnd, connectString); - server_version version = get_postgresql_version(sql); - if ( version >= server_version(9,2)) - { - std::string result; - std::string valid_input = "{\"tool\":\"soci\",\"result\":42}"; - std::string invalid_input = "{\"tool\":\"other\",\"result\":invalid}"; - - table_creator_json tableCreator(sql); - - sql << "insert into soci_json_test (data) values(:data)",use(valid_input); - sql << "select data from soci_json_test",into(result); - CHECK(result == valid_input); - - CHECK_THROWS_AS(( - sql << "insert into soci_json_test (data) values(:data)",use(invalid_input)), - soci_error - ); - } - else - { - WARN("JSON test skipped (PostgreSQL >= 9.2 required, found " << version.first << "." << version.second << ")"); - } -} - -struct table_creator_text : public table_creator_base -{ - table_creator_text(soci::session& sql) : table_creator_base(sql) - { - sql << "drop table if exists soci_test;"; - sql << "create table soci_test(name varchar(20))"; - } -}; - -// Test deallocate_prepared_statement called for non-existing statement -// which creation failed due to invalid SQL syntax. -// https://github.com/SOCI/soci/issues/116 -TEST_CASE("PostgreSQL statement prepare failure", "[postgresql][prepare]") -{ - soci::session sql(backEnd, connectString); - table_creator_text tableCreator(sql); - - try - { - // types mismatch should lead to PQprepare failure - statement get_trades = - (sql.prepare - << "select * from soci_test where name=9999"); - FAIL("expected exception not thrown"); - } - catch(soci_error const& e) - { - std::string const msg(e.what()); - CAPTURE(msg); - - // poor-man heuristics - CHECK(msg.find("prepared statement") == std::string::npos); - CHECK(msg.find("operator does not exist") != std::string::npos); - } -} - -// Test the support of PostgreSQL-style casts with ORM -TEST_CASE("PostgreSQL ORM cast", "[postgresql][orm]") -{ - soci::session sql(backEnd, connectString); - values v; - v.set("a", 1); - sql << "select :a::int", use(v); // Must not throw an exception! -} - -// Test the DDL and metadata functionality -TEST_CASE("PostgreSQL DDL with metadata", "[postgresql][ddl]") -{ - soci::session sql(backEnd, connectString); - - // note: prepare_column_descriptions expects l-value - std::string ddl_t1 = "ddl_t1"; - std::string ddl_t2 = "ddl_t2"; - std::string ddl_t3 = "ddl_t3"; - - // single-expression variant: - sql.create_table(ddl_t1).column("i", soci::dt_integer).column("j", soci::dt_integer); - - // check whether this table was created: - - bool ddl_t1_found = false; - bool ddl_t2_found = false; - bool ddl_t3_found = false; - std::string table_name; - soci::statement st = (sql.prepare_table_names(), into(table_name)); - st.execute(); - while (st.fetch()) - { - if (table_name == ddl_t1) { ddl_t1_found = true; } - if (table_name == ddl_t2) { ddl_t2_found = true; } - if (table_name == ddl_t3) { ddl_t3_found = true; } - } - - CHECK(ddl_t1_found); - CHECK(ddl_t2_found == false); - CHECK(ddl_t3_found == false); - - // check whether ddl_t1 has the right structure: - - bool i_found = false; - bool j_found = false; - bool other_found = false; - soci::column_info ci; - soci::statement st1 = (sql.prepare_column_descriptions(ddl_t1), into(ci)); - st1.execute(); - while (st1.fetch()) - { - if (ci.name == "i") - { - CHECK(ci.type == soci::dt_integer); - CHECK(ci.nullable); - i_found = true; - } - else if (ci.name == "j") - { - CHECK(ci.type == soci::dt_integer); - CHECK(ci.nullable); - j_found = true; - } - else - { - other_found = true; - } - } - - CHECK(i_found); - CHECK(j_found); - CHECK(other_found == false); - - // two more tables: - - // separately defined columns: - // (note: statement is executed when ddl object goes out of scope) - { - soci::ddl_type ddl = sql.create_table(ddl_t2); - ddl.column("i", soci::dt_integer); - ddl.column("j", soci::dt_integer); - ddl.column("k", soci::dt_integer)("not null"); - ddl.primary_key("t2_pk", "j"); - } - - sql.add_column(ddl_t1, "k", soci::dt_integer); - sql.add_column(ddl_t1, "big", soci::dt_string, 0); // "unlimited" length -> text - sql.drop_column(ddl_t1, "i"); - - // or with constraint as in t2: - sql.add_column(ddl_t2, "m", soci::dt_integer)("not null"); - - // third table with a foreign key to the second one - { - soci::ddl_type ddl = sql.create_table(ddl_t3); - ddl.column("x", soci::dt_integer); - ddl.column("y", soci::dt_integer); - ddl.foreign_key("t3_fk", "x", ddl_t2, "j"); - } - - // check if all tables were created: - - ddl_t1_found = false; - ddl_t2_found = false; - ddl_t3_found = false; - soci::statement st2 = (sql.prepare_table_names(), into(table_name)); - st2.execute(); - while (st2.fetch()) - { - if (table_name == ddl_t1) { ddl_t1_found = true; } - if (table_name == ddl_t2) { ddl_t2_found = true; } - if (table_name == ddl_t3) { ddl_t3_found = true; } - } - - CHECK(ddl_t1_found); - CHECK(ddl_t2_found); - CHECK(ddl_t3_found); - - // check if ddl_t1 has the right structure (it was altered): - - i_found = false; - j_found = false; - bool k_found = false; - bool big_found = false; - other_found = false; - soci::statement st3 = (sql.prepare_column_descriptions(ddl_t1), into(ci)); - st3.execute(); - while (st3.fetch()) - { - if (ci.name == "j") - { - CHECK(ci.type == soci::dt_integer); - CHECK(ci.nullable); - j_found = true; - } - else if (ci.name == "k") - { - CHECK(ci.type == soci::dt_integer); - CHECK(ci.nullable); - k_found = true; - } - else if (ci.name == "big") - { - CHECK(ci.type == soci::dt_string); - CHECK(ci.precision == 0); // "unlimited" for strings - big_found = true; - } - else - { - other_found = true; - } - } - - CHECK(i_found == false); - CHECK(j_found); - CHECK(k_found); - CHECK(big_found); - CHECK(other_found == false); - - // check if ddl_t2 has the right structure: - - i_found = false; - j_found = false; - k_found = false; - bool m_found = false; - other_found = false; - soci::statement st4 = (sql.prepare_column_descriptions(ddl_t2), into(ci)); - st4.execute(); - while (st4.fetch()) - { - if (ci.name == "i") - { - CHECK(ci.type == soci::dt_integer); - CHECK(ci.nullable); - i_found = true; - } - else if (ci.name == "j") - { - CHECK(ci.type == soci::dt_integer); - CHECK(ci.nullable == false); // primary key - j_found = true; - } - else if (ci.name == "k") - { - CHECK(ci.type == soci::dt_integer); - CHECK(ci.nullable == false); - k_found = true; - } - else if (ci.name == "m") - { - CHECK(ci.type == soci::dt_integer); - CHECK(ci.nullable == false); - m_found = true; - } - else - { - other_found = true; - } - } - - CHECK(i_found); - CHECK(j_found); - CHECK(k_found); - CHECK(m_found); - CHECK(other_found == false); - - sql.drop_table(ddl_t1); - sql.drop_table(ddl_t3); // note: this must be dropped before ddl_t2 - sql.drop_table(ddl_t2); - - // check if all tables were dropped: - - ddl_t1_found = false; - ddl_t2_found = false; - ddl_t3_found = false; - st2 = (sql.prepare_table_names(), into(table_name)); - st2.execute(); - while (st2.fetch()) - { - if (table_name == ddl_t1) { ddl_t1_found = true; } - if (table_name == ddl_t2) { ddl_t2_found = true; } - if (table_name == ddl_t3) { ddl_t3_found = true; } - } - - CHECK(ddl_t1_found == false); - CHECK(ddl_t2_found == false); - CHECK(ddl_t3_found == false); - - int i = -1; - sql << "select lo_unlink(" + sql.empty_blob() + ")", into(i); - CHECK(i == 1); - sql << "select " + sql.nvl() + "(1, 2)", into(i); - CHECK(i == 1); - sql << "select " + sql.nvl() + "(NULL, 2)", into(i); - CHECK(i == 2); -} - -// Test the bulk iterators functionality -TEST_CASE("Bulk iterators", "[postgresql][bulkiters]") -{ - soci::session sql(backEnd, connectString); - - sql << "create table t (i integer)"; - - // test bulk iterators with basic types - { - std::vector v; - v.push_back(10); - v.push_back(20); - v.push_back(30); - v.push_back(40); - v.push_back(50); - - std::size_t begin = 2; - std::size_t end = 5; - sql << "insert into t (i) values (:v)", soci::use(v, begin, end); - - v.clear(); - v.resize(20); - begin = 5; - end = 20; - sql << "select i from t", soci::into(v, begin, end); - - CHECK(end == 8); - for (std::size_t i = 0; i != 5; ++i) - { - CHECK(v[i] == 0); - } - CHECK(v[5] == 30); - CHECK(v[6] == 40); - CHECK(v[7] == 50); - for (std::size_t i = end; i != 20; ++i) - { - CHECK(v[i] == 0); - } - } - - sql << "delete from t"; - - // test bulk iterators with user types - { - std::vector v; - v.push_back(MyInt(10)); - v.push_back(MyInt(20)); - v.push_back(MyInt(30)); - v.push_back(MyInt(40)); - v.push_back(MyInt(50)); - - std::size_t begin = 2; - std::size_t end = 5; - sql << "insert into t (i) values (:v)", soci::use(v, begin, end); - - v.clear(); - for (std::size_t i = 0; i != 20; ++i) - { - v.push_back(MyInt(-1)); - } - - begin = 5; - end = 20; - sql << "select i from t", soci::into(v, begin, end); - - CHECK(end == 8); - for (std::size_t i = 0; i != 5; ++i) - { - CHECK(v[i].get() == -1); - } - CHECK(v[5].get() == 30); - CHECK(v[6].get() == 40); - CHECK(v[7].get() == 50); - for (std::size_t i = end; i != 20; ++i) - { - CHECK(v[i].get() == -1); - } - } - - sql << "drop table t"; -} - -// -// Support for soci Common Tests -// - -// DDL Creation objects for common tests -struct table_creator_one : public table_creator_base -{ - table_creator_one(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(id integer, val integer, c char, " - "str varchar(20), sh int2, ul numeric(20), d float8, " - "num76 numeric(7,6), " - "tm timestamp, i1 integer, i2 integer, i3 integer, " - "name varchar(20))"; - } -}; - -struct table_creator_two : public table_creator_base -{ - table_creator_two(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(num_float float8, num_int integer," - " name varchar(20), sometime timestamp, chr char)"; - } -}; - -struct table_creator_three : public table_creator_base -{ - table_creator_three(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(name varchar(100) not null, " - "phone varchar(15))"; - } -}; - -struct table_creator_for_get_affected_rows : table_creator_base -{ - table_creator_for_get_affected_rows(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(val integer)"; - } -}; - -struct table_creator_for_xml : table_creator_base -{ - table_creator_for_xml(soci::session& sql) - : table_creator_base(sql) - { - sql << "create table soci_test(id integer, x xml)"; - } -}; - -struct table_creator_for_clob : table_creator_base -{ - table_creator_for_clob(soci::session& sql) - : table_creator_base(sql) - { - sql << "create table soci_test(id integer, s text)"; - } -}; - -// Common tests context -class test_context : public test_context_base -{ -public: - test_context(backend_factory const &backEnd, std::string const &connectString) - : test_context_base(backEnd, connectString) - {} - - table_creator_base* table_creator_1(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_one(s); - } - - table_creator_base* table_creator_2(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_two(s); - } - - table_creator_base* table_creator_3(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_three(s); - } - - table_creator_base* table_creator_4(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_for_get_affected_rows(s); - } - - table_creator_base* table_creator_xml(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_for_xml(s); - } - - table_creator_base* table_creator_clob(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_for_clob(s); - } - - bool has_real_xml_support() const SOCI_OVERRIDE - { - return true; - } - - std::string to_date_time(std::string const &datdt_string) const SOCI_OVERRIDE - { - return "timestamptz(\'" + datdt_string + "\')"; - } - - bool has_fp_bug() const SOCI_OVERRIDE - { - return false; - } - - std::string sql_length(std::string const& s) const SOCI_OVERRIDE - { - return "char_length(" + s + ")"; - } -}; - -int main(int argc, char** argv) -{ - -#ifdef _MSC_VER - // Redirect errors, unrecoverable problems, and assert() failures to STDERR, - // instead of debug message window. - // This hack is required to run assert()-driven tests by Buildbot. - // NOTE: Comment this 2 lines for debugging with Visual C++ debugger to catch assertions inside. - _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); - _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); -#endif //_MSC_VER - - if (argc >= 2) - { - connectString = argv[1]; - - // Replace the connect string with the process name to ensure that - // CATCH uses the correct name in its messages. - argv[1] = argv[0]; - - argc--; - argv++; - } - else - { - std::cout << "usage: " << argv[0] - << " connectstring [test-arguments...]\n" - << "example: " << argv[0] - << " \'connect_string_for_PostgreSQL\'\n"; - return EXIT_FAILURE; - } - - test_context tc(backEnd, connectString); - - return Catch::Session().run(argc, argv); -} diff --git a/src/soci/tests/sqlite3/CMakeLists.txt b/src/soci/tests/sqlite3/CMakeLists.txt deleted file mode 100644 index 0fe8e77383..0000000000 --- a/src/soci/tests/sqlite3/CMakeLists.txt +++ /dev/null @@ -1,16 +0,0 @@ -############################################################################### -# -# This file is part of CMake configuration for SOCI library -# -# Copyright (C) 2010-2013 Mateusz Loskot -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) -# -############################################################################### - -soci_backend_test( - BACKEND SQLite3 - DEPENDS SQLite3 - SOURCE test-sqlite3.cpp ${SOCI_TESTS_COMMON} - CONNSTR ":memory:") diff --git a/src/soci/tests/sqlite3/Makefile.basic b/src/soci/tests/sqlite3/Makefile.basic deleted file mode 100644 index 697d67404d..0000000000 --- a/src/soci/tests/sqlite3/Makefile.basic +++ /dev/null @@ -1,12 +0,0 @@ -COMPILER = g++ -CXXFLAGS = -Wall -pedantic -Wno-long-long -INCLUDEDIRS = -I../../include -I../../include/private -I.. -I/usr/include/sqlite3 -LIBDIRS = -L../../src/core -L../../src/backends/sqlite3 -L/usr/lib/x86_64-linux-gnu -LIBS = -lsoci_sqlite3 -lsoci_core -ldl -lsqlite3 - -test-sqlite3 : test-sqlite3.cpp - ${COMPILER} $? -o $@ ${INCLUDEDIRS} ${LIBDIRS} ${LIBS} - - -clean : - rm -f test-sqlite3 diff --git a/src/soci/tests/sqlite3/test-sqlite3.cpp b/src/soci/tests/sqlite3/test-sqlite3.cpp deleted file mode 100644 index 33878fbe8b..0000000000 --- a/src/soci/tests/sqlite3/test-sqlite3.cpp +++ /dev/null @@ -1,421 +0,0 @@ -// -// Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney -// Distributed under the Boost Software License, Version 1.0. -// (See accompanying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// - -#include -#include -#include "common-tests.h" -#include -#include -#include -#include -#include -#include - -using namespace soci; -using namespace soci::tests; - -std::string connectString; -backend_factory const &backEnd = *soci::factory_sqlite3(); - -// ROWID test -// In sqlite3 the row id can be called ROWID, _ROWID_ or oid -TEST_CASE("SQLite rowid", "[sqlite][rowid][oid]") -{ - soci::session sql(backEnd, connectString); - - try { sql << "drop table test1"; } - catch (soci_error const &) {} // ignore if error - - sql << - "create table test1 (" - " id integer," - " name varchar(100)" - ")"; - - sql << "insert into test1(id, name) values(7, \'John\')"; - - rowid rid(sql); - sql << "select oid from test1 where id = 7", into(rid); - - int id; - std::string name; - - sql << "select id, name from test1 where oid = :rid", - into(id), into(name), use(rid); - - CHECK(id == 7); - CHECK(name == "John"); - - sql << "drop table test1"; -} - -// BLOB test -struct blob_table_creator : public table_creator_base -{ - blob_table_creator(soci::session & sql) - : table_creator_base(sql) - { - sql << - "create table soci_test (" - " id integer," - " img blob" - ")"; - } -}; - -TEST_CASE("SQLite blob", "[sqlite][blob]") -{ - soci::session sql(backEnd, connectString); - - blob_table_creator tableCreator(sql); - - char buf[] = "abcdefghijklmnopqrstuvwxyz"; - - sql << "insert into soci_test(id, img) values(7, '')"; - - { - blob b(sql); - - sql << "select img from soci_test where id = 7", into(b); - CHECK(b.get_len() == 0); - - b.write(0, buf, sizeof(buf)); - CHECK(b.get_len() == sizeof(buf)); - sql << "update soci_test set img=? where id = 7", use(b); - - b.append(buf, sizeof(buf)); - CHECK(b.get_len() == 2 * sizeof(buf)); - sql << "insert into soci_test(id, img) values(8, ?)", use(b); - } - { - blob b(sql); - sql << "select img from soci_test where id = 8", into(b); - CHECK(b.get_len() == 2 * sizeof(buf)); - char buf2[100]; - b.read(0, buf2, 10); - CHECK(std::strncmp(buf2, "abcdefghij", 10) == 0); - - sql << "select img from soci_test where id = 7", into(b); - CHECK(b.get_len() == sizeof(buf)); - - } -} - -// This test was put in to fix a problem that occurs when there are both -// into and use elements in the same query and one of them (into) binds -// to a vector object. - -struct test3_table_creator : table_creator_base -{ - test3_table_creator(soci::session & sql) : table_creator_base(sql) - { - sql << "create table soci_test( id integer, name varchar, subname varchar);"; - } -}; - -TEST_CASE("SQLite use and vector into", "[sqlite][use][into][vector]") -{ - soci::session sql(backEnd, connectString); - - test3_table_creator tableCreator(sql); - - sql << "insert into soci_test(id,name,subname) values( 1,'john','smith')"; - sql << "insert into soci_test(id,name,subname) values( 2,'george','vals')"; - sql << "insert into soci_test(id,name,subname) values( 3,'ann','smith')"; - sql << "insert into soci_test(id,name,subname) values( 4,'john','grey')"; - sql << "insert into soci_test(id,name,subname) values( 5,'anthony','wall')"; - - { - std::vector v(10); - - statement s(sql.prepare << "Select id from soci_test where name = :name"); - - std::string name = "john"; - - s.exchange(use(name, "name")); - s.exchange(into(v)); - - s.define_and_bind(); - s.execute(true); - - CHECK(v.size() == 2); - } -} - - -// Test case from Amnon David 11/1/2007 -// I've noticed that table schemas in SQLite3 can sometimes have typeless -// columns. One (and only?) example is the sqlite_sequence that sqlite -// creates for autoincrement . Attempting to traverse this table caused -// SOCI to crash. I've made the following code change in statement.cpp to -// create a workaround: - -struct test4_table_creator : table_creator_base -{ - test4_table_creator(soci::session & sql) : table_creator_base(sql) - { - sql << "create table soci_test (col INTEGER PRIMARY KEY AUTOINCREMENT, name char)"; - } -}; - -TEST_CASE("SQLite select from sequence", "[sqlite][sequence]") -{ - // we need to have an table that uses autoincrement to test this. - soci::session sql(backEnd, connectString); - - test4_table_creator tableCreator(sql); - - sql << "insert into soci_test(name) values('john')"; - sql << "insert into soci_test(name) values('james')"; - - { - int key; - std::string name; - sql << "select * from soci_test", into(key), into(name); - CHECK(name == "john"); - - rowset rs = (sql.prepare << "select * from sqlite_sequence"); - rowset::const_iterator it = rs.begin(); - row const& r1 = (*it); - CHECK(r1.get(0) == "soci_test"); - CHECK(r1.get(1) == "2"); - } -} - -struct longlong_table_creator : table_creator_base -{ - longlong_table_creator(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(val number(20))"; - } -}; - -// long long test -TEST_CASE("SQLite long long", "[sqlite][longlong]") -{ - soci::session sql(backEnd, connectString); - - longlong_table_creator tableCreator(sql); - - long long v1 = 1000000000000LL; - sql << "insert into soci_test(val) values(:val)", use(v1); - - long long v2 = 0LL; - sql << "select val from soci_test", into(v2); - - CHECK(v2 == v1); -} - -TEST_CASE("SQLite vector long long", "[sqlite][vector][longlong]") -{ - soci::session sql(backEnd, connectString); - - longlong_table_creator tableCreator(sql); - - std::vector v1; - v1.push_back(1000000000000LL); - v1.push_back(1000000000001LL); - v1.push_back(1000000000002LL); - v1.push_back(1000000000003LL); - v1.push_back(1000000000004LL); - - sql << "insert into soci_test(val) values(:val)", use(v1); - - std::vector v2(10); - sql << "select val from soci_test order by val desc", into(v2); - - REQUIRE(v2.size() == 5); - CHECK(v2[0] == 1000000000004LL); - CHECK(v2[1] == 1000000000003LL); - CHECK(v2[2] == 1000000000002LL); - CHECK(v2[3] == 1000000000001LL); - CHECK(v2[4] == 1000000000000LL); -} - -TEST_CASE("SQLite DDL wrappers", "[sqlite][ddl]") -{ - soci::session sql(backEnd, connectString); - - int i = -1; - sql << "select length(" + sql.empty_blob() + ")", into(i); - CHECK(i == 0); - sql << "select " + sql.nvl() + "(1, 2)", into(i); - CHECK(i == 1); - sql << "select " + sql.nvl() + "(NULL, 2)", into(i); - CHECK(i == 2); -} - -struct table_creator_for_get_last_insert_id : table_creator_base -{ - table_creator_for_get_last_insert_id(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(id integer primary key autoincrement)"; - sql << "insert into soci_test (id) values (41)"; - sql << "delete from soci_test where id = 41"; - } -}; - -TEST_CASE("SQLite last insert id", "[sqlite][last-insert-id]") -{ - soci::session sql(backEnd, connectString); - table_creator_for_get_last_insert_id tableCreator(sql); - sql << "insert into soci_test default values"; - long id; - bool result = sql.get_last_insert_id("soci_test", id); - CHECK(result == true); - CHECK(id == 42); -} - -// DDL Creation objects for common tests -struct table_creator_one : public table_creator_base -{ - table_creator_one(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(id integer, val integer, c char, " - "str varchar(20), sh smallint, ul numeric(20), d float, " - "num76 numeric(7,6), " - "tm datetime, i1 integer, i2 integer, i3 integer, " - "name varchar(20))"; - } -}; - -struct table_creator_two : public table_creator_base -{ - table_creator_two(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(num_float float, num_int integer," - " name varchar(20), sometime datetime, chr char)"; - } -}; - -struct table_creator_three : public table_creator_base -{ - table_creator_three(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(name varchar(100) not null, " - "phone varchar(15))"; - } -}; - -// Originally, submitted to SQLite3 backend and later moved to common test. -// Test commit b394d039530f124802d06c3b1a969c3117683152 -// Author: Mika Fischer -// Date: Thu Nov 17 13:28:07 2011 +0100 -// Implement get_affected_rows for SQLite3 backend -struct table_creator_for_get_affected_rows : table_creator_base -{ - table_creator_for_get_affected_rows(soci::session & sql) - : table_creator_base(sql) - { - sql << "create table soci_test(val integer)"; - } -}; - -// -// Support for SOCI Common Tests -// - -class test_context : public test_context_base -{ -public: - test_context(backend_factory const &backEnd, - std::string const &connectString) - : test_context_base(backEnd, connectString) {} - - table_creator_base* table_creator_1(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_one(s); - } - - table_creator_base* table_creator_2(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_two(s); - } - - table_creator_base* table_creator_3(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_three(s); - } - - table_creator_base* table_creator_4(soci::session& s) const SOCI_OVERRIDE - { - return new table_creator_for_get_affected_rows(s); - } - - std::string to_date_time(std::string const &datdt_string) const SOCI_OVERRIDE - { - return "datetime(\'" + datdt_string + "\')"; - } - - bool has_fp_bug() const SOCI_OVERRIDE - { - /* - SQLite seems to be buggy when using text conversion, e.g.: - - % echo 'create table t(f real); \ - insert into t(f) values(1.79999999999999982); \ - select * from t;' | sqlite3 - 1.8 - - And there doesn't seem to be any way to avoid this rounding, so we - have no hope of getting back exactly what we write into it unless, - perhaps, we start using sqlite3_bind_double() in the backend code. - */ - - return true; - } - - bool enable_std_char_padding(soci::session&) const SOCI_OVERRIDE - { - // SQLite does not support right padded char type. - return false; - } - - std::string sql_length(std::string const& s) const SOCI_OVERRIDE - { - return "length(" + s + ")"; - } -}; - -int main(int argc, char** argv) -{ - -#ifdef _MSC_VER - // Redirect errors, unrecoverable problems, and assert() failures to STDERR, - // instead of debug message window. - // This hack is required to run assert()-driven tests by Buildbot. - // NOTE: Comment this 2 lines for debugging with Visual C++ debugger to catch assertions inside. - _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); - _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); -#endif //_MSC_VER - - if (argc >= 2 && argv[1][0] != '-') - { - connectString = argv[1]; - - // Replace the connect string with the process name to ensure that - // CATCH uses the correct name in its messages. - argv[1] = argv[0]; - - argc--; - argv++; - } - else - { - // If no file name is specfied then work in-memory - connectString = ":memory:"; - } - - test_context tc(backEnd, connectString); - - return Catch::Session().run(argc, argv); -} diff --git a/src/soci/valgrind.suppress b/src/soci/valgrind.suppress deleted file mode 100644 index 5c5d2fdd01..0000000000 --- a/src/soci/valgrind.suppress +++ /dev/null @@ -1,9 +0,0 @@ -# Reported as a leak in Travis CI Ubuntu 12.04.5 LTS builds. -{ - ignored libc NSS leak - Memcheck:Leak - fun:malloc - fun:nss_parse_service_list - fun:__nss_database_lookup -} - diff --git a/src/soci/www/articles.html b/src/soci/www/articles.html deleted file mode 100644 index 21b6307182..0000000000 --- a/src/soci/www/articles.html +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - SOCI - articles - - - - - - - - - - - - - -
-

The following articles were published about SOCI:

- - -

as well as presentations:

- -
- -Fork us on GitHub - - diff --git a/src/soci/www/doc.html b/src/soci/www/doc.html deleted file mode 100644 index 2328afe624..0000000000 --- a/src/soci/www/doc.html +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - SOCI - documentation - - - - - - - - - - - - - -
-

SOCI documentation:

- -
- - - Fork us on GitHub - - - diff --git a/src/soci/www/doc/README.md b/src/soci/www/doc/README.md deleted file mode 100644 index 720b530c81..0000000000 --- a/src/soci/www/doc/README.md +++ /dev/null @@ -1,11 +0,0 @@ -SOCI Documentation -================== - -/www/doc directory is a placeholder for documentation published online, -with subdirectories of versioned documentation, one per each release: - -* doc/3.2 -* doc/3.1 -... - -Documentation pages are copied from /doc directory of each release. diff --git a/src/soci/www/doc/index.html b/src/soci/www/doc/index.html deleted file mode 100644 index eecab5930b..0000000000 --- a/src/soci/www/doc/index.html +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - SOCI - documentation - - - - - - - - - - - - - -
-

SOCI documentation:

- -
- - - Fork us on GitHub - - - diff --git a/src/soci/www/events.html b/src/soci/www/events.html deleted file mode 100644 index bb41701447..0000000000 --- a/src/soci/www/events.html +++ /dev/null @@ -1,101 +0,0 @@ - - - - - - SOCI - events - - - - - - - - - - - - - -
-

Events:

- -2015-04-09: -
3.2.3 version is released. -
- -2013-09-11: -
3.2.2 version is released. -
-2013-04-13: -
3.2.1 version is released. -
-
-2013-03-25: -
3.2.0 version is released. -
-
-2012-11-12: -
SOCI development (Git repository and bug tracker) moved to github.com/SOCI. -
-
-2011-10-11: -
3.1.0 version is released. -
-
-2008-07-10: -
3.0.0 version is released. -
-
-2006-12-04: -
2.2.0 version is released. -
-
-2006-05-15: -
2.1.0 version is released. -
-
-2006-01-16: -
2.0.0 version is released. -
-
-2005-10-14: -
1.2.1 version is released. -
-
-2005-10-02: -
1.2.0 version is released. -
-
-2005-03-06: -
1.1.0 version is released. -
-
-2004-10-16: -
1.0.1 version is released. -
-
-2004-10-12: -
SOCI project is registered at SourceForge. -
-
-2004-09-29: -
First version of SOCI is announced on comp.lang.c++.moderated. -
-
- -Fork us on GitHub - - diff --git a/src/soci/www/forkus_github.png b/src/soci/www/forkus_github.png deleted file mode 100644 index e782f36b9a158d2681e7bafca818242479eedce0..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5735 zcmX|F2T)U6*QJFLdhZG-0wEOXMTDSeM8QxJLaza70YRGd01Aj8y-7!U3n;xyGjxz3 zT>ojGbRS~qJG+xLlL$9r?~@;~ErljbD8*sHfn(BzB1J`18R+KFqP)DkOli4r zZp{p=APo=wBR(5PmST{wu9VZJ?eahNG1cQ-IV^$r4y%^n^~JclOizaM#l-=%U9l4! zy>x3e;V-JvtNqh)gQabZ82x(nG=9ZP!NP4tM`6)sWmjU?+>+a*VTMmd234=KbDMt< zF`UlDoh9v1++oMSr-DwY+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knoR50LU2ftrhV19R zoU#jYD;VP3s9Ix+7@JX`; z1Yl)SOxjw@Ujb^26wd+P1_;{zA_O`9{WHgTs{}1j!{=kuG%Ska@zsDN=8L6@MTShM z=ve<__VVN6jd!?)!DHkQ@G?8MnOO(2PfJk+L_BVPq-`6ku_gJZN&L%>D|X(fl}szW z90-;t?C;L{f4f8^#*Pz2>7VcYcFgnlI-&+ww_Km2rzyMSG+;tJtExYd^fdkc zLmEH@=iXeU0)3RUbqF89(ZQZe*VDwy5&b!U`?J3Ji+r@BWH1;={4vD?6D5SF{FU2- zWEJx@3prvynmvuxHP3+heie65t^-6Fo;)*Oqg8kx&(OxXNS~w`Rp>|a1a@&5mfXUs zS|q?u{wy?t{{+)J67x^LGHmqjxxWNSEoql}BEd?y1bvMN-?GyMXcV~@GiJV3C+(dn zH9ut^%a;W@@O=tfaItFI>uHso^Yf8S5tnBQB;O{D)`uQ1tF`iPrGp?|2AP?@@d*9%QI5RdLRtaLVv(?NdHcF? zrvgLB8J=*H4JgER!FBg=TUoIw^)Hm$K=DSNuO#379LB`w-k$bgpv`%4lmoK9Bl;G8 zrh(uc#Lif-D=K8MVO#L`TkpOK_CBPRQ*Nf;>ShdCA`WqT>FIOb2&81n*C@iB&l7GN z^Yee|a}W^{|HN*GW+6s~`0=;BY6wX52GJ%Sh>H^T zvhhbm8p7-kB>ywTM@`DNLjhV+Op&70`Vekn;4y|UU2rvPKY$Dh=*<_<6L|mHmtOzRv;{%WxLeYi?~3G21#k|C!~1PRL}XL-tWg- zJy1YpuZcGJ{F7jLDUYX^myIe~1Ju}nd=tbzr<&^g0ZqyIHOiU?%faI2I_1%n@}%bQ z=y%T7sJu$#L6l;>Qp)Blg?iRQIL%8kEb)!I$ZE5r>w8H!!1@7E? diff --git a/src/soci/www/index.html b/src/soci/www/index.html deleted file mode 100644 index cb836da6c9..0000000000 --- a/src/soci/www/index.html +++ /dev/null @@ -1,134 +0,0 @@ - - - - - - SOCI - - - - - - - - - - - - - -
-

SOCI is a database access library -for C++ that makes the illusion of embedding -SQL queries in the regular -C++ code, staying entirely within the Standard C++.

- -

The idea is to provide C++ programmers a way to access SQL -databases in the most natural and intuitive way. If you find existing -libraries too difficult for your needs or just distracting, SOCI can be -a good alternative.

- -

The simplest motivating code example for the SQL query that is supposed -to retrieve a single row is:

-
-int id = ...;
-string name;
-int salary;
-
-sql << "select name, salary from persons where id = " << id,
-       into(name), into(salary);
-
- -

and the following benefits from extensive support for object-relational -mapping:

-
-int id = ...;
-Person p;
-
-sql << "select first_name, last_name, date_of_birth "
-       "from persons where id = " << id,
-       into(p);
-
- -

Integration with STL is also supported:

- -
-Rowset<string> rs = (sql.prepare << "select name from persons");
-copy(rs.begin(), rs.end(), ostream_iterator<string>(cout, "\n"));
-
- -

SOCI offers also extensive integration with Boost datatypes (optional, tuple and fusion) and flexible support -for user-defined datatypes.

- -

Even though SOCI is mainly a C++ library, it also allows to use it from other programming languages. Currently the package contains the Ada binding, with more bindings likely to come in the future.

- -

Starting from its 2.0.0 release, SOCI uses the plug-in architecture for -backends - this allows to target various database servers. -Currently (3.2.3), the following database systems are supported:

-
    -
  • DB2
  • -
  • Firebird
  • -
  • MySQL
  • -
  • ODBC (generic backend)
  • -
  • Oracle
  • -
  • PostgreSQL
  • -
  • SQLite3
  • -
- -

The intent of the library is to cover as many database technologies as -possible. For this, the project has to rely on volunteer contributions -from other programmers, who have expertise with the existing database -interfaces and would like to help writing dedicated backends.
-If you are interested in participating, please contact the project admin.

- -

The SOCI library is distributed under the terms of the Boost -Software License.

- -

All SOCI downloads are hosted on SourceForge.net servers. The current -stable release (3.2.3) can be downloaded here, -and all previous releases are available -here.

- -

The development of SOCI happens on GitHub. All repositories live -under the SOCI -organization where all Git repositories are available.

- -

The main Git repository with SOCI source code can be cloned with:

-
-$ git clone git://github.com/SOCI/soci.git
-
- -

The Issues tracker is open -for bug reports and patches submission.

- -

The best way to contribute to SOCI is to follow the typical GitHub workflow: -fork SOCI, apply your edits and submit Pull Request. -
Feel free to join SOCI development!

- -

To meet other users, please consider subscribing to the -SOCI-users mailing list. -There is also SOCI-devel mailing list -available dedicated to development discussions only.

- -

There is also community-driven Wiki -and FAQ hosted at GitHub, where everybody -is welcome to contribute.

-
- -Fork us on GitHub - - diff --git a/src/soci/www/links.html b/src/soci/www/links.html deleted file mode 100644 index d2d18cbcee..0000000000 --- a/src/soci/www/links.html +++ /dev/null @@ -1,78 +0,0 @@ - - - - - - SOCI - links - - - - - - - - - - - - - -
-

Some links you may find useful:

- -ORAPP - Oracle OCI C++ Interface Library - -
- -OCI C++ Library - -
- -Oracle, ODBC and DB2-CLI Template Library - -
- -Oracle C++ Call Interface - -
- -Oracle Open Source Projects - -
- -Database Template Library - -
- -MyMySQL - A lightweight C++ wrapper around MySQL client API - -
- -CMake Cross Platform make - -
- -Fork us on GitHub - - diff --git a/src/soci/www/people.html b/src/soci/www/people.html deleted file mode 100644 index eba7029fb3..0000000000 --- a/src/soci/www/people.html +++ /dev/null @@ -1,122 +0,0 @@ - - - - - - - - SOCI - people - - - - - - - - - - - - - -
-

SOCI People:

-

Core team developers and contributors, current and previous, all people actively involved -

- Maciej Sobczak (see homepage) -
- Project admin
- Core development
- Initial Oracle Call Interface support (author)
- Plug-in backend architecture (author)
- PostgreSQL backend (author)
- Documentation -

- Mateusz Åoskot (see homepage) -
- Project admin
- Core development
- Iterator support
- Oracle backend (maintainer)
- PostgreSQL backend (maintainer)
- Build, test and release troublemaker
- Documentation -

- Paweł Aleksander Fedoryński (see homepage) -
- MySQL backend (author, maintainer)
- Documentation -

- Steve Hutton (see homepage) -
- Core development
- Bulk (vector) operations
- Dynamic result binding
- Object-Relational mapping facilities
- Common tests framework
- Documentation -

- David Courtney (see homepage) -
- SQLite backend (author)
- MS SQL Server (via ODBC) backend (author) -

- Rafał Bobrowski -
- Firebird backend (author) -

-
-
- Vadim Zeitlin (see GitHub) -
- ODBC backend (maintainer)
- Core development
-

- Viacheslav Naydenov (see GitHub) -
- Firebird backend (maintainer)
- Core development
-

- Alex Ott (see homepage) -
- Plug-in backend architecture
- Core development
-

- Denis Chapligin (see GitHub) -
- IBM DB2 backend (author) -

- Denis Arnaud (see GitHub) -
- Fedora and Debian packaging
- Contributor
- Troubleshooter
-

- Julian Taylor (see GitHub) -
- Debian packaging
- Contributor
- Troubleshooter
-

- Sergei Nikulov (see GitHub) -
- SQLite3 contributor
- Troubleshooter -

-
-
Fork us on GitHub - - diff --git a/src/soci/www/style.css b/src/soci/www/style.css deleted file mode 100644 index 8836c3ba74..0000000000 --- a/src/soci/www/style.css +++ /dev/null @@ -1,87 +0,0 @@ -body -{ - background-color: white; - color: black; - margin-left: 100px; - margin-right: 100px; -/* font-family: arial, sans-serif; */ -} - -table.banner -{ - width: 100%; - border-bottom-color: black; - border-bottom-style: solid; - border-bottom-width: 1px; - padding-top: 16px; - padding-right: 16px; - padding-bottom: 5px; -} - -td.banner_left -{ - font-size: x-large; - font-weight: bold; - font-stretch: expanded; -} - -td.banner_right -{ - text-align: right; -} - -table.footer -{ - width: 100%; - border-top-color: black; - border-top-style: solid; - border-top-width: 1px; - padding-bottom: 16px; - padding-top: 5px; -} - -table.main -{ - width: 60%; - padding-top: 25px; -} - -td.main_navigator -{ - vertical-align: top; -} - -td.main_text -{ - vertical-align: top; - padding-left: 20px; -} - -span.bold -{ - font-weight: bold; -} - -span.literal -{ - font-weight: bold; - background-color: white; - color: #8B0000; -} - -div.indent -{ - margin-left: 40px; -} - -div.column-left -{ - width: 50%; - float: left; -} - -div.column-right -{ - width: 50%; - float: right; -} diff --git a/src/sqlite/sqlite.h b/src/sqlite/sqlite.h deleted file mode 100644 index 64d0993119..0000000000 --- a/src/sqlite/sqlite.h +++ /dev/null @@ -1,34 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of rippled: https://github.com/ripple/rippled - Copyright (c) 2012-2015 Ripple Labs Inc. - - Permission to use, copy, modify, and/or 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 THE AUTHOR DISCLAIMS ALL WARRANTIES - WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR 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. -*/ -//============================================================================== - -#ifndef RIPPLE_SQLITE_SQLITE_H_INCLUDED -#define RIPPLE_SQLITE_SQLITE_H_INCLUDED - -/** A self-contained, serverless, zero configuration, transactional SQL engine. - - This external module provides the SQLite embedded database library. - - SQLite is public domain software, visit http://sqlite.org -*/ - -#ifndef RIPPLE_SQLITE_CPP_INCLUDED -#include -#endif - -#endif diff --git a/src/sqlite/sqlite/sqlite3.c b/src/sqlite/sqlite/sqlite3.c deleted file mode 100644 index 0dd969fed7..0000000000 --- a/src/sqlite/sqlite/sqlite3.c +++ /dev/null @@ -1,205352 +0,0 @@ -/****************************************************************************** -** This file is an amalgamation of many separate C source files from SQLite -** version 3.21.0. By combining all the individual C code files into this -** single large file, the entire code can be compiled as a single translation -** unit. This allows many compilers to do optimizations that would not be -** possible if the files were compiled separately. Performance improvements -** of 5% or more are commonly seen when SQLite is compiled as a single -** translation unit. -** -** This file is all you need to compile SQLite. To use SQLite in other -** programs, you need this file and the "sqlite3.h" header file that defines -** the programming interface to the SQLite library. (If you do not have -** the "sqlite3.h" header file at hand, you will find a copy embedded within -** the text of this file. Search for "Begin file sqlite3.h" to find the start -** of the embedded sqlite3.h header file.) Additional code files may be needed -** if you want a wrapper to interface SQLite with your choice of programming -** language. The code for the "sqlite3" command-line shell is also in a -** separate file. This file contains only code for the core SQLite library. -*/ -#define SQLITE_CORE 1 -#define SQLITE_AMALGAMATION 1 -#ifndef SQLITE_PRIVATE -# define SQLITE_PRIVATE static -#endif -/************** Begin file ctime.c *******************************************/ -/* -** 2010 February 23 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file implements routines used to report what compile-time options -** SQLite was built with. -*/ - -#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS - -/* -** Include the configuration header output by 'configure' if we're using the -** autoconf-based build -*/ -#if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H) -#include "config.h" -#define SQLITECONFIG_H 1 -#endif - -/* These macros are provided to "stringify" the value of the define -** for those options in which the value is meaningful. */ -#define CTIMEOPT_VAL_(opt) #opt -#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) - -/* -** An array of names of all compile-time options. This array should -** be sorted A-Z. -** -** This array looks large, but in a typical installation actually uses -** only a handful of compile-time options, so most times this array is usually -** rather short and uses little memory space. -*/ -static const char * const sqlite3azCompileOpt[] = { - -/* -** BEGIN CODE GENERATED BY tool/mkctime.tcl -*/ -#if SQLITE_32BIT_ROWID - "32BIT_ROWID", -#endif -#if SQLITE_4_BYTE_ALIGNED_MALLOC - "4_BYTE_ALIGNED_MALLOC", -#endif -#if SQLITE_64BIT_STATS - "64BIT_STATS", -#endif -#if SQLITE_ALLOW_COVERING_INDEX_SCAN - "ALLOW_COVERING_INDEX_SCAN", -#endif -#if SQLITE_ALLOW_URI_AUTHORITY - "ALLOW_URI_AUTHORITY", -#endif -#ifdef SQLITE_BITMASK_TYPE - "BITMASK_TYPE=" CTIMEOPT_VAL(SQLITE_BITMASK_TYPE), -#endif -#if SQLITE_BUG_COMPATIBLE_20160819 - "BUG_COMPATIBLE_20160819", -#endif -#if SQLITE_CASE_SENSITIVE_LIKE - "CASE_SENSITIVE_LIKE", -#endif -#if SQLITE_CHECK_PAGES - "CHECK_PAGES", -#endif -#if defined(__clang__) && defined(__clang_major__) - "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "." - CTIMEOPT_VAL(__clang_minor__) "." - CTIMEOPT_VAL(__clang_patchlevel__), -#elif defined(_MSC_VER) - "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER), -#elif defined(__GNUC__) && defined(__VERSION__) - "COMPILER=gcc-" __VERSION__, -#endif -#if SQLITE_COVERAGE_TEST - "COVERAGE_TEST", -#endif -#if SQLITE_DEBUG - "DEBUG", -#endif -#if SQLITE_DEFAULT_AUTOMATIC_INDEX - "DEFAULT_AUTOMATIC_INDEX", -#endif -#if SQLITE_DEFAULT_AUTOVACUUM - "DEFAULT_AUTOVACUUM", -#endif -#ifdef SQLITE_DEFAULT_CACHE_SIZE - "DEFAULT_CACHE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_CACHE_SIZE), -#endif -#if SQLITE_DEFAULT_CKPTFULLFSYNC - "DEFAULT_CKPTFULLFSYNC", -#endif -#ifdef SQLITE_DEFAULT_FILE_FORMAT - "DEFAULT_FILE_FORMAT=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_FORMAT), -#endif -#ifdef SQLITE_DEFAULT_FILE_PERMISSIONS - "DEFAULT_FILE_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_PERMISSIONS), -#endif -#if SQLITE_DEFAULT_FOREIGN_KEYS - "DEFAULT_FOREIGN_KEYS", -#endif -#ifdef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT - "DEFAULT_JOURNAL_SIZE_LIMIT=" CTIMEOPT_VAL(SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT), -#endif -#ifdef SQLITE_DEFAULT_LOCKING_MODE - "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE), -#endif -#ifdef SQLITE_DEFAULT_LOOKASIDE - "DEFAULT_LOOKASIDE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOOKASIDE), -#endif -#if SQLITE_DEFAULT_MEMSTATUS - "DEFAULT_MEMSTATUS", -#endif -#ifdef SQLITE_DEFAULT_MMAP_SIZE - "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE), -#endif -#ifdef SQLITE_DEFAULT_PAGE_SIZE - "DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_PAGE_SIZE), -#endif -#ifdef SQLITE_DEFAULT_PCACHE_INITSZ - "DEFAULT_PCACHE_INITSZ=" CTIMEOPT_VAL(SQLITE_DEFAULT_PCACHE_INITSZ), -#endif -#ifdef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS - "DEFAULT_PROXYDIR_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_PROXYDIR_PERMISSIONS), -#endif -#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS - "DEFAULT_RECURSIVE_TRIGGERS", -#endif -#ifdef SQLITE_DEFAULT_ROWEST - "DEFAULT_ROWEST=" CTIMEOPT_VAL(SQLITE_DEFAULT_ROWEST), -#endif -#ifdef SQLITE_DEFAULT_SECTOR_SIZE - "DEFAULT_SECTOR_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_SECTOR_SIZE), -#endif -#ifdef SQLITE_DEFAULT_SYNCHRONOUS - "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS), -#endif -#ifdef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT - "DEFAULT_WAL_AUTOCHECKPOINT=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_AUTOCHECKPOINT), -#endif -#ifdef SQLITE_DEFAULT_WAL_SYNCHRONOUS - "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS), -#endif -#ifdef SQLITE_DEFAULT_WORKER_THREADS - "DEFAULT_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WORKER_THREADS), -#endif -#if SQLITE_DIRECT_OVERFLOW_READ - "DIRECT_OVERFLOW_READ", -#endif -#if SQLITE_DISABLE_DIRSYNC - "DISABLE_DIRSYNC", -#endif -#if SQLITE_DISABLE_FTS3_UNICODE - "DISABLE_FTS3_UNICODE", -#endif -#if SQLITE_DISABLE_FTS4_DEFERRED - "DISABLE_FTS4_DEFERRED", -#endif -#if SQLITE_DISABLE_INTRINSIC - "DISABLE_INTRINSIC", -#endif -#if SQLITE_DISABLE_LFS - "DISABLE_LFS", -#endif -#if SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS - "DISABLE_PAGECACHE_OVERFLOW_STATS", -#endif -#if SQLITE_DISABLE_SKIPAHEAD_DISTINCT - "DISABLE_SKIPAHEAD_DISTINCT", -#endif -#ifdef SQLITE_ENABLE_8_3_NAMES - "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES), -#endif -#if SQLITE_ENABLE_API_ARMOR - "ENABLE_API_ARMOR", -#endif -#if SQLITE_ENABLE_ATOMIC_WRITE - "ENABLE_ATOMIC_WRITE", -#endif -#if SQLITE_ENABLE_BATCH_ATOMIC_WRITE - "ENABLE_BATCH_ATOMIC_WRITE", -#endif -#if SQLITE_ENABLE_CEROD - "ENABLE_CEROD", -#endif -#if SQLITE_ENABLE_COLUMN_METADATA - "ENABLE_COLUMN_METADATA", -#endif -#if SQLITE_ENABLE_COLUMN_USED_MASK - "ENABLE_COLUMN_USED_MASK", -#endif -#if SQLITE_ENABLE_COSTMULT - "ENABLE_COSTMULT", -#endif -#if SQLITE_ENABLE_CURSOR_HINTS - "ENABLE_CURSOR_HINTS", -#endif -#if SQLITE_ENABLE_DBSTAT_VTAB - "ENABLE_DBSTAT_VTAB", -#endif -#if SQLITE_ENABLE_EXPENSIVE_ASSERT - "ENABLE_EXPENSIVE_ASSERT", -#endif -#if SQLITE_ENABLE_FTS1 - "ENABLE_FTS1", -#endif -#if SQLITE_ENABLE_FTS2 - "ENABLE_FTS2", -#endif -#if SQLITE_ENABLE_FTS3 - "ENABLE_FTS3", -#endif -#if SQLITE_ENABLE_FTS3_PARENTHESIS - "ENABLE_FTS3_PARENTHESIS", -#endif -#if SQLITE_ENABLE_FTS3_TOKENIZER - "ENABLE_FTS3_TOKENIZER", -#endif -#if SQLITE_ENABLE_FTS4 - "ENABLE_FTS4", -#endif -#if SQLITE_ENABLE_FTS5 - "ENABLE_FTS5", -#endif -#if SQLITE_ENABLE_HIDDEN_COLUMNS - "ENABLE_HIDDEN_COLUMNS", -#endif -#if SQLITE_ENABLE_ICU - "ENABLE_ICU", -#endif -#if SQLITE_ENABLE_IOTRACE - "ENABLE_IOTRACE", -#endif -#if SQLITE_ENABLE_JSON1 - "ENABLE_JSON1", -#endif -#if SQLITE_ENABLE_LOAD_EXTENSION - "ENABLE_LOAD_EXTENSION", -#endif -#ifdef SQLITE_ENABLE_LOCKING_STYLE - "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE), -#endif -#if SQLITE_ENABLE_MEMORY_MANAGEMENT - "ENABLE_MEMORY_MANAGEMENT", -#endif -#if SQLITE_ENABLE_MEMSYS3 - "ENABLE_MEMSYS3", -#endif -#if SQLITE_ENABLE_MEMSYS5 - "ENABLE_MEMSYS5", -#endif -#if SQLITE_ENABLE_MULTIPLEX - "ENABLE_MULTIPLEX", -#endif -#if SQLITE_ENABLE_NULL_TRIM - "ENABLE_NULL_TRIM", -#endif -#if SQLITE_ENABLE_OVERSIZE_CELL_CHECK - "ENABLE_OVERSIZE_CELL_CHECK", -#endif -#if SQLITE_ENABLE_PREUPDATE_HOOK - "ENABLE_PREUPDATE_HOOK", -#endif -#if SQLITE_ENABLE_QPSG - "ENABLE_QPSG", -#endif -#if SQLITE_ENABLE_RBU - "ENABLE_RBU", -#endif -#if SQLITE_ENABLE_RTREE - "ENABLE_RTREE", -#endif -#if SQLITE_ENABLE_SELECTTRACE - "ENABLE_SELECTTRACE", -#endif -#if SQLITE_ENABLE_SESSION - "ENABLE_SESSION", -#endif -#if SQLITE_ENABLE_SNAPSHOT - "ENABLE_SNAPSHOT", -#endif -#if SQLITE_ENABLE_SQLLOG - "ENABLE_SQLLOG", -#endif -#if defined(SQLITE_ENABLE_STAT4) - "ENABLE_STAT4", -#elif defined(SQLITE_ENABLE_STAT3) - "ENABLE_STAT3", -#endif -#if SQLITE_ENABLE_STMTVTAB - "ENABLE_STMTVTAB", -#endif -#if SQLITE_ENABLE_STMT_SCANSTATUS - "ENABLE_STMT_SCANSTATUS", -#endif -#if SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION - "ENABLE_UNKNOWN_SQL_FUNCTION", -#endif -#if SQLITE_ENABLE_UNLOCK_NOTIFY - "ENABLE_UNLOCK_NOTIFY", -#endif -#if SQLITE_ENABLE_UPDATE_DELETE_LIMIT - "ENABLE_UPDATE_DELETE_LIMIT", -#endif -#if SQLITE_ENABLE_URI_00_ERROR - "ENABLE_URI_00_ERROR", -#endif -#if SQLITE_ENABLE_VFSTRACE - "ENABLE_VFSTRACE", -#endif -#if SQLITE_ENABLE_WHERETRACE - "ENABLE_WHERETRACE", -#endif -#if SQLITE_ENABLE_ZIPVFS - "ENABLE_ZIPVFS", -#endif -#if SQLITE_EXPLAIN_ESTIMATED_ROWS - "EXPLAIN_ESTIMATED_ROWS", -#endif -#if SQLITE_EXTRA_IFNULLROW - "EXTRA_IFNULLROW", -#endif -#ifdef SQLITE_EXTRA_INIT - "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT), -#endif -#ifdef SQLITE_EXTRA_SHUTDOWN - "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN), -#endif -#ifdef SQLITE_FTS3_MAX_EXPR_DEPTH - "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH), -#endif -#if SQLITE_FTS5_ENABLE_TEST_MI - "FTS5_ENABLE_TEST_MI", -#endif -#if SQLITE_FTS5_NO_WITHOUT_ROWID - "FTS5_NO_WITHOUT_ROWID", -#endif -#if SQLITE_HAS_CODEC - "HAS_CODEC", -#endif -#if HAVE_ISNAN || SQLITE_HAVE_ISNAN - "HAVE_ISNAN", -#endif -#if SQLITE_HOMEGROWN_RECURSIVE_MUTEX - "HOMEGROWN_RECURSIVE_MUTEX", -#endif -#if SQLITE_IGNORE_AFP_LOCK_ERRORS - "IGNORE_AFP_LOCK_ERRORS", -#endif -#if SQLITE_IGNORE_FLOCK_LOCK_ERRORS - "IGNORE_FLOCK_LOCK_ERRORS", -#endif -#if SQLITE_INLINE_MEMCPY - "INLINE_MEMCPY", -#endif -#if SQLITE_INT64_TYPE - "INT64_TYPE", -#endif -#ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX - "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX), -#endif -#if SQLITE_LIKE_DOESNT_MATCH_BLOBS - "LIKE_DOESNT_MATCH_BLOBS", -#endif -#if SQLITE_LOCK_TRACE - "LOCK_TRACE", -#endif -#if SQLITE_LOG_CACHE_SPILL - "LOG_CACHE_SPILL", -#endif -#ifdef SQLITE_MALLOC_SOFT_LIMIT - "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT), -#endif -#ifdef SQLITE_MAX_ATTACHED - "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED), -#endif -#ifdef SQLITE_MAX_COLUMN - "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN), -#endif -#ifdef SQLITE_MAX_COMPOUND_SELECT - "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT), -#endif -#ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE - "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE), -#endif -#ifdef SQLITE_MAX_EXPR_DEPTH - "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH), -#endif -#ifdef SQLITE_MAX_FUNCTION_ARG - "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG), -#endif -#ifdef SQLITE_MAX_LENGTH - "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH), -#endif -#ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH - "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH), -#endif -#ifdef SQLITE_MAX_MEMORY - "MAX_MEMORY=" CTIMEOPT_VAL(SQLITE_MAX_MEMORY), -#endif -#ifdef SQLITE_MAX_MMAP_SIZE - "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE), -#endif -#ifdef SQLITE_MAX_MMAP_SIZE_ - "MAX_MMAP_SIZE_=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_), -#endif -#ifdef SQLITE_MAX_PAGE_COUNT - "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT), -#endif -#ifdef SQLITE_MAX_PAGE_SIZE - "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE), -#endif -#ifdef SQLITE_MAX_SCHEMA_RETRY - "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY), -#endif -#ifdef SQLITE_MAX_SQL_LENGTH - "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH), -#endif -#ifdef SQLITE_MAX_TRIGGER_DEPTH - "MAX_TRIGGER_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH), -#endif -#ifdef SQLITE_MAX_VARIABLE_NUMBER - "MAX_VARIABLE_NUMBER=" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER), -#endif -#ifdef SQLITE_MAX_VDBE_OP - "MAX_VDBE_OP=" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP), -#endif -#ifdef SQLITE_MAX_WORKER_THREADS - "MAX_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS), -#endif -#if SQLITE_MEMDEBUG - "MEMDEBUG", -#endif -#if SQLITE_MIXED_ENDIAN_64BIT_FLOAT - "MIXED_ENDIAN_64BIT_FLOAT", -#endif -#if SQLITE_MMAP_READWRITE - "MMAP_READWRITE", -#endif -#if SQLITE_MUTEX_NOOP - "MUTEX_NOOP", -#endif -#if SQLITE_MUTEX_NREF - "MUTEX_NREF", -#endif -#if SQLITE_MUTEX_OMIT - "MUTEX_OMIT", -#endif -#if SQLITE_MUTEX_PTHREADS - "MUTEX_PTHREADS", -#endif -#if SQLITE_MUTEX_W32 - "MUTEX_W32", -#endif -#if SQLITE_NEED_ERR_NAME - "NEED_ERR_NAME", -#endif -#if SQLITE_NOINLINE - "NOINLINE", -#endif -#if SQLITE_NO_SYNC - "NO_SYNC", -#endif -#if SQLITE_OMIT_ALTERTABLE - "OMIT_ALTERTABLE", -#endif -#if SQLITE_OMIT_ANALYZE - "OMIT_ANALYZE", -#endif -#if SQLITE_OMIT_ATTACH - "OMIT_ATTACH", -#endif -#if SQLITE_OMIT_AUTHORIZATION - "OMIT_AUTHORIZATION", -#endif -#if SQLITE_OMIT_AUTOINCREMENT - "OMIT_AUTOINCREMENT", -#endif -#if SQLITE_OMIT_AUTOINIT - "OMIT_AUTOINIT", -#endif -#if SQLITE_OMIT_AUTOMATIC_INDEX - "OMIT_AUTOMATIC_INDEX", -#endif -#if SQLITE_OMIT_AUTORESET - "OMIT_AUTORESET", -#endif -#if SQLITE_OMIT_AUTOVACUUM - "OMIT_AUTOVACUUM", -#endif -#if SQLITE_OMIT_BETWEEN_OPTIMIZATION - "OMIT_BETWEEN_OPTIMIZATION", -#endif -#if SQLITE_OMIT_BLOB_LITERAL - "OMIT_BLOB_LITERAL", -#endif -#if SQLITE_OMIT_BTREECOUNT - "OMIT_BTREECOUNT", -#endif -#if SQLITE_OMIT_CAST - "OMIT_CAST", -#endif -#if SQLITE_OMIT_CHECK - "OMIT_CHECK", -#endif -#if SQLITE_OMIT_COMPLETE - "OMIT_COMPLETE", -#endif -#if SQLITE_OMIT_COMPOUND_SELECT - "OMIT_COMPOUND_SELECT", -#endif -#if SQLITE_OMIT_CONFLICT_CLAUSE - "OMIT_CONFLICT_CLAUSE", -#endif -#if SQLITE_OMIT_CTE - "OMIT_CTE", -#endif -#if SQLITE_OMIT_DATETIME_FUNCS - "OMIT_DATETIME_FUNCS", -#endif -#if SQLITE_OMIT_DECLTYPE - "OMIT_DECLTYPE", -#endif -#if SQLITE_OMIT_DEPRECATED - "OMIT_DEPRECATED", -#endif -#if SQLITE_OMIT_DISKIO - "OMIT_DISKIO", -#endif -#if SQLITE_OMIT_EXPLAIN - "OMIT_EXPLAIN", -#endif -#if SQLITE_OMIT_FLAG_PRAGMAS - "OMIT_FLAG_PRAGMAS", -#endif -#if SQLITE_OMIT_FLOATING_POINT - "OMIT_FLOATING_POINT", -#endif -#if SQLITE_OMIT_FOREIGN_KEY - "OMIT_FOREIGN_KEY", -#endif -#if SQLITE_OMIT_GET_TABLE - "OMIT_GET_TABLE", -#endif -#if SQLITE_OMIT_HEX_INTEGER - "OMIT_HEX_INTEGER", -#endif -#if SQLITE_OMIT_INCRBLOB - "OMIT_INCRBLOB", -#endif -#if SQLITE_OMIT_INTEGRITY_CHECK - "OMIT_INTEGRITY_CHECK", -#endif -#if SQLITE_OMIT_LIKE_OPTIMIZATION - "OMIT_LIKE_OPTIMIZATION", -#endif -#if SQLITE_OMIT_LOAD_EXTENSION - "OMIT_LOAD_EXTENSION", -#endif -#if SQLITE_OMIT_LOCALTIME - "OMIT_LOCALTIME", -#endif -#if SQLITE_OMIT_LOOKASIDE - "OMIT_LOOKASIDE", -#endif -#if SQLITE_OMIT_MEMORYDB - "OMIT_MEMORYDB", -#endif -#if SQLITE_OMIT_OR_OPTIMIZATION - "OMIT_OR_OPTIMIZATION", -#endif -#if SQLITE_OMIT_PAGER_PRAGMAS - "OMIT_PAGER_PRAGMAS", -#endif -#if SQLITE_OMIT_PARSER_TRACE - "OMIT_PARSER_TRACE", -#endif -#if SQLITE_OMIT_POPEN - "OMIT_POPEN", -#endif -#if SQLITE_OMIT_PRAGMA - "OMIT_PRAGMA", -#endif -#if SQLITE_OMIT_PROGRESS_CALLBACK - "OMIT_PROGRESS_CALLBACK", -#endif -#if SQLITE_OMIT_QUICKBALANCE - "OMIT_QUICKBALANCE", -#endif -#if SQLITE_OMIT_REINDEX - "OMIT_REINDEX", -#endif -#if SQLITE_OMIT_SCHEMA_PRAGMAS - "OMIT_SCHEMA_PRAGMAS", -#endif -#if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS - "OMIT_SCHEMA_VERSION_PRAGMAS", -#endif -#if SQLITE_OMIT_SHARED_CACHE - "OMIT_SHARED_CACHE", -#endif -#if SQLITE_OMIT_SHUTDOWN_DIRECTORIES - "OMIT_SHUTDOWN_DIRECTORIES", -#endif -#if SQLITE_OMIT_SUBQUERY - "OMIT_SUBQUERY", -#endif -#if SQLITE_OMIT_TCL_VARIABLE - "OMIT_TCL_VARIABLE", -#endif -#if SQLITE_OMIT_TEMPDB - "OMIT_TEMPDB", -#endif -#if SQLITE_OMIT_TEST_CONTROL - "OMIT_TEST_CONTROL", -#endif -#if SQLITE_OMIT_TRACE - "OMIT_TRACE", -#endif -#if SQLITE_OMIT_TRIGGER - "OMIT_TRIGGER", -#endif -#if SQLITE_OMIT_TRUNCATE_OPTIMIZATION - "OMIT_TRUNCATE_OPTIMIZATION", -#endif -#if SQLITE_OMIT_UTF16 - "OMIT_UTF16", -#endif -#if SQLITE_OMIT_VACUUM - "OMIT_VACUUM", -#endif -#if SQLITE_OMIT_VIEW - "OMIT_VIEW", -#endif -#if SQLITE_OMIT_VIRTUALTABLE - "OMIT_VIRTUALTABLE", -#endif -#if SQLITE_OMIT_WAL - "OMIT_WAL", -#endif -#if SQLITE_OMIT_WSD - "OMIT_WSD", -#endif -#if SQLITE_OMIT_XFER_OPT - "OMIT_XFER_OPT", -#endif -#if SQLITE_PCACHE_SEPARATE_HEADER - "PCACHE_SEPARATE_HEADER", -#endif -#if SQLITE_PERFORMANCE_TRACE - "PERFORMANCE_TRACE", -#endif -#if SQLITE_POWERSAFE_OVERWRITE - "POWERSAFE_OVERWRITE", -#endif -#if SQLITE_PREFER_PROXY_LOCKING - "PREFER_PROXY_LOCKING", -#endif -#if SQLITE_PROXY_DEBUG - "PROXY_DEBUG", -#endif -#if SQLITE_REVERSE_UNORDERED_SELECTS - "REVERSE_UNORDERED_SELECTS", -#endif -#if SQLITE_RTREE_INT_ONLY - "RTREE_INT_ONLY", -#endif -#if SQLITE_SECURE_DELETE - "SECURE_DELETE", -#endif -#if SQLITE_SMALL_STACK - "SMALL_STACK", -#endif -#ifdef SQLITE_SORTER_PMASZ - "SORTER_PMASZ=" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ), -#endif -#if SQLITE_SOUNDEX - "SOUNDEX", -#endif -#ifdef SQLITE_STAT4_SAMPLES - "STAT4_SAMPLES=" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES), -#endif -#ifdef SQLITE_STMTJRNL_SPILL - "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL), -#endif -#if SQLITE_SUBSTR_COMPATIBILITY - "SUBSTR_COMPATIBILITY", -#endif -#if SQLITE_SYSTEM_MALLOC - "SYSTEM_MALLOC", -#endif -#if SQLITE_TCL - "TCL", -#endif -#ifdef SQLITE_TEMP_STORE - "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE), -#endif -#if SQLITE_TEST - "TEST", -#endif -#if defined(SQLITE_THREADSAFE) - "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE), -#elif defined(THREADSAFE) - "THREADSAFE=" CTIMEOPT_VAL(THREADSAFE), -#else - "THREADSAFE=1", -#endif -#if SQLITE_UNLINK_AFTER_CLOSE - "UNLINK_AFTER_CLOSE", -#endif -#if SQLITE_UNTESTABLE - "UNTESTABLE", -#endif -#if SQLITE_USER_AUTHENTICATION - "USER_AUTHENTICATION", -#endif -#if SQLITE_USE_ALLOCA - "USE_ALLOCA", -#endif -#if SQLITE_USE_FCNTL_TRACE - "USE_FCNTL_TRACE", -#endif -#if SQLITE_USE_URI - "USE_URI", -#endif -#if SQLITE_VDBE_COVERAGE - "VDBE_COVERAGE", -#endif -#if SQLITE_WIN32_MALLOC - "WIN32_MALLOC", -#endif -#if SQLITE_ZERO_MALLOC - "ZERO_MALLOC", -#endif -/* -** END CODE GENERATED BY tool/mkctime.tcl -*/ -}; - -SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){ - *pnOpt = sizeof(sqlite3azCompileOpt) / sizeof(sqlite3azCompileOpt[0]); - return (const char**)sqlite3azCompileOpt; -} - -#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ - -/************** End of ctime.c ***********************************************/ -/************** Begin file sqliteInt.h ***************************************/ -/* -** 2001 September 15 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** Internal interface definitions for SQLite. -** -*/ -#ifndef SQLITEINT_H -#define SQLITEINT_H - -/* Special Comments: -** -** Some comments have special meaning to the tools that measure test -** coverage: -** -** NO_TEST - The branches on this line are not -** measured by branch coverage. This is -** used on lines of code that actually -** implement parts of coverage testing. -** -** OPTIMIZATION-IF-TRUE - This branch is allowed to alway be false -** and the correct answer is still obtained, -** though perhaps more slowly. -** -** OPTIMIZATION-IF-FALSE - This branch is allowed to alway be true -** and the correct answer is still obtained, -** though perhaps more slowly. -** -** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread -** that would be harmless and undetectable -** if it did occur. -** -** In all cases, the special comment must be enclosed in the usual -** slash-asterisk...asterisk-slash comment marks, with no spaces between the -** asterisks and the comment text. -*/ - -/* -** Make sure the Tcl calling convention macro is defined. This macro is -** only used by test code and Tcl integration code. -*/ -#ifndef SQLITE_TCLAPI -# define SQLITE_TCLAPI -#endif - -/* -** Include the header file used to customize the compiler options for MSVC. -** This should be done first so that it can successfully prevent spurious -** compiler warnings due to subsequent content in this file and other files -** that are included by this file. -*/ -/************** Include msvc.h in the middle of sqliteInt.h ******************/ -/************** Begin file msvc.h ********************************************/ -/* -** 2015 January 12 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This file contains code that is specific to MSVC. -*/ -#ifndef SQLITE_MSVC_H -#define SQLITE_MSVC_H - -#if defined(_MSC_VER) -#pragma warning(disable : 4054) -#pragma warning(disable : 4055) -#pragma warning(disable : 4100) -#pragma warning(disable : 4127) -#pragma warning(disable : 4130) -#pragma warning(disable : 4152) -#pragma warning(disable : 4189) -#pragma warning(disable : 4206) -#pragma warning(disable : 4210) -#pragma warning(disable : 4232) -#pragma warning(disable : 4244) -#pragma warning(disable : 4305) -#pragma warning(disable : 4306) -#pragma warning(disable : 4702) -#pragma warning(disable : 4706) -#endif /* defined(_MSC_VER) */ - -#endif /* SQLITE_MSVC_H */ - -/************** End of msvc.h ************************************************/ -/************** Continuing where we left off in sqliteInt.h ******************/ - -/* -** Special setup for VxWorks -*/ -/************** Include vxworks.h in the middle of sqliteInt.h ***************/ -/************** Begin file vxworks.h *****************************************/ -/* -** 2015-03-02 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This file contains code that is specific to Wind River's VxWorks -*/ -#if defined(__RTP__) || defined(_WRS_KERNEL) -/* This is VxWorks. Set up things specially for that OS -*/ -#include -#include /* amalgamator: dontcache */ -#define OS_VXWORKS 1 -#define SQLITE_OS_OTHER 0 -#define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1 -#define SQLITE_OMIT_LOAD_EXTENSION 1 -#define SQLITE_ENABLE_LOCKING_STYLE 0 -#define HAVE_UTIME 1 -#else -/* This is not VxWorks. */ -#define OS_VXWORKS 0 -#define HAVE_FCHOWN 1 -#define HAVE_READLINK 1 -#define HAVE_LSTAT 1 -#endif /* defined(_WRS_KERNEL) */ - -/************** End of vxworks.h *********************************************/ -/************** Continuing where we left off in sqliteInt.h ******************/ - -/* -** These #defines should enable >2GB file support on POSIX if the -** underlying operating system supports it. If the OS lacks -** large file support, or if the OS is windows, these should be no-ops. -** -** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any -** system #includes. Hence, this block of code must be the very first -** code in all source files. -** -** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch -** on the compiler command line. This is necessary if you are compiling -** on a recent machine (ex: Red Hat 7.2) but you want your code to work -** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2 -** without this option, LFS is enable. But LFS does not exist in the kernel -** in Red Hat 6.0, so the code won't work. Hence, for maximum binary -** portability you should omit LFS. -** -** The previous paragraph was written in 2005. (This paragraph is written -** on 2008-11-28.) These days, all Linux kernels support large files, so -** you should probably leave LFS enabled. But some embedded platforms might -** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful. -** -** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later. -*/ -#ifndef SQLITE_DISABLE_LFS -# define _LARGE_FILE 1 -# ifndef _FILE_OFFSET_BITS -# define _FILE_OFFSET_BITS 64 -# endif -# define _LARGEFILE_SOURCE 1 -#endif - -/* The GCC_VERSION and MSVC_VERSION macros are used to -** conditionally include optimizations for each of these compilers. A -** value of 0 means that compiler is not being used. The -** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific -** optimizations, and hence set all compiler macros to 0 -** -** There was once also a CLANG_VERSION macro. However, we learn that the -** version numbers in clang are for "marketing" only and are inconsistent -** and unreliable. Fortunately, all versions of clang also recognize the -** gcc version numbers and have reasonable settings for gcc version numbers, -** so the GCC_VERSION macro will be set to a correct non-zero value even -** when compiling with clang. -*/ -#if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC) -# define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__) -#else -# define GCC_VERSION 0 -#endif -#if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC) -# define MSVC_VERSION _MSC_VER -#else -# define MSVC_VERSION 0 -#endif - -/* Needed for various definitions... */ -#if defined(__GNUC__) && !defined(_GNU_SOURCE) -# define _GNU_SOURCE -#endif - -#if defined(__OpenBSD__) && !defined(_BSD_SOURCE) -# define _BSD_SOURCE -#endif - -/* -** For MinGW, check to see if we can include the header file containing its -** version information, among other things. Normally, this internal MinGW -** header file would [only] be included automatically by other MinGW header -** files; however, the contained version information is now required by this -** header file to work around binary compatibility issues (see below) and -** this is the only known way to reliably obtain it. This entire #if block -** would be completely unnecessary if there was any other way of detecting -** MinGW via their preprocessor (e.g. if they customized their GCC to define -** some MinGW-specific macros). When compiling for MinGW, either the -** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be -** defined; otherwise, detection of conditions specific to MinGW will be -** disabled. -*/ -#if defined(_HAVE_MINGW_H) -# include "mingw.h" -#elif defined(_HAVE__MINGW_H) -# include "_mingw.h" -#endif - -/* -** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T -** define is required to maintain binary compatibility with the MSVC runtime -** library in use (e.g. for Windows XP). -*/ -#if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \ - defined(_WIN32) && !defined(_WIN64) && \ - defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \ - defined(__MSVCRT__) -# define _USE_32BIT_TIME_T -#endif - -/* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear -** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for -** MinGW. -*/ -/************** Include sqlite3.h in the middle of sqliteInt.h ***************/ -/************** Begin file sqlite3.h *****************************************/ -/* -** 2001-09-15 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This header file defines the interface that the SQLite library -** presents to client programs. If a C-function, structure, datatype, -** or constant definition does not appear in this file, then it is -** not a published API of SQLite, is subject to change without -** notice, and should not be referenced by programs that use SQLite. -** -** Some of the definitions that are in this file are marked as -** "experimental". Experimental interfaces are normally new -** features recently added to SQLite. We do not anticipate changes -** to experimental interfaces but reserve the right to make minor changes -** if experience from use "in the wild" suggest such changes are prudent. -** -** The official C-language API documentation for SQLite is derived -** from comments in this file. This file is the authoritative source -** on how SQLite interfaces are supposed to operate. -** -** The name of this file under configuration management is "sqlite.h.in". -** The makefile makes some minor changes to this file (such as inserting -** the version number) and changes its name to "sqlite3.h" as -** part of the build process. -*/ -#ifndef SQLITE3_H -#define SQLITE3_H -#include /* Needed for the definition of va_list */ - -/* -** Make sure we can call this stuff from C++. -*/ -#if 0 -extern "C" { -#endif - - -/* -** Provide the ability to override linkage features of the interface. -*/ -#ifndef SQLITE_EXTERN -# define SQLITE_EXTERN extern -#endif -#ifndef SQLITE_API -# define SQLITE_API -#endif -#ifndef SQLITE_CDECL -# define SQLITE_CDECL -#endif -#ifndef SQLITE_APICALL -# define SQLITE_APICALL -#endif -#ifndef SQLITE_STDCALL -# define SQLITE_STDCALL SQLITE_APICALL -#endif -#ifndef SQLITE_CALLBACK -# define SQLITE_CALLBACK -#endif -#ifndef SQLITE_SYSAPI -# define SQLITE_SYSAPI -#endif - -/* -** These no-op macros are used in front of interfaces to mark those -** interfaces as either deprecated or experimental. New applications -** should not use deprecated interfaces - they are supported for backwards -** compatibility only. Application writers should be aware that -** experimental interfaces are subject to change in point releases. -** -** These macros used to resolve to various kinds of compiler magic that -** would generate warning messages when they were used. But that -** compiler magic ended up generating such a flurry of bug reports -** that we have taken it all out and gone back to using simple -** noop macros. -*/ -#define SQLITE_DEPRECATED -#define SQLITE_EXPERIMENTAL - -/* -** Ensure these symbols were not defined by some previous header file. -*/ -#ifdef SQLITE_VERSION -# undef SQLITE_VERSION -#endif -#ifdef SQLITE_VERSION_NUMBER -# undef SQLITE_VERSION_NUMBER -#endif - -/* -** CAPI3REF: Compile-Time Library Version Numbers -** -** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header -** evaluates to a string literal that is the SQLite version in the -** format "X.Y.Z" where X is the major version number (always 3 for -** SQLite3) and Y is the minor version number and Z is the release number.)^ -** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer -** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same -** numbers used in [SQLITE_VERSION].)^ -** The SQLITE_VERSION_NUMBER for any given release of SQLite will also -** be larger than the release from which it is derived. Either Y will -** be held constant and Z will be incremented or else Y will be incremented -** and Z will be reset to zero. -** -** Since [version 3.6.18] ([dateof:3.6.18]), -** SQLite source code has been stored in the -** Fossil configuration management -** system. ^The SQLITE_SOURCE_ID macro evaluates to -** a string which identifies a particular check-in of SQLite -** within its configuration management system. ^The SQLITE_SOURCE_ID -** string contains the date and time of the check-in (UTC) and a SHA1 -** or SHA3-256 hash of the entire source tree. If the source code has -** been edited in any way since it was last checked in, then the last -** four hexadecimal digits of the hash may be modified. -** -** See also: [sqlite3_libversion()], -** [sqlite3_libversion_number()], [sqlite3_sourceid()], -** [sqlite_version()] and [sqlite_source_id()]. -*/ -#define SQLITE_VERSION "3.21.0" -#define SQLITE_VERSION_NUMBER 3021000 -#define SQLITE_SOURCE_ID "2017-10-24 18:55:49 1a584e499906b5c87ec7d43d4abce641fdf017c42125b083109bc77c4de48827" - -/* -** 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); -#endif - -/* -** CAPI3REF: Test To See If The Library Is Threadsafe -** -** ^The sqlite3_threadsafe() function returns zero if and only if -** SQLite was compiled with mutexing code omitted due to the -** [SQLITE_THREADSAFE] compile-time option being set to 0. -** -** SQLite can be compiled with or without mutexes. When -** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes -** are enabled and SQLite is threadsafe. When the -** [SQLITE_THREADSAFE] macro is 0, -** the mutexes are omitted. Without the mutexes, it is not safe -** to use SQLite concurrently from more than one thread. -** -** Enabling mutexes incurs a measurable performance penalty. -** So if speed is of utmost importance, it makes sense to disable -** the mutexes. But for maximum safety, mutexes should be enabled. -** ^The default behavior is for mutexes to be enabled. -** -** This interface can be used by an application to make sure that the -** version of SQLite that it is linking against was compiled with -** the desired setting of the [SQLITE_THREADSAFE] macro. -** -** This interface only reports on the compile-time mutex setting -** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with -** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but -** can be fully or partially disabled using a call to [sqlite3_config()] -** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], -** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the -** sqlite3_threadsafe() function shows only the compile-time setting of -** thread safety, not any run-time changes to that setting made by -** sqlite3_config(). In other words, the return value from sqlite3_threadsafe() -** is unchanged by calls to sqlite3_config().)^ -** -** See the [threading mode] documentation for additional information. -*/ -SQLITE_API int sqlite3_threadsafe(void); - -/* -** CAPI3REF: Database Connection Handle -** KEYWORDS: {database connection} {database connections} -** -** Each open SQLite database is represented by a pointer to an instance of -** the opaque structure named "sqlite3". It is useful to think of an sqlite3 -** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and -** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()] -** and [sqlite3_close_v2()] are its destructors. There are many other -** interfaces (such as -** [sqlite3_prepare_v2()], [sqlite3_create_function()], and -** [sqlite3_busy_timeout()] to name but three) that are methods on an -** sqlite3 object. -*/ -typedef struct sqlite3 sqlite3; - -/* -** CAPI3REF: 64-Bit Integer Types -** KEYWORDS: sqlite_int64 sqlite_uint64 -** -** Because there is no cross-platform way to specify 64-bit integer types -** SQLite includes typedefs for 64-bit signed and unsigned integers. -** -** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions. -** The sqlite_int64 and sqlite_uint64 types are supported for backwards -** compatibility only. -** -** ^The sqlite3_int64 and sqlite_int64 types can store integer values -** between -9223372036854775808 and +9223372036854775807 inclusive. ^The -** sqlite3_uint64 and sqlite_uint64 types can store integer values -** between 0 and +18446744073709551615 inclusive. -*/ -#ifdef SQLITE_INT64_TYPE - typedef SQLITE_INT64_TYPE sqlite_int64; -# ifdef SQLITE_UINT64_TYPE - typedef SQLITE_UINT64_TYPE sqlite_uint64; -# else - typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; -# endif -#elif defined(_MSC_VER) || defined(__BORLANDC__) - typedef __int64 sqlite_int64; - typedef unsigned __int64 sqlite_uint64; -#else - typedef long long int sqlite_int64; - typedef unsigned long long int sqlite_uint64; -#endif -typedef sqlite_int64 sqlite3_int64; -typedef sqlite_uint64 sqlite3_uint64; - -/* -** If compiling for a processor that lacks floating point support, -** substitute integer for floating-point. -*/ -#ifdef SQLITE_OMIT_FLOATING_POINT -# define double sqlite3_int64 -#endif - -/* -** CAPI3REF: Closing A Database Connection -** DESTRUCTOR: sqlite3 -** -** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors -** for the [sqlite3] object. -** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if -** the [sqlite3] object is successfully destroyed and all associated -** resources are deallocated. -** -** ^If the database connection is associated with unfinalized prepared -** statements or unfinished sqlite3_backup objects then sqlite3_close() -** will leave the database connection open and return [SQLITE_BUSY]. -** ^If sqlite3_close_v2() is called with unfinalized prepared statements -** and/or unfinished sqlite3_backups, then the database connection becomes -** an unusable "zombie" which will automatically be deallocated when the -** last prepared statement is finalized or the last sqlite3_backup is -** finished. The sqlite3_close_v2() interface is intended for use with -** host languages that are garbage collected, and where the order in which -** destructors are called is arbitrary. -** -** Applications should [sqlite3_finalize | finalize] all [prepared statements], -** [sqlite3_blob_close | close] all [BLOB handles], and -** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated -** with the [sqlite3] object prior to attempting to close the object. ^If -** sqlite3_close_v2() is called on a [database connection] that still has -** outstanding [prepared statements], [BLOB handles], and/or -** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation -** of resources is deferred until all [prepared statements], [BLOB handles], -** and [sqlite3_backup] objects are also destroyed. -** -** ^If an [sqlite3] object is destroyed while a transaction is open, -** the transaction is automatically rolled back. -** -** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)] -** must be either a NULL -** pointer or an [sqlite3] object pointer obtained -** from [sqlite3_open()], [sqlite3_open16()], or -** [sqlite3_open_v2()], and not previously closed. -** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer -** argument is a harmless no-op. -*/ -SQLITE_API int sqlite3_close(sqlite3*); -SQLITE_API int sqlite3_close_v2(sqlite3*); - -/* -** The type for a callback function. -** This is legacy and deprecated. It is included for historical -** compatibility and is not documented. -*/ -typedef int (*sqlite3_callback)(void*,int,char**, char**); - -/* -** CAPI3REF: One-Step Query Execution Interface -** METHOD: sqlite3 -** -** The sqlite3_exec() interface is a convenience wrapper around -** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()], -** that allows an application to run multiple statements of SQL -** without having to use a lot of C code. -** -** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded, -** semicolon-separate SQL statements passed into its 2nd argument, -** in the context of the [database connection] passed in as its 1st -** argument. ^If the callback function of the 3rd argument to -** sqlite3_exec() is not NULL, then it is invoked for each result row -** coming out of the evaluated SQL statements. ^The 4th argument to -** sqlite3_exec() is relayed through to the 1st argument of each -** callback invocation. ^If the callback pointer to sqlite3_exec() -** is NULL, then no callback is ever invoked and result rows are -** ignored. -** -** ^If an error occurs while evaluating the SQL statements passed into -** sqlite3_exec(), then execution of the current statement stops and -** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec() -** is not NULL then any error message is written into memory obtained -** from [sqlite3_malloc()] and passed back through the 5th parameter. -** To avoid memory leaks, the application should invoke [sqlite3_free()] -** on error message strings returned through the 5th parameter of -** sqlite3_exec() after the error message string is no longer needed. -** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors -** occur, then sqlite3_exec() sets the pointer in its 5th parameter to -** NULL before returning. -** -** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec() -** routine returns SQLITE_ABORT without invoking the callback again and -** without running any subsequent SQL statements. -** -** ^The 2nd argument to the sqlite3_exec() callback function is the -** number of columns in the result. ^The 3rd argument to the sqlite3_exec() -** callback is an array of pointers to strings obtained as if from -** [sqlite3_column_text()], one for each column. ^If an element of a -** result row is NULL then the corresponding string pointer for the -** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the -** sqlite3_exec() callback is an array of pointers to strings where each -** entry represents the name of corresponding result column as obtained -** from [sqlite3_column_name()]. -** -** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer -** to an empty string, or a pointer that contains only whitespace and/or -** SQL comments, then no SQL statements are evaluated and the database -** is not changed. -** -** Restrictions: -** -**
    -**
  • The application must ensure that the 1st parameter to sqlite3_exec() -** is a valid and open [database connection]. -**
  • The application must not close the [database connection] specified by -** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running. -**
  • The application must not modify the SQL statement text passed into -** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running. -**
-*/ -SQLITE_API int sqlite3_exec( - sqlite3*, /* An open database */ - const char *sql, /* SQL to be evaluated */ - int (*callback)(void*,int,char**,char**), /* Callback function */ - void *, /* 1st argument to callback */ - char **errmsg /* Error msg written here */ -); - -/* -** CAPI3REF: Result Codes -** KEYWORDS: {result code definitions} -** -** Many SQLite functions return an integer result code from the set shown -** here in order to indicate success or failure. -** -** New error codes may be added in future versions of SQLite. -** -** See also: [extended result code definitions] -*/ -#define SQLITE_OK 0 /* Successful result */ -/* beginning-of-error-codes */ -#define SQLITE_ERROR 1 /* Generic error */ -#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ -#define SQLITE_PERM 3 /* Access permission denied */ -#define SQLITE_ABORT 4 /* Callback routine requested an abort */ -#define SQLITE_BUSY 5 /* The database file is locked */ -#define SQLITE_LOCKED 6 /* A table in the database is locked */ -#define SQLITE_NOMEM 7 /* A malloc() failed */ -#define SQLITE_READONLY 8 /* Attempt to write a readonly database */ -#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ -#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ -#define SQLITE_CORRUPT 11 /* The database disk image is malformed */ -#define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */ -#define SQLITE_FULL 13 /* Insertion failed because database is full */ -#define SQLITE_CANTOPEN 14 /* Unable to open the database file */ -#define SQLITE_PROTOCOL 15 /* Database lock protocol error */ -#define SQLITE_EMPTY 16 /* Internal use only */ -#define SQLITE_SCHEMA 17 /* The database schema changed */ -#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ -#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ -#define SQLITE_MISMATCH 20 /* Data type mismatch */ -#define SQLITE_MISUSE 21 /* Library used incorrectly */ -#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ -#define SQLITE_AUTH 23 /* Authorization denied */ -#define SQLITE_FORMAT 24 /* Not used */ -#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ -#define SQLITE_NOTADB 26 /* File opened that is not a database file */ -#define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */ -#define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */ -#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ -#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ -/* end-of-error-codes */ - -/* -** CAPI3REF: Extended Result Codes -** KEYWORDS: {extended result code definitions} -** -** In its default configuration, SQLite API routines return one of 30 integer -** [result codes]. However, experience has shown that many of -** these result codes are too coarse-grained. They do not provide as -** much information about problems as programmers might like. In an effort to -** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8] -** and later) include -** support for additional result codes that provide more detailed information -** about errors. These [extended result codes] are enabled or disabled -** on a per database connection basis using the -** [sqlite3_extended_result_codes()] API. Or, the extended code for -** the most recent error can be obtained using -** [sqlite3_extended_errcode()]. -*/ -#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) -#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) -#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) -#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) -#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) -#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) -#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) -#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) -#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) -#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) -#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) -#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) -#define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8)) -#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8)) -#define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8)) -#define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8)) -#define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8)) -#define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8)) -#define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8)) -#define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8)) -#define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8)) -#define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8)) -#define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8)) -#define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8)) -#define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8)) -#define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8)) -#define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8)) -#define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8)) -#define SQLITE_IOERR_BEGIN_ATOMIC (SQLITE_IOERR | (29<<8)) -#define SQLITE_IOERR_COMMIT_ATOMIC (SQLITE_IOERR | (30<<8)) -#define SQLITE_IOERR_ROLLBACK_ATOMIC (SQLITE_IOERR | (31<<8)) -#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8)) -#define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8)) -#define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8)) -#define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8)) -#define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8)) -#define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8)) -#define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8)) -#define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<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_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8)) -#define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8)) -#define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8)) -#define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8)) -#define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8)) -#define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8)) -#define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8)) -#define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8)) -#define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8)) -#define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8)) -#define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8)) -#define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8)) -#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8)) -#define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8)) -#define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8)) -#define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8)) - -/* -** CAPI3REF: Flags For File Open Operations -** -** These bit values are intended for use in the -** 3rd parameter to the [sqlite3_open_v2()] interface and -** in the 4th parameter to the [sqlite3_vfs.xOpen] method. -*/ -#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ -#define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ -#define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */ -#define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */ -#define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */ -#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */ -#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */ -#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */ -#define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */ -#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */ -#define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */ -#define SQLITE_OPEN_WAL 0x00080000 /* VFS only */ - -/* Reserved: 0x00F00000 */ - -/* -** CAPI3REF: Device Characteristics -** -** The xDeviceCharacteristics method of the [sqlite3_io_methods] -** object returns an integer which is a vector of these -** bit values expressing I/O characteristics of the mass storage -** device that holds the file that the [sqlite3_io_methods] -** refers to. -** -** The SQLITE_IOCAP_ATOMIC property means that all writes of -** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values -** mean that writes of blocks that are nnn bytes in size and -** are aligned to an address which is an integer multiple of -** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means -** that when data is appended to a file, the data is appended -** first then the size of the file is extended, never the other -** way around. The SQLITE_IOCAP_SEQUENTIAL property means that -** information is written to disk in the same order as calls -** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that -** after reboot following a crash or power loss, the only bytes in a -** file that were written at the application level might have changed -** and that adjacent bytes, even bytes within the same sector are -** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN -** flag indicates that a file cannot be deleted when open. The -** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on -** read-only media and cannot be changed even by processes with -** elevated privileges. -** -** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying -** filesystem supports doing multiple write operations atomically when those -** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and -** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. -*/ -#define SQLITE_IOCAP_ATOMIC 0x00000001 -#define SQLITE_IOCAP_ATOMIC512 0x00000002 -#define SQLITE_IOCAP_ATOMIC1K 0x00000004 -#define SQLITE_IOCAP_ATOMIC2K 0x00000008 -#define SQLITE_IOCAP_ATOMIC4K 0x00000010 -#define SQLITE_IOCAP_ATOMIC8K 0x00000020 -#define SQLITE_IOCAP_ATOMIC16K 0x00000040 -#define SQLITE_IOCAP_ATOMIC32K 0x00000080 -#define SQLITE_IOCAP_ATOMIC64K 0x00000100 -#define SQLITE_IOCAP_SAFE_APPEND 0x00000200 -#define SQLITE_IOCAP_SEQUENTIAL 0x00000400 -#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800 -#define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000 -#define SQLITE_IOCAP_IMMUTABLE 0x00002000 -#define SQLITE_IOCAP_BATCH_ATOMIC 0x00004000 - -/* -** CAPI3REF: File Locking Levels -** -** SQLite uses one of these integer values as the second -** argument to calls it makes to the xLock() and xUnlock() methods -** of an [sqlite3_io_methods] object. -*/ -#define SQLITE_LOCK_NONE 0 -#define SQLITE_LOCK_SHARED 1 -#define SQLITE_LOCK_RESERVED 2 -#define SQLITE_LOCK_PENDING 3 -#define SQLITE_LOCK_EXCLUSIVE 4 - -/* -** CAPI3REF: Synchronization Type Flags -** -** When SQLite invokes the xSync() method of an -** [sqlite3_io_methods] object it uses a combination of -** these integer values as the second argument. -** -** When the SQLITE_SYNC_DATAONLY flag is used, it means that the -** sync operation only needs to flush data to mass storage. Inode -** information need not be flushed. If the lower four bits of the flag -** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics. -** If the lower four bits equal SQLITE_SYNC_FULL, that means -** to use Mac OS X style fullsync instead of fsync(). -** -** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags -** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL -** settings. The [synchronous pragma] determines when calls to the -** xSync VFS method occur and applies uniformly across all platforms. -** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how -** energetic or rigorous or forceful the sync operations are and -** only make a difference on Mac OSX for the default SQLite code. -** (Third-party VFS implementations might also make the distinction -** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the -** operating systems natively supported by SQLite, only Mac OSX -** cares about the difference.) -*/ -#define SQLITE_SYNC_NORMAL 0x00002 -#define SQLITE_SYNC_FULL 0x00003 -#define SQLITE_SYNC_DATAONLY 0x00010 - -/* -** CAPI3REF: OS Interface Open File Handle -** -** An [sqlite3_file] object represents an open file in the -** [sqlite3_vfs | OS interface layer]. Individual OS interface -** implementations will -** want to subclass this object by appending additional fields -** for their own use. The pMethods entry is a pointer to an -** [sqlite3_io_methods] object that defines methods for performing -** I/O operations on the open file. -*/ -typedef struct sqlite3_file sqlite3_file; -struct sqlite3_file { - const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ -}; - -/* -** CAPI3REF: OS Interface File Virtual Methods Object -** -** Every file opened by the [sqlite3_vfs.xOpen] method populates an -** [sqlite3_file] object (or, more commonly, a subclass of the -** [sqlite3_file] object) with a pointer to an instance of this object. -** This object defines the methods used to perform various operations -** against the open file represented by the [sqlite3_file] object. -** -** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element -** to a non-NULL pointer, then the sqlite3_io_methods.xClose method -** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The -** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen] -** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element -** to NULL. -** -** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or -** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). -** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY] -** flag may be ORed in to indicate that only the data of the file -** and not its inode needs to be synced. -** -** The integer values to xLock() and xUnlock() are one of -**
    -**
  • [SQLITE_LOCK_NONE], -**
  • [SQLITE_LOCK_SHARED], -**
  • [SQLITE_LOCK_RESERVED], -**
  • [SQLITE_LOCK_PENDING], or -**
  • [SQLITE_LOCK_EXCLUSIVE]. -**
-** xLock() increases the lock. xUnlock() decreases the lock. -** The xCheckReservedLock() method checks whether any database connection, -** either in this process or in some other process, is holding a RESERVED, -** PENDING, or EXCLUSIVE lock on the file. It returns true -** if such a lock exists and false otherwise. -** -** The xFileControl() method is a generic interface that allows custom -** VFS implementations to directly control an open file using the -** [sqlite3_file_control()] interface. The second "op" argument is an -** integer opcode. The third argument is a generic pointer intended to -** point to a structure that may contain arguments or space in which to -** write return values. Potential uses for xFileControl() might be -** functions to enable blocking locks with timeouts, to change the -** locking strategy (for example to use dot-file locks), to inquire -** about the status of a lock, or to break stale locks. The SQLite -** core reserves all opcodes less than 100 for its own use. -** A [file control opcodes | list of opcodes] less than 100 is available. -** Applications that define a custom xFileControl method should use opcodes -** greater than 100 to avoid conflicts. VFS implementations should -** return [SQLITE_NOTFOUND] for file control opcodes that they do not -** recognize. -** -** The xSectorSize() method returns the sector size of the -** device that underlies the file. The sector size is the -** minimum write that can be performed without disturbing -** other bytes in the file. The xDeviceCharacteristics() -** method returns a bit vector describing behaviors of the -** underlying device: -** -**
    -**
  • [SQLITE_IOCAP_ATOMIC] -**
  • [SQLITE_IOCAP_ATOMIC512] -**
  • [SQLITE_IOCAP_ATOMIC1K] -**
  • [SQLITE_IOCAP_ATOMIC2K] -**
  • [SQLITE_IOCAP_ATOMIC4K] -**
  • [SQLITE_IOCAP_ATOMIC8K] -**
  • [SQLITE_IOCAP_ATOMIC16K] -**
  • [SQLITE_IOCAP_ATOMIC32K] -**
  • [SQLITE_IOCAP_ATOMIC64K] -**
  • [SQLITE_IOCAP_SAFE_APPEND] -**
  • [SQLITE_IOCAP_SEQUENTIAL] -**
  • [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN] -**
  • [SQLITE_IOCAP_POWERSAFE_OVERWRITE] -**
  • [SQLITE_IOCAP_IMMUTABLE] -**
  • [SQLITE_IOCAP_BATCH_ATOMIC] -**
-** -** The SQLITE_IOCAP_ATOMIC property means that all writes of -** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values -** mean that writes of blocks that are nnn bytes in size and -** are aligned to an address which is an integer multiple of -** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means -** that when data is appended to a file, the data is appended -** first then the size of the file is extended, never the other -** way around. The SQLITE_IOCAP_SEQUENTIAL property means that -** information is written to disk in the same order as calls -** to xWrite(). -** -** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill -** in the unread portions of the buffer with zeros. A VFS that -** fails to zero-fill short reads might seem to work. However, -** failure to zero-fill short reads will eventually lead to -** database corruption. -*/ -typedef struct sqlite3_io_methods sqlite3_io_methods; -struct sqlite3_io_methods { - int iVersion; - int (*xClose)(sqlite3_file*); - int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); - int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); - int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); - int (*xSync)(sqlite3_file*, int flags); - int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); - int (*xLock)(sqlite3_file*, int); - int (*xUnlock)(sqlite3_file*, int); - int (*xCheckReservedLock)(sqlite3_file*, int *pResOut); - int (*xFileControl)(sqlite3_file*, int op, void *pArg); - int (*xSectorSize)(sqlite3_file*); - int (*xDeviceCharacteristics)(sqlite3_file*); - /* Methods above are valid for version 1 */ - int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**); - int (*xShmLock)(sqlite3_file*, int offset, int n, int flags); - void (*xShmBarrier)(sqlite3_file*); - int (*xShmUnmap)(sqlite3_file*, int deleteFlag); - /* Methods above are valid for version 2 */ - int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp); - int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p); - /* Methods above are valid for version 3 */ - /* Additional methods may be added in future releases */ -}; - -/* -** CAPI3REF: Standard File Control Opcodes -** KEYWORDS: {file control opcodes} {file control opcode} -** -** These integer constants are opcodes for the xFileControl method -** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] -** interface. -** -**
    -**
  • [[SQLITE_FCNTL_LOCKSTATE]] -** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This -** opcode causes the xFileControl method to write the current state of -** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], -** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) -** into an integer that the pArg argument points to. This capability -** is used during testing and is only available when the SQLITE_TEST -** compile-time option is used. -** -**
  • [[SQLITE_FCNTL_SIZE_HINT]] -** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS -** layer a hint of how large the database file will grow to be during the -** current transaction. This hint is not guaranteed to be accurate but it -** is often close. The underlying VFS might choose to preallocate database -** file space based on this hint in order to help writes to the database -** file run faster. -** -**
  • [[SQLITE_FCNTL_CHUNK_SIZE]] -** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS -** extends and truncates the database file in chunks of a size specified -** by the user. The fourth argument to [sqlite3_file_control()] should -** point to an integer (type int) containing the new chunk-size to use -** for the nominated database. Allocating database file space in large -** chunks (say 1MB at a time), may reduce file-system fragmentation and -** improve performance on some systems. -** -**
  • [[SQLITE_FCNTL_FILE_POINTER]] -** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer -** to the [sqlite3_file] object associated with a particular database -** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER]. -** -**
  • [[SQLITE_FCNTL_JOURNAL_POINTER]] -** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer -** to the [sqlite3_file] object associated with the journal file (either -** the [rollback journal] or the [write-ahead log]) for a particular database -** connection. See also [SQLITE_FCNTL_FILE_POINTER]. -** -**
  • [[SQLITE_FCNTL_SYNC_OMITTED]] -** No longer in use. -** -**
  • [[SQLITE_FCNTL_SYNC]] -** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and -** sent to the VFS immediately before the xSync method is invoked on a -** database file descriptor. Or, if the xSync method is not invoked -** because the user has configured SQLite with -** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place -** of the xSync method. In most cases, the pointer argument passed with -** this file-control is NULL. However, if the database file is being synced -** as part of a multi-database commit, the argument points to a nul-terminated -** string containing the transactions master-journal file name. VFSes that -** do not need this signal should silently ignore this opcode. Applications -** should not call [sqlite3_file_control()] with this opcode as doing so may -** disrupt the operation of the specialized VFSes that do require it. -** -**
  • [[SQLITE_FCNTL_COMMIT_PHASETWO]] -** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite -** and sent to the VFS after a transaction has been committed immediately -** but before the database is unlocked. VFSes that do not need this signal -** should silently ignore this opcode. Applications should not call -** [sqlite3_file_control()] with this opcode as doing so may disrupt the -** operation of the specialized VFSes that do require it. -** -**
  • [[SQLITE_FCNTL_WIN32_AV_RETRY]] -** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic -** retry counts and intervals for certain disk I/O operations for the -** windows [VFS] in order to provide robustness in the presence of -** anti-virus programs. By default, the windows VFS will retry file read, -** file write, and file delete operations up to 10 times, with a delay -** of 25 milliseconds before the first retry and with the delay increasing -** by an additional 25 milliseconds with each subsequent retry. This -** opcode allows these two values (10 retries and 25 milliseconds of delay) -** to be adjusted. The values are changed for all database connections -** within the same process. The argument is a pointer to an array of two -** integers where the first integer is the new retry count and the second -** integer is the delay. If either integer is negative, then the setting -** is not changed but instead the prior value of that setting is written -** into the array entry, allowing the current retry settings to be -** interrogated. The zDbName parameter is ignored. -** -**
  • [[SQLITE_FCNTL_PERSIST_WAL]] -** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the -** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary -** write ahead log and shared memory files used for transaction control -** are automatically deleted when the latest connection to the database -** closes. Setting persistent WAL mode causes those files to persist after -** close. Persisting the files is useful when other processes that do not -** have write permission on the directory containing the database file want -** to read the database file, as the WAL and shared memory files must exist -** in order for the database to be readable. The fourth parameter to -** [sqlite3_file_control()] for this opcode should be a pointer to an integer. -** That integer is 0 to disable persistent WAL mode or 1 to enable persistent -** WAL mode. If the integer is -1, then it is overwritten with the current -** WAL persistence setting. -** -**
  • [[SQLITE_FCNTL_POWERSAFE_OVERWRITE]] -** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the -** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting -** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the -** xDeviceCharacteristics methods. The fourth parameter to -** [sqlite3_file_control()] for this opcode should be a pointer to an integer. -** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage -** mode. If the integer is -1, then it is overwritten with the current -** zero-damage mode setting. -** -**
  • [[SQLITE_FCNTL_OVERWRITE]] -** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening -** a write transaction to indicate that, unless it is rolled back for some -** reason, the entire database file will be overwritten by the current -** transaction. This is used by VACUUM operations. -** -**
  • [[SQLITE_FCNTL_VFSNAME]] -** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of -** all [VFSes] in the VFS stack. The names are of all VFS shims and the -** final bottom-level VFS are written into memory obtained from -** [sqlite3_malloc()] and the result is stored in the char* variable -** that the fourth parameter of [sqlite3_file_control()] points to. -** The caller is responsible for freeing the memory when done. As with -** all file-control actions, there is no guarantee that this will actually -** do anything. Callers should initialize the char* variable to a NULL -** pointer in case this file-control is not implemented. This file-control -** is intended for diagnostic use only. -** -**
  • [[SQLITE_FCNTL_VFS_POINTER]] -** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level -** [VFSes] currently in use. ^(The argument X in -** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be -** of type "[sqlite3_vfs] **". This opcodes will set *X -** to a pointer to the top-level VFS.)^ -** ^When there are multiple VFS shims in the stack, this opcode finds the -** upper-most shim only. -** -**
  • [[SQLITE_FCNTL_PRAGMA]] -** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] -** file control is sent to the open [sqlite3_file] object corresponding -** to the database file to which the pragma statement refers. ^The argument -** to the [SQLITE_FCNTL_PRAGMA] file control is an array of -** pointers to strings (char**) in which the second element of the array -** is the name of the pragma and the third element is the argument to the -** pragma or NULL if the pragma has no argument. ^The handler for an -** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element -** of the char** argument point to a string obtained from [sqlite3_mprintf()] -** or the equivalent and that string will become the result of the pragma or -** the error message if the pragma fails. ^If the -** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal -** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA] -** file control returns [SQLITE_OK], then the parser assumes that the -** VFS has handled the PRAGMA itself and the parser generates a no-op -** prepared statement if result string is NULL, or that returns a copy -** of the result string if the string is non-NULL. -** ^If the [SQLITE_FCNTL_PRAGMA] file control returns -** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means -** that the VFS encountered an error while handling the [PRAGMA] and the -** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA] -** file control occurs at the beginning of pragma statement analysis and so -** it is able to override built-in [PRAGMA] statements. -** -**
  • [[SQLITE_FCNTL_BUSYHANDLER]] -** ^The [SQLITE_FCNTL_BUSYHANDLER] -** file-control may be invoked by SQLite on the database file handle -** shortly after it is opened in order to provide a custom VFS with access -** to the connections busy-handler callback. The argument is of type (void **) -** - an array of two (void *) values. The first (void *) actually points -** to a function of type (int (*)(void *)). In order to invoke the connections -** busy-handler, this function should be invoked with the second (void *) in -** the array as the only argument. If it returns non-zero, then the operation -** should be retried. If it returns zero, the custom VFS should abandon the -** current operation. -** -**
  • [[SQLITE_FCNTL_TEMPFILENAME]] -** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control -** to have SQLite generate a -** temporary filename using the same algorithm that is followed to generate -** temporary filenames for TEMP tables and other internal uses. The -** argument should be a char** which will be filled with the filename -** written into memory obtained from [sqlite3_malloc()]. The caller should -** invoke [sqlite3_free()] on the result to avoid a memory leak. -** -**
  • [[SQLITE_FCNTL_MMAP_SIZE]] -** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the -** maximum number of bytes that will be used for memory-mapped I/O. -** The argument is a pointer to a value of type sqlite3_int64 that -** is an advisory maximum number of bytes in the file to memory map. The -** pointer is overwritten with the old value. The limit is not changed if -** the value originally pointed to is negative, and so the current limit -** can be queried by passing in a pointer to a negative number. This -** file-control is used internally to implement [PRAGMA mmap_size]. -** -**
  • [[SQLITE_FCNTL_TRACE]] -** The [SQLITE_FCNTL_TRACE] file control provides advisory information -** to the VFS about what the higher layers of the SQLite stack are doing. -** This file control is used by some VFS activity tracing [shims]. -** The argument is a zero-terminated string. Higher layers in the -** SQLite stack may generate instances of this file control if -** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled. -** -**
  • [[SQLITE_FCNTL_HAS_MOVED]] -** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a -** pointer to an integer and it writes a boolean into that integer depending -** on whether or not the file has been renamed, moved, or deleted since it -** was first opened. -** -**
  • [[SQLITE_FCNTL_WIN32_GET_HANDLE]] -** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the -** underlying native file handle associated with a file handle. This file -** control interprets its argument as a pointer to a native file handle and -** writes the resulting value there. -** -**
  • [[SQLITE_FCNTL_WIN32_SET_HANDLE]] -** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This -** opcode causes the xFileControl method to swap the file handle with the one -** pointed to by the pArg argument. This capability is used during testing -** and only needs to be supported when SQLITE_TEST is defined. -** -**
  • [[SQLITE_FCNTL_WAL_BLOCK]] -** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might -** be advantageous to block on the next WAL lock if the lock is not immediately -** available. The WAL subsystem issues this signal during rare -** circumstances in order to fix a problem with priority inversion. -** Applications should not use this file-control. -** -**
  • [[SQLITE_FCNTL_ZIPVFS]] -** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other -** VFS should return SQLITE_NOTFOUND for this opcode. -** -**
  • [[SQLITE_FCNTL_RBU]] -** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by -** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for -** this opcode. -** -**
  • [[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]] -** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then -** the file descriptor is placed in "batch write mode", which -** means all subsequent write operations will be deferred and done -** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. Systems -** that do not support batch atomic writes will return SQLITE_NOTFOUND. -** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to -** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or -** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make -** no VFS interface calls on the same [sqlite3_file] file descriptor -** except for calls to the xWrite method and the xFileControl method -** with [SQLITE_FCNTL_SIZE_HINT]. -** -**
  • [[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]] -** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write -** operations since the previous successful call to -** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically. -** This file control returns [SQLITE_OK] if and only if the writes were -** all performed successfully and have been committed to persistent storage. -** ^Regardless of whether or not it is successful, this file control takes -** the file descriptor out of batch write mode so that all subsequent -** write operations are independent. -** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without -** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]. -** -**
  • [[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]] -** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write -** operations since the previous successful call to -** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back. -** ^This file control takes the file descriptor out of batch write mode -** so that all subsequent write operations are independent. -** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without -** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]. -**
-*/ -#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 - -/* 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 value of the iVersion field is initially 1 but may be larger in -** future versions of SQLite. Additional fields may be appended to this -** object when the iVersion value is increased. Note that the structure -** of the sqlite3_vfs object changes in the transaction between -** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not -** modified. -** -** The szOsFile field is the size of the subclassed [sqlite3_file] -** structure used by this VFS. mxPathname is the maximum length of -** a pathname in this VFS. -** -** Registered sqlite3_vfs objects are kept on a linked list formed by -** the pNext pointer. The [sqlite3_vfs_register()] -** and [sqlite3_vfs_unregister()] interfaces manage this list -** in a thread-safe way. The [sqlite3_vfs_find()] interface -** searches the list. Neither the application code nor the VFS -** implementation should use the pNext pointer. -** -** The pNext field is the only field in the sqlite3_vfs -** structure that SQLite will ever modify. SQLite will only access -** or modify this field while holding a particular static mutex. -** The application should never modify anything within the sqlite3_vfs -** object once the object has been registered. -** -** The zName field holds the name of the VFS module. The name must -** be unique across all VFS modules. -** -** [[sqlite3_vfs.xOpen]] -** ^SQLite guarantees that the zFilename parameter to xOpen -** is either a NULL pointer or string obtained -** from xFullPathname() with an optional suffix added. -** ^If a suffix is added to the zFilename parameter, it will -** consist of a single "-" character followed by no more than -** 11 alphanumeric and/or "-" characters. -** ^SQLite further guarantees that -** the string will be valid and unchanged until xClose() is -** called. Because of the previous sentence, -** the [sqlite3_file] can safely store a pointer to the -** filename if it needs to remember the filename for some reason. -** If the zFilename parameter to xOpen is a NULL pointer then xOpen -** must invent its own temporary name for the file. ^Whenever the -** xFilename parameter is NULL it will also be the case that the -** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE]. -** -** The flags argument to xOpen() includes all bits set in -** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] -** or [sqlite3_open16()] is used, then flags includes at least -** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. -** If xOpen() opens a file read-only then it sets *pOutFlags to -** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set. -** -** ^(SQLite will also add one of the following flags to the xOpen() -** call, depending on the object being opened: -** -**
    -**
  • [SQLITE_OPEN_MAIN_DB] -**
  • [SQLITE_OPEN_MAIN_JOURNAL] -**
  • [SQLITE_OPEN_TEMP_DB] -**
  • [SQLITE_OPEN_TEMP_JOURNAL] -**
  • [SQLITE_OPEN_TRANSIENT_DB] -**
  • [SQLITE_OPEN_SUBJOURNAL] -**
  • [SQLITE_OPEN_MASTER_JOURNAL] -**
  • [SQLITE_OPEN_WAL] -**
)^ -** -** The file I/O implementation can use the object type flags to -** change the way it deals with files. For example, an application -** that does not care about crash recovery or rollback might make -** the open of a journal file a no-op. Writes to this journal would -** also be no-ops, and any attempt to read the journal would return -** SQLITE_IOERR. Or the implementation might recognize that a database -** file will be doing page-aligned sector reads and writes in a random -** order and set up its I/O subsystem accordingly. -** -** SQLite might also add one of the following flags to the xOpen method: -** -**
    -**
  • [SQLITE_OPEN_DELETEONCLOSE] -**
  • [SQLITE_OPEN_EXCLUSIVE] -**
-** -** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be -** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE] -** will be set for TEMP databases and their journals, transient -** databases, and subjournals. -** -** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction -** with the [SQLITE_OPEN_CREATE] flag, which are both directly -** analogous to the O_EXCL and O_CREAT flags of the POSIX open() -** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the -** SQLITE_OPEN_CREATE, is used to indicate that file should always -** be created, and that it is an error if it already exists. -** It is not used to indicate the file should be opened -** for exclusive access. -** -** ^At least szOsFile bytes of memory are allocated by SQLite -** to hold the [sqlite3_file] structure passed as the third -** argument to xOpen. The xOpen method does not have to -** allocate the structure; it should just fill it in. Note that -** the xOpen method must set the sqlite3_file.pMethods to either -** a valid [sqlite3_io_methods] object or to NULL. xOpen must do -** this even if the open fails. SQLite expects that the sqlite3_file.pMethods -** element will be valid after xOpen returns regardless of the success -** or failure of the xOpen call. -** -** [[sqlite3_vfs.xAccess]] -** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] -** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to -** test whether a file is readable and writable, or [SQLITE_ACCESS_READ] -** to test whether a file is at least readable. The file can be a -** directory. -** -** ^SQLite will always allocate at least mxPathname+1 bytes for the -** output buffer xFullPathname. The exact size of the output buffer -** is also passed as a parameter to both methods. If the output buffer -** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is -** handled as a fatal error by SQLite, vfs implementations should endeavor -** to prevent this by setting mxPathname to a sufficiently large value. -** -** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64() -** interfaces are not strictly a part of the filesystem, but they are -** included in the VFS structure for completeness. -** The xRandomness() function attempts to return nBytes bytes -** of good-quality randomness into zOut. The return value is -** the actual number of bytes of randomness obtained. -** The xSleep() method causes the calling thread to sleep for at -** least the number of microseconds given. ^The xCurrentTime() -** method returns a Julian Day Number for the current date and time as -** a floating point value. -** ^The xCurrentTimeInt64() method returns, as an integer, the Julian -** Day Number multiplied by 86400000 (the number of milliseconds in -** a 24-hour day). -** ^SQLite will use the xCurrentTimeInt64() method to get the current -** date and time if that method is available (if iVersion is 2 or -** greater and the function pointer is not NULL) and will fall back -** to xCurrentTime() if xCurrentTimeInt64() is unavailable. -** -** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces -** are not used by the SQLite core. These optional interfaces are provided -** by some VFSes to facilitate testing of the VFS code. By overriding -** system calls with functions under its control, a test program can -** simulate faults and error conditions that would otherwise be difficult -** or impossible to induce. The set of system calls that can be overridden -** varies from one VFS to another, and from one version of the same VFS to the -** next. Applications that use these interfaces must be prepared for any -** or all of these interfaces to be NULL or for their behavior to change -** from one release to the next. Applications must not attempt to access -** any of these methods if the iVersion of the VFS is less than 3. -*/ -typedef struct sqlite3_vfs sqlite3_vfs; -typedef void (*sqlite3_syscall_ptr)(void); -struct sqlite3_vfs { - int iVersion; /* Structure version number (currently 3) */ - int szOsFile; /* Size of subclassed sqlite3_file */ - int mxPathname; /* Maximum file pathname length */ - sqlite3_vfs *pNext; /* Next registered VFS */ - const char *zName; /* Name of this virtual file system */ - void *pAppData; /* Pointer to application-specific data */ - int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, - int flags, int *pOutFlags); - int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); - int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); - int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); - void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); - void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); - void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void); - void (*xDlClose)(sqlite3_vfs*, void*); - int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); - int (*xSleep)(sqlite3_vfs*, int microseconds); - int (*xCurrentTime)(sqlite3_vfs*, double*); - int (*xGetLastError)(sqlite3_vfs*, int, char *); - /* - ** The methods above are in version 1 of the sqlite_vfs object - ** definition. Those that follow are added in version 2 or later - */ - int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*); - /* - ** The methods above are in versions 1 and 2 of the sqlite_vfs object. - ** Those below are for version 3 and greater. - */ - int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr); - sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName); - const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName); - /* - ** The methods above are in versions 1 through 3 of the sqlite_vfs object. - ** New fields may be appended in future versions. The iVersion - ** value will increment whenever this happens. - */ -}; - -/* -** CAPI3REF: Flags for the xAccess VFS method -** -** These integer constants can be used as the third parameter to -** the xAccess method of an [sqlite3_vfs] object. They determine -** what kind of permissions the xAccess method is looking for. -** With SQLITE_ACCESS_EXISTS, the xAccess method -** simply checks whether the file exists. -** With SQLITE_ACCESS_READWRITE, the xAccess method -** checks whether the named directory is both readable and writable -** (in other words, if files can be added, removed, and renamed within -** the directory). -** The SQLITE_ACCESS_READWRITE constant is currently used only by the -** [temp_store_directory pragma], though this could change in a future -** release of SQLite. -** With SQLITE_ACCESS_READ, the xAccess method -** checks whether the file is readable. The SQLITE_ACCESS_READ constant is -** currently unused, though it might be used in a future release of -** SQLite. -*/ -#define SQLITE_ACCESS_EXISTS 0 -#define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */ -#define SQLITE_ACCESS_READ 2 /* Unused */ - -/* -** CAPI3REF: Flags for the xShmLock VFS method -** -** These integer constants define the various locking operations -** allowed by the xShmLock method of [sqlite3_io_methods]. The -** following are the only legal combinations of flags to the -** xShmLock method: -** -**
    -**
  • SQLITE_SHM_LOCK | SQLITE_SHM_SHARED -**
  • SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE -**
  • SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED -**
  • SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE -**
-** -** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as -** was given on the corresponding lock. -** -** The xShmLock method can transition between unlocked and SHARED or -** between unlocked and EXCLUSIVE. It cannot transition between SHARED -** and EXCLUSIVE. -*/ -#define SQLITE_SHM_UNLOCK 1 -#define SQLITE_SHM_LOCK 2 -#define SQLITE_SHM_SHARED 4 -#define SQLITE_SHM_EXCLUSIVE 8 - -/* -** CAPI3REF: Maximum xShmLock index -** -** The xShmLock method on [sqlite3_io_methods] may use values -** between 0 and this upper bound as its "offset" argument. -** The SQLite core will never attempt to acquire or release a -** lock outside of this range -*/ -#define SQLITE_SHM_NLOCK 8 - - -/* -** CAPI3REF: Initialize The SQLite Library -** -** ^The sqlite3_initialize() routine initializes the -** SQLite library. ^The sqlite3_shutdown() routine -** deallocates any resources that were allocated by sqlite3_initialize(). -** These routines are designed to aid in process initialization and -** shutdown on embedded systems. Workstation applications using -** SQLite normally do not need to invoke either of these routines. -** -** A call to sqlite3_initialize() is an "effective" call if it is -** the first time sqlite3_initialize() is invoked during the lifetime of -** the process, or if it is the first time sqlite3_initialize() is invoked -** following a call to sqlite3_shutdown(). ^(Only an effective call -** of sqlite3_initialize() does any initialization. All other calls -** are harmless no-ops.)^ -** -** A call to sqlite3_shutdown() is an "effective" call if it is the first -** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only -** an effective call to sqlite3_shutdown() does any deinitialization. -** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^ -** -** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown() -** is not. The sqlite3_shutdown() interface must only be called from a -** single thread. All open [database connections] must be closed and all -** other SQLite resources must be deallocated prior to invoking -** sqlite3_shutdown(). -** -** Among other things, ^sqlite3_initialize() will invoke -** sqlite3_os_init(). Similarly, ^sqlite3_shutdown() -** will invoke sqlite3_os_end(). -** -** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success. -** ^If for some reason, sqlite3_initialize() is unable to initialize -** the library (perhaps it is unable to allocate a needed resource such -** as a mutex) it returns an [error code] other than [SQLITE_OK]. -** -** ^The sqlite3_initialize() routine is called internally by many other -** SQLite interfaces so that an application usually does not need to -** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] -** calls sqlite3_initialize() so the SQLite library will be automatically -** initialized when [sqlite3_open()] is called if it has not be initialized -** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT] -** compile-time option, then the automatic calls to sqlite3_initialize() -** are omitted and the application must call sqlite3_initialize() directly -** prior to using any other SQLite interface. For maximum portability, -** it is recommended that applications always invoke sqlite3_initialize() -** directly prior to using any other SQLite interface. Future releases -** of SQLite may require this. In other words, the behavior exhibited -** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the -** default behavior in some future release of SQLite. -** -** The sqlite3_os_init() routine does operating-system specific -** initialization of the SQLite library. The sqlite3_os_end() -** routine undoes the effect of sqlite3_os_init(). Typical tasks -** performed by these routines include allocation or deallocation -** of static resources, initialization of global variables, -** setting up a default [sqlite3_vfs] module, or setting up -** a default configuration using [sqlite3_config()]. -** -** The application should never invoke either sqlite3_os_init() -** or sqlite3_os_end() directly. The application should only invoke -** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init() -** interface is called automatically by sqlite3_initialize() and -** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate -** implementations for sqlite3_os_init() and sqlite3_os_end() -** are built into SQLite when it is compiled for Unix, Windows, or OS/2. -** When [custom builds | built for other platforms] -** (using the [SQLITE_OS_OTHER=1] compile-time -** option) the application must supply a suitable implementation for -** sqlite3_os_init() and sqlite3_os_end(). An application-supplied -** implementation of sqlite3_os_init() or sqlite3_os_end() -** must return [SQLITE_OK] on success and some other [error code] upon -** failure. -*/ -SQLITE_API int sqlite3_initialize(void); -SQLITE_API int sqlite3_shutdown(void); -SQLITE_API int sqlite3_os_init(void); -SQLITE_API int sqlite3_os_end(void); - -/* -** CAPI3REF: Configuring The SQLite Library -** -** The sqlite3_config() interface is used to make global configuration -** changes to SQLite in order to tune SQLite to the specific needs of -** the application. The default configuration is recommended for most -** applications and so this routine is usually not necessary. It is -** provided to support rare applications with unusual needs. -** -** The sqlite3_config() interface is not threadsafe. The application -** must ensure that no other SQLite interfaces are invoked by other -** threads while sqlite3_config() is running. -** -** The sqlite3_config() interface -** may only be invoked prior to library initialization using -** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. -** ^If sqlite3_config() is called after [sqlite3_initialize()] and before -** [sqlite3_shutdown()] then it will return SQLITE_MISUSE. -** Note, however, that ^sqlite3_config() can be called as part of the -** implementation of an application-defined [sqlite3_os_init()]. -** -** The first argument to sqlite3_config() is an integer -** [configuration option] that determines -** what property of SQLite is to be configured. Subsequent arguments -** vary depending on the [configuration option] -** in the first argument. -** -** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK]. -** ^If the option is unknown or SQLite is unable to set the option -** then this routine returns a non-zero [error code]. -*/ -SQLITE_API int sqlite3_config(int, ...); - -/* -** CAPI3REF: Configure database connections -** METHOD: sqlite3 -** -** The sqlite3_db_config() interface is used to make configuration -** changes to a [database connection]. The interface is similar to -** [sqlite3_config()] except that the changes apply to a single -** [database connection] (specified in the first argument). -** -** The second argument to sqlite3_db_config(D,V,...) is the -** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code -** that indicates what aspect of the [database connection] is being configured. -** Subsequent arguments vary depending on the configuration verb. -** -** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if -** the call is considered successful. -*/ -SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...); - -/* -** CAPI3REF: Memory Allocation Routines -** -** An instance of this object defines the interface between SQLite -** and low-level memory allocation routines. -** -** This object is used in only one place in the SQLite interface. -** A pointer to an instance of this object is the argument to -** [sqlite3_config()] when the configuration option is -** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC]. -** By creating an instance of this object -** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC]) -** during configuration, an application can specify an alternative -** memory allocation subsystem for SQLite to use for all of its -** dynamic memory needs. -** -** Note that SQLite comes with several [built-in memory allocators] -** that are perfectly adequate for the overwhelming majority of applications -** and that this object is only useful to a tiny minority of applications -** with specialized memory allocation requirements. This object is -** also used during testing of SQLite in order to specify an alternative -** memory allocator that simulates memory out-of-memory conditions in -** order to verify that SQLite recovers gracefully from such -** conditions. -** -** The xMalloc, xRealloc, and xFree methods must work like the -** malloc(), realloc() and free() functions from the standard C library. -** ^SQLite guarantees that the second argument to -** xRealloc is always a value returned by a prior call to xRoundup. -** -** xSize should return the allocated size of a memory allocation -** previously obtained from xMalloc or xRealloc. The allocated size -** is always at least as big as the requested size but may be larger. -** -** The xRoundup method returns what would be the allocated size of -** a memory allocation given a particular requested size. Most memory -** allocators round up memory allocations at least to the next multiple -** of 8. Some allocators round up to a larger multiple or to a power of 2. -** Every memory allocation request coming in through [sqlite3_malloc()] -** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0, -** that causes the corresponding memory allocation to fail. -** -** The xInit method initializes the memory allocator. For example, -** it might allocate any require mutexes or initialize internal data -** structures. The xShutdown method is invoked (indirectly) by -** [sqlite3_shutdown()] and should deallocate any resources acquired -** by xInit. The pAppData pointer is used as the only parameter to -** xInit and xShutdown. -** -** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes -** the xInit method, so the xInit method need not be threadsafe. The -** xShutdown method is only called from [sqlite3_shutdown()] so it does -** not need to be threadsafe either. For all other methods, SQLite -** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the -** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which -** it is by default) and so the methods are automatically serialized. -** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other -** methods must be threadsafe or else make their own arrangements for -** serialization. -** -** SQLite will never invoke xInit() more than once without an intervening -** call to xShutdown(). -*/ -typedef struct sqlite3_mem_methods sqlite3_mem_methods; -struct sqlite3_mem_methods { - void *(*xMalloc)(int); /* Memory allocation function */ - void (*xFree)(void*); /* Free a prior allocation */ - void *(*xRealloc)(void*,int); /* Resize an allocation */ - int (*xSize)(void*); /* Return the size of an allocation */ - int (*xRoundup)(int); /* Round up request size to allocation size */ - int (*xInit)(void*); /* Initialize the memory allocator */ - void (*xShutdown)(void*); /* Deinitialize the memory allocator */ - void *pAppData; /* Argument to xInit() and xShutdown() */ -}; - -/* -** CAPI3REF: Configuration Options -** KEYWORDS: {configuration option} -** -** These constants are the available integer configuration options that -** can be passed as the first argument to the [sqlite3_config()] interface. -** -** New configuration options may be added in future releases of SQLite. -** Existing configuration options might be discontinued. Applications -** should check the return code from [sqlite3_config()] to make sure that -** the call worked. The [sqlite3_config()] interface will return a -** non-zero [error code] if a discontinued or unsupported configuration option -** is invoked. -** -**
-** [[SQLITE_CONFIG_SINGLETHREAD]]
SQLITE_CONFIG_SINGLETHREAD
-**
There are no arguments to this option. ^This option sets the -** [threading mode] to Single-thread. In other words, it disables -** all mutexing and puts SQLite into a mode where it can only be used -** by a single thread. ^If SQLite is compiled with -** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then -** it is not possible to change the [threading mode] from its default -** value of Single-thread and so [sqlite3_config()] will return -** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD -** configuration option.
-** -** [[SQLITE_CONFIG_MULTITHREAD]]
SQLITE_CONFIG_MULTITHREAD
-**
There are no arguments to this option. ^This option sets the -** [threading mode] to Multi-thread. In other words, it disables -** mutexing on [database connection] and [prepared statement] objects. -** The application is responsible for serializing access to -** [database connections] and [prepared statements]. But other mutexes -** are enabled so that SQLite will be safe to use in a multi-threaded -** environment as long as no two threads attempt to use the same -** [database connection] at the same time. ^If SQLite is compiled with -** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then -** it is not possible to set the Multi-thread [threading mode] and -** [sqlite3_config()] will return [SQLITE_ERROR] if called with the -** SQLITE_CONFIG_MULTITHREAD configuration option.
-** -** [[SQLITE_CONFIG_SERIALIZED]]
SQLITE_CONFIG_SERIALIZED
-**
There are no arguments to this option. ^This option sets the -** [threading mode] to Serialized. In other words, this option enables -** all mutexes including the recursive -** mutexes on [database connection] and [prepared statement] objects. -** In this mode (which is the default when SQLite is compiled with -** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access -** to [database connections] and [prepared statements] so that the -** application is free to use the same [database connection] or the -** same [prepared statement] in different threads at the same time. -** ^If SQLite is compiled with -** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then -** it is not possible to set the Serialized [threading mode] and -** [sqlite3_config()] will return [SQLITE_ERROR] if called with the -** SQLITE_CONFIG_SERIALIZED configuration option.
-** -** [[SQLITE_CONFIG_MALLOC]]
SQLITE_CONFIG_MALLOC
-**
^(The SQLITE_CONFIG_MALLOC option takes a single argument which is -** a pointer to an instance of the [sqlite3_mem_methods] structure. -** The argument specifies -** alternative low-level memory allocation routines to be used in place of -** the memory allocation routines built into SQLite.)^ ^SQLite makes -** its own private copy of the content of the [sqlite3_mem_methods] structure -** before the [sqlite3_config()] call returns.
-** -** [[SQLITE_CONFIG_GETMALLOC]]
SQLITE_CONFIG_GETMALLOC
-**
^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which -** is a pointer to an instance of the [sqlite3_mem_methods] structure. -** The [sqlite3_mem_methods] -** structure is filled with the currently defined memory allocation routines.)^ -** This option can be used to overload the default memory allocation -** routines with a wrapper that simulations memory allocation failure or -** tracks memory usage, for example.
-** -** [[SQLITE_CONFIG_SMALL_MALLOC]]
SQLITE_CONFIG_SMALL_MALLOC
-**
^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of -** type int, interpreted as a boolean, which if true provides a hint to -** SQLite that it should avoid large memory allocations if possible. -** SQLite will run faster if it is free to make large memory allocations, -** but some application might prefer to run slower in exchange for -** guarantees about memory fragmentation that are possible if large -** allocations are avoided. This hint is normally off. -**
-** -** [[SQLITE_CONFIG_MEMSTATUS]]
SQLITE_CONFIG_MEMSTATUS
-**
^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int, -** interpreted as a boolean, which enables or disables the collection of -** memory allocation statistics. ^(When memory allocation statistics are -** disabled, the following SQLite interfaces become non-operational: -**
    -**
  • [sqlite3_memory_used()] -**
  • [sqlite3_memory_highwater()] -**
  • [sqlite3_soft_heap_limit64()] -**
  • [sqlite3_status64()] -**
)^ -** ^Memory allocation statistics are enabled by default unless SQLite is -** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory -** allocation statistics are disabled by default. -**
-** -** [[SQLITE_CONFIG_SCRATCH]]
SQLITE_CONFIG_SCRATCH
-**
The SQLITE_CONFIG_SCRATCH option is no longer used. -**
-** -** [[SQLITE_CONFIG_PAGECACHE]]
SQLITE_CONFIG_PAGECACHE
-**
^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool -** that SQLite can use for the database page cache with the default page -** cache implementation. -** This configuration option is a no-op if an application-define page -** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2]. -** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to -** 8-byte aligned memory (pMem), the size of each page cache line (sz), -** and the number of cache lines (N). -** The sz argument should be the size of the largest database page -** (a power of two between 512 and 65536) plus some extra bytes for each -** page header. ^The number of extra bytes needed by the page header -** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ]. -** ^It is harmless, apart from the wasted memory, -** for the sz parameter to be larger than necessary. The pMem -** argument must be either a NULL pointer or a pointer to an 8-byte -** aligned block of memory of at least sz*N bytes, otherwise -** subsequent behavior is undefined. -** ^When pMem is not NULL, SQLite will strive to use the memory provided -** to satisfy page cache needs, falling back to [sqlite3_malloc()] if -** a page cache line is larger than sz bytes or if all of the pMem buffer -** is exhausted. -** ^If pMem is NULL and N is non-zero, then each database connection -** does an initial bulk allocation for page cache memory -** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or -** of -1024*N bytes if N is negative, . ^If additional -** page cache memory is needed beyond what is provided by the initial -** allocation, then SQLite goes to [sqlite3_malloc()] separately for each -** additional cache line.
-** -** [[SQLITE_CONFIG_HEAP]]
SQLITE_CONFIG_HEAP
-**
^The SQLITE_CONFIG_HEAP option specifies a static memory buffer -** that SQLite will use for all of its dynamic memory allocation needs -** beyond those provided for by [SQLITE_CONFIG_PAGECACHE]. -** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled -** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns -** [SQLITE_ERROR] if invoked otherwise. -** ^There are three arguments to SQLITE_CONFIG_HEAP: -** An 8-byte aligned pointer to the memory, -** the number of bytes in the memory buffer, and the minimum allocation size. -** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts -** to using its default memory allocator (the system malloc() implementation), -** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the -** memory pointer is not NULL then the alternative memory -** allocator is engaged to handle all of SQLites memory allocation needs. -** The first pointer (the memory pointer) must be aligned to an 8-byte -** boundary or subsequent behavior of SQLite will be undefined. -** The minimum allocation size is capped at 2**12. Reasonable values -** for the minimum allocation size are 2**5 through 2**8.
-** -** [[SQLITE_CONFIG_MUTEX]]
SQLITE_CONFIG_MUTEX
-**
^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a -** pointer to an instance of the [sqlite3_mutex_methods] structure. -** The argument specifies alternative low-level mutex routines to be used -** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of -** the content of the [sqlite3_mutex_methods] structure before the call to -** [sqlite3_config()] returns. ^If SQLite is compiled with -** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then -** the entire mutexing subsystem is omitted from the build and hence calls to -** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will -** return [SQLITE_ERROR].
-** -** [[SQLITE_CONFIG_GETMUTEX]]
SQLITE_CONFIG_GETMUTEX
-**
^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which -** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The -** [sqlite3_mutex_methods] -** structure is filled with the currently defined mutex routines.)^ -** This option can be used to overload the default mutex allocation -** routines with a wrapper used to track mutex usage for performance -** profiling or testing, for example. ^If SQLite is compiled with -** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then -** the entire mutexing subsystem is omitted from the build and hence calls to -** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will -** return [SQLITE_ERROR].
-** -** [[SQLITE_CONFIG_LOOKASIDE]]
SQLITE_CONFIG_LOOKASIDE
-**
^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine -** the default size of lookaside memory on each [database connection]. -** The first argument is the -** size of each lookaside buffer slot and the second is the number of -** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE -** sets the default lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE] -** option to [sqlite3_db_config()] can be used to change the lookaside -** configuration on individual connections.)^
-** -** [[SQLITE_CONFIG_PCACHE2]]
SQLITE_CONFIG_PCACHE2
-**
^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is -** a pointer to an [sqlite3_pcache_methods2] object. This object specifies -** the interface to a custom page cache implementation.)^ -** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.
-** -** [[SQLITE_CONFIG_GETPCACHE2]]
SQLITE_CONFIG_GETPCACHE2
-**
^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which -** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of -** the current page cache implementation into that object.)^
-** -** [[SQLITE_CONFIG_LOG]]
SQLITE_CONFIG_LOG
-**
The SQLITE_CONFIG_LOG option is used to configure the SQLite -** global [error log]. -** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a -** function with a call signature of void(*)(void*,int,const char*), -** and a pointer to void. ^If the function pointer is not NULL, it is -** invoked by [sqlite3_log()] to process each logging event. ^If the -** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op. -** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is -** passed through as the first parameter to the application-defined logger -** function whenever that function is invoked. ^The second parameter to -** the logger function is a copy of the first parameter to the corresponding -** [sqlite3_log()] call and is intended to be a [result code] or an -** [extended result code]. ^The third parameter passed to the logger is -** log message after formatting via [sqlite3_snprintf()]. -** The SQLite logging interface is not reentrant; the logger function -** supplied by the application must not invoke any SQLite interface. -** In a multi-threaded application, the application-defined logger -** function must be threadsafe.
-** -** [[SQLITE_CONFIG_URI]]
SQLITE_CONFIG_URI -**
^(The SQLITE_CONFIG_URI option takes a single argument of type int. -** If non-zero, then URI handling is globally enabled. If the parameter is zero, -** then URI handling is globally disabled.)^ ^If URI handling is globally -** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()], -** [sqlite3_open16()] or -** specified as part of [ATTACH] commands are interpreted as URIs, regardless -** of whether or not the [SQLITE_OPEN_URI] flag is set when the database -** connection is opened. ^If it is globally disabled, filenames are -** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the -** database connection is opened. ^(By default, URI handling is globally -** disabled. The default value may be changed by compiling with the -** [SQLITE_USE_URI] symbol defined.)^ -** -** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]]
SQLITE_CONFIG_COVERING_INDEX_SCAN -**
^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer -** argument which is interpreted as a boolean in order to enable or disable -** the use of covering indices for full table scans in the query optimizer. -** ^The default setting is determined -** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on" -** if that compile-time option is omitted. -** The ability to disable the use of covering indices for full table scans -** is because some incorrectly coded legacy applications might malfunction -** when the optimization is enabled. Providing the ability to -** disable the optimization allows the older, buggy application code to work -** without change even with newer versions of SQLite. -** -** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]] -**
SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE -**
These options are obsolete and should not be used by new code. -** They are retained for backwards compatibility but are now no-ops. -**
-** -** [[SQLITE_CONFIG_SQLLOG]] -**
SQLITE_CONFIG_SQLLOG -**
This option is only available if sqlite is compiled with the -** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should -** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int). -** The second should be of type (void*). The callback is invoked by the library -** in three separate circumstances, identified by the value passed as the -** fourth parameter. If the fourth parameter is 0, then the database connection -** passed as the second argument has just been opened. The third argument -** points to a buffer containing the name of the main database file. If the -** fourth parameter is 1, then the SQL statement that the third parameter -** points to has just been executed. Or, if the fourth parameter is 2, then -** the connection being passed as the second parameter is being closed. The -** third parameter is passed NULL In this case. An example of using this -** configuration option can be seen in the "test_sqllog.c" source file in -** the canonical SQLite source tree.
-** -** [[SQLITE_CONFIG_MMAP_SIZE]] -**
SQLITE_CONFIG_MMAP_SIZE -**
^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values -** that are the default mmap size limit (the default setting for -** [PRAGMA mmap_size]) and the maximum allowed mmap size limit. -** ^The default setting can be overridden by each database connection using -** either the [PRAGMA mmap_size] command, or by using the -** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size -** will be silently truncated if necessary so that it does not exceed the -** compile-time maximum mmap size set by the -** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^ -** ^If either argument to this option is negative, then that argument is -** changed to its compile-time default. -** -** [[SQLITE_CONFIG_WIN32_HEAPSIZE]] -**
SQLITE_CONFIG_WIN32_HEAPSIZE -**
^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is -** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro -** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value -** that specifies the maximum size of the created heap. -** -** [[SQLITE_CONFIG_PCACHE_HDRSZ]] -**
SQLITE_CONFIG_PCACHE_HDRSZ -**
^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which -** is a pointer to an integer and writes into that integer the number of extra -** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE]. -** The amount of extra space required can change depending on the compiler, -** target platform, and SQLite version. -** -** [[SQLITE_CONFIG_PMASZ]] -**
SQLITE_CONFIG_PMASZ -**
^The SQLITE_CONFIG_PMASZ option takes a single parameter which -** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded -** sorter to that integer. The default minimum PMA Size is set by the -** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched -** to help with sort operations when multithreaded sorting -** is enabled (using the [PRAGMA threads] command) and the amount of content -** to be sorted exceeds the page size times the minimum of the -** [PRAGMA cache_size] setting and this value. -** -** [[SQLITE_CONFIG_STMTJRNL_SPILL]] -**
SQLITE_CONFIG_STMTJRNL_SPILL -**
^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which -** becomes the [statement journal] spill-to-disk threshold. -** [Statement journals] are held in memory until their size (in bytes) -** exceeds this threshold, at which point they are written to disk. -** Or if the threshold is -1, statement journals are always held -** exclusively in memory. -** Since many statement journals never become large, setting the spill -** threshold to a value such as 64KiB can greatly reduce the amount of -** I/O required to support statement rollback. -** The default value for this setting is controlled by the -** [SQLITE_STMTJRNL_SPILL] compile-time option. -**
-*/ -#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 */ - -/* -** CAPI3REF: Database Connection Configuration Options -** -** These constants are the available integer configuration options that -** can be passed as the second argument to the [sqlite3_db_config()] interface. -** -** New configuration options may be added in future releases of SQLite. -** Existing configuration options might be discontinued. Applications -** should check the return code from [sqlite3_db_config()] to make sure that -** the call worked. ^The [sqlite3_db_config()] interface will return a -** non-zero [error code] if a discontinued or unsupported configuration option -** is invoked. -** -**
-**
SQLITE_DBCONFIG_LOOKASIDE
-**
^This option takes three additional arguments that determine the -** [lookaside memory allocator] configuration for the [database connection]. -** ^The first argument (the third parameter to [sqlite3_db_config()] is a -** pointer to a memory buffer to use for lookaside memory. -** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb -** may be NULL in which case SQLite will allocate the -** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the -** size of each lookaside buffer slot. ^The third argument is the number of -** slots. The size of the buffer in the first argument must be greater than -** or equal to the product of the second and third arguments. The buffer -** must be aligned to an 8-byte boundary. ^If the second argument to -** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally -** rounded down to the next smaller multiple of 8. ^(The lookaside memory -** configuration for a database connection can only be changed when that -** connection is not currently using lookaside memory, or in other words -** when the "current value" returned by -** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero. -** Any attempt to change the lookaside memory configuration when lookaside -** memory is in use leaves the configuration unchanged and returns -** [SQLITE_BUSY].)^
-** -**
SQLITE_DBCONFIG_ENABLE_FKEY
-**
^This option is used to enable or disable the enforcement of -** [foreign key constraints]. There should be two additional arguments. -** The first argument is an integer which is 0 to disable FK enforcement, -** positive to enable FK enforcement or negative to leave FK enforcement -** unchanged. The second parameter is a pointer to an integer into which -** is written 0 or 1 to indicate whether FK enforcement is off or on -** following this call. The second parameter may be a NULL pointer, in -** which case the FK enforcement setting is not reported back.
-** -**
SQLITE_DBCONFIG_ENABLE_TRIGGER
-**
^This option is used to enable or disable [CREATE TRIGGER | triggers]. -** There should be two additional arguments. -** The first argument is an integer which is 0 to disable triggers, -** positive to enable triggers or negative to leave the setting unchanged. -** The second parameter is a pointer to an integer into which -** is written 0 or 1 to indicate whether triggers are disabled or enabled -** following this call. The second parameter may be a NULL pointer, in -** which case the trigger setting is not reported back.
-** -**
SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
-**
^This option is used to enable or disable the two-argument -** version of 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
-**
^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
-**
^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
-**
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 - non-zero to disable checkpoints-on-close, or zero (the -** default) to enable them. 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
-**
^(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. -**
-** -**
-*/ -#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* */ - - -/* -** 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. -** -** See also the [sqlite3_total_changes()] interface, the -** [count_changes pragma], and the [changes() SQL function]. -** -** If a separate thread makes changes on the same database connection -** while [sqlite3_changes()] is running then the value returned -** is unpredictable and not meaningful. -*/ -SQLITE_API int sqlite3_changes(sqlite3*); - -/* -** CAPI3REF: Total Number Of Rows Modified -** 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. -** -** See also the [sqlite3_changes()] interface, the -** [count_changes pragma], and the [total_changes() SQL function]. -** -** If a separate thread makes changes on the same database connection -** while [sqlite3_total_changes()] is running then the value -** returned is unpredictable and not meaningful. -*/ -SQLITE_API int sqlite3_total_changes(sqlite3*); - -/* -** CAPI3REF: Interrupt A Long-Running Query -** METHOD: sqlite3 -** -** ^This function causes any pending database operation to abort and -** return at its earliest opportunity. This routine is typically -** called in response to a user action such as pressing "Cancel" -** or Ctrl-C where the user wants a long query operation to halt -** immediately. -** -** ^It is safe to call this routine from a thread different from the -** thread that is currently running the database operation. But it -** is not safe to call this routine with a [database connection] that -** is closed or might close before sqlite3_interrupt() returns. -** -** ^If an SQL operation is very nearly finished at the time when -** sqlite3_interrupt() is called, then it might not have an opportunity -** to be interrupted and might continue to completion. -** -** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT]. -** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE -** that is inside an explicit transaction, then the entire transaction -** will be rolled back automatically. -** -** ^The sqlite3_interrupt(D) call is in effect until all currently running -** SQL statements on [database connection] D complete. ^Any new SQL statements -** that are started after the sqlite3_interrupt() call and before the -** running statements reaches zero are interrupted as if they had been -** running prior to the sqlite3_interrupt() call. ^New SQL statements -** that are started after the running statement count reaches zero are -** not effected by the sqlite3_interrupt(). -** ^A call to sqlite3_interrupt(D) that occurs when there are no running -** SQL statements is a no-op and has no effect on SQL statements -** that are started after the sqlite3_interrupt() call returns. -*/ -SQLITE_API void sqlite3_interrupt(sqlite3*); - -/* -** CAPI3REF: Determine If An SQL Statement Is Complete -** -** These routines are useful during command-line input to determine if the -** currently entered text seems to form a complete SQL statement or -** if additional input is needed before sending the text into -** SQLite for parsing. ^These routines return 1 if the input string -** appears to be a complete SQL statement. ^A statement is judged to be -** complete if it ends with a semicolon token and is not a prefix of a -** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within -** string literals or quoted identifier names or comments are not -** independent tokens (they are part of the token in which they are -** embedded) and thus do not count as a statement terminator. ^Whitespace -** and comments that follow the final semicolon are ignored. -** -** ^These routines return 0 if the statement is incomplete. ^If a -** memory allocation fails, then SQLITE_NOMEM is returned. -** -** ^These routines do not parse the SQL statements thus -** will not detect syntactically incorrect SQL. -** -** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior -** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked -** automatically by sqlite3_complete16(). If that initialization fails, -** then the return value from sqlite3_complete16() will be non-zero -** regardless of whether or not the input SQL is complete.)^ -** -** The input to [sqlite3_complete()] must be a zero-terminated -** UTF-8 string. -** -** The input to [sqlite3_complete16()] must be a zero-terminated -** UTF-16 string in native byte order. -*/ -SQLITE_API int sqlite3_complete(const char *sql); -SQLITE_API int sqlite3_complete16(const void *sql); - -/* -** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors -** KEYWORDS: {busy-handler callback} {busy handler} -** METHOD: sqlite3 -** -** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X -** that might be invoked with argument P whenever -** an attempt is made to access a database table associated with -** [database connection] D when another thread -** or process has the table locked. -** The sqlite3_busy_handler() interface is used to implement -** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout]. -** -** ^If the busy callback is NULL, then [SQLITE_BUSY] -** is returned immediately upon encountering the lock. ^If the busy callback -** is not NULL, then the callback might be invoked with two arguments. -** -** ^The first argument to the busy handler is a copy of the void* pointer which -** is the third argument to sqlite3_busy_handler(). ^The second argument to -** the busy handler callback is the number of times that the busy handler has -** been invoked previously for the same locking event. ^If the -** busy callback returns 0, then no additional attempts are made to -** access the database and [SQLITE_BUSY] is returned -** to the application. -** ^If the callback returns non-zero, then another attempt -** is made to access the database and the cycle repeats. -** -** The presence of a busy handler does not guarantee that it will be invoked -** when there is lock contention. ^If SQLite determines that invoking the busy -** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY] -** to the application instead of invoking the -** busy handler. -** Consider a scenario where one process is holding a read lock that -** it is trying to promote to a reserved lock and -** a second process is holding a reserved lock that it is trying -** to promote to an exclusive lock. The first process cannot proceed -** because it is blocked by the second and the second process cannot -** proceed because it is blocked by the first. If both processes -** invoke the busy handlers, neither will make any progress. Therefore, -** SQLite returns [SQLITE_BUSY] for the first process, hoping that this -** will induce the first process to release its read lock and allow -** the second process to proceed. -** -** ^The default busy callback is NULL. -** -** ^(There can only be a single busy handler defined for each -** [database connection]. Setting a new busy handler clears any -** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()] -** or evaluating [PRAGMA busy_timeout=N] will change the -** busy handler and thus clear any previously set busy handler. -** -** The busy callback should not take any actions which modify the -** database connection that invoked the busy handler. In other words, -** the busy handler is not reentrant. Any such actions -** result in undefined behavior. -** -** A busy handler must not close the database connection -** or [prepared statement] that invoked the busy handler. -*/ -SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*); - -/* -** CAPI3REF: Set A Busy Timeout -** METHOD: sqlite3 -** -** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps -** for a specified amount of time when a table is locked. ^The handler -** will sleep multiple times until at least "ms" milliseconds of sleeping -** have accumulated. ^After at least "ms" milliseconds of sleeping, -** the handler returns 0 which causes [sqlite3_step()] to return -** [SQLITE_BUSY]. -** -** ^Calling this routine with an argument less than or equal to zero -** turns off all busy handlers. -** -** ^(There can only be a single busy handler for a particular -** [database connection] at any given moment. If another busy handler -** was defined (using [sqlite3_busy_handler()]) prior to calling -** this routine, that other busy handler is cleared.)^ -** -** See also: [PRAGMA busy_timeout] -*/ -SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); - -/* -** CAPI3REF: Convenience Routines For Running Queries -** METHOD: sqlite3 -** -** This is a legacy interface that is preserved for backwards compatibility. -** Use of this interface is not recommended. -** -** Definition: A result table is memory data structure created by the -** [sqlite3_get_table()] interface. A result table records the -** complete query results from one or more queries. -** -** The table conceptually has a number of rows and columns. But -** these numbers are not part of the result table itself. These -** numbers are obtained separately. Let N be the number of rows -** and M be the number of columns. -** -** A result table is an array of pointers to zero-terminated UTF-8 strings. -** There are (N+1)*M elements in the array. The first M pointers point -** to zero-terminated strings that contain the names of the columns. -** The remaining entries all point to query results. NULL values result -** in NULL pointers. All other values are in their UTF-8 zero-terminated -** string representation as returned by [sqlite3_column_text()]. -** -** A result table might consist of one or more memory allocations. -** It is not safe to pass a result table directly to [sqlite3_free()]. -** A result table should be deallocated using [sqlite3_free_table()]. -** -** ^(As an example of the result table format, suppose a query result -** is as follows: -** -**
-**        Name        | Age
-**        -----------------------
-**        Alice       | 43
-**        Bob         | 28
-**        Cindy       | 21
-** 
-** -** There are two column (M==2) and three rows (N==3). Thus the -** result table has 8 entries. Suppose the result table is stored -** in an array names azResult. Then azResult holds this content: -** -**
-**        azResult[0] = "Name";
-**        azResult[1] = "Age";
-**        azResult[2] = "Alice";
-**        azResult[3] = "43";
-**        azResult[4] = "Bob";
-**        azResult[5] = "28";
-**        azResult[6] = "Cindy";
-**        azResult[7] = "21";
-** 
)^ -** -** ^The sqlite3_get_table() function evaluates one or more -** semicolon-separated SQL statements in the zero-terminated UTF-8 -** string of its 2nd parameter and returns a result table to the -** pointer given in its 3rd parameter. -** -** After the application has finished with the result from sqlite3_get_table(), -** it must pass the result table pointer to sqlite3_free_table() in order to -** release the memory that was malloced. Because of the way the -** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling -** function must not try to call [sqlite3_free()] directly. Only -** [sqlite3_free_table()] is able to release the memory properly and safely. -** -** The sqlite3_get_table() interface is implemented as a wrapper around -** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access -** to any internal data structures of SQLite. It uses only the public -** interface defined here. As a consequence, errors that occur in the -** wrapper layer outside of the internal [sqlite3_exec()] call are not -** reflected in subsequent calls to [sqlite3_errcode()] or -** [sqlite3_errmsg()]. -*/ -SQLITE_API int sqlite3_get_table( - sqlite3 *db, /* An open database */ - const char *zSql, /* SQL to be evaluated */ - char ***pazResult, /* Results of the query */ - int *pnRow, /* Number of result rows written here */ - int *pnColumn, /* Number of result columns written here */ - char **pzErrmsg /* Error msg written here */ -); -SQLITE_API void sqlite3_free_table(char **result); - -/* -** CAPI3REF: Formatted String Printing Functions -** -** These routines are work-alikes of the "printf()" family of functions -** from the standard C library. -** These routines understand most of the common K&R formatting options, -** plus some additional non-standard formats, detailed below. -** Note that some of the more obscure formatting options from recent -** C-library standards are omitted from this implementation. -** -** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their -** results into memory obtained from [sqlite3_malloc()]. -** The strings returned by these two routines should be -** released by [sqlite3_free()]. ^Both routines return a -** NULL pointer if [sqlite3_malloc()] is unable to allocate enough -** memory to hold the resulting string. -** -** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from -** the standard C library. The result is written into the -** buffer supplied as the second parameter whose size is given by -** the first parameter. Note that the order of the -** first two parameters is reversed from snprintf().)^ This is an -** historical accident that cannot be fixed without breaking -** backwards compatibility. ^(Note also that sqlite3_snprintf() -** returns a pointer to its buffer instead of the number of -** characters actually written into the buffer.)^ We admit that -** the number of characters written would be a more useful return -** value but we cannot change the implementation of sqlite3_snprintf() -** now without breaking compatibility. -** -** ^As long as the buffer size is greater than zero, sqlite3_snprintf() -** guarantees that the buffer is always zero-terminated. ^The first -** parameter "n" is the total size of the buffer, including space for -** the zero terminator. So the longest string that can be completely -** written will be n-1 characters. -** -** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf(). -** -** These routines all implement some additional formatting -** options that are useful for constructing SQL statements. -** All of the usual printf() formatting options apply. In addition, there -** is are "%q", "%Q", "%w" and "%z" options. -** -** ^(The %q option works like %s in that it substitutes a nul-terminated -** string from the argument list. But %q also doubles every '\'' character. -** %q is designed for use inside a string literal.)^ By doubling each '\'' -** character it escapes that character and allows it to be inserted into -** the string. -** -** For example, assume the string variable zText contains text as follows: -** -**
-**  char *zText = "It's a happy day!";
-** 
-** -** One can use this text in an SQL statement as follows: -** -**
-**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
-**  sqlite3_exec(db, zSQL, 0, 0, 0);
-**  sqlite3_free(zSQL);
-** 
-** -** Because the %q format string is used, the '\'' character in zText -** is escaped and the SQL generated is as follows: -** -**
-**  INSERT INTO table1 VALUES('It''s a happy day!')
-** 
-** -** This is correct. Had we used %s instead of %q, the generated SQL -** would have looked like this: -** -**
-**  INSERT INTO table1 VALUES('It's a happy day!');
-** 
-** -** This second example is an SQL syntax error. As a general rule you should -** always use %q instead of %s when inserting text into a string literal. -** -** ^(The %Q option works like %q except it also adds single quotes around -** the outside of the total string. Additionally, if the parameter in the -** argument list is a NULL pointer, %Q substitutes the text "NULL" (without -** single quotes).)^ So, for example, one could say: -** -**
-**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
-**  sqlite3_exec(db, zSQL, 0, 0, 0);
-**  sqlite3_free(zSQL);
-** 
-** -** The code above will render a correct SQL statement in the zSQL -** variable even if the zText variable is a NULL pointer. -** -** ^(The "%w" formatting option is like "%q" except that it expects to -** be contained within double-quotes instead of single quotes, and it -** escapes the double-quote character instead of the single-quote -** character.)^ The "%w" formatting option is intended for safely inserting -** table and column names into a constructed SQL statement. -** -** ^(The "%z" formatting option works like "%s" but with the -** addition that after the string has been read and copied into -** the result, [sqlite3_free()] is called on the input string.)^ -*/ -SQLITE_API char *sqlite3_mprintf(const char*,...); -SQLITE_API char *sqlite3_vmprintf(const char*, va_list); -SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...); -SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list); - -/* -** CAPI3REF: Memory Allocation Subsystem -** -** The SQLite core uses these three routines for all of its own -** internal memory allocation needs. "Core" in the previous sentence -** does not include operating-system specific VFS implementation. The -** Windows VFS uses native malloc() and free() for some operations. -** -** ^The sqlite3_malloc() routine returns a pointer to a block -** of memory at least N bytes in length, where N is the parameter. -** ^If sqlite3_malloc() is unable to obtain sufficient free -** memory, it returns a NULL pointer. ^If the parameter N to -** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns -** a NULL pointer. -** -** ^The sqlite3_malloc64(N) routine works just like -** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead -** of a signed 32-bit integer. -** -** ^Calling sqlite3_free() with a pointer previously returned -** by sqlite3_malloc() or sqlite3_realloc() releases that memory so -** that it might be reused. ^The sqlite3_free() routine is -** a no-op if is called with a NULL pointer. Passing a NULL pointer -** to sqlite3_free() is harmless. After being freed, memory -** should neither be read nor written. Even reading previously freed -** memory might result in a segmentation fault or other severe error. -** Memory corruption, a segmentation fault, or other severe error -** might result if sqlite3_free() is called with a non-NULL pointer that -** was not obtained from sqlite3_malloc() or sqlite3_realloc(). -** -** ^The sqlite3_realloc(X,N) interface attempts to resize a -** prior memory allocation X to be at least N bytes. -** ^If the X parameter to sqlite3_realloc(X,N) -** is a NULL pointer then its behavior is identical to calling -** sqlite3_malloc(N). -** ^If the N parameter to sqlite3_realloc(X,N) is zero or -** negative then the behavior is exactly the same as calling -** sqlite3_free(X). -** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation -** of at least N bytes in size or NULL if insufficient memory is available. -** ^If M is the size of the prior allocation, then min(N,M) bytes -** of the prior allocation are copied into the beginning of buffer returned -** by sqlite3_realloc(X,N) and the prior allocation is freed. -** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the -** prior allocation is not freed. -** -** ^The sqlite3_realloc64(X,N) interfaces works the same as -** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead -** of a 32-bit signed integer. -** -** ^If X is a memory allocation previously obtained from sqlite3_malloc(), -** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then -** sqlite3_msize(X) returns the size of that memory allocation in bytes. -** ^The value returned by sqlite3_msize(X) might be larger than the number -** of bytes requested when X was allocated. ^If X is a NULL pointer then -** sqlite3_msize(X) returns zero. If X points to something that is not -** the beginning of memory allocation, or if it points to a formerly -** valid memory allocation that has now been freed, then the behavior -** of sqlite3_msize(X) is undefined and possibly harmful. -** -** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(), -** sqlite3_malloc64(), and sqlite3_realloc64() -** is always aligned to at least an 8 byte boundary, or to a -** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time -** option is used. -** -** In SQLite version 3.5.0 and 3.5.1, it was possible to define -** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in -** implementation of these routines to be omitted. That capability -** is no longer provided. Only built-in memory allocators can be used. -** -** Prior to SQLite version 3.7.10, the Windows OS interface layer called -** the system malloc() and free() directly when converting -** filenames between the UTF-8 encoding used by SQLite -** and whatever filename encoding is used by the particular Windows -** installation. Memory allocation errors were detected, but -** they were reported back as [SQLITE_CANTOPEN] or -** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. -** -** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] -** must be either NULL or else pointers obtained from a prior -** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have -** not yet been released. -** -** The application must not read or write any part of -** a block of memory after it has been released using -** [sqlite3_free()] or [sqlite3_realloc()]. -*/ -SQLITE_API void *sqlite3_malloc(int); -SQLITE_API void *sqlite3_malloc64(sqlite3_uint64); -SQLITE_API void *sqlite3_realloc(void*, int); -SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64); -SQLITE_API void sqlite3_free(void*); -SQLITE_API sqlite3_uint64 sqlite3_msize(void*); - -/* -** CAPI3REF: Memory Allocator Statistics -** -** SQLite provides these two interfaces for reporting on the status -** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] -** routines, which form the built-in memory allocation subsystem. -** -** ^The [sqlite3_memory_used()] routine returns the number of bytes -** of memory currently outstanding (malloced but not freed). -** ^The [sqlite3_memory_highwater()] routine returns the maximum -** value of [sqlite3_memory_used()] since the high-water mark -** was last reset. ^The values returned by [sqlite3_memory_used()] and -** [sqlite3_memory_highwater()] include any overhead -** added by SQLite in its implementation of [sqlite3_malloc()], -** but not overhead added by the any underlying system library -** routines that [sqlite3_malloc()] may call. -** -** ^The memory high-water mark is reset to the current value of -** [sqlite3_memory_used()] if and only if the parameter to -** [sqlite3_memory_highwater()] is true. ^The value returned -** by [sqlite3_memory_highwater(1)] is the high-water mark -** prior to the reset. -*/ -SQLITE_API sqlite3_int64 sqlite3_memory_used(void); -SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); - -/* -** CAPI3REF: Pseudo-Random Number Generator -** -** SQLite contains a high-quality pseudo-random number generator (PRNG) used to -** select random [ROWID | ROWIDs] when inserting new records into a table that -** already uses the largest possible [ROWID]. The PRNG is also used for -** the build-in random() and randomblob() SQL functions. This interface allows -** applications to access the same PRNG for other purposes. -** -** ^A call to this routine stores N bytes of randomness into buffer P. -** ^The P parameter can be a NULL pointer. -** -** ^If this routine has not been previously called or if the previous -** call had N less than one or a NULL pointer for P, then the PRNG is -** seeded using randomness obtained from the xRandomness method of -** the default [sqlite3_vfs] object. -** ^If the previous call to this routine had an N of 1 or more and a -** non-NULL P then the pseudo-randomness is generated -** internally and without recourse to the [sqlite3_vfs] xRandomness -** method. -*/ -SQLITE_API void sqlite3_randomness(int N, void *P); - -/* -** CAPI3REF: Compile-Time Authorization Callbacks -** METHOD: sqlite3 -** KEYWORDS: {authorizer callback} -** -** ^This routine registers an authorizer callback with a particular -** [database connection], supplied in the first argument. -** ^The authorizer callback is invoked as SQL statements are being compiled -** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], -** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()], -** and [sqlite3_prepare16_v3()]. ^At various -** points during the compilation process, as logic is being created -** to perform various actions, the authorizer callback is invoked to -** see if those actions are allowed. ^The authorizer callback should -** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the -** specific action but allow the SQL statement to continue to be -** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be -** rejected with an error. ^If the authorizer callback returns -** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] -** then the [sqlite3_prepare_v2()] or equivalent call that triggered -** the authorizer will fail with an error message. -** -** When the callback returns [SQLITE_OK], that means the operation -** requested is ok. ^When the callback returns [SQLITE_DENY], the -** [sqlite3_prepare_v2()] or equivalent call that triggered the -** authorizer will fail with an error message explaining that -** access is denied. -** -** ^The first parameter to the authorizer callback is a copy of the third -** parameter to the sqlite3_set_authorizer() interface. ^The second parameter -** to the callback is an integer [SQLITE_COPY | action code] that specifies -** the particular action to be authorized. ^The third through sixth parameters -** to the callback are either NULL pointers or zero-terminated strings -** that contain additional details about the action to be authorized. -** Applications must always be prepared to encounter a NULL pointer in any -** of the third through the sixth parameters of the authorization callback. -** -** ^If the action code is [SQLITE_READ] -** and the callback returns [SQLITE_IGNORE] then the -** [prepared statement] statement is constructed to substitute -** a NULL value in place of the table column that would have -** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] -** return can be used to deny an untrusted user access to individual -** columns of a table. -** ^When a table is referenced by a [SELECT] but no column values are -** extracted from that table (for example in a query like -** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback -** is invoked once for that table with a column name that is an empty string. -** ^If the action code is [SQLITE_DELETE] and the callback returns -** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the -** [truncate optimization] is disabled and all rows are deleted individually. -** -** An authorizer is used when [sqlite3_prepare | preparing] -** SQL statements from an untrusted source, to ensure that the SQL statements -** do not try to access data they are not allowed to see, or that they do not -** try to execute malicious statements that damage the database. For -** example, an application may allow a user to enter arbitrary -** SQL queries for evaluation by a database. But the application does -** not want the user to be able to make arbitrary changes to the -** database. An authorizer could then be put in place while the -** user-entered SQL is being [sqlite3_prepare | prepared] that -** disallows everything except [SELECT] statements. -** -** Applications that need to process SQL from untrusted sources -** might also consider lowering resource limits using [sqlite3_limit()] -** and limiting database size using the [max_page_count] [PRAGMA] -** in addition to using an authorizer. -** -** ^(Only a single authorizer can be in place on a database connection -** at a time. Each call to sqlite3_set_authorizer overrides the -** previous call.)^ ^Disable the authorizer by installing a NULL callback. -** The authorizer is disabled by default. -** -** The authorizer callback must not do anything that will modify -** the database connection that invoked the authorizer callback. -** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their -** database connections for the meaning of "modify" in this paragraph. -** -** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the -** statement might be re-prepared during [sqlite3_step()] due to a -** schema change. Hence, the application should ensure that the -** correct authorizer callback remains in place during the [sqlite3_step()]. -** -** ^Note that the authorizer callback is invoked only during -** [sqlite3_prepare()] or its variants. Authorization is not -** performed during statement evaluation in [sqlite3_step()], unless -** as stated in the previous paragraph, sqlite3_step() invokes -** sqlite3_prepare_v2() to reprepare a statement after a schema change. -*/ -SQLITE_API int sqlite3_set_authorizer( - sqlite3*, - int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), - void *pUserData -); - -/* -** CAPI3REF: Authorizer Return Codes -** -** The [sqlite3_set_authorizer | authorizer callback function] must -** return either [SQLITE_OK] or one of these two constants in order -** to signal SQLite whether or not the action is permitted. See the -** [sqlite3_set_authorizer | authorizer documentation] for additional -** information. -** -** Note that SQLITE_IGNORE is also used as a [conflict resolution mode] -** returned from the [sqlite3_vtab_on_conflict()] interface. -*/ -#define SQLITE_DENY 1 /* Abort the SQL statement with an error */ -#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ - -/* -** CAPI3REF: Authorizer Action Codes -** -** The [sqlite3_set_authorizer()] interface registers a callback function -** that is invoked to authorize certain SQL statement actions. The -** second parameter to the callback is an integer code that specifies -** what action is being authorized. These are the integer action codes that -** the authorizer callback may be passed. -** -** These action code values signify what kind of operation is to be -** authorized. The 3rd and 4th parameters to the authorization -** callback function will be parameters or NULL depending on which of these -** codes is used as the second parameter. ^(The 5th parameter to the -** authorizer callback is the name of the database ("main", "temp", -** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback -** is the name of the inner-most trigger or view that is responsible for -** the access attempt or NULL if this access attempt is directly from -** top-level SQL code. -*/ -/******************************************* 3rd ************ 4th ***********/ -#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ -#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ -#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ -#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ -#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ -#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ -#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ -#define SQLITE_CREATE_VIEW 8 /* View Name NULL */ -#define SQLITE_DELETE 9 /* Table Name NULL */ -#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ -#define SQLITE_DROP_TABLE 11 /* Table Name NULL */ -#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ -#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ -#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ -#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ -#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ -#define SQLITE_DROP_VIEW 17 /* View Name NULL */ -#define SQLITE_INSERT 18 /* Table Name NULL */ -#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ -#define SQLITE_READ 20 /* Table Name Column Name */ -#define SQLITE_SELECT 21 /* NULL NULL */ -#define SQLITE_TRANSACTION 22 /* Operation NULL */ -#define SQLITE_UPDATE 23 /* Table Name Column Name */ -#define SQLITE_ATTACH 24 /* Filename NULL */ -#define SQLITE_DETACH 25 /* Database Name NULL */ -#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ -#define SQLITE_REINDEX 27 /* Index Name NULL */ -#define SQLITE_ANALYZE 28 /* Table Name NULL */ -#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ -#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ -#define SQLITE_FUNCTION 31 /* NULL Function Name */ -#define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */ -#define SQLITE_COPY 0 /* No longer used */ -#define SQLITE_RECURSIVE 33 /* NULL NULL */ - -/* -** CAPI3REF: Tracing And Profiling Functions -** METHOD: sqlite3 -** -** These routines are deprecated. Use the [sqlite3_trace_v2()] interface -** instead of the routines described here. -** -** These routines register callback functions that can be used for -** tracing and profiling the execution of SQL statements. -** -** ^The callback function registered by sqlite3_trace() is invoked at -** various times when an SQL statement is being run by [sqlite3_step()]. -** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the -** SQL statement text as the statement first begins executing. -** ^(Additional sqlite3_trace() callbacks might occur -** as each triggered subprogram is entered. The callbacks for triggers -** contain a UTF-8 SQL comment that identifies the trigger.)^ -** -** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit -** the length of [bound parameter] expansion in the output of sqlite3_trace(). -** -** ^The callback function registered by sqlite3_profile() is invoked -** as each SQL statement finishes. ^The profile callback contains -** the original statement text and an estimate of wall-clock time -** of how long that statement took to run. ^The profile callback -** time is in units of nanoseconds, however the current implementation -** is only capable of millisecond resolution so the six least significant -** digits in the time are meaningless. Future versions of SQLite -** might provide greater resolution on the profiler callback. The -** sqlite3_profile() function is considered experimental and is -** subject to change in future versions of SQLite. -*/ -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 third argument -** to [sqlite3_trace_v2()] is an OR-ed combination of one or more of -** the following constants. ^The first argument to the trace callback -** is one of the following constants. -** -** New tracing constants may be added in future releases. -** -** ^A trace callback has four arguments: xCallback(T,C,P,X). -** ^The T argument is one of the integer type codes above. -** ^The C argument is a copy of the context pointer passed in as the -** fourth argument to [sqlite3_trace_v2()]. -** The P and X arguments are pointers whose meanings depend on T. -** -**
-** [[SQLITE_TRACE_STMT]]
SQLITE_TRACE_STMT
-**
^An SQLITE_TRACE_STMT callback is invoked when a prepared statement -** first begins running and possibly at other times during the -** execution of the prepared statement, such as at the start of each -** trigger subprogram. ^The P argument is a pointer to the -** [prepared statement]. ^The X argument is a pointer to a string which -** is the unexpanded SQL text of the prepared statement or an SQL comment -** that indicates the invocation of a trigger. ^The callback can compute -** the same text that would have been returned by the legacy [sqlite3_trace()] -** interface by using the X argument when X begins with "--" and invoking -** [sqlite3_expanded_sql(P)] otherwise. -** -** [[SQLITE_TRACE_PROFILE]]
SQLITE_TRACE_PROFILE
-**
^An SQLITE_TRACE_PROFILE callback provides approximately the same -** information as is provided by the [sqlite3_profile()] callback. -** ^The P argument is a pointer to the [prepared statement] and the -** X argument points to a 64-bit integer which is the estimated of -** the number of nanosecond that the prepared statement took to run. -** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes. -** -** [[SQLITE_TRACE_ROW]]
SQLITE_TRACE_ROW
-**
^An SQLITE_TRACE_ROW callback is invoked whenever a prepared -** statement generates a single row of result. -** ^The P argument is a pointer to the [prepared statement] and the -** X argument is unused. -** -** [[SQLITE_TRACE_CLOSE]]
SQLITE_TRACE_CLOSE
-**
^An SQLITE_TRACE_CLOSE callback is invoked when a database -** connection closes. -** ^The P argument is a pointer to the [database connection] object -** and the X argument is unused. -**
-*/ -#define SQLITE_TRACE_STMT 0x01 -#define SQLITE_TRACE_PROFILE 0x02 -#define SQLITE_TRACE_ROW 0x04 -#define SQLITE_TRACE_CLOSE 0x08 - -/* -** CAPI3REF: SQL Trace Hook -** METHOD: sqlite3 -** -** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback -** function X against [database connection] D, using property mask M -** and context pointer P. ^If the X callback is -** NULL or if the M mask is zero, then tracing is disabled. The -** M argument should be the bitwise OR-ed combination of -** zero or more [SQLITE_TRACE] constants. -** -** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides -** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2(). -** -** ^The X callback is invoked whenever any of the events identified by -** mask M occur. ^The integer return value from the callback is currently -** ignored, though this may change in future releases. Callback -** implementations should return zero to ensure future compatibility. -** -** ^A trace callback is invoked with four arguments: callback(T,C,P,X). -** ^The T argument is one of the [SQLITE_TRACE] -** constants to indicate why the callback was invoked. -** ^The C argument is a copy of the context pointer. -** The P and X arguments are pointers whose meanings depend on T. -** -** The sqlite3_trace_v2() interface is intended to replace the legacy -** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which -** are deprecated. -*/ -SQLITE_API int sqlite3_trace_v2( - sqlite3*, - unsigned uMask, - int(*xCallback)(unsigned,void*,void*,void*), - void *pCtx -); - -/* -** CAPI3REF: Query Progress Callbacks -** METHOD: sqlite3 -** -** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback -** function X to be invoked periodically during long running calls to -** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for -** database connection D. An example use for this -** interface is to keep a GUI updated during a large query. -** -** ^The parameter P is passed through as the only parameter to the -** callback function X. ^The parameter N is the approximate number of -** [virtual machine instructions] that are evaluated between successive -** invocations of the callback X. ^If N is less than one then the progress -** handler is disabled. -** -** ^Only a single progress handler may be defined at one time per -** [database connection]; setting a new progress handler cancels the -** old one. ^Setting parameter X to NULL disables the progress handler. -** ^The progress handler is also disabled by setting N to a value less -** than 1. -** -** ^If the progress callback returns non-zero, the operation is -** interrupted. This feature can be used to implement a -** "Cancel" button on a GUI progress dialog box. -** -** The progress handler callback must not do anything that will modify -** the database connection that invoked the progress handler. -** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their -** database connections for the meaning of "modify" in this paragraph. -** -*/ -SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); - -/* -** CAPI3REF: Opening A New Database Connection -** CONSTRUCTOR: sqlite3 -** -** ^These routines open an SQLite database file as specified by the -** filename argument. ^The filename argument is interpreted as UTF-8 for -** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte -** order for sqlite3_open16(). ^(A [database connection] handle is usually -** returned in *ppDb, even if an error occurs. The only exception is that -** if SQLite is unable to allocate memory to hold the [sqlite3] object, -** a NULL will be written into *ppDb instead of a pointer to the [sqlite3] -** object.)^ ^(If the database is opened (and/or created) successfully, then -** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The -** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain -** an English language description of the error following a failure of any -** of the sqlite3_open() routines. -** -** ^The default encoding will be UTF-8 for databases created using -** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases -** created using sqlite3_open16() will be UTF-16 in the native byte order. -** -** Whether or not an error occurs when it is opened, resources -** associated with the [database connection] handle should be released by -** passing it to [sqlite3_close()] when it is no longer required. -** -** The sqlite3_open_v2() interface works like sqlite3_open() -** except that it accepts two additional parameters for additional control -** over the new database connection. ^(The flags parameter to -** sqlite3_open_v2() can take one of -** the following three values, optionally combined with the -** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE], -** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^ -** -**
-** ^(
[SQLITE_OPEN_READONLY]
-**
The database is opened in read-only mode. If the database does not -** already exist, an error is returned.
)^ -** -** ^(
[SQLITE_OPEN_READWRITE]
-**
The database is opened for reading and writing if possible, or reading -** only if the file is write protected by the operating system. In either -** case the database must already exist, otherwise an error is returned.
)^ -** -** ^(
[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
-**
The database is opened for reading and writing, and is created if -** it does not already exist. This is the behavior that is always used for -** sqlite3_open() and sqlite3_open16().
)^ -**
-** -** If the 3rd parameter to sqlite3_open_v2() is not one of the -** combinations shown above optionally combined with other -** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits] -** then the behavior is undefined. -** -** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection -** opens in the multi-thread [threading mode] as long as the single-thread -** mode has not been set at compile-time or start-time. ^If the -** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens -** in the serialized [threading mode] unless single-thread was -** previously selected at compile-time or start-time. -** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be -** eligible to use [shared cache mode], regardless of whether or not shared -** cache is enabled using [sqlite3_enable_shared_cache()]. ^The -** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not -** participate in [shared cache mode] even if it is enabled. -** -** ^The fourth parameter to sqlite3_open_v2() is the name of the -** [sqlite3_vfs] object that defines the operating system interface that -** the new database connection should use. ^If the fourth parameter is -** a NULL pointer then the default [sqlite3_vfs] object is used. -** -** ^If the filename is ":memory:", then a private, temporary in-memory database -** is created for the connection. ^This in-memory database will vanish when -** the database connection is closed. Future versions of SQLite might -** make use of additional special filenames that begin with the ":" character. -** It is recommended that when a database filename actually does begin with -** a ":" character you should prefix the filename with a pathname such as -** "./" to avoid ambiguity. -** -** ^If the filename is an empty string, then a private, temporary -** on-disk database will be created. ^This private database will be -** automatically deleted as soon as the database connection is closed. -** -** [[URI filenames in sqlite3_open()]]

URI Filenames

-** -** ^If [URI filename] interpretation is enabled, and the filename argument -** begins with "file:", then the filename is interpreted as a URI. ^URI -** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is -** set in the third argument to sqlite3_open_v2(), or if it has -** been enabled globally using the [SQLITE_CONFIG_URI] option with the -** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option. -** URI filename interpretation is turned off -** by default, but future releases of SQLite might enable URI filename -** interpretation by default. See "[URI filenames]" for additional -** information. -** -** URI filenames are parsed according to RFC 3986. ^If the URI contains an -** authority, then it must be either an empty string or the string -** "localhost". ^If the authority is not an empty string or "localhost", an -** error is returned to the caller. ^The fragment component of a URI, if -** present, is ignored. -** -** ^SQLite uses the path component of the URI as the name of the disk file -** which contains the database. ^If the path begins with a '/' character, -** then it is interpreted as an absolute path. ^If the path does not begin -** with a '/' (meaning that the authority section is omitted from the URI) -** then the path is interpreted as a relative path. -** ^(On windows, the first component of an absolute path -** is a drive specification (e.g. "C:").)^ -** -** [[core URI query parameters]] -** The query component of a URI may contain parameters that are interpreted -** either by SQLite itself, or by a [VFS | custom VFS implementation]. -** SQLite and its built-in [VFSes] interpret the -** following query parameters: -** -**
    -**
  • vfs: ^The "vfs" parameter may be used to specify the name of -** a VFS object that provides the operating system interface that should -** be used to access the database file on disk. ^If this option is set to -** an empty string the default VFS object is used. ^Specifying an unknown -** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is -** present, then the VFS specified by the option takes precedence over -** the value passed as the fourth parameter to sqlite3_open_v2(). -** -**
  • mode: ^(The mode parameter may be set to either "ro", "rw", -** "rwc", or "memory". Attempting to set it to any other value is -** an error)^. -** ^If "ro" is specified, then the database is opened for read-only -** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the -** third argument to sqlite3_open_v2(). ^If the mode option is set to -** "rw", then the database is opened for read-write (but not create) -** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had -** been set. ^Value "rwc" is equivalent to setting both -** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is -** set to "memory" then a pure [in-memory database] that never reads -** or writes from disk is used. ^It is an error to specify a value for -** the mode parameter that is less restrictive than that specified by -** the flags passed in the third parameter to sqlite3_open_v2(). -** -**
  • cache: ^The cache parameter may be set to either "shared" or -** "private". ^Setting it to "shared" is equivalent to setting the -** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to -** sqlite3_open_v2(). ^Setting the cache parameter to "private" is -** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit. -** ^If sqlite3_open_v2() is used and the "cache" parameter is present in -** a URI filename, its value overrides any behavior requested by setting -** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag. -** -**
  • psow: ^The psow parameter indicates whether or not the -** [powersafe overwrite] property does or does not apply to the -** storage media on which the database file resides. -** -**
  • nolock: ^The nolock parameter is a boolean query parameter -** which if set disables file locking in rollback journal modes. This -** is useful for accessing a database on a filesystem that does not -** support locking. Caution: Database corruption might result if two -** or more processes write to the same database and any one of those -** processes uses nolock=1. -** -**
  • immutable: ^The immutable parameter is a boolean query -** parameter that indicates that the database file is stored on -** read-only media. ^When immutable is set, SQLite assumes that the -** database file cannot be changed, even by a process with higher -** privilege, and so the database is opened read-only and all locking -** and change detection is disabled. Caution: Setting the immutable -** property on a database file that does in fact change can result -** in incorrect query results and/or [SQLITE_CORRUPT] errors. -** See also: [SQLITE_IOCAP_IMMUTABLE]. -** -**
-** -** ^Specifying an unknown parameter in the query component of a URI is not an -** error. Future versions of SQLite might understand additional query -** parameters. See "[query parameters with special meaning to SQLite]" for -** additional information. -** -** [[URI filename examples]]

URI filename examples

-** -** -**
URI filenames Results -**
file:data.db -** Open the file "data.db" in the current directory. -**
file:/home/fred/data.db
-** file:///home/fred/data.db
-** file://localhost/home/fred/data.db
-** Open the database file "/home/fred/data.db". -**
file://darkstar/home/fred/data.db -** An error. "darkstar" is not a recognized authority. -**
-** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db -** Windows only: Open the file "data.db" on fred's desktop on drive -** C:. Note that the %20 escaping in this example is not strictly -** necessary - space characters can be used literally -** in URI filenames. -**
file:data.db?mode=ro&cache=private -** Open file "data.db" in the current directory for read-only access. -** Regardless of whether or not shared-cache mode is enabled by -** default, use a private cache. -**
file:/home/fred/data.db?vfs=unix-dotfile -** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile" -** that uses dot-files in place of posix advisory locking. -**
file:data.db?mode=readonly -** An error. "readonly" is not a valid option for the "mode" parameter. -**
-** -** ^URI hexadecimal escape sequences (%HH) are supported within the path and -** query components of a URI. A hexadecimal escape sequence consists of a -** percent sign - "%" - followed by exactly two hexadecimal digits -** specifying an octet value. ^Before the path or query components of a -** URI filename are interpreted, they are encoded using UTF-8 and all -** hexadecimal escape sequences replaced by a single byte containing the -** corresponding octet. If this process generates an invalid UTF-8 encoding, -** the results are undefined. -** -** Note to Windows users: The encoding used for the filename argument -** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever -** codepage is currently defined. Filenames containing international -** characters must be converted to UTF-8 prior to passing them into -** sqlite3_open() or sqlite3_open_v2(). -** -** Note to Windows Runtime users: The temporary directory must be set -** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various -** features that require the use of temporary files may fail. -** -** See also: [sqlite3_temp_directory] -*/ -SQLITE_API int sqlite3_open( - const char *filename, /* Database filename (UTF-8) */ - sqlite3 **ppDb /* OUT: SQLite db handle */ -); -SQLITE_API int sqlite3_open16( - const void *filename, /* Database filename (UTF-16) */ - sqlite3 **ppDb /* OUT: SQLite db handle */ -); -SQLITE_API int sqlite3_open_v2( - const char *filename, /* Database filename (UTF-8) */ - sqlite3 **ppDb, /* OUT: SQLite db handle */ - int flags, /* Flags */ - const char *zVfs /* Name of VFS module to use */ -); - -/* -** CAPI3REF: Obtain Values For URI Parameters -** -** These are utility routines, useful to VFS implementations, that check -** to see if a database file was a URI that contained a specific query -** parameter, and if so obtains the value of that query parameter. -** -** If F is the database filename pointer passed into the xOpen() method of -** a VFS implementation when the flags parameter to xOpen() has one or -** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and -** P is the name of the query parameter, then -** sqlite3_uri_parameter(F,P) returns the value of the P -** parameter if it exists or a NULL pointer if P does not appear as a -** query parameter on F. If P is a query parameter of F -** has no explicit value, then sqlite3_uri_parameter(F,P) returns -** a pointer to an empty string. -** -** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean -** parameter and returns true (1) or false (0) according to the value -** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the -** value of query parameter P is one of "yes", "true", or "on" in any -** case or if the value begins with a non-zero number. The -** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of -** query parameter P is one of "no", "false", or "off" in any case or -** if the value begins with a numeric zero. If P is not a query -** parameter on F or if the value of P is does not match any of the -** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0). -** -** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a -** 64-bit signed integer and returns that integer, or D if P does not -** exist. If the value of P is something other than an integer, then -** zero is returned. -** -** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and -** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and -** is not a database file pathname pointer that SQLite passed into the xOpen -** VFS method, then the behavior of this routine is undefined and probably -** undesirable. -*/ -SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam); -SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault); -SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64); - - -/* -** CAPI3REF: Error Codes And Messages -** METHOD: sqlite3 -** -** ^If the most recent sqlite3_* API call associated with -** [database connection] D failed, then the sqlite3_errcode(D) interface -** returns the numeric [result code] or [extended result code] for that -** API call. -** If the most recent API call was successful, -** then the return value from sqlite3_errcode() is undefined. -** ^The sqlite3_extended_errcode() -** interface is the same except that it always returns the -** [extended result code] even when extended result codes are -** disabled. -** -** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language -** text that describes the error, as either UTF-8 or UTF-16 respectively. -** ^(Memory to hold the error message string is managed internally. -** The application does not need to worry about freeing the result. -** However, the error string might be overwritten or deallocated by -** subsequent calls to other SQLite interface functions.)^ -** -** ^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. -**
-*/ -#define SQLITE_PREPARE_PERSISTENT 0x01 - -/* -** 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 [parameter | host parameter] in the -** WHERE clause might influence the choice of query plan for a statement, -** then the statement will be automatically recompiled, as if there had been -** a schema change, on the first [sqlite3_step()] call following any change -** to the [sqlite3_bind_text | bindings] of that [parameter]. -** ^The specific value of WHERE-clause [parameter] might influence the -** choice of query plan if the parameter is the left-hand side of a [LIKE] -** or [GLOB] operator or if the parameter is compared to an indexed column -** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled. -**
  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. -** -** ^(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 string returned by sqlite3_sql(P) is managed by SQLite and is -** 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); - -/* -** 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: Determine If A Prepared Statement Has Been Reset -** METHOD: sqlite3_stmt -** -** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the -** [prepared statement] S has been stepped at least once using -** [sqlite3_step(S)] but has neither run to completion (returned -** [SQLITE_DONE] from [sqlite3_step(S)]) nor -** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S) -** interface returns false if S is a NULL pointer. If S is not a -** NULL pointer and is not a pointer to a valid [prepared statement] -** object, then the behavior is undefined and probably undesirable. -** -** This interface can be used in combination [sqlite3_next_stmt()] -** to locate all prepared statements associated with a database -** connection that are in need of being reset. This can be used, -** for example, in diagnostic routines to search for prepared -** statements that are holding a transaction open. -*/ -SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*); - -/* -** CAPI3REF: Dynamically Typed Value Object -** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value} -** -** SQLite uses the sqlite3_value object to represent all values -** that can be stored in a database table. SQLite uses dynamic typing -** for the values it stores. ^Values stored in sqlite3_value objects -** can be integers, floating point values, strings, BLOBs, or NULL. -** -** An sqlite3_value object may be either "protected" or "unprotected". -** Some interfaces require a protected sqlite3_value. Other interfaces -** will accept either a protected or an unprotected sqlite3_value. -** Every interface that accepts sqlite3_value arguments specifies -** whether or not it requires a protected sqlite3_value. The -** [sqlite3_value_dup()] interface can be used to construct a new -** protected sqlite3_value from an unprotected sqlite3_value. -** -** The terms "protected" and "unprotected" refer to whether or not -** a mutex is held. An internal mutex is held for a protected -** sqlite3_value object but no mutex is held for an unprotected -** sqlite3_value object. If SQLite is compiled to be single-threaded -** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0) -** or if SQLite is run in one of reduced mutex modes -** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD] -** then there is no distinction between protected and unprotected -** sqlite3_value objects and they can be used interchangeably. However, -** for maximum code portability it is recommended that applications -** still make the distinction between protected and unprotected -** sqlite3_value objects even when not strictly required. -** -** ^The sqlite3_value objects that are passed as parameters into the -** implementation of [application-defined SQL functions] are protected. -** ^The sqlite3_value object returned by -** [sqlite3_column_value()] is unprotected. -** Unprotected sqlite3_value objects may only be used as arguments -** to [sqlite3_result_value()], [sqlite3_bind_value()], and -** [sqlite3_value_dup()]. -** The [sqlite3_value_blob | sqlite3_value_type()] family of -** interfaces require protected sqlite3_value objects. -*/ -typedef struct sqlite3_value sqlite3_value; - -/* -** CAPI3REF: SQL Function Context Object -** -** The context in which an SQL function executes is stored in an -** sqlite3_context object. ^A pointer to an sqlite3_context object -** is always first parameter to [application-defined SQL functions]. -** The application-defined SQL function implementation will pass this -** pointer through into calls to [sqlite3_result_int | sqlite3_result()], -** [sqlite3_aggregate_context()], [sqlite3_user_data()], -** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()], -** and/or [sqlite3_set_auxdata()]. -*/ -typedef struct sqlite3_context sqlite3_context; - -/* -** CAPI3REF: Binding Values To Prepared Statements -** KEYWORDS: {host parameter} {host parameters} {host parameter name} -** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} -** METHOD: sqlite3_stmt -** -** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants, -** literals may be replaced by a [parameter] that matches one of following -** templates: -** -**
    -**
  • ? -**
  • ?NNN -**
  • :VVV -**
  • @VVV -**
  • $VVV -**
-** -** In the templates above, NNN represents an integer literal, -** and VVV represents an alphanumeric identifier.)^ ^The values of these -** parameters (also called "host parameter names" or "SQL parameters") -** can be set using the sqlite3_bind_*() routines defined here. -** -** ^The first argument to the sqlite3_bind_*() routines is always -** a pointer to the [sqlite3_stmt] object returned from -** [sqlite3_prepare_v2()] or its variants. -** -** ^The second argument is the index of the SQL parameter to be set. -** ^The leftmost SQL parameter has an index of 1. ^When the same named -** SQL parameter is used more than once, second and subsequent -** occurrences have the same index as the first occurrence. -** ^The index for named parameters can be looked up using the -** [sqlite3_bind_parameter_index()] API if desired. ^The index -** for "?NNN" parameters is the value of NNN. -** ^The NNN value must be between 1 and the [sqlite3_limit()] -** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999). -** -** ^The third argument is the value to bind to the parameter. -** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16() -** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter -** is ignored and the end result is the same as sqlite3_bind_null(). -** -** ^(In those routines that have a fourth argument, its value is the -** number of bytes in the parameter. To be clear: the value is the -** number of bytes in the value, not the number of characters.)^ -** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16() -** is negative, then the length of the string is -** the number of bytes up to the first zero terminator. -** If the fourth parameter to sqlite3_bind_blob() is negative, then -** the behavior is undefined. -** If a non-negative fourth parameter is provided to sqlite3_bind_text() -** or sqlite3_bind_text16() or sqlite3_bind_text64() then -** that parameter must be the byte offset -** where the NUL terminator would occur assuming the string were NUL -** terminated. If any NUL characters occur at byte offsets less than -** the value of the fourth parameter then the resulting string value will -** contain embedded NULs. The result of expressions involving strings -** with embedded NULs is undefined. -** -** ^The fifth argument to the BLOB and string binding interfaces -** is a destructor used to dispose of the BLOB or -** string after SQLite has finished with it. ^The destructor is called -** to dispose of the BLOB or string even if the call to bind API fails. -** ^If the fifth argument is -** the special value [SQLITE_STATIC], then SQLite assumes that the -** information is in static, unmanaged space and does not need to be freed. -** ^If the fifth argument has the value [SQLITE_TRANSIENT], then -** SQLite makes its own private copy of the data immediately, before -** the sqlite3_bind_*() routine returns. -** -** ^The sixth argument to sqlite3_bind_text64() must be one of -** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE] -** to specify the encoding of the text in the third parameter. If -** the sixth argument to sqlite3_bind_text64() is not one of the -** allowed values shown above, or if the text encoding is different -** from the encoding specified by the sixth parameter, then the behavior -** is undefined. -** -** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that -** is filled with zeroes. ^A zeroblob uses a fixed amount of memory -** (just an integer to hold its size) while it is being processed. -** Zeroblobs are intended to serve as placeholders for BLOBs whose -** content is later written using -** [sqlite3_blob_open | incremental BLOB I/O] routines. -** ^A negative value for the zeroblob results in a zero-length BLOB. -** -** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in -** [prepared statement] S to have an SQL value of NULL, but to also be -** associated with the pointer P of type T. ^D is either a NULL pointer or -** a pointer to a destructor function for P. ^SQLite will invoke the -** destructor D with a single argument of P when it is finished using -** P. The T parameter should be a static string, preferably a string -** literal. The sqlite3_bind_pointer() routine is part of the -** [pointer passing interface] added for SQLite 3.20.0. -** -** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer -** for the [prepared statement] or with a prepared statement for which -** [sqlite3_step()] has been called more recently than [sqlite3_reset()], -** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_() -** routine is passed a [prepared statement] that has been finalized, the -** result is undefined and probably harmful. -** -** ^Bindings are not cleared by the [sqlite3_reset()] routine. -** ^Unbound parameters are interpreted as NULL. -** -** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an -** [error code] if anything goes wrong. -** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB -** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or -** [SQLITE_MAX_LENGTH]. -** ^[SQLITE_RANGE] is returned if the parameter -** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails. -** -** See also: [sqlite3_bind_parameter_count()], -** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. -*/ -SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); -SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64, - void(*)(void*)); -SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double); -SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int); -SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); -SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int); -SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*)); -SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); -SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64, - void(*)(void*), unsigned char encoding); -SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); -SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*)); -SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); -SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64); - -/* -** CAPI3REF: Number Of SQL Parameters -** METHOD: sqlite3_stmt -** -** ^This routine can be used to find the number of [SQL parameters] -** in a [prepared statement]. SQL parameters are tokens of the -** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as -** placeholders for values that are [sqlite3_bind_blob | bound] -** to the parameters at a later time. -** -** ^(This routine actually returns the index of the largest (rightmost) -** parameter. For all forms except ?NNN, this will correspond to the -** number of unique parameters. If parameters of the ?NNN form are used, -** there may be gaps in the list.)^ -** -** See also: [sqlite3_bind_blob|sqlite3_bind()], -** [sqlite3_bind_parameter_name()], and -** [sqlite3_bind_parameter_index()]. -*/ -SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); - -/* -** CAPI3REF: Name Of A Host Parameter -** METHOD: sqlite3_stmt -** -** ^The sqlite3_bind_parameter_name(P,N) interface returns -** the name of the N-th [SQL parameter] in the [prepared statement] P. -** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" -** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" -** respectively. -** In other words, the initial ":" or "$" or "@" or "?" -** is included as part of the name.)^ -** ^Parameters of the form "?" without a following integer have no name -** and are referred to as "nameless" or "anonymous parameters". -** -** ^The first host parameter has an index of 1, not 0. -** -** ^If the value N is out of range or if the N-th parameter is -** nameless, then NULL is returned. ^The returned string is -** always in UTF-8 encoding even if the named parameter was -** originally specified as UTF-16 in [sqlite3_prepare16()], -** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()]. -** -** See also: [sqlite3_bind_blob|sqlite3_bind()], -** [sqlite3_bind_parameter_count()], and -** [sqlite3_bind_parameter_index()]. -*/ -SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); - -/* -** CAPI3REF: Index Of A Parameter With A Given Name -** METHOD: sqlite3_stmt -** -** ^Return the index of an SQL parameter given its name. ^The -** index value returned is suitable for use as the second -** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero -** is returned if no matching parameter is found. ^The parameter -** name must be given in UTF-8 even if the original statement -** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or -** [sqlite3_prepare16_v3()]. -** -** See also: [sqlite3_bind_blob|sqlite3_bind()], -** [sqlite3_bind_parameter_count()], and -** [sqlite3_bind_parameter_name()]. -*/ -SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); - -/* -** CAPI3REF: Reset All Bindings On A Prepared Statement -** METHOD: sqlite3_stmt -** -** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset -** the [sqlite3_bind_blob | bindings] on a [prepared statement]. -** ^Use this routine to reset all host parameters to NULL. -*/ -SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); - -/* -** CAPI3REF: Number Of Columns In A Result Set -** METHOD: sqlite3_stmt -** -** ^Return the number of columns in the result set returned by the -** [prepared statement]. ^If this routine returns 0, that means the -** [prepared statement] returns no data (for example an [UPDATE]). -** ^However, just because this routine returns a positive number does not -** mean that one or more rows of data will be returned. ^A SELECT statement -** will always have a positive sqlite3_column_count() but depending on the -** WHERE clause constraints and the table content, it might return no rows. -** -** See also: [sqlite3_data_count()] -*/ -SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); - -/* -** CAPI3REF: Column Names In A Result Set -** METHOD: sqlite3_stmt -** -** ^These routines return the name assigned to a particular column -** in the result set of a [SELECT] statement. ^The sqlite3_column_name() -** interface returns a pointer to a zero-terminated UTF-8 string -** and sqlite3_column_name16() returns a pointer to a zero-terminated -** UTF-16 string. ^The first parameter is the [prepared statement] -** that implements the [SELECT] statement. ^The second parameter is the -** column number. ^The leftmost column is number 0. -** -** ^The returned string pointer is valid until either the [prepared statement] -** is destroyed by [sqlite3_finalize()] or until the statement is automatically -** reprepared by the first call to [sqlite3_step()] for a particular run -** or until the next call to -** sqlite3_column_name() or sqlite3_column_name16() on the same column. -** -** ^If sqlite3_malloc() fails during the processing of either routine -** (for example during a conversion from UTF-8 to UTF-16) then a -** NULL pointer is returned. -** -** ^The name of a result column is the value of the "AS" clause for -** that column, if there is an AS clause. If there is no AS clause -** then the name of the column is unspecified and may change from -** one release of SQLite to the next. -*/ -SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N); -SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); - -/* -** CAPI3REF: Source Of Data In A Query Result -** METHOD: sqlite3_stmt -** -** ^These routines provide a means to determine the database, table, and -** table column that is the origin of a particular result column in -** [SELECT] statement. -** ^The name of the database or table or column can be returned as -** either a UTF-8 or UTF-16 string. ^The _database_ routines return -** the database name, the _table_ routines return the table name, and -** the origin_ routines return the column name. -** ^The returned string is valid until the [prepared statement] is destroyed -** using [sqlite3_finalize()] or until the statement is automatically -** reprepared by the first call to [sqlite3_step()] for a particular run -** or until the same information is requested -** again in a different encoding. -** -** ^The names returned are the original un-aliased names of the -** database, table, and column. -** -** ^The first argument to these interfaces is a [prepared statement]. -** ^These functions return information about the Nth result column returned by -** the statement, where N is the second function argument. -** ^The left-most column is column 0 for these routines. -** -** ^If the Nth column returned by the statement is an expression or -** subquery and is not a column value, then all of these functions return -** NULL. ^These routine might also return NULL if a memory allocation error -** occurs. ^Otherwise, they return the name of the attached database, table, -** or column that query result column was extracted from. -** -** ^As with all other SQLite APIs, those whose names end with "16" return -** UTF-16 encoded strings and the other functions return UTF-8. -** -** ^These APIs are only available if the library was compiled with the -** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol. -** -** If two or more threads call one or more of these routines against the same -** prepared statement and column at the same time then the results are -** undefined. -** -** If two or more threads call one or more -** [sqlite3_column_database_name | column metadata interfaces] -** for the same [prepared statement] and result column -** at the same time then the results are undefined. -*/ -SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int); -SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int); -SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int); -SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int); -SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int); -SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); - -/* -** CAPI3REF: Declared Datatype Of A Query Result -** METHOD: sqlite3_stmt -** -** ^(The first parameter is a [prepared statement]. -** If this statement is a [SELECT] statement and the Nth column of the -** returned result set of that [SELECT] is a table column (not an -** expression or subquery) then the declared type of the table -** column is returned.)^ ^If the Nth column of the result set is an -** expression or subquery, then a NULL pointer is returned. -** ^The returned string is always UTF-8 encoded. -** -** ^(For example, given the database schema: -** -** CREATE TABLE t1(c1 VARIANT); -** -** and the following statement to be compiled: -** -** SELECT c1 + 1, c1 FROM t1; -** -** this routine would return the string "VARIANT" for the second result -** column (i==1), and a NULL pointer for the first result column (i==0).)^ -** -** ^SQLite uses dynamic run-time typing. ^So just because a column -** is declared to contain a particular type does not mean that the -** data stored in that column is of the declared type. SQLite is -** strongly typed, but the typing is dynamic not static. ^Type -** is associated with individual values, not with the containers -** used to hold those values. -*/ -SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int); -SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); - -/* -** CAPI3REF: Evaluate An SQL Statement -** METHOD: sqlite3_stmt -** -** After a [prepared statement] has been prepared using any of -** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()], -** or [sqlite3_prepare16_v3()] or one of the legacy -** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function -** must be called one or more times to evaluate the statement. -** -** The details of the behavior of the sqlite3_step() interface depend -** on whether the statement was prepared using the newer "vX" interfaces -** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()], -** [sqlite3_prepare16_v2()] or the older legacy -** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the -** new "vX" interface is recommended for new applications but the legacy -** interface will continue to be supported. -** -** ^In the legacy interface, the return value will be either [SQLITE_BUSY], -** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. -** ^With the "v2" interface, any of the other [result codes] or -** [extended result codes] might be returned as well. -** -** ^[SQLITE_BUSY] means that the database engine was unable to acquire the -** database locks it needs to do its job. ^If the statement is a [COMMIT] -** or occurs outside of an explicit transaction, then you can retry the -** statement. If the statement is not a [COMMIT] and occurs within an -** explicit transaction then you should rollback the transaction before -** continuing. -** -** ^[SQLITE_DONE] means that the statement has finished executing -** successfully. sqlite3_step() should not be called again on this virtual -** machine without first calling [sqlite3_reset()] to reset the virtual -** machine back to its initial state. -** -** ^If the SQL statement being executed returns any data, then [SQLITE_ROW] -** is returned each time a new row of data is ready for processing by the -** caller. The values may be accessed using the [column access functions]. -** sqlite3_step() is called again to retrieve the next row of data. -** -** ^[SQLITE_ERROR] means that a run-time error (such as a constraint -** violation) has occurred. sqlite3_step() should not be called again on -** the VM. More information may be found by calling [sqlite3_errmsg()]. -** ^With the legacy interface, a more specific error code (for example, -** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) -** can be obtained by calling [sqlite3_reset()] on the -** [prepared statement]. ^In the "v2" interface, -** the more specific error code is returned directly by sqlite3_step(). -** -** [SQLITE_MISUSE] means that the this routine was called inappropriately. -** Perhaps it was called on a [prepared statement] that has -** already been [sqlite3_finalize | finalized] or on one that had -** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could -** be the case that the same database connection is being used by two or -** more threads at the same moment in time. -** -** For all versions of SQLite up to and including 3.6.23.1, a call to -** [sqlite3_reset()] was required after sqlite3_step() returned anything -** other than [SQLITE_ROW] before any subsequent invocation of -** sqlite3_step(). Failure to reset the prepared statement using -** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from -** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1], -** sqlite3_step() began -** calling [sqlite3_reset()] automatically in this circumstance rather -** than returning [SQLITE_MISUSE]. This is not considered a compatibility -** break because any application that ever receives an SQLITE_MISUSE error -** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option -** can be used to restore the legacy behavior. -** -** Goofy Interface Alert: In the legacy interface, the sqlite3_step() -** API always returns a generic error code, [SQLITE_ERROR], following any -** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call -** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the -** specific [error codes] that better describes the error. -** We admit that this is a goofy design. The problem has been fixed -** with the "v2" interface. If you prepare all of your SQL statements -** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()] -** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead -** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces, -** then the more specific [error codes] are returned directly -** by sqlite3_step(). The use of the "vX" interfaces is recommended. -*/ -SQLITE_API int sqlite3_step(sqlite3_stmt*); - -/* -** CAPI3REF: Number of columns in a result set -** METHOD: sqlite3_stmt -** -** ^The sqlite3_data_count(P) interface returns the number of columns in the -** current row of the result set of [prepared statement] P. -** ^If prepared statement P does not have results ready to return -** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of -** interfaces) then sqlite3_data_count(P) returns 0. -** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer. -** ^The sqlite3_data_count(P) routine returns 0 if the previous call to -** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P) -** will return non-zero if previous call to [sqlite3_step](P) returned -** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum] -** where it always returns zero since each step of that multi-step -** pragma returns 0 columns of data. -** -** See also: [sqlite3_column_count()] -*/ -SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); - -/* -** CAPI3REF: Fundamental Datatypes -** KEYWORDS: SQLITE_TEXT -** -** ^(Every value in SQLite has one of five fundamental datatypes: -** -**
    -**
  • 64-bit signed integer -**
  • 64-bit IEEE floating point number -**
  • string -**
  • BLOB -**
  • NULL -**
)^ -** -** These constants are codes for each of those types. -** -** Note that the SQLITE_TEXT constant was also used in SQLite version 2 -** for a completely different meaning. Software that links against both -** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not -** SQLITE_TEXT. -*/ -#define SQLITE_INTEGER 1 -#define SQLITE_FLOAT 2 -#define SQLITE_BLOB 4 -#define SQLITE_NULL 5 -#ifdef SQLITE_TEXT -# undef SQLITE_TEXT -#else -# define SQLITE_TEXT 3 -#endif -#define SQLITE3_TEXT 3 - -/* -** CAPI3REF: Result Values From A Query -** KEYWORDS: {column access functions} -** METHOD: sqlite3_stmt -** -** Summary: -**
-**
sqlite3_column_blobBLOB result -**
sqlite3_column_doubleREAL result -**
sqlite3_column_int32-bit INTEGER result -**
sqlite3_column_int6464-bit INTEGER result -**
sqlite3_column_textUTF-8 TEXT result -**
sqlite3_column_text16UTF-16 TEXT result -**
sqlite3_column_valueThe result as an -** [sqlite3_value|unprotected sqlite3_value] object. -**
    -**
sqlite3_column_bytesSize of a BLOB -** or a UTF-8 TEXT result in bytes -**
sqlite3_column_bytes16   -** →  Size of UTF-16 -** TEXT in bytes -**
sqlite3_column_typeDefault -** 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()]. -** -** ^(If a memory allocation error occurs during the evaluation of any -** of these routines, a default value is returned. The default value -** is either the integer 0, the floating point number 0.0, or a NULL -** pointer. Subsequent calls to [sqlite3_errcode()] will return -** [SQLITE_NOMEM].)^ -*/ -SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); -SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol); -SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol); -SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); -SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); -SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); -SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); -SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol); -SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); -SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol); - -/* -** CAPI3REF: Destroy A Prepared Statement Object -** DESTRUCTOR: sqlite3_stmt -** -** ^The sqlite3_finalize() function is called to delete a [prepared statement]. -** ^If the most recent evaluation of the statement encountered no errors -** or if the statement is never been evaluated, then sqlite3_finalize() returns -** SQLITE_OK. ^If the most recent evaluation of statement S failed, then -** sqlite3_finalize(S) returns the appropriate [error code] or -** [extended error code]. -** -** ^The sqlite3_finalize(S) routine can be called at any point during -** the life cycle of [prepared statement] S: -** before statement S is ever evaluated, after -** one or more calls to [sqlite3_reset()], or after any call -** to [sqlite3_step()] regardless of whether or not the statement has -** completed execution. -** -** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op. -** -** The application must finalize every [prepared statement] in order to avoid -** resource leaks. It is a grievous error for the application to try to use -** a prepared statement after it has been finalized. Any use of a prepared -** statement after it has been finalized can result in undefined and -** undesirable behavior such as segfaults and heap corruption. -*/ -SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt); - -/* -** CAPI3REF: Reset A Prepared Statement Object -** METHOD: sqlite3_stmt -** -** The sqlite3_reset() function is called to reset a [prepared statement] -** object back to its initial state, ready to be re-executed. -** ^Any SQL statement variables that had values bound to them using -** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. -** Use [sqlite3_clear_bindings()] to reset the bindings. -** -** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S -** back to the beginning of its program. -** -** ^If the most recent call to [sqlite3_step(S)] for the -** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE], -** or if [sqlite3_step(S)] has never before been called on S, -** then [sqlite3_reset(S)] returns [SQLITE_OK]. -** -** ^If the most recent call to [sqlite3_step(S)] for the -** [prepared statement] S indicated an error, then -** [sqlite3_reset(S)] returns an appropriate [error code]. -** -** ^The [sqlite3_reset(S)] interface does not change the values -** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S. -*/ -SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); - -/* -** CAPI3REF: Create Or Redefine SQL Functions -** KEYWORDS: {function creation routines} -** KEYWORDS: {application-defined SQL function} -** KEYWORDS: {application-defined SQL functions} -** METHOD: sqlite3 -** -** ^These functions (collectively known as "function creation routines") -** are used to add SQL functions or aggregates or to redefine the behavior -** of existing SQL functions or aggregates. The only differences between -** these routines are the text encoding expected for -** the second parameter (the name of the function being created) -** and the presence or absence of a destructor callback for -** the application data pointer. -** -** ^The first parameter is the [database connection] to which the SQL -** function is to be added. ^If an application uses more than one database -** connection then application-defined SQL functions must be added -** to each database connection separately. -** -** ^The second parameter is the name of the SQL function to be created or -** redefined. ^The length of the name is limited to 255 bytes in a UTF-8 -** representation, exclusive of the zero-terminator. ^Note that the name -** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes. -** ^Any attempt to create a function with a longer name -** will result in [SQLITE_MISUSE] being returned. -** -** ^The third parameter (nArg) -** is the number of arguments that the SQL function or -** aggregate takes. ^If this parameter is -1, then the SQL function or -** aggregate may take any number of arguments between 0 and the limit -** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third -** parameter is less than -1 or greater than 127 then the behavior is -** undefined. -** -** ^The fourth parameter, eTextRep, specifies what -** [SQLITE_UTF8 | text encoding] this SQL function prefers for -** its parameters. The application should set this parameter to -** [SQLITE_UTF16LE] if the function implementation invokes -** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the -** implementation invokes [sqlite3_value_text16be()] on an input, or -** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8] -** otherwise. ^The same SQL function may be registered multiple times using -** different preferred text encodings, with different implementations for -** each encoding. -** ^When multiple implementations of the same function are available, SQLite -** will pick the one that involves the least amount of data conversion. -** -** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC] -** to signal that the function will always return the same result given -** the same inputs within a single SQL statement. Most SQL functions are -** deterministic. The built-in [random()] SQL function is an example of a -** function that is not deterministic. The SQLite query planner is able to -** perform additional optimizations on deterministic functions, so use -** of the [SQLITE_DETERMINISTIC] flag is recommended where possible. -** -** ^(The fifth parameter is an arbitrary pointer. The implementation of the -** function can gain access to this pointer using [sqlite3_user_data()].)^ -** -** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are -** pointers to C-language functions that implement the SQL function or -** aggregate. ^A scalar SQL function requires an implementation of the xFunc -** callback only; NULL pointers must be passed as the xStep and xFinal -** parameters. ^An aggregate SQL function requires an implementation of xStep -** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing -** SQL function or aggregate, pass NULL pointers for all three function -** callbacks. -** -** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL, -** then it is destructor for the application data pointer. -** The destructor is invoked when the function is deleted, either by being -** overloaded or when the database connection closes.)^ -** ^The destructor is also invoked if the call to -** sqlite3_create_function_v2() fails. -** ^When the destructor callback of the tenth parameter is invoked, it -** is passed a single argument which is a copy of the application data -** pointer which was the fifth parameter to sqlite3_create_function_v2(). -** -** ^It is permitted to register multiple implementations of the same -** functions with the same name but with either differing numbers of -** arguments or differing preferred text encodings. ^SQLite will use -** the implementation that most closely matches the way in which the -** SQL function is used. ^A function implementation with a non-negative -** nArg parameter is a better match than a function implementation with -** a negative nArg. ^A function where the preferred text encoding -** matches the database encoding is a better -** match than a function where the encoding is different. -** ^A function where the encoding difference is between UTF16le and UTF16be -** is a closer match than a function where the encoding difference is -** between UTF8 and UTF16. -** -** ^Built-in functions may be overloaded by new application-defined functions. -** -** ^An application-defined function is permitted to call other -** SQLite interfaces. However, such calls must not -** close the database connection nor finalize or reset the prepared -** statement in which the function is running. -*/ -SQLITE_API int sqlite3_create_function( - sqlite3 *db, - 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*) -); - -/* -** CAPI3REF: Text Encodings -** -** These constant define integer codes that represent the various -** text encodings supported by SQLite. -*/ -#define SQLITE_UTF8 1 /* IMP: R-37514-35566 */ -#define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */ -#define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */ -#define SQLITE_UTF16 4 /* Use native byte order */ -#define SQLITE_ANY 5 /* Deprecated */ -#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ - -/* -** CAPI3REF: Function Flags -** -** These constants may be ORed together with the -** [SQLITE_UTF8 | preferred text encoding] as the fourth argument -** to [sqlite3_create_function()], [sqlite3_create_function16()], or -** [sqlite3_create_function_v2()]. -*/ -#define SQLITE_DETERMINISTIC 0x800 - -/* -** CAPI3REF: Deprecated Functions -** DEPRECATED -** -** These functions are [deprecated]. In order to maintain -** backwards compatibility with older code, these functions continue -** to be supported. However, new applications should avoid -** the use of these functions. To encourage programmers to avoid -** these functions, we will not explain what they do. -*/ -#ifndef SQLITE_OMIT_DEPRECATED -SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*); -SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*); -SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); -SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void); -SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void); -SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int), - void*,sqlite3_int64); -#endif - -/* -** CAPI3REF: Obtaining SQL Values -** METHOD: sqlite3_value -** -** Summary: -**
-**
sqlite3_value_blobBLOB value -**
sqlite3_value_doubleREAL value -**
sqlite3_value_int32-bit INTEGER value -**
sqlite3_value_int6464-bit INTEGER value -**
sqlite3_value_pointerPointer value -**
sqlite3_value_textUTF-8 TEXT value -**
sqlite3_value_text16UTF-16 TEXT value in -** the native byteorder -**
sqlite3_value_text16beUTF-16be TEXT value -**
sqlite3_value_text16leUTF-16le TEXT value -**
    -**
sqlite3_value_bytesSize of a BLOB -** or a UTF-8 TEXT in bytes -**
sqlite3_value_bytes16   -** →  Size of UTF-16 -** TEXT in bytes -**
sqlite3_value_typeDefault -** datatype of the value -**
sqlite3_value_numeric_type   -** →  Best numeric datatype of the value -**
-** -** Details: -** -** These routines extract type, size, and content information from -** [protected sqlite3_value] objects. Protected sqlite3_value objects -** are used to pass parameter information into implementation of -** [application-defined SQL functions] and [virtual tables]. -** -** These routines work only with [protected sqlite3_value] objects. -** Any attempt to use these routines on an [unprotected sqlite3_value] -** is not threadsafe. -** -** ^These routines work just like the corresponding [column access functions] -** except that these routines take a single [protected sqlite3_value] object -** pointer instead of a [sqlite3_stmt*] pointer and an integer column number. -** -** ^The sqlite3_value_text16() interface extracts a UTF-16 string -** in the native byte-order of the host machine. ^The -** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces -** extract UTF-16 strings as big-endian and little-endian respectively. -** -** ^If [sqlite3_value] object V was initialized -** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)] -** and if X and Y are strings that compare equal according to strcmp(X,Y), -** then sqlite3_value_pointer(V,Y) will return the pointer P. ^Otherwise, -** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer() -** routine is part of the [pointer passing interface] added for SQLite 3.20.0. -** -** ^(The sqlite3_value_type(V) interface returns the -** [SQLITE_INTEGER | datatype code] for the initial datatype of the -** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER], -** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^ -** Other interfaces might change the datatype for an sqlite3_value object. -** For example, if the datatype is initially SQLITE_INTEGER and -** sqlite3_value_text(V) is called to extract a text value for that -** integer, then subsequent calls to sqlite3_value_type(V) might return -** SQLITE_TEXT. Whether or not a persistent internal datatype conversion -** occurs is undefined and may change from one release of SQLite to the next. -** -** ^(The sqlite3_value_numeric_type() interface attempts to apply -** numeric affinity to the value. This means that an attempt is -** made to convert the value to an integer or floating point. If -** such a conversion is possible without loss of information (in other -** words, if the value is a string that looks like a number) -** then the conversion is performed. Otherwise no conversion occurs. -** The [SQLITE_INTEGER | datatype] after conversion is returned.)^ -** -** Please pay particular attention to the fact that the pointer returned -** from [sqlite3_value_blob()], [sqlite3_value_text()], or -** [sqlite3_value_text16()] can be invalidated by a subsequent call to -** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], -** or [sqlite3_value_text16()]. -** -** These routines must be called from the same thread as -** the SQL function that supplied the [sqlite3_value*] parameters. -*/ -SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); -SQLITE_API 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*); - -/* -** CAPI3REF: Finding The Subtype Of SQL Values -** METHOD: sqlite3_value -** -** The sqlite3_value_subtype(V) function returns the subtype for -** an [application-defined SQL function] argument V. The subtype -** information can be used to pass a limited amount of context from -** one SQL function to another. Use the [sqlite3_result_subtype()] -** routine to set the subtype for the return value of an SQL function. -*/ -SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*); - -/* -** CAPI3REF: Copy And Free SQL Values -** METHOD: sqlite3_value -** -** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value] -** object D and returns a pointer to that copy. ^The [sqlite3_value] returned -** is a [protected sqlite3_value] object even if the input is not. -** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a -** memory allocation fails. -** -** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object -** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer -** then sqlite3_value_free(V) is a harmless no-op. -*/ -SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*); -SQLITE_API void sqlite3_value_free(sqlite3_value*); - -/* -** CAPI3REF: Obtain Aggregate Function Context -** METHOD: sqlite3_context -** -** Implementations of aggregate SQL functions use this -** routine to allocate memory for storing their state. -** -** ^The first time the sqlite3_aggregate_context(C,N) routine is called -** for a particular aggregate function, SQLite -** allocates N of memory, zeroes out that memory, and returns a pointer -** to the new memory. ^On second and subsequent calls to -** sqlite3_aggregate_context() for the same aggregate function instance, -** the same buffer is returned. Sqlite3_aggregate_context() is normally -** called once for each invocation of the xStep callback and then one -** last time when the xFinal callback is invoked. ^(When no rows match -** an aggregate query, the xStep() callback of the aggregate function -** implementation is never called and xFinal() is called exactly once. -** In those cases, sqlite3_aggregate_context() might be called for the -** first time from within xFinal().)^ -** -** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer -** when first called if N is less than or equal to zero or if a memory -** allocate error occurs. -** -** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is -** determined by the N parameter on first successful call. Changing the -** value of N in subsequent call to sqlite3_aggregate_context() within -** the same aggregate function instance will not resize the memory -** allocation.)^ Within the xFinal callback, it is customary to set -** N=0 in calls to sqlite3_aggregate_context(C,N) so that no -** pointless memory allocations occur. -** -** ^SQLite automatically frees the memory allocated by -** sqlite3_aggregate_context() when the aggregate query concludes. -** -** The first parameter must be a copy of the -** [sqlite3_context | SQL function context] that is the first parameter -** to the xStep or xFinal callback routine that implements the aggregate -** function. -** -** This routine must be called from the same thread in which -** the aggregate SQL function is running. -*/ -SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); - -/* -** CAPI3REF: User Data For Functions -** METHOD: sqlite3_context -** -** ^The sqlite3_user_data() interface returns a copy of -** the pointer that was the pUserData parameter (the 5th parameter) -** of the [sqlite3_create_function()] -** and [sqlite3_create_function16()] routines that originally -** registered the application defined function. -** -** This routine must be called from the same thread in which -** the application-defined function is running. -*/ -SQLITE_API void *sqlite3_user_data(sqlite3_context*); - -/* -** CAPI3REF: Database Connection For Functions -** METHOD: sqlite3_context -** -** ^The sqlite3_context_db_handle() interface returns a copy of -** the pointer to the [database connection] (the 1st parameter) -** of the [sqlite3_create_function()] -** and [sqlite3_create_function16()] routines that originally -** registered the application defined function. -*/ -SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); - -/* -** CAPI3REF: Function Auxiliary Data -** METHOD: sqlite3_context -** -** These functions may be used by (non-aggregate) SQL functions to -** associate metadata with argument values. If the same value is passed to -** multiple invocations of the same SQL function during query execution, under -** some circumstances the associated metadata may be preserved. An example -** of where this might be useful is in a regular-expression matching -** function. The compiled version of the regular expression can be stored as -** metadata associated with the pattern string. -** Then as long as the pattern string remains the same, -** the compiled regular expression can be reused on multiple -** invocations of the same function. -** -** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata -** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument -** value to the application-defined function. ^N is zero for the left-most -** function argument. ^If there is no metadata -** associated with the function argument, the sqlite3_get_auxdata(C,N) interface -** returns a NULL pointer. -** -** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th -** argument of the application-defined function. ^Subsequent -** calls to sqlite3_get_auxdata(C,N) return P from the most recent -** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or -** NULL if the metadata has been discarded. -** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL, -** SQLite will invoke the destructor function X with parameter P exactly -** once, when the metadata is discarded. -** SQLite is free to discard the metadata at any time, including:
    -**
  • ^(when the corresponding function parameter changes)^, or -**
  • ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the -** SQL statement)^, or -**
  • ^(when sqlite3_set_auxdata() is invoked again on the same -** parameter)^, or -**
  • ^(during the original sqlite3_set_auxdata() call when a memory -** allocation error occurs.)^
-** -** Note the last bullet in particular. The destructor X in -** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the -** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata() -** should be called near the end of the function implementation and the -** function implementation should not make any use of P after -** sqlite3_set_auxdata() has been called. -** -** ^(In practice, metadata is preserved between function calls for -** function parameters that are compile-time constants, including literal -** values and [parameters] and expressions composed from the same.)^ -** -** The value of the N parameter to these interfaces should be non-negative. -** Future enhancements may make use of negative N values to define new -** kinds of function caching behavior. -** -** These routines must be called from the same thread in which -** the SQL function is running. -*/ -SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N); -SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); - - -/* -** CAPI3REF: Constants Defining Special Destructor Behavior -** -** These are special values for the destructor that is passed in as the -** final argument to routines like [sqlite3_result_blob()]. ^If the destructor -** argument is SQLITE_STATIC, it means that the content pointer is constant -** and will never change. It does not need to be destroyed. ^The -** SQLITE_TRANSIENT value means that the content will likely change in -** the near future and that SQLite should make its own private copy of -** the content before returning. -** -** The typedef is necessary to work around problems in certain -** C++ compilers. -*/ -typedef void (*sqlite3_destructor_type)(void*); -#define SQLITE_STATIC ((sqlite3_destructor_type)0) -#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) - -/* -** CAPI3REF: Setting The Result Of An SQL Function -** METHOD: sqlite3_context -** -** These routines are used by the xFunc or xFinal callbacks that -** implement SQL functions and aggregates. See -** [sqlite3_create_function()] and [sqlite3_create_function16()] -** for additional information. -** -** These functions work very much like the [parameter binding] family of -** functions used to bind values to host parameters in prepared statements. -** Refer to the [SQL parameter] documentation for additional information. -** -** ^The sqlite3_result_blob() interface sets the result from -** an application-defined function to be the BLOB whose content is pointed -** to by the second parameter and which is N bytes long where N is the -** third parameter. -** -** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N) -** interfaces set the result of the application-defined function to be -** a BLOB containing all zero bytes and N bytes in size. -** -** ^The sqlite3_result_double() interface sets the result from -** an application-defined function to be a floating point value specified -** by its 2nd argument. -** -** ^The sqlite3_result_error() and sqlite3_result_error16() functions -** cause the implemented SQL function to throw an exception. -** ^SQLite uses the string pointed to by the -** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() -** as the text of an error message. ^SQLite interprets the error -** message string from sqlite3_result_error() as UTF-8. ^SQLite -** interprets the string from sqlite3_result_error16() as UTF-16 in native -** byte order. ^If the third parameter to sqlite3_result_error() -** or sqlite3_result_error16() is negative then SQLite takes as the error -** message all text up through the first zero character. -** ^If the third parameter to sqlite3_result_error() or -** sqlite3_result_error16() is non-negative then SQLite takes that many -** bytes (not characters) from the 2nd parameter as the error message. -** ^The sqlite3_result_error() and sqlite3_result_error16() -** routines make a private copy of the error message text before -** they return. Hence, the calling function can deallocate or -** modify the text after they return without harm. -** ^The sqlite3_result_error_code() function changes the error code -** returned by SQLite as a result of an error in a function. ^By default, -** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error() -** or sqlite3_result_error16() resets the error code to SQLITE_ERROR. -** -** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an -** error indicating that a string or BLOB is too long to represent. -** -** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an -** error indicating that a memory allocation failed. -** -** ^The sqlite3_result_int() interface sets the return value -** of the application-defined function to be the 32-bit signed integer -** value given in the 2nd argument. -** ^The sqlite3_result_int64() interface sets the return value -** of the application-defined function to be the 64-bit signed integer -** value given in the 2nd argument. -** -** ^The sqlite3_result_null() interface sets the return value -** of the application-defined function to be NULL. -** -** ^The sqlite3_result_text(), sqlite3_result_text16(), -** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces -** set the return value of the application-defined function to be -** a text string which is represented as UTF-8, UTF-16 native byte order, -** UTF-16 little endian, or UTF-16 big endian, respectively. -** ^The sqlite3_result_text64() interface sets the return value of an -** application-defined function to be a text string in an encoding -** specified by the fifth (and last) parameter, which must be one -** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]. -** ^SQLite takes the text result from the application from -** the 2nd parameter of the sqlite3_result_text* interfaces. -** ^If the 3rd parameter to the sqlite3_result_text* interfaces -** is negative, then SQLite takes result text from the 2nd parameter -** through the first zero character. -** ^If the 3rd parameter to the sqlite3_result_text* interfaces -** is non-negative, then as many bytes (not characters) of the text -** pointed to by the 2nd parameter are taken as the application-defined -** function result. If the 3rd parameter is non-negative, then it -** must be the byte offset into the string where the NUL terminator would -** appear if the string where NUL terminated. If any NUL characters occur -** in the string at a byte offset that is less than the value of the 3rd -** parameter, then the resulting string will contain embedded NULs and the -** result of expressions operating on strings with embedded NULs is undefined. -** ^If the 4th parameter to the sqlite3_result_text* interfaces -** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that -** function as the destructor on the text or BLOB result when it has -** finished using that result. -** ^If the 4th parameter to the sqlite3_result_text* interfaces or to -** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite -** assumes that the text or BLOB result is in constant space and does not -** copy the content of the parameter nor call a destructor on the content -** when it has finished using that result. -** ^If the 4th parameter to the sqlite3_result_text* interfaces -** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT -** then SQLite makes a copy of the result into space obtained -** from [sqlite3_malloc()] before it returns. -** -** ^The sqlite3_result_value() interface sets the result of -** the application-defined function to be a copy of the -** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The -** sqlite3_result_value() interface makes a copy of the [sqlite3_value] -** so that the [sqlite3_value] specified in the parameter may change or -** be deallocated after sqlite3_result_value() returns without harm. -** ^A [protected sqlite3_value] object may always be used where an -** [unprotected sqlite3_value] object is required, so either -** kind of [sqlite3_value] object can be used with this interface. -** -** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an -** SQL NULL value, just like [sqlite3_result_null(C)], except that it -** also associates the host-language pointer P or type T with that -** NULL value such that the pointer can be retrieved within an -** [application-defined SQL function] using [sqlite3_value_pointer()]. -** ^If the D parameter is not NULL, then it is a pointer to a destructor -** for the P parameter. ^SQLite invokes D with P as its only argument -** when SQLite is finished with P. The T parameter should be a static -** string and preferably a string literal. The sqlite3_result_pointer() -** routine is part of the [pointer passing interface] added for SQLite 3.20.0. -** -** If these routines are called from within the different thread -** than the one containing the application-defined function that received -** the [sqlite3_context] pointer, the results are undefined. -*/ -SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); -SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*, - sqlite3_uint64,void(*)(void*)); -SQLITE_API void sqlite3_result_double(sqlite3_context*, double); -SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int); -SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int); -SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*); -SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*); -SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int); -SQLITE_API void sqlite3_result_int(sqlite3_context*, int); -SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); -SQLITE_API void sqlite3_result_null(sqlite3_context*); -SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); -SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64, - void(*)(void*), unsigned char encoding); -SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); -SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); -SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); -SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*); -SQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*)); -SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n); -SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n); - - -/* -** CAPI3REF: Setting The Subtype Of An SQL Function -** METHOD: sqlite3_context -** -** The sqlite3_result_subtype(C,T) function causes the subtype of -** the result from the [application-defined SQL function] with -** [sqlite3_context] C to be the value T. Only the lower 8 bits -** of the subtype T are preserved in current versions of SQLite; -** higher order bits are discarded. -** The number of subtype bytes preserved by SQLite might increase -** in future releases of SQLite. -*/ -SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int); - -/* -** CAPI3REF: Define New Collating Sequences -** METHOD: sqlite3 -** -** ^These functions add, remove, or modify a [collation] associated -** with the [database connection] specified as the first argument. -** -** ^The name of the collation is a UTF-8 string -** for sqlite3_create_collation() and sqlite3_create_collation_v2() -** and a UTF-16 string in native byte order for sqlite3_create_collation16(). -** ^Collation names that compare equal according to [sqlite3_strnicmp()] are -** considered to be the same name. -** -** ^(The third argument (eTextRep) must be one of the constants: -**
    -**
  • [SQLITE_UTF8], -**
  • [SQLITE_UTF16LE], -**
  • [SQLITE_UTF16BE], -**
  • [SQLITE_UTF16], or -**
  • [SQLITE_UTF16_ALIGNED]. -**
)^ -** ^The eTextRep argument determines the encoding of strings passed -** to the collating function callback, xCallback. -** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep -** force strings to be UTF16 with native byte order. -** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin -** on an even byte address. -** -** ^The fourth argument, pArg, is an application data pointer that is passed -** through as the first argument to the collating function callback. -** -** ^The fifth argument, xCallback, is a pointer to the collating function. -** ^Multiple collating functions can be registered using the same name but -** with different eTextRep parameters and SQLite will use whichever -** function requires the least amount of data transformation. -** ^If the xCallback argument is NULL then the collating function is -** deleted. ^When all collating functions having the same name are deleted, -** that collation is no longer usable. -** -** ^The collating function callback is invoked with a copy of the pArg -** application data pointer and with two strings in the encoding specified -** by the eTextRep argument. The collating function must return an -** integer that is negative, zero, or positive -** if the first string is less than, equal to, or greater than the second, -** respectively. A collating function must always return the same answer -** given the same inputs. If two or more collating functions are registered -** to the same collation name (using different eTextRep values) then all -** must give an equivalent answer when invoked with equivalent strings. -** The collating function must obey the following properties for all -** strings A, B, and C: -** -**
    -**
  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_HAS_CODEC -/* -** Specify the key for an encrypted database. This routine should be -** called right after sqlite3_open(). -** -** The code to implement this API is not available in the public release -** of SQLite. -*/ -SQLITE_API int sqlite3_key( - sqlite3 *db, /* Database to be rekeyed */ - const void *pKey, int nKey /* The key */ -); -SQLITE_API int sqlite3_key_v2( - sqlite3 *db, /* Database to be rekeyed */ - const char *zDbName, /* Name of the database */ - const void *pKey, int nKey /* The key */ -); - -/* -** Change the key on an open database. If the current database is not -** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the -** database is decrypted. -** -** The code to implement this API is not available in the public release -** of SQLite. -*/ -SQLITE_API int sqlite3_rekey( - sqlite3 *db, /* Database to be rekeyed */ - const void *pKey, int nKey /* The new key */ -); -SQLITE_API int sqlite3_rekey_v2( - sqlite3 *db, /* Database to be rekeyed */ - const char *zDbName, /* Name of the database */ - const void *pKey, int nKey /* The new key */ -); - -/* -** Specify the activation key for a SEE database. Unless -** activated, none of the SEE routines will work. -*/ -SQLITE_API void sqlite3_activate_see( - const char *zPassPhrase /* Activation phrase */ -); -#endif - -#ifdef SQLITE_ENABLE_CEROD -/* -** Specify the activation key for a CEROD database. Unless -** activated, none of the CEROD routines will work. -*/ -SQLITE_API void sqlite3_activate_cerod( - const char *zPassPhrase /* Activation phrase */ -); -#endif - -/* -** CAPI3REF: Suspend Execution For A Short Time -** -** The sqlite3_sleep() function causes the current thread to suspend execution -** for at least a number of milliseconds specified in its parameter. -** -** If the operating system does not support sleep requests with -** millisecond time resolution, then the time will be rounded up to -** the nearest second. The number of milliseconds of sleep actually -** requested from the operating system is returned. -** -** ^SQLite implements this interface by calling the xSleep() -** method of the default [sqlite3_vfs] object. If the xSleep() method -** of the default VFS is not implemented correctly, or not implemented at -** all, then the behavior of sqlite3_sleep() may deviate from the description -** in the previous paragraphs. -*/ -SQLITE_API int sqlite3_sleep(int); - -/* -** CAPI3REF: Name Of The Folder Holding Temporary Files -** -** ^(If this global variable is made to point to a string which is -** the name of a folder (a.k.a. directory), then all temporary files -** created by SQLite when using a built-in [sqlite3_vfs | VFS] -** will be placed in that directory.)^ ^If this variable -** is a NULL pointer, then SQLite performs a search for an appropriate -** temporary file directory. -** -** Applications are strongly discouraged from using this global variable. -** It is required to set a temporary folder on Windows Runtime (WinRT). -** But for all other platforms, it is highly recommended that applications -** neither read nor write this variable. This global variable is a relic -** that exists for backwards compatibility of legacy applications and should -** be avoided in new projects. -** -** It is not safe to read or modify this variable in more than one -** thread at a time. It is not safe to read or modify this variable -** if a [database connection] is being used at the same time in a separate -** thread. -** It is intended that this variable be set once -** as part of process initialization and before any SQLite interface -** routines have been called and that this variable remain unchanged -** thereafter. -** -** ^The [temp_store_directory pragma] may modify this variable and cause -** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, -** the [temp_store_directory pragma] always assumes that any string -** that this variable points to is held in memory obtained from -** [sqlite3_malloc] and the pragma may attempt to free that memory -** using [sqlite3_free]. -** Hence, if this variable is modified directly, either it should be -** made NULL or made to point to memory obtained from [sqlite3_malloc] -** or else the use of the [temp_store_directory pragma] should be avoided. -** Except when requested by the [temp_store_directory pragma], SQLite -** does not free the memory that sqlite3_temp_directory points to. If -** the application wants that memory to be freed, it must do -** so itself, taking care to only do so after all [database connection] -** objects have been destroyed. -** -** Note to Windows Runtime users: The temporary directory must be set -** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various -** features that require the use of temporary files may fail. Here is an -** example of how to do this using C++ with the Windows Runtime: -** -**
-** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
-**       TemporaryFolder->Path->Data();
-** char zPathBuf[MAX_PATH + 1];
-** memset(zPathBuf, 0, sizeof(zPathBuf));
-** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
-**       NULL, NULL);
-** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
-** 
-*/ -SQLITE_API char *sqlite3_temp_directory; - -/* -** CAPI3REF: Name Of The Folder Holding Database Files -** -** ^(If this global variable is made to point to a string which is -** the name of a folder (a.k.a. directory), then all database files -** specified with a relative pathname and created or accessed by -** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed -** to be relative to that directory.)^ ^If this variable is a NULL -** pointer, then SQLite assumes that all database files specified -** with a relative pathname are relative to the current directory -** for the process. Only the windows VFS makes use of this global -** variable; it is ignored by the unix VFS. -** -** Changing the value of this variable while a database connection is -** open can result in a corrupt database. -** -** It is not safe to read or modify this variable in more than one -** thread at a time. It is not safe to read or modify this variable -** if a [database connection] is being used at the same time in a separate -** thread. -** It is intended that this variable be set once -** as part of process initialization and before any SQLite interface -** routines have been called and that this variable remain unchanged -** thereafter. -** -** ^The [data_store_directory pragma] may modify this variable and cause -** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore, -** the [data_store_directory pragma] always assumes that any string -** that this variable points to is held in memory obtained from -** [sqlite3_malloc] and the pragma may attempt to free that memory -** using [sqlite3_free]. -** Hence, if this variable is modified directly, either it should be -** made NULL or made to point to memory obtained from [sqlite3_malloc] -** or else the use of the [data_store_directory pragma] should be avoided. -*/ -SQLITE_API char *sqlite3_data_directory; - -/* -** CAPI3REF: Test For Auto-Commit Mode -** KEYWORDS: {autocommit mode} -** METHOD: sqlite3 -** -** ^The sqlite3_get_autocommit() interface returns non-zero or -** zero if the given database connection is or is not in autocommit mode, -** respectively. ^Autocommit mode is on by default. -** ^Autocommit mode is disabled by a [BEGIN] statement. -** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK]. -** -** If certain kinds of errors occur on a statement within a multi-statement -** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR], -** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the -** transaction might be rolled back automatically. The only way to -** find out whether SQLite automatically rolled back the transaction after -** an error is to use this function. -** -** If another thread changes the autocommit status of the database -** connection while this routine is running, then the return value -** is undefined. -*/ -SQLITE_API int sqlite3_get_autocommit(sqlite3*); - -/* -** CAPI3REF: Find The Database Handle Of A Prepared Statement -** METHOD: sqlite3_stmt -** -** ^The sqlite3_db_handle interface returns the [database connection] handle -** to which a [prepared statement] belongs. ^The [database connection] -** returned by sqlite3_db_handle is the same [database connection] -** that was the first argument -** to the [sqlite3_prepare_v2()] call (or its variants) that was used to -** create the statement in the first place. -*/ -SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*); - -/* -** CAPI3REF: Return The Filename For A Database Connection -** METHOD: sqlite3 -** -** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename -** associated with database N of connection D. ^The main database file -** has the name "main". If there is no attached database N on the database -** connection D, or if database N is a temporary or in-memory database, then -** a NULL pointer is returned. -** -** ^The filename returned by this function is the output of the -** xFullPathname method of the [VFS]. ^In other words, the filename -** will be an absolute pathname, even if the filename used -** to open the database originally was a URI or relative pathname. -*/ -SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName); - -/* -** CAPI3REF: Determine if a database is read-only -** METHOD: sqlite3 -** -** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N -** of connection D is read-only, 0 if it is read/write, or -1 if N is not -** the name of a database on connection D. -*/ -SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName); - -/* -** CAPI3REF: Find the next prepared statement -** METHOD: sqlite3 -** -** ^This interface returns a pointer to the next [prepared statement] after -** pStmt associated with the [database connection] pDb. ^If pStmt is NULL -** then this interface returns a pointer to the first prepared statement -** associated with the database connection pDb. ^If no prepared statement -** satisfies the conditions of this routine, it returns NULL. -** -** The [database connection] pointer D in a call to -** [sqlite3_next_stmt(D,S)] must refer to an open database -** connection and in particular must not be a NULL pointer. -*/ -SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); - -/* -** CAPI3REF: Commit And Rollback Notification Callbacks -** METHOD: sqlite3 -** -** ^The sqlite3_commit_hook() interface registers a callback -** function to be invoked whenever a transaction is [COMMIT | committed]. -** ^Any callback set by a previous call to sqlite3_commit_hook() -** for the same database connection is overridden. -** ^The sqlite3_rollback_hook() interface registers a callback -** function to be invoked whenever a transaction is [ROLLBACK | rolled back]. -** ^Any callback set by a previous call to sqlite3_rollback_hook() -** for the same database connection is overridden. -** ^The pArg argument is passed through to the callback. -** ^If the callback on a commit hook function returns non-zero, -** then the commit is converted into a rollback. -** -** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions -** return the P argument from the previous call of the same function -** on the same [database connection] D, or NULL for -** the first call for each function on D. -** -** The commit and rollback hook callbacks are not reentrant. -** The callback implementation must not do anything that will modify -** the database connection that invoked the callback. Any actions -** to modify the database connection must be deferred until after the -** completion of the [sqlite3_step()] call that triggered the commit -** or rollback hook in the first place. -** Note that running any other SQL statements, including SELECT statements, -** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify -** the database connections for the meaning of "modify" in this paragraph. -** -** ^Registering a NULL function disables the callback. -** -** ^When the commit hook callback routine returns zero, the [COMMIT] -** operation is allowed to continue normally. ^If the commit hook -** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK]. -** ^The rollback hook is invoked on a rollback that results from a commit -** hook returning non-zero, just as it would be with any other rollback. -** -** ^For the purposes of this API, a transaction is said to have been -** rolled back if an explicit "ROLLBACK" statement is executed, or -** an error or constraint causes an implicit rollback to occur. -** ^The rollback callback is not invoked if a transaction is -** automatically rolled back because the database connection is closed. -** -** See also the [sqlite3_update_hook()] interface. -*/ -SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); -SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); - -/* -** CAPI3REF: Data Change Notification Callbacks -** METHOD: sqlite3 -** -** ^The sqlite3_update_hook() interface registers a callback function -** with the [database connection] identified by the first argument -** to be invoked whenever a row is updated, inserted or deleted in -** a [rowid table]. -** ^Any callback set by a previous call to this function -** for the same database connection is overridden. -** -** ^The second argument is a pointer to the function to invoke when a -** row is updated, inserted or deleted in a rowid table. -** ^The first argument to the callback is a copy of the third argument -** to sqlite3_update_hook(). -** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], -** or [SQLITE_UPDATE], depending on the operation that caused the callback -** to be invoked. -** ^The third and fourth arguments to the callback contain pointers to the -** database and table name containing the affected row. -** ^The final callback parameter is the [rowid] of the row. -** ^In the case of an update, this is the [rowid] after the update takes place. -** -** ^(The update hook is not invoked when internal system tables are -** modified (i.e. sqlite_master and sqlite_sequence).)^ -** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified. -** -** ^In the current implementation, the update hook -** is not invoked when conflicting rows are deleted because of an -** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook -** invoked when rows are deleted using the [truncate optimization]. -** The exceptions defined in this paragraph might change in a future -** release of SQLite. -** -** The update hook implementation must not do anything that will modify -** the database connection that invoked the update hook. Any actions -** to modify the database connection must be deferred until after the -** completion of the [sqlite3_step()] call that triggered the update hook. -** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their -** database connections for the meaning of "modify" in this paragraph. -** -** ^The sqlite3_update_hook(D,C,P) function -** returns the P argument from the previous call -** on the same [database connection] D, or NULL for -** the first call on D. -** -** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()], -** and [sqlite3_preupdate_hook()] interfaces. -*/ -SQLITE_API void *sqlite3_update_hook( - sqlite3*, - void(*)(void *,int ,char const *,char const *,sqlite3_int64), - void* -); - -/* -** CAPI3REF: Enable Or Disable Shared Pager Cache -** -** ^(This routine enables or disables the sharing of the database cache -** and schema data structures between [database connection | connections] -** to the same database. Sharing is enabled if the argument is true -** and disabled if the argument is false.)^ -** -** ^Cache sharing is enabled and disabled for an entire process. -** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]). -** In prior versions of SQLite, -** sharing was enabled or disabled for each thread separately. -** -** ^(The cache sharing mode set by this interface effects all subsequent -** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. -** Existing database connections continue use the sharing mode -** that was in effect at the time they were opened.)^ -** -** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled -** successfully. An [error code] is returned otherwise.)^ -** -** ^Shared cache is disabled by default. But this might change in -** future releases of SQLite. Applications that care about shared -** cache setting should set it explicitly. -** -** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0 -** and will always return SQLITE_MISUSE. On those systems, -** shared cache mode should be enabled per-database connection via -** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE]. -** -** This interface is threadsafe on processors where writing a -** 32-bit integer is atomic. -** -** See Also: [SQLite Shared-Cache Mode] -*/ -SQLITE_API int sqlite3_enable_shared_cache(int); - -/* -** CAPI3REF: Attempt To Free Heap Memory -** -** ^The sqlite3_release_memory() interface attempts to free N bytes -** of heap memory by deallocating non-essential memory allocations -** held by the database library. Memory used to cache database -** pages to improve performance is an example of non-essential memory. -** ^sqlite3_release_memory() returns the number of bytes actually freed, -** which might be more or less than the amount requested. -** ^The sqlite3_release_memory() routine is a no-op returning zero -** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT]. -** -** See also: [sqlite3_db_release_memory()] -*/ -SQLITE_API int sqlite3_release_memory(int); - -/* -** CAPI3REF: Free Memory Used By A Database Connection -** METHOD: sqlite3 -** -** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap -** memory as possible from database connection D. Unlike the -** [sqlite3_release_memory()] interface, this interface is in effect even -** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is -** omitted. -** -** See also: [sqlite3_release_memory()] -*/ -SQLITE_API int sqlite3_db_release_memory(sqlite3*); - -/* -** CAPI3REF: Impose A Limit On Heap Size -** -** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the -** soft limit on the amount of heap memory that may be allocated by SQLite. -** ^SQLite strives to keep heap memory utilization below the soft heap -** limit by reducing the number of pages held in the page cache -** as heap memory usages approaches the limit. -** ^The soft heap limit is "soft" because even though SQLite strives to stay -** below the limit, it will exceed the limit rather than generate -** an [SQLITE_NOMEM] error. In other words, the soft heap limit -** is advisory only. -** -** ^The return value from sqlite3_soft_heap_limit64() is the size of -** the soft heap limit prior to the call, or negative in the case of an -** error. ^If the argument N is negative -** then no change is made to the soft heap limit. Hence, the current -** size of the soft heap limit can be determined by invoking -** sqlite3_soft_heap_limit64() with a negative argument. -** -** ^If the argument N is zero then the soft heap limit is disabled. -** -** ^(The soft heap limit is not enforced in the current implementation -** if one or more of following conditions are true: -** -**
    -**
  • The soft heap limit is set to zero. -**
  • Memory accounting is disabled using a combination of the -** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and -** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option. -**
  • An alternative page cache implementation is specified using -** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...). -**
  • The page cache allocates from its own memory pool supplied -** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than -** from the heap. -**
)^ -** -** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]), -** the soft heap limit is enforced -** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT] -** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT], -** the soft heap limit is enforced on every memory allocation. Without -** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced -** when memory is allocated by the page cache. Testing suggests that because -** the page cache is the predominate memory user in SQLite, most -** applications will achieve adequate soft heap limit enforcement without -** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT]. -** -** The circumstances under which SQLite will enforce the soft heap limit may -** changes in future releases of SQLite. -*/ -SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N); - -/* -** CAPI3REF: Deprecated Soft Heap Limit Interface -** DEPRECATED -** -** This is a deprecated version of the [sqlite3_soft_heap_limit64()] -** interface. This routine is provided for historical compatibility -** only. All new applications should use the -** [sqlite3_soft_heap_limit64()] interface rather than this one. -*/ -SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N); - - -/* -** CAPI3REF: Extract Metadata About A Column Of A Table -** METHOD: sqlite3 -** -** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns -** information about column C of table T in database D -** on [database connection] X.)^ ^The sqlite3_table_column_metadata() -** interface returns SQLITE_OK and fills in the non-NULL pointers in -** the final five arguments with appropriate values if the specified -** column exists. ^The sqlite3_table_column_metadata() interface returns -** SQLITE_ERROR and if the specified column does not exist. -** ^If the column-name parameter to sqlite3_table_column_metadata() is a -** NULL pointer, then this routine simply checks for the existence of the -** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it -** does not. If the table name parameter T in a call to -** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is -** undefined behavior. -** -** ^The column is identified by the second, third and fourth parameters to -** this function. ^(The second parameter is either the name of the database -** (i.e. "main", "temp", or an attached database) containing the specified -** table or NULL.)^ ^If it is NULL, then all attached databases are searched -** for the table using the same algorithm used by the database engine to -** resolve unqualified table references. -** -** ^The third and fourth parameters to this function are the table and column -** name of the desired column, respectively. -** -** ^Metadata is returned by writing to the memory locations passed as the 5th -** and subsequent parameters to this function. ^Any of these arguments may be -** NULL, in which case the corresponding element of metadata is omitted. -** -** ^(
-** -**
Parameter Output
Type
Description -** -**
5th const char* Data type -**
6th const char* Name of default collation sequence -**
7th int True if column has a NOT NULL constraint -**
8th int True if column is part of the PRIMARY KEY -**
9th int True if column is [AUTOINCREMENT] -**
-**
)^ -** -** ^The memory pointed to by the character pointers returned for the -** declaration type and collation sequence is valid until the next -** call to any SQLite API function. -** -** ^If the specified table is actually a view, an [error code] is returned. -** -** ^If the specified column is "rowid", "oid" or "_rowid_" and the table -** is not a [WITHOUT ROWID] table and an -** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output -** parameters are set for the explicitly declared column. ^(If there is no -** [INTEGER PRIMARY KEY] column, then the outputs -** for the [rowid] are set as follows: -** -**
-**     data type: "INTEGER"
-**     collation sequence: "BINARY"
-**     not null: 0
-**     primary key: 1
-**     auto increment: 0
-** 
)^ -** -** ^This function causes all database schemas to be read from disk and -** parsed, if that has not already been done, and returns an error if -** any errors are encountered while loading the schema. -*/ -SQLITE_API int sqlite3_table_column_metadata( - sqlite3 *db, /* Connection handle */ - const char *zDbName, /* Database name or NULL */ - const char *zTableName, /* Table name */ - const char *zColumnName, /* Column name */ - char const **pzDataType, /* OUTPUT: Declared data type */ - char const **pzCollSeq, /* OUTPUT: Collation sequence name */ - int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ - int *pPrimaryKey, /* OUTPUT: True if column part of PK */ - int *pAutoinc /* OUTPUT: True if column is auto-increment */ -); - -/* -** CAPI3REF: Load An Extension -** METHOD: sqlite3 -** -** ^This interface loads an SQLite extension library from the named file. -** -** ^The sqlite3_load_extension() interface attempts to load an -** [SQLite extension] library contained in the file zFile. If -** the file cannot be loaded directly, attempts are made to load -** with various operating-system specific extensions added. -** So for example, if "samplelib" cannot be loaded, then names like -** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might -** be tried also. -** -** ^The entry point is zProc. -** ^(zProc may be 0, in which case SQLite will try to come up with an -** entry point name on its own. It first tries "sqlite3_extension_init". -** If that does not work, it constructs a name "sqlite3_X_init" where the -** X is consists of the lower-case equivalent of all ASCII alphabetic -** characters in the filename from the last "/" to the first following -** "." and omitting any initial "lib".)^ -** ^The sqlite3_load_extension() interface returns -** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. -** ^If an error occurs and pzErrMsg is not 0, then the -** [sqlite3_load_extension()] interface shall attempt to -** fill *pzErrMsg with error message text stored in memory -** obtained from [sqlite3_malloc()]. The calling function -** should free this memory by calling [sqlite3_free()]. -** -** ^Extension loading must be enabled using -** [sqlite3_enable_load_extension()] or -** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL) -** prior to calling this API, -** otherwise an error will be returned. -** -** Security warning: It is recommended that the -** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this -** interface. The use of the [sqlite3_enable_load_extension()] interface -** should be avoided. This will keep the SQL function [load_extension()] -** disabled and prevent SQL injections from giving attackers -** access to extension loading capabilities. -** -** See also the [load_extension() SQL function]. -*/ -SQLITE_API int sqlite3_load_extension( - sqlite3 *db, /* Load the extension into this database connection */ - const char *zFile, /* Name of the shared library containing extension */ - const char *zProc, /* Entry point. Derived from zFile if 0 */ - char **pzErrMsg /* Put error message here if not 0 */ -); - -/* -** CAPI3REF: Enable Or Disable Extension Loading -** METHOD: sqlite3 -** -** ^So as not to open security holes in older applications that are -** unprepared to deal with [extension loading], and as a means of disabling -** [extension loading] while evaluating user-entered SQL, the following API -** is provided to turn the [sqlite3_load_extension()] mechanism on and off. -** -** ^Extension loading is off by default. -** ^Call the sqlite3_enable_load_extension() routine with onoff==1 -** to turn extension loading on and call it with onoff==0 to turn -** it back off again. -** -** ^This interface enables or disables both the C-API -** [sqlite3_load_extension()] and the SQL function [load_extension()]. -** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..) -** to enable or disable only the C-API.)^ -** -** Security warning: It is recommended that extension loading -** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method -** rather than this interface, so the [load_extension()] SQL function -** remains disabled. This will prevent SQL injections from giving attackers -** access to extension loading capabilities. -*/ -SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); - -/* -** CAPI3REF: Automatically Load Statically Linked Extensions -** -** ^This interface causes the xEntryPoint() function to be invoked for -** each new [database connection] that is created. The idea here is that -** xEntryPoint() is the entry point for a statically linked [SQLite extension] -** that is to be automatically loaded into all new database connections. -** -** ^(Even though the function prototype shows that xEntryPoint() takes -** no arguments and returns void, SQLite invokes xEntryPoint() with three -** arguments and expects an integer result as if the signature of the -** entry point where as follows: -** -**
-**    int xEntryPoint(
-**      sqlite3 *db,
-**      const char **pzErrMsg,
-**      const struct sqlite3_api_routines *pThunk
-**    );
-** 
)^ -** -** If the xEntryPoint routine encounters an error, it should make *pzErrMsg -** point to an appropriate error message (obtained from [sqlite3_mprintf()]) -** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg -** is NULL before calling the xEntryPoint(). ^SQLite will invoke -** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any -** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()], -** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail. -** -** ^Calling sqlite3_auto_extension(X) with an entry point X that is already -** on the list of automatic extensions is a harmless no-op. ^No entry point -** will be called more than once for each database connection that is opened. -** -** See also: [sqlite3_reset_auto_extension()] -** and [sqlite3_cancel_auto_extension()] -*/ -SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void)); - -/* -** CAPI3REF: Cancel Automatic Extension Loading -** -** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the -** initialization routine X that was registered using a prior call to -** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)] -** routine returns 1 if initialization routine X was successfully -** unregistered and it returns 0 if X was not on the list of initialization -** routines. -*/ -SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void)); - -/* -** CAPI3REF: Reset Automatic Extension Loading -** -** ^This interface disables all automatic extensions previously -** registered using [sqlite3_auto_extension()]. -*/ -SQLITE_API void sqlite3_reset_auto_extension(void); - -/* -** The interface to the virtual-table mechanism is currently considered -** to be experimental. The interface might change in incompatible ways. -** If this is a problem for you, do not use the interface at this time. -** -** When the virtual-table mechanism stabilizes, we will declare the -** interface fixed, support it indefinitely, and remove this comment. -*/ - -/* -** Structures used by the virtual table interface -*/ -typedef struct sqlite3_vtab sqlite3_vtab; -typedef struct sqlite3_index_info sqlite3_index_info; -typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; -typedef struct sqlite3_module sqlite3_module; - -/* -** CAPI3REF: Virtual Table Object -** KEYWORDS: sqlite3_module {virtual table module} -** -** This structure, sometimes called a "virtual table module", -** defines the implementation of a [virtual tables]. -** This structure consists mostly of methods for the module. -** -** ^A virtual table module is created by filling in a persistent -** instance of this structure and passing a pointer to that instance -** to [sqlite3_create_module()] or [sqlite3_create_module_v2()]. -** ^The registration remains valid until it is replaced by a different -** module or until the [database connection] closes. The content -** of this structure must not change while it is registered with -** any database connection. -*/ -struct sqlite3_module { - int iVersion; - int (*xCreate)(sqlite3*, void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVTab, char**); - int (*xConnect)(sqlite3*, void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVTab, char**); - int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); - int (*xDisconnect)(sqlite3_vtab *pVTab); - int (*xDestroy)(sqlite3_vtab *pVTab); - int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); - int (*xClose)(sqlite3_vtab_cursor*); - int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, - int argc, sqlite3_value **argv); - int (*xNext)(sqlite3_vtab_cursor*); - int (*xEof)(sqlite3_vtab_cursor*); - int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); - int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); - int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); - int (*xBegin)(sqlite3_vtab *pVTab); - int (*xSync)(sqlite3_vtab *pVTab); - int (*xCommit)(sqlite3_vtab *pVTab); - int (*xRollback)(sqlite3_vtab *pVTab); - int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, - void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), - void **ppArg); - int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); - /* The methods above are in version 1 of the sqlite_module object. Those - ** below are for version 2 and greater. */ - int (*xSavepoint)(sqlite3_vtab *pVTab, int); - int (*xRelease)(sqlite3_vtab *pVTab, int); - int (*xRollbackTo)(sqlite3_vtab *pVTab, int); -}; - -/* -** CAPI3REF: Virtual Table Indexing Information -** KEYWORDS: sqlite3_index_info -** -** The sqlite3_index_info structure and its substructures is used as part -** of the [virtual table] interface to -** pass information into and receive the reply from the [xBestIndex] -** method of a [virtual table module]. The fields under **Inputs** are the -** inputs to xBestIndex and are read-only. xBestIndex inserts its -** results into the **Outputs** fields. -** -** ^(The aConstraint[] array records WHERE clause constraints of the form: -** -**
column OP expr
-** -** where OP is =, <, <=, >, or >=.)^ ^(The particular operator is -** stored in aConstraint[].op using one of the -** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^ -** ^(The index of the column is stored in -** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the -** expr on the right-hand side can be evaluated (and thus the constraint -** is usable) and false if it cannot.)^ -** -** ^The optimizer automatically inverts terms of the form "expr OP column" -** and makes other simplifications to the WHERE clause in an attempt to -** get as many WHERE clause terms into the form shown above as possible. -** ^The aConstraint[] array only reports WHERE clause terms that are -** relevant to the particular virtual table being queried. -** -** ^Information about the ORDER BY clause is stored in aOrderBy[]. -** ^Each term of aOrderBy records a column of the ORDER BY clause. -** -** The colUsed field indicates which columns of the virtual table may be -** required by the current scan. Virtual table columns are numbered from -** zero in the order in which they appear within the CREATE TABLE statement -** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62), -** the corresponding bit is set within the colUsed mask if the column may be -** required by SQLite. If the table has at least 64 columns and any column -** to the right of the first 63 is required, then bit 63 of colUsed is also -** set. In other words, column iCol may be required if the expression -** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to -** non-zero. -** -** The [xBestIndex] method must fill aConstraintUsage[] with information -** about what parameters to pass to xFilter. ^If argvIndex>0 then -** the right-hand side of the corresponding aConstraint[] is evaluated -** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit -** is true, then the constraint is assumed to be fully handled by the -** virtual table and is not checked again by SQLite.)^ -** -** ^The idxNum and idxPtr values are recorded and passed into the -** [xFilter] method. -** ^[sqlite3_free()] is used to free idxPtr if and only if -** needToFreeIdxPtr is true. -** -** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in -** the correct order to satisfy the ORDER BY clause so that no separate -** sorting step is required. -** -** ^The estimatedCost value is an estimate of the cost of a particular -** strategy. A cost of N indicates that the cost of the strategy is similar -** to a linear scan of an SQLite table with N rows. A cost of log(N) -** indicates that the expense of the operation is similar to that of a -** binary search on a unique indexed field of an SQLite table with N rows. -** -** ^The estimatedRows value is an estimate of the number of rows that -** will be returned by the strategy. -** -** The xBestIndex method may optionally populate the idxFlags field with a -** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag - -** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite -** assumes that the strategy may visit at most one row. -** -** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then -** SQLite also assumes that if a call to the xUpdate() method is made as -** part of the same statement to delete or update a virtual table row and the -** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback -** any database changes. In other words, if the xUpdate() returns -** SQLITE_CONSTRAINT, the database contents must be exactly as they were -** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not -** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by -** the xUpdate method are automatically rolled back by SQLite. -** -** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info -** structure for SQLite [version 3.8.2] ([dateof:3.8.2]). -** If a virtual table extension is -** used with an SQLite version earlier than 3.8.2, the results of attempting -** to read or write the estimatedRows field are undefined (but are likely -** to included crashing the application). The estimatedRows field should -** therefore only be used if [sqlite3_libversion_number()] returns a -** value greater than or equal to 3008002. Similarly, the idxFlags field -** was added for [version 3.9.0] ([dateof:3.9.0]). -** It may therefore only be used if -** sqlite3_libversion_number() returns a value greater than or equal to -** 3009000. -*/ -struct sqlite3_index_info { - /* Inputs */ - int nConstraint; /* Number of entries in aConstraint */ - struct sqlite3_index_constraint { - int iColumn; /* Column constrained. -1 for ROWID */ - unsigned char op; /* Constraint operator */ - unsigned char usable; /* True if this constraint is usable */ - int iTermOffset; /* Used internally - xBestIndex should ignore */ - } *aConstraint; /* Table of WHERE clause constraints */ - int nOrderBy; /* Number of terms in the ORDER BY clause */ - struct sqlite3_index_orderby { - int iColumn; /* Column number */ - unsigned char desc; /* True for DESC. False for ASC. */ - } *aOrderBy; /* The ORDER BY clause */ - /* Outputs */ - struct sqlite3_index_constraint_usage { - int argvIndex; /* if >0, constraint is part of argv to xFilter */ - unsigned char omit; /* Do not code a test for this constraint */ - } *aConstraintUsage; - int idxNum; /* Number used to identify the index */ - char *idxStr; /* String, possibly obtained from sqlite3_malloc */ - int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ - int orderByConsumed; /* True if output is already ordered */ - double estimatedCost; /* Estimated cost of using this index */ - /* Fields below are only available in SQLite 3.8.2 and later */ - sqlite3_int64 estimatedRows; /* Estimated number of rows returned */ - /* Fields below are only available in SQLite 3.9.0 and later */ - int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */ - /* Fields below are only available in SQLite 3.10.0 and later */ - sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */ -}; - -/* -** CAPI3REF: Virtual Table Scan Flags -*/ -#define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */ - -/* -** CAPI3REF: Virtual Table Constraint Operator Codes -** -** These macros defined the allowed values for the -** [sqlite3_index_info].aConstraint[].op field. Each value represents -** an operator that is part of a constraint term in the wHERE clause of -** a query that uses a [virtual table]. -*/ -#define SQLITE_INDEX_CONSTRAINT_EQ 2 -#define SQLITE_INDEX_CONSTRAINT_GT 4 -#define SQLITE_INDEX_CONSTRAINT_LE 8 -#define SQLITE_INDEX_CONSTRAINT_LT 16 -#define SQLITE_INDEX_CONSTRAINT_GE 32 -#define SQLITE_INDEX_CONSTRAINT_MATCH 64 -#define SQLITE_INDEX_CONSTRAINT_LIKE 65 -#define SQLITE_INDEX_CONSTRAINT_GLOB 66 -#define SQLITE_INDEX_CONSTRAINT_REGEXP 67 -#define SQLITE_INDEX_CONSTRAINT_NE 68 -#define SQLITE_INDEX_CONSTRAINT_ISNOT 69 -#define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70 -#define SQLITE_INDEX_CONSTRAINT_ISNULL 71 -#define SQLITE_INDEX_CONSTRAINT_IS 72 - -/* -** CAPI3REF: Register A Virtual Table Implementation -** METHOD: sqlite3 -** -** ^These routines are used to register a new [virtual table module] name. -** ^Module names must be registered before -** creating a new [virtual table] using the module and before using a -** preexisting [virtual table] for the module. -** -** ^The module name is registered on the [database connection] specified -** by the first parameter. ^The name of the module is given by the -** second parameter. ^The third parameter is a pointer to -** the implementation of the [virtual table module]. ^The fourth -** parameter is an arbitrary client data pointer that is passed through -** into the [xCreate] and [xConnect] methods of the virtual table module -** when a new virtual table is be being created or reinitialized. -** -** ^The sqlite3_create_module_v2() interface has a fifth parameter which -** is a pointer to a destructor for the pClientData. ^SQLite will -** invoke the destructor function (if it is not NULL) when SQLite -** no longer needs the pClientData pointer. ^The destructor will also -** be invoked if the call to sqlite3_create_module_v2() fails. -** ^The sqlite3_create_module() -** interface is equivalent to sqlite3_create_module_v2() with a NULL -** destructor. -*/ -SQLITE_API int sqlite3_create_module( - sqlite3 *db, /* SQLite connection to register module with */ - const char *zName, /* Name of the module */ - const sqlite3_module *p, /* Methods for the module */ - void *pClientData /* Client data for xCreate/xConnect */ -); -SQLITE_API int sqlite3_create_module_v2( - sqlite3 *db, /* SQLite connection to register module with */ - const char *zName, /* Name of the module */ - const sqlite3_module *p, /* Methods for the module */ - void *pClientData, /* Client data for xCreate/xConnect */ - void(*xDestroy)(void*) /* Module destructor function */ -); - -/* -** CAPI3REF: Virtual Table Instance Object -** KEYWORDS: sqlite3_vtab -** -** Every [virtual table module] implementation uses a subclass -** of this object to describe a particular instance -** of the [virtual table]. Each subclass will -** be tailored to the specific needs of the module implementation. -** The purpose of this superclass is to define certain fields that are -** common to all module implementations. -** -** ^Virtual tables methods can set an error message by assigning a -** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should -** take care that any prior string is freed by a call to [sqlite3_free()] -** prior to assigning a new string to zErrMsg. ^After the error message -** is delivered up to the client application, the string will be automatically -** freed by sqlite3_free() and the zErrMsg field will be zeroed. -*/ -struct sqlite3_vtab { - const sqlite3_module *pModule; /* The module for this virtual table */ - int nRef; /* Number of open cursors */ - char *zErrMsg; /* Error message from sqlite3_mprintf() */ - /* Virtual table implementations will typically add additional fields */ -}; - -/* -** CAPI3REF: Virtual Table Cursor Object -** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor} -** -** Every [virtual table module] implementation uses a subclass of the -** following structure to describe cursors that point into the -** [virtual table] and are used -** to loop through the virtual table. Cursors are created using the -** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed -** by the [sqlite3_module.xClose | xClose] method. Cursors are used -** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods -** of the module. Each module implementation will define -** the content of a cursor structure to suit its own needs. -** -** This superclass exists in order to define fields of the cursor that -** are common to all implementations. -*/ -struct sqlite3_vtab_cursor { - sqlite3_vtab *pVtab; /* Virtual table of this cursor */ - /* Virtual table implementations will typically add additional fields */ -}; - -/* -** CAPI3REF: Declare The Schema Of A Virtual Table -** -** ^The [xCreate] and [xConnect] methods of a -** [virtual table module] call this interface -** to declare the format (the names and datatypes of the columns) of -** the virtual tables they implement. -*/ -SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL); - -/* -** CAPI3REF: Overload A Function For A Virtual Table -** METHOD: sqlite3 -** -** ^(Virtual tables can provide alternative implementations of functions -** using the [xFindFunction] method of the [virtual table module]. -** But global versions of those functions -** must exist in order to be overloaded.)^ -** -** ^(This API makes sure a global version of a function with a particular -** name and number of parameters exists. If no such function exists -** before this API is called, a new function is created.)^ ^The implementation -** of the new function always causes an exception to be thrown. So -** the new function is not good for anything by itself. Its only -** purpose is to be a placeholder function that can be overloaded -** by a [virtual table]. -*/ -SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); - -/* -** The interface to the virtual-table mechanism defined above (back up -** to a comment remarkably similar to this one) is currently considered -** to be experimental. The interface might change in incompatible ways. -** If this is a problem for you, do not use the interface at this time. -** -** When the virtual-table mechanism stabilizes, we will declare the -** interface fixed, support it indefinitely, and remove this comment. -*/ - -/* -** CAPI3REF: A Handle To An Open BLOB -** KEYWORDS: {BLOB handle} {BLOB handles} -** -** An instance of this object represents an open BLOB on which -** [sqlite3_blob_open | incremental BLOB I/O] can be performed. -** ^Objects of this type are created by [sqlite3_blob_open()] -** and destroyed by [sqlite3_blob_close()]. -** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces -** can be used to read or write small subsections of the BLOB. -** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. -*/ -typedef struct sqlite3_blob sqlite3_blob; - -/* -** CAPI3REF: Open A BLOB For Incremental I/O -** METHOD: sqlite3 -** CONSTRUCTOR: sqlite3_blob -** -** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located -** in row iRow, column zColumn, table zTable in database zDb; -** in other words, the same BLOB that would be selected by: -** -**
-**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
-** 
)^ -** -** ^(Parameter zDb is not the filename that contains the database, but -** rather the symbolic name of the database. For attached databases, this is -** the name that appears after the AS keyword in the [ATTACH] statement. -** For the main database file, the database name is "main". For TEMP -** tables, the database name is "temp".)^ -** -** ^If the flags parameter is non-zero, then the BLOB is opened for read -** and write access. ^If the flags parameter is zero, the BLOB is opened for -** read-only access. -** -** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored -** in *ppBlob. Otherwise an [error code] is returned and, unless the error -** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided -** the API is not misused, it is always safe to call [sqlite3_blob_close()] -** on *ppBlob after this function it returns. -** -** This function fails with SQLITE_ERROR if any of the following are true: -**
    -**
  • ^(Database zDb does not exist)^, -**
  • ^(Table zTable does not exist within database zDb)^, -**
  • ^(Table zTable is a WITHOUT ROWID table)^, -**
  • ^(Column zColumn does not exist)^, -**
  • ^(Row iRow is not present in the table)^, -**
  • ^(The specified column of row iRow contains a value that is not -** a TEXT or BLOB value)^, -**
  • ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE -** constraint and the blob is being opened for read/write access)^, -**
  • ^([foreign key constraints | Foreign key constraints] are enabled, -** column zColumn is part of a [child key] definition and the blob is -** being opened for read/write access)^. -**
-** -** ^Unless it returns SQLITE_MISUSE, this function sets the -** [database connection] error code and message accessible via -** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. -** -** A BLOB referenced by sqlite3_blob_open() may be read using the -** [sqlite3_blob_read()] interface and modified by using -** [sqlite3_blob_write()]. The [BLOB handle] can be moved to a -** different row of the same table using the [sqlite3_blob_reopen()] -** interface. However, the column, table, or database of a [BLOB handle] -** cannot be changed after the [BLOB handle] is opened. -** -** ^(If the row that a BLOB handle points to is modified by an -** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects -** then the BLOB handle is marked as "expired". -** This is true if any column of the row is changed, even a column -** other than the one the BLOB handle is open on.)^ -** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for -** an expired BLOB handle fail with a return code of [SQLITE_ABORT]. -** ^(Changes written into a BLOB prior to the BLOB expiring are not -** rolled back by the expiration of the BLOB. Such changes will eventually -** commit if the transaction continues to completion.)^ -** -** ^Use the [sqlite3_blob_bytes()] interface to determine the size of -** the opened blob. ^The size of a blob may not be changed by this -** interface. Use the [UPDATE] SQL command to change the size of a -** blob. -** -** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces -** and the built-in [zeroblob] SQL function may be used to create a -** zero-filled blob to read or write using the incremental-blob interface. -** -** To avoid a resource leak, every open [BLOB handle] should eventually -** be released by a call to [sqlite3_blob_close()]. -** -** See also: [sqlite3_blob_close()], -** [sqlite3_blob_reopen()], [sqlite3_blob_read()], -** [sqlite3_blob_bytes()], [sqlite3_blob_write()]. -*/ -SQLITE_API int sqlite3_blob_open( - sqlite3*, - const char *zDb, - const char *zTable, - const char *zColumn, - sqlite3_int64 iRow, - int flags, - sqlite3_blob **ppBlob -); - -/* -** CAPI3REF: Move a BLOB Handle to a New Row -** METHOD: sqlite3_blob -** -** ^This function is used to move an existing [BLOB handle] so that it points -** to a different row of the same database table. ^The new row is identified -** by the rowid value passed as the second argument. Only the row can be -** changed. ^The database, table and column on which the blob handle is open -** remain the same. Moving an existing [BLOB handle] to a new row is -** faster than closing the existing handle and opening a new one. -** -** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] - -** it must exist and there must be either a blob or text value stored in -** the nominated column.)^ ^If the new row is not present in the table, or if -** it does not contain a blob or text value, or if another error occurs, an -** SQLite error code is returned and the blob handle is considered aborted. -** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or -** [sqlite3_blob_reopen()] on an aborted blob handle immediately return -** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle -** always returns zero. -** -** ^This function sets the database handle error code and message. -*/ -SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64); - -/* -** CAPI3REF: Close A BLOB Handle -** DESTRUCTOR: sqlite3_blob -** -** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed -** unconditionally. Even if this routine returns an error code, the -** handle is still closed.)^ -** -** ^If the blob handle being closed was opened for read-write access, and if -** the database is in auto-commit mode and there are no other open read-write -** blob handles or active write statements, the current transaction is -** committed. ^If an error occurs while committing the transaction, an error -** code is returned and the transaction rolled back. -** -** Calling this function with an argument that is not a NULL pointer or an -** open blob handle results in undefined behaviour. ^Calling this routine -** with a null pointer (such as would be returned by a failed call to -** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function -** is passed a valid open blob handle, the values returned by the -** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning. -*/ -SQLITE_API int sqlite3_blob_close(sqlite3_blob *); - -/* -** CAPI3REF: Return The Size Of An Open BLOB -** METHOD: sqlite3_blob -** -** ^Returns the size in bytes of the BLOB accessible via the -** successfully opened [BLOB handle] in its only argument. ^The -** incremental blob I/O routines can only read or overwriting existing -** blob content; they cannot change the size of a blob. -** -** This routine only works on a [BLOB handle] which has been created -** by a prior successful call to [sqlite3_blob_open()] and which has not -** been closed by [sqlite3_blob_close()]. Passing any other pointer in -** to this routine results in undefined and probably undesirable behavior. -*/ -SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); - -/* -** CAPI3REF: Read Data From A BLOB Incrementally -** METHOD: sqlite3_blob -** -** ^(This function is used to read data from an open [BLOB handle] into a -** caller-supplied buffer. N bytes of data are copied into buffer Z -** from the open BLOB, starting at offset iOffset.)^ -** -** ^If offset iOffset is less than N bytes from the end of the BLOB, -** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is -** less than zero, [SQLITE_ERROR] is returned and no data is read. -** ^The size of the blob (and hence the maximum value of N+iOffset) -** can be determined using the [sqlite3_blob_bytes()] interface. -** -** ^An attempt to read from an expired [BLOB handle] fails with an -** error code of [SQLITE_ABORT]. -** -** ^(On success, sqlite3_blob_read() returns SQLITE_OK. -** Otherwise, an [error code] or an [extended error code] is returned.)^ -** -** This routine only works on a [BLOB handle] which has been created -** by a prior successful call to [sqlite3_blob_open()] and which has not -** been closed by [sqlite3_blob_close()]. Passing any other pointer in -** to this routine results in undefined and probably undesirable behavior. -** -** See also: [sqlite3_blob_write()]. -*/ -SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); - -/* -** CAPI3REF: Write Data Into A BLOB Incrementally -** METHOD: sqlite3_blob -** -** ^(This function is used to write data into an open [BLOB handle] from a -** caller-supplied buffer. N bytes of data are copied from the buffer Z -** into the open BLOB, starting at offset iOffset.)^ -** -** ^(On success, sqlite3_blob_write() returns SQLITE_OK. -** Otherwise, an [error code] or an [extended error code] is returned.)^ -** ^Unless SQLITE_MISUSE is returned, this function sets the -** [database connection] error code and message accessible via -** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. -** -** ^If the [BLOB handle] passed as the first argument was not opened for -** writing (the flags parameter to [sqlite3_blob_open()] was zero), -** this function returns [SQLITE_READONLY]. -** -** This function may only modify the contents of the BLOB; it is -** not possible to increase the size of a BLOB using this API. -** ^If offset iOffset is less than N bytes from the end of the BLOB, -** [SQLITE_ERROR] is returned and no data is written. The size of the -** BLOB (and hence the maximum value of N+iOffset) can be determined -** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less -** than zero [SQLITE_ERROR] is returned and no data is written. -** -** ^An attempt to write to an expired [BLOB handle] fails with an -** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred -** before the [BLOB handle] expired are not rolled back by the -** expiration of the handle, though of course those changes might -** have been overwritten by the statement that expired the BLOB handle -** or by other independent statements. -** -** This routine only works on a [BLOB handle] which has been created -** by a prior successful call to [sqlite3_blob_open()] and which has not -** been closed by [sqlite3_blob_close()]. Passing any other pointer in -** to this routine results in undefined and probably undesirable behavior. -** -** See also: [sqlite3_blob_read()]. -*/ -SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); - -/* -** CAPI3REF: Virtual File System Objects -** -** A virtual filesystem (VFS) is an [sqlite3_vfs] object -** that SQLite uses to interact -** with the underlying operating system. Most SQLite builds come with a -** single default VFS that is appropriate for the host computer. -** New VFSes can be registered and existing VFSes can be unregistered. -** The following interfaces are provided. -** -** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name. -** ^Names are case sensitive. -** ^Names are zero-terminated UTF-8 strings. -** ^If there is no match, a NULL pointer is returned. -** ^If zVfsName is NULL then the default VFS is returned. -** -** ^New VFSes are registered with sqlite3_vfs_register(). -** ^Each new VFS becomes the default VFS if the makeDflt flag is set. -** ^The same VFS can be registered multiple times without injury. -** ^To make an existing VFS into the default VFS, register it again -** with the makeDflt flag set. If two different VFSes with the -** same name are registered, the behavior is undefined. If a -** VFS is registered with a name that is NULL or an empty string, -** then the behavior is undefined. -** -** ^Unregister a VFS with the sqlite3_vfs_unregister() interface. -** ^(If the default VFS is unregistered, another VFS is chosen as -** the default. The choice for the new VFS is arbitrary.)^ -*/ -SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); -SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); -SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); - -/* -** CAPI3REF: Mutexes -** -** The SQLite core uses these routines for thread -** synchronization. Though they are intended for internal -** use by SQLite, code that links against SQLite is -** permitted to use any of these routines. -** -** The SQLite source code contains multiple implementations -** of these mutex routines. An appropriate implementation -** is selected automatically at compile-time. The following -** implementations are available in the SQLite core: -** -**
    -**
  • SQLITE_MUTEX_PTHREADS -**
  • SQLITE_MUTEX_W32 -**
  • SQLITE_MUTEX_NOOP -**
-** -** The SQLITE_MUTEX_NOOP implementation is a set of routines -** that does no real locking and is appropriate for use in -** a single-threaded application. The SQLITE_MUTEX_PTHREADS and -** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix -** and Windows. -** -** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor -** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex -** implementation is included with the library. In this case the -** application must supply a custom mutex implementation using the -** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function -** before calling sqlite3_initialize() or any other public sqlite3_ -** function that calls sqlite3_initialize(). -** -** ^The sqlite3_mutex_alloc() routine allocates a new -** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc() -** routine returns NULL if it is unable to allocate the requested -** mutex. The argument to sqlite3_mutex_alloc() must one of these -** integer constants: -** -**
    -**
  • SQLITE_MUTEX_FAST -**
  • SQLITE_MUTEX_RECURSIVE -**
  • SQLITE_MUTEX_STATIC_MASTER -**
  • SQLITE_MUTEX_STATIC_MEM -**
  • SQLITE_MUTEX_STATIC_OPEN -**
  • SQLITE_MUTEX_STATIC_PRNG -**
  • SQLITE_MUTEX_STATIC_LRU -**
  • SQLITE_MUTEX_STATIC_PMEM -**
  • SQLITE_MUTEX_STATIC_APP1 -**
  • SQLITE_MUTEX_STATIC_APP2 -**
  • SQLITE_MUTEX_STATIC_APP3 -**
  • SQLITE_MUTEX_STATIC_VFS1 -**
  • SQLITE_MUTEX_STATIC_VFS2 -**
  • SQLITE_MUTEX_STATIC_VFS3 -**
-** -** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) -** cause sqlite3_mutex_alloc() to create -** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE -** is used but not necessarily so when SQLITE_MUTEX_FAST is used. -** The mutex implementation does not need to make a distinction -** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does -** not want to. SQLite will only request a recursive mutex in -** cases where it really needs one. If a faster non-recursive mutex -** implementation is available on the host platform, the mutex subsystem -** might return such a mutex in response to SQLITE_MUTEX_FAST. -** -** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other -** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return -** a pointer to a static preexisting mutex. ^Nine static mutexes are -** used by the current version of SQLite. Future versions of SQLite -** may add additional static mutexes. Static mutexes are for internal -** use by SQLite only. Applications that use SQLite mutexes should -** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or -** SQLITE_MUTEX_RECURSIVE. -** -** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST -** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() -** returns a different mutex on every call. ^For the static -** mutex types, the same mutex is returned on every call that has -** the same type number. -** -** ^The sqlite3_mutex_free() routine deallocates a previously -** allocated dynamic mutex. Attempting to deallocate a static -** mutex results in undefined behavior. -** -** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt -** to enter a mutex. ^If another thread is already within the mutex, -** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return -** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK] -** upon successful entry. ^(Mutexes created using -** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. -** In such cases, the -** mutex must be exited an equal number of times before another thread -** can enter.)^ If the same thread tries to enter any mutex other -** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined. -** -** ^(Some systems (for example, Windows 95) do not support the operation -** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() -** will always return SQLITE_BUSY. The SQLite core only ever uses -** sqlite3_mutex_try() as an optimization so this is acceptable -** behavior.)^ -** -** ^The sqlite3_mutex_leave() routine exits a mutex that was -** previously entered by the same thread. The behavior -** is undefined if the mutex is not currently entered by the -** calling thread or is not currently allocated. -** -** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or -** sqlite3_mutex_leave() is a NULL pointer, then all three routines -** behave as no-ops. -** -** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. -*/ -SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int); -SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*); -SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*); -SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*); -SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); - -/* -** CAPI3REF: Mutex Methods Object -** -** An instance of this structure defines the low-level routines -** used to allocate and use mutexes. -** -** Usually, the default mutex implementations provided by SQLite are -** sufficient, however the application has the option of substituting a custom -** implementation for specialized deployments or systems for which SQLite -** does not provide a suitable implementation. In this case, the application -** creates and populates an instance of this structure to pass -** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. -** Additionally, an instance of this structure can be used as an -** output variable when querying the system for the current mutex -** implementation, using the [SQLITE_CONFIG_GETMUTEX] option. -** -** ^The xMutexInit method defined by this structure is invoked as -** part of system initialization by the sqlite3_initialize() function. -** ^The xMutexInit routine is called by SQLite exactly once for each -** effective call to [sqlite3_initialize()]. -** -** ^The xMutexEnd method defined by this structure is invoked as -** part of system shutdown by the sqlite3_shutdown() function. The -** implementation of this method is expected to release all outstanding -** resources obtained by the mutex methods implementation, especially -** those obtained by the xMutexInit method. ^The xMutexEnd() -** interface is invoked exactly once for each call to [sqlite3_shutdown()]. -** -** ^(The remaining seven methods defined by this structure (xMutexAlloc, -** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and -** xMutexNotheld) implement the following interfaces (respectively): -** -**
    -**
  • [sqlite3_mutex_alloc()]
  • -**
  • [sqlite3_mutex_free()]
  • -**
  • [sqlite3_mutex_enter()]
  • -**
  • [sqlite3_mutex_try()]
  • -**
  • [sqlite3_mutex_leave()]
  • -**
  • [sqlite3_mutex_held()]
  • -**
  • [sqlite3_mutex_notheld()]
  • -**
)^ -** -** The only difference is that the public sqlite3_XXX functions enumerated -** above silently ignore any invocations that pass a NULL pointer instead -** of a valid mutex handle. The implementations of the methods defined -** by this structure are not required to handle this case, the results -** of passing a NULL pointer instead of a valid mutex handle are undefined -** (i.e. it is acceptable to provide an implementation that segfaults if -** it is passed a NULL pointer). -** -** The xMutexInit() method must be threadsafe. It must be harmless to -** invoke xMutexInit() multiple times within the same process and without -** intervening calls to xMutexEnd(). Second and subsequent calls to -** xMutexInit() must be no-ops. -** -** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()] -** and its associates). Similarly, xMutexAlloc() must not use SQLite memory -** allocation for a static mutex. ^However xMutexAlloc() may use SQLite -** memory allocation for a fast or recursive mutex. -** -** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is -** called, but only if the prior call to xMutexInit returned SQLITE_OK. -** If xMutexInit fails in any way, it is expected to clean up after itself -** prior to returning. -*/ -typedef struct sqlite3_mutex_methods sqlite3_mutex_methods; -struct sqlite3_mutex_methods { - int (*xMutexInit)(void); - int (*xMutexEnd)(void); - sqlite3_mutex *(*xMutexAlloc)(int); - void (*xMutexFree)(sqlite3_mutex *); - void (*xMutexEnter)(sqlite3_mutex *); - int (*xMutexTry)(sqlite3_mutex *); - void (*xMutexLeave)(sqlite3_mutex *); - int (*xMutexHeld)(sqlite3_mutex *); - int (*xMutexNotheld)(sqlite3_mutex *); -}; - -/* -** CAPI3REF: Mutex Verification Routines -** -** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines -** are intended for use inside assert() statements. The SQLite core -** never uses these routines except inside an assert() and applications -** are advised to follow the lead of the core. The SQLite core only -** provides implementations for these routines when it is compiled -** with the SQLITE_DEBUG flag. External mutex implementations -** are only required to provide these routines if SQLITE_DEBUG is -** defined and if NDEBUG is not defined. -** -** These routines should return true if the mutex in their argument -** is held or not held, respectively, by the calling thread. -** -** The implementation is not required to provide versions of these -** routines that actually work. If the implementation does not provide working -** versions of these routines, it should at least provide stubs that always -** return true so that one does not get spurious assertion failures. -** -** If the argument to sqlite3_mutex_held() is a NULL pointer then -** the routine should return 1. This seems counter-intuitive since -** clearly the mutex cannot be held if it does not exist. But -** the reason the mutex does not exist is because the build is not -** using mutexes. And we do not want the assert() containing the -** call to sqlite3_mutex_held() to fail, so a non-zero return is -** the appropriate thing to do. The sqlite3_mutex_notheld() -** interface should also return 1 when given a NULL pointer. -*/ -#ifndef NDEBUG -SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*); -SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); -#endif - -/* -** CAPI3REF: Mutex Types -** -** The [sqlite3_mutex_alloc()] interface takes a single argument -** which is one of these integer constants. -** -** The set of static mutexes may change from one SQLite release to the -** next. Applications that override the built-in mutex logic must be -** prepared to accommodate additional static mutexes. -*/ -#define SQLITE_MUTEX_FAST 0 -#define SQLITE_MUTEX_RECURSIVE 1 -#define SQLITE_MUTEX_STATIC_MASTER 2 -#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ -#define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */ -#define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */ -#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */ -#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ -#define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */ -#define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */ -#define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */ -#define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */ -#define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */ -#define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */ -#define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */ -#define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */ - -/* -** CAPI3REF: Retrieve the mutex for a database connection -** METHOD: sqlite3 -** -** ^This interface returns a pointer the [sqlite3_mutex] object that -** serializes access to the [database connection] given in the argument -** when the [threading mode] is Serialized. -** ^If the [threading mode] is Single-thread or Multi-thread then this -** routine returns a NULL pointer. -*/ -SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*); - -/* -** CAPI3REF: Low-Level Control Of Database Files -** METHOD: sqlite3 -** -** ^The [sqlite3_file_control()] interface makes a direct call to the -** xFileControl method for the [sqlite3_io_methods] object associated -** with a particular database identified by the second argument. ^The -** name of the database is "main" for the main database or "temp" for the -** TEMP database, or the name that appears after the AS keyword for -** databases that are added using the [ATTACH] SQL command. -** ^A NULL pointer can be used in place of "main" to refer to the -** main database file. -** ^The third and fourth parameters to this routine -** are passed directly through to the second and third parameters of -** the xFileControl method. ^The return value of the xFileControl -** method becomes the return value of this routine. -** -** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes -** a pointer to the underlying [sqlite3_file] object to be written into -** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER -** case is a short-circuit path which does not actually invoke the -** underlying sqlite3_io_methods.xFileControl method. -** -** ^If the second parameter (zDbName) does not match the name of any -** open database file, then SQLITE_ERROR is returned. ^This error -** code is not remembered and will not be recalled by [sqlite3_errcode()] -** or [sqlite3_errmsg()]. The underlying xFileControl method might -** also return SQLITE_ERROR. There is no way to distinguish between -** an incorrect zDbName and an SQLITE_ERROR return from the underlying -** xFileControl method. -** -** See also: [SQLITE_FCNTL_LOCKSTATE] -*/ -SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); - -/* -** CAPI3REF: Testing Interface -** -** ^The sqlite3_test_control() interface is used to read out internal -** state of SQLite and to inject faults into SQLite for testing -** purposes. ^The first parameter is an operation code that determines -** the number, meaning, and operation of all subsequent parameters. -** -** This interface is not for use by applications. It exists solely -** for verifying the correct operation of the SQLite library. Depending -** on how the SQLite library is compiled, this interface might not exist. -** -** The details of the operation codes, their meanings, the parameters -** they take, and what they do are all subject to change without notice. -** Unlike most of the SQLite API, this function is not guaranteed to -** operate consistently from one release to the next. -*/ -SQLITE_API int sqlite3_test_control(int op, ...); - -/* -** CAPI3REF: Testing Interface Operation Codes -** -** These constants are the valid operation code parameters used -** as the first argument to [sqlite3_test_control()]. -** -** These parameters and their meanings are subject to change -** without notice. These values are for testing purposes only. -** Applications should not use any of these parameters or the -** [sqlite3_test_control()] interface. -*/ -#define SQLITE_TESTCTRL_FIRST 5 -#define SQLITE_TESTCTRL_PRNG_SAVE 5 -#define SQLITE_TESTCTRL_PRNG_RESTORE 6 -#define SQLITE_TESTCTRL_PRNG_RESET 7 -#define SQLITE_TESTCTRL_BITVEC_TEST 8 -#define SQLITE_TESTCTRL_FAULT_INSTALL 9 -#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10 -#define SQLITE_TESTCTRL_PENDING_BYTE 11 -#define SQLITE_TESTCTRL_ASSERT 12 -#define SQLITE_TESTCTRL_ALWAYS 13 -#define SQLITE_TESTCTRL_RESERVE 14 -#define SQLITE_TESTCTRL_OPTIMIZATIONS 15 -#define SQLITE_TESTCTRL_ISKEYWORD 16 -#define SQLITE_TESTCTRL_SCRATCHMALLOC 17 /* NOT USED */ -#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_LAST 25 - -/* -** CAPI3REF: SQLite Runtime Status -** -** ^These interfaces are used to retrieve runtime status information -** about the performance of SQLite, and optionally to reset various -** highwater marks. ^The first argument is an integer code for -** the specific parameter to measure. ^(Recognized integer codes -** are of the form [status parameters | SQLITE_STATUS_...].)^ -** ^The current value of the parameter is returned into *pCurrent. -** ^The highest recorded value is returned in *pHighwater. ^If the -** resetFlag is true, then the highest record value is reset after -** *pHighwater is written. ^(Some parameters do not record the highest -** value. For those parameters -** nothing is written into *pHighwater and the resetFlag is ignored.)^ -** ^(Other parameters record only the highwater mark and not the current -** value. For these latter parameters nothing is written into *pCurrent.)^ -** -** ^The sqlite3_status() and sqlite3_status64() routines return -** SQLITE_OK on success and a non-zero [error code] on failure. -** -** If either the current value or the highwater mark is too large to -** be represented by a 32-bit integer, then the values returned by -** sqlite3_status() are undefined. -** -** See also: [sqlite3_db_status()] -*/ -SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); -SQLITE_API int sqlite3_status64( - int op, - sqlite3_int64 *pCurrent, - sqlite3_int64 *pHighwater, - int resetFlag -); - - -/* -** CAPI3REF: Status Parameters -** KEYWORDS: {status parameters} -** -** These integer constants designate various run-time status parameters -** that can be returned by [sqlite3_status()]. -** -**
-** [[SQLITE_STATUS_MEMORY_USED]] ^(
SQLITE_STATUS_MEMORY_USED
-**
This parameter is the current amount of memory checked out -** using [sqlite3_malloc()], either directly or indirectly. The -** figure includes calls made to [sqlite3_malloc()] by the application -** and internal memory usage by the SQLite library. Auxiliary page-cache -** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in -** this parameter. The amount returned is the sum of the allocation -** sizes as reported by the xSize method in [sqlite3_mem_methods].
)^ -** -** [[SQLITE_STATUS_MALLOC_SIZE]] ^(
SQLITE_STATUS_MALLOC_SIZE
-**
This parameter records the largest memory allocation request -** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their -** internal equivalents). Only the value returned in the -** *pHighwater parameter to [sqlite3_status()] is of interest. -** The value written into the *pCurrent parameter is undefined.
)^ -** -** [[SQLITE_STATUS_MALLOC_COUNT]] ^(
SQLITE_STATUS_MALLOC_COUNT
-**
This parameter records the number of separate memory allocations -** currently checked out.
)^ -** -** [[SQLITE_STATUS_PAGECACHE_USED]] ^(
SQLITE_STATUS_PAGECACHE_USED
-**
This parameter returns the number of pages used out of the -** [pagecache memory allocator] that was configured using -** [SQLITE_CONFIG_PAGECACHE]. The -** value returned is in pages, not in bytes.
)^ -** -** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] -** ^(
SQLITE_STATUS_PAGECACHE_OVERFLOW
-**
This parameter returns the number of bytes of page cache -** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE] -** buffer and where forced to overflow to [sqlite3_malloc()]. The -** returned value includes allocations that overflowed because they -** where too large (they were larger than the "sz" parameter to -** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because -** no space was left in the page cache.
)^ -** -** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(
SQLITE_STATUS_PAGECACHE_SIZE
-**
This parameter records the largest memory allocation request -** handed to [pagecache memory allocator]. Only the value returned in the -** *pHighwater parameter to [sqlite3_status()] is of interest. -** The value written into the *pCurrent parameter is undefined.
)^ -** -** [[SQLITE_STATUS_SCRATCH_USED]]
SQLITE_STATUS_SCRATCH_USED
-**
No longer used.
-** -** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(
SQLITE_STATUS_SCRATCH_OVERFLOW
-**
No longer used.
-** -** [[SQLITE_STATUS_SCRATCH_SIZE]]
SQLITE_STATUS_SCRATCH_SIZE
-**
No longer used.
-** -** [[SQLITE_STATUS_PARSER_STACK]] ^(
SQLITE_STATUS_PARSER_STACK
-**
The *pHighwater parameter records the deepest parser stack. -** The *pCurrent value is undefined. The *pHighwater value is only -** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].
)^ -**
-** -** New status parameters may be added from time to time. -*/ -#define SQLITE_STATUS_MEMORY_USED 0 -#define SQLITE_STATUS_PAGECACHE_USED 1 -#define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 -#define SQLITE_STATUS_SCRATCH_USED 3 /* NOT USED */ -#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 /* NOT USED */ -#define SQLITE_STATUS_MALLOC_SIZE 5 -#define SQLITE_STATUS_PARSER_STACK 6 -#define SQLITE_STATUS_PAGECACHE_SIZE 7 -#define SQLITE_STATUS_SCRATCH_SIZE 8 /* NOT USED */ -#define SQLITE_STATUS_MALLOC_COUNT 9 - -/* -** CAPI3REF: Database Connection Status -** METHOD: sqlite3 -** -** ^This interface is used to retrieve runtime status information -** about a single [database connection]. ^The first argument is the -** database connection object to be interrogated. ^The second argument -** is an integer constant, taken from the set of -** [SQLITE_DBSTATUS options], that -** determines the parameter to interrogate. The set of -** [SQLITE_DBSTATUS options] is likely -** to grow in future releases of SQLite. -** -** ^The current value of the requested parameter is written into *pCur -** and the highest instantaneous value is written into *pHiwtr. ^If -** the resetFlg is true, then the highest instantaneous value is -** reset back down to the current value. -** -** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a -** non-zero [error code] on failure. -** -** See also: [sqlite3_status()] and [sqlite3_stmt_status()]. -*/ -SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg); - -/* -** CAPI3REF: Status Parameters for database connections -** KEYWORDS: {SQLITE_DBSTATUS options} -** -** These constants are the available integer "verbs" that can be passed as -** the second argument to the [sqlite3_db_status()] interface. -** -** New verbs may be added in future releases of SQLite. Existing verbs -** might be discontinued. Applications should check the return code from -** [sqlite3_db_status()] to make sure that the call worked. -** The [sqlite3_db_status()] interface will return a non-zero error code -** if a discontinued or unsupported verb is invoked. -** -**
-** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(
SQLITE_DBSTATUS_LOOKASIDE_USED
-**
This parameter returns the number of lookaside memory slots currently -** checked out.
)^ -** -** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(
SQLITE_DBSTATUS_LOOKASIDE_HIT
-**
This parameter returns the number malloc attempts that were -** satisfied using lookaside memory. Only the high-water value is meaningful; -** the current value is always zero.)^ -** -** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]] -** ^(
SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
-**
This parameter returns the number malloc attempts that might have -** been satisfied using lookaside memory but failed due to the amount of -** memory requested being larger than the lookaside slot size. -** Only the high-water value is meaningful; -** the current value is always zero.)^ -** -** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]] -** ^(
SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
-**
This parameter returns the number malloc attempts that might have -** been satisfied using lookaside memory but failed due to all lookaside -** memory already being in use. -** Only the high-water value is meaningful; -** the current value is always zero.)^ -** -** [[SQLITE_DBSTATUS_CACHE_USED]] ^(
SQLITE_DBSTATUS_CACHE_USED
-**
This parameter returns the approximate number of bytes of heap -** memory used by all pager caches associated with the database connection.)^ -** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0. -** -** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]] -** ^(
SQLITE_DBSTATUS_CACHE_USED_SHARED
-**
This parameter is similar to DBSTATUS_CACHE_USED, except that if a -** pager cache is shared between two or more connections the bytes of heap -** memory used by that pager cache is divided evenly between the attached -** connections.)^ In other words, if none of the pager caches associated -** with the database connection are shared, this request returns the same -** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are -** shared, the value returned by this call will be smaller than that returned -** by DBSTATUS_CACHE_USED. ^The highwater mark associated with -** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0. -** -** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(
SQLITE_DBSTATUS_SCHEMA_USED
-**
This parameter returns the approximate number of bytes of heap -** memory used to store the schema for all databases associated -** with the connection - main, temp, and any [ATTACH]-ed databases.)^ -** ^The full amount of memory used by the schemas is reported, even if the -** schema memory is shared with other database connections due to -** [shared cache mode] being enabled. -** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0. -** -** [[SQLITE_DBSTATUS_STMT_USED]] ^(
SQLITE_DBSTATUS_STMT_USED
-**
This parameter returns the approximate number of bytes of heap -** and lookaside memory used by all prepared statements associated with -** the database connection.)^ -** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0. -**
-** -** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(
SQLITE_DBSTATUS_CACHE_HIT
-**
This parameter returns the number of pager cache hits that have -** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT -** is always 0. -**
-** -** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(
SQLITE_DBSTATUS_CACHE_MISS
-**
This parameter returns the number of pager cache misses that have -** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS -** is always 0. -**
-** -** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(
SQLITE_DBSTATUS_CACHE_WRITE
-**
This parameter returns the number of dirty cache entries that have -** been written to disk. Specifically, the number of pages written to the -** wal file in wal mode databases, or the number of pages written to the -** database file in rollback mode databases. Any pages written as part of -** transaction rollback or database recovery operations are not included. -** If an IO or other error occurs while writing a page to disk, the effect -** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The -** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0. -**
-** -** [[SQLITE_DBSTATUS_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_MAX 11 /* Largest defined DBSTATUS */ - - -/* -** CAPI3REF: Prepared Statement Status -** METHOD: sqlite3_stmt -** -** ^(Each prepared statement maintains various -** [SQLITE_STMTSTATUS counters] that measure the number -** of times it has performed specific operations.)^ These counters can -** be used to monitor the performance characteristics of the prepared -** statements. For example, if the number of table steps greatly exceeds -** the number of table searches or result rows, that would tend to indicate -** that the prepared statement is using a full table scan rather than -** an index. -** -** ^(This interface is used to retrieve and reset counter values from -** a [prepared statement]. The first argument is the prepared statement -** object to be interrogated. The second argument -** is an integer code for a specific [SQLITE_STMTSTATUS counter] -** to be interrogated.)^ -** ^The current value of the requested counter is returned. -** ^If the resetFlg is true, then the counter is reset to zero after this -** interface call returns. -** -** See also: [sqlite3_status()] and [sqlite3_db_status()]. -*/ -SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); - -/* -** CAPI3REF: Status Parameters for prepared statements -** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters} -** -** These preprocessor macros define integer codes that name counter -** values associated with the [sqlite3_stmt_status()] interface. -** The meanings of the various counters are as follows: -** -**
-** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]]
SQLITE_STMTSTATUS_FULLSCAN_STEP
-**
^This is the number of times that SQLite has stepped forward in -** a table as part of a full table scan. Large numbers for this counter -** may indicate opportunities for performance improvement through -** careful use of indices.
-** -** [[SQLITE_STMTSTATUS_SORT]]
SQLITE_STMTSTATUS_SORT
-**
^This is the number of sort operations that have occurred. -** A non-zero value in this counter may indicate an opportunity to -** improvement performance through careful use of indices.
-** -** [[SQLITE_STMTSTATUS_AUTOINDEX]]
SQLITE_STMTSTATUS_AUTOINDEX
-**
^This is the number of rows inserted into transient indices that -** were created automatically in order to help joins run faster. -** A non-zero value in this counter may indicate an opportunity to -** improvement performance by adding permanent indices that do not -** need to be reinitialized each time the statement is run.
-** -** [[SQLITE_STMTSTATUS_VM_STEP]]
SQLITE_STMTSTATUS_VM_STEP
-**
^This is the number of virtual machine operations executed -** by the prepared statement if that number is less than or equal -** to 2147483647. The number of virtual machine operations can be -** used as a proxy for the total work done by the prepared statement. -** If the number of virtual machine operations exceeds 2147483647 -** then the value returned by this statement status code is undefined. -** -** [[SQLITE_STMTSTATUS_REPREPARE]]
SQLITE_STMTSTATUS_REPREPARE
-**
^This is the number of times that the prepare statement has been -** automatically regenerated due to schema changes or change to -** [bound parameters] that might affect the query plan. -** -** [[SQLITE_STMTSTATUS_RUN]]
SQLITE_STMTSTATUS_RUN
-**
^This is the number of times that the prepared statement has -** been run. A single "run" for the purposes of this counter is one -** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()]. -** The counter is incremented on the first [sqlite3_step()] call of each -** cycle. -** -** [[SQLITE_STMTSTATUS_MEMUSED]]
SQLITE_STMTSTATUS_MEMUSED
-**
^This is the approximate number of bytes of heap memory -** used to store the prepared statement. ^This value is not actually -** a counter, and so the resetFlg parameter to sqlite3_stmt_status() -** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED. -**
-**
-*/ -#define SQLITE_STMTSTATUS_FULLSCAN_STEP 1 -#define SQLITE_STMTSTATUS_SORT 2 -#define SQLITE_STMTSTATUS_AUTOINDEX 3 -#define SQLITE_STMTSTATUS_VM_STEP 4 -#define SQLITE_STMTSTATUS_REPREPARE 5 -#define SQLITE_STMTSTATUS_RUN 6 -#define SQLITE_STMTSTATUS_MEMUSED 99 - -/* -** CAPI3REF: Custom Page Cache Object -** -** The sqlite3_pcache type is opaque. It is implemented by -** the pluggable module. The SQLite core has no knowledge of -** its size or internal structure and never deals with the -** sqlite3_pcache object except by holding and passing pointers -** to the object. -** -** See [sqlite3_pcache_methods2] for additional information. -*/ -typedef struct sqlite3_pcache sqlite3_pcache; - -/* -** CAPI3REF: Custom Page Cache Object -** -** The sqlite3_pcache_page object represents a single page in the -** page cache. The page cache will allocate instances of this -** object. Various methods of the page cache use pointers to instances -** of this object as parameters or as their return value. -** -** See [sqlite3_pcache_methods2] for additional information. -*/ -typedef struct sqlite3_pcache_page sqlite3_pcache_page; -struct sqlite3_pcache_page { - void *pBuf; /* The content of the page */ - void *pExtra; /* Extra information associated with the page */ -}; - -/* -** CAPI3REF: Application Defined Page Cache. -** KEYWORDS: {page cache} -** -** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can -** register an alternative page cache implementation by passing in an -** instance of the sqlite3_pcache_methods2 structure.)^ -** In many applications, most of the heap memory allocated by -** SQLite is used for the page cache. -** By implementing a -** custom page cache using this API, an application can better control -** the amount of memory consumed by SQLite, the way in which -** that memory is allocated and released, and the policies used to -** determine exactly which parts of a database file are cached and for -** how long. -** -** The alternative page cache mechanism is an -** extreme measure that is only needed by the most demanding applications. -** The built-in page cache is recommended for most uses. -** -** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an -** internal buffer by SQLite within the call to [sqlite3_config]. Hence -** the application may discard the parameter after the call to -** [sqlite3_config()] returns.)^ -** -** [[the xInit() page cache method]] -** ^(The xInit() method is called once for each effective -** call to [sqlite3_initialize()])^ -** (usually only once during the lifetime of the process). ^(The xInit() -** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^ -** The intent of the xInit() method is to set up global data structures -** required by the custom page cache implementation. -** ^(If the xInit() method is NULL, then the -** built-in default page cache is used instead of the application defined -** page cache.)^ -** -** [[the xShutdown() page cache method]] -** ^The xShutdown() method is called by [sqlite3_shutdown()]. -** It can be used to clean up -** any outstanding resources before process shutdown, if required. -** ^The xShutdown() method may be NULL. -** -** ^SQLite automatically serializes calls to the xInit method, -** so the xInit method need not be threadsafe. ^The -** xShutdown method is only called from [sqlite3_shutdown()] so it does -** not need to be threadsafe either. All other methods must be threadsafe -** in multithreaded applications. -** -** ^SQLite will never invoke xInit() more than once without an intervening -** call to xShutdown(). -** -** [[the xCreate() page cache methods]] -** ^SQLite invokes the xCreate() method to construct a new cache instance. -** SQLite will typically create one cache instance for each open database file, -** though this is not guaranteed. ^The -** first parameter, szPage, is the size in bytes of the pages that must -** be allocated by the cache. ^szPage will always a power of two. ^The -** second parameter szExtra is a number of bytes of extra storage -** associated with each page cache entry. ^The szExtra parameter will -** a number less than 250. SQLite will use the -** extra szExtra bytes on each page to store metadata about the underlying -** database page on disk. The value passed into szExtra depends -** on the SQLite version, the target platform, and how SQLite was compiled. -** ^The third argument to xCreate(), bPurgeable, is true if the cache being -** created will be used to cache database pages of a file stored on disk, or -** false if it is used for an in-memory database. The cache implementation -** does not have to do anything special based with the value of bPurgeable; -** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will -** never invoke xUnpin() except to deliberately delete a page. -** ^In other words, calls to xUnpin() on a cache with bPurgeable set to -** false will always have the "discard" flag set to true. -** ^Hence, a cache created with bPurgeable false will -** never contain any unpinned pages. -** -** [[the xCachesize() page cache method]] -** ^(The xCachesize() method may be called at any time by SQLite to set the -** suggested maximum cache-size (number of pages stored by) the cache -** instance passed as the first argument. This is the value configured using -** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable -** parameter, the implementation is not required to do anything with this -** value; it is advisory only. -** -** [[the xPagecount() page cache methods]] -** The xPagecount() method must return the number of pages currently -** stored in the cache, both pinned and unpinned. -** -** [[the xFetch() page cache methods]] -** The xFetch() method locates a page in the cache and returns a pointer to -** an sqlite3_pcache_page object associated with that page, or a NULL pointer. -** The pBuf element of the returned sqlite3_pcache_page object will be a -** pointer to a buffer of szPage bytes used to store the content of a -** single database page. The pExtra element of sqlite3_pcache_page will be -** a pointer to the szExtra bytes of extra storage that SQLite has requested -** for each entry in the page cache. -** -** The page to be fetched is determined by the key. ^The minimum key value -** is 1. After it has been retrieved using xFetch, the page is considered -** to be "pinned". -** -** If the requested page is already in the page cache, then the page cache -** implementation must return a pointer to the page buffer with its content -** intact. If the requested page is not already in the cache, then the -** cache implementation should use the value of the createFlag -** parameter to help it determined what action to take: -** -** -**
createFlag Behavior when page is not already in cache -**
0 Do not allocate a new page. Return NULL. -**
1 Allocate a new page if it easy and convenient to do so. -** Otherwise return NULL. -**
2 Make every effort to allocate a new page. Only return -** NULL if allocating a new page is effectively impossible. -**
-** -** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite -** will only use a createFlag of 2 after a prior call with a createFlag of 1 -** failed.)^ In between the to xFetch() calls, SQLite may -** attempt to unpin one or more cache pages by spilling the content of -** pinned pages to disk and synching the operating system disk cache. -** -** [[the xUnpin() page cache method]] -** ^xUnpin() is called by SQLite with a pointer to a currently pinned page -** as its second argument. If the third parameter, discard, is non-zero, -** then the page must be evicted from the cache. -** ^If the discard parameter is -** zero, then the page may be discarded or retained at the discretion of -** page cache implementation. ^The page cache implementation -** may choose to evict unpinned pages at any time. -** -** The cache must not perform any reference counting. A single -** call to xUnpin() unpins the page regardless of the number of prior calls -** to xFetch(). -** -** [[the xRekey() page cache methods]] -** The xRekey() method is used to change the key value associated with the -** page passed as the second argument. If the cache -** previously contains an entry associated with newKey, it must be -** discarded. ^Any prior cache entry associated with newKey is guaranteed not -** to be pinned. -** -** When SQLite calls the xTruncate() method, the cache must discard all -** existing cache entries with page numbers (keys) greater than or equal -** to the value of the iLimit parameter passed to xTruncate(). If any -** of these pages are pinned, they are implicitly unpinned, meaning that -** they can be safely discarded. -** -** [[the xDestroy() page cache method]] -** ^The xDestroy() method is used to delete a cache allocated by xCreate(). -** All resources associated with the specified cache should be freed. ^After -** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*] -** handle invalid, and will not use it with any other sqlite3_pcache_methods2 -** functions. -** -** [[the xShrink() page cache method]] -** ^SQLite invokes the xShrink() method when it wants the page cache to -** free up as much of heap memory as possible. The page cache implementation -** is not obligated to free any memory, but well-behaved implementations should -** do their best. -*/ -typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2; -struct sqlite3_pcache_methods2 { - int iVersion; - void *pArg; - int (*xInit)(void*); - void (*xShutdown)(void*); - sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable); - void (*xCachesize)(sqlite3_pcache*, int nCachesize); - int (*xPagecount)(sqlite3_pcache*); - sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); - void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard); - void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, - unsigned oldKey, unsigned newKey); - void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); - void (*xDestroy)(sqlite3_pcache*); - void (*xShrink)(sqlite3_pcache*); -}; - -/* -** This is the obsolete pcache_methods object that has now been replaced -** by sqlite3_pcache_methods2. This object is not used by SQLite. It is -** retained in the header file for backwards compatibility only. -*/ -typedef struct sqlite3_pcache_methods sqlite3_pcache_methods; -struct sqlite3_pcache_methods { - void *pArg; - int (*xInit)(void*); - void (*xShutdown)(void*); - sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable); - void (*xCachesize)(sqlite3_pcache*, int nCachesize); - int (*xPagecount)(sqlite3_pcache*); - void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag); - void (*xUnpin)(sqlite3_pcache*, void*, int discard); - void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey); - void (*xTruncate)(sqlite3_pcache*, unsigned iLimit); - void (*xDestroy)(sqlite3_pcache*); -}; - - -/* -** CAPI3REF: Online Backup Object -** -** The sqlite3_backup object records state information about an ongoing -** online backup operation. ^The sqlite3_backup object is created by -** a call to [sqlite3_backup_init()] and is destroyed by a call to -** [sqlite3_backup_finish()]. -** -** See Also: [Using the SQLite Online Backup API] -*/ -typedef struct sqlite3_backup sqlite3_backup; - -/* -** CAPI3REF: Online Backup API. -** -** The backup API copies the content of one database into another. -** It is useful either for creating backups of databases or -** for copying in-memory databases to or from persistent files. -** -** See Also: [Using the SQLite Online Backup API] -** -** ^SQLite holds a write transaction open on the destination database file -** for the duration of the backup operation. -** ^The source database is read-locked only while it is being read; -** it is not locked continuously for the entire backup operation. -** ^Thus, the backup may be performed on a live source database without -** preventing other database connections from -** reading or writing to the source database while the backup is underway. -** -** ^(To perform a backup operation: -**
    -**
  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 connections transaction. -** -** ^(If sqlite3_unlock_notify() is called in a multi-threaded application, -** there is a chance that the blocking connection will have already -** concluded its transaction by the time sqlite3_unlock_notify() is invoked. -** If this happens, then the specified callback is invoked immediately, -** from within the call to sqlite3_unlock_notify().)^ -** -** ^If the blocked connection is attempting to obtain a write-lock on a -** shared-cache table, and more than one other connection currently holds -** a read-lock on the same table, then SQLite arbitrarily selects one of -** the other connections to use as the blocking connection. -** -** ^(There may be at most one unlock-notify callback registered by a -** blocked connection. If sqlite3_unlock_notify() is called when the -** blocked connection already has a registered unlock-notify callback, -** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is -** called with a NULL pointer as its second argument, then any existing -** unlock-notify callback is canceled. ^The blocked connections -** unlock-notify callback may also be canceled by closing the blocked -** connection using [sqlite3_close()]. -** -** The unlock-notify callback is not reentrant. If an application invokes -** any sqlite3_xxx API functions from within an unlock-notify callback, a -** crash or deadlock may be the result. -** -** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always -** returns SQLITE_OK. -** -** Callback Invocation Details -** -** When an unlock-notify callback is registered, the application provides a -** single void* pointer that is passed to the callback when it is invoked. -** However, the signature of the callback function allows SQLite to pass -** it an array of void* context pointers. The first argument passed to -** an unlock-notify callback is a pointer to an array of void* pointers, -** and the second is the number of entries in the array. -** -** When a blocking connections transaction is concluded, there may be -** more than one blocked connection that has registered for an unlock-notify -** callback. ^If two or more such blocked connections have specified the -** same callback function, then instead of invoking the callback function -** multiple times, it is invoked once with the set of void* context pointers -** specified by the blocked connections bundled together into an array. -** This gives the application an opportunity to prioritize any actions -** related to the set of unblocked database connections. -** -** Deadlock Detection -** -** Assuming that after registering for an unlock-notify callback a -** database waits for the callback to be issued before taking any further -** action (a reasonable assumption), then using this API may cause the -** application to deadlock. For example, if connection X is waiting for -** connection Y's transaction to be concluded, and similarly connection -** Y is waiting on connection X's transaction, then neither connection -** will proceed and the system may remain deadlocked indefinitely. -** -** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock -** detection. ^If a given call to sqlite3_unlock_notify() would put the -** system in a deadlocked state, then SQLITE_LOCKED is returned and no -** unlock-notify callback is registered. The system is said to be in -** a deadlocked state if connection A has registered for an unlock-notify -** callback on the conclusion of connection B's transaction, and connection -** B has itself registered for an unlock-notify callback when connection -** A's transaction is concluded. ^Indirect deadlock is also detected, so -** the system is also considered to be deadlocked if connection B has -** registered for an unlock-notify callback on the conclusion of connection -** C's transaction, where connection C is waiting on connection A. ^Any -** number of levels of indirection are allowed. -** -** The "DROP TABLE" Exception -** -** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost -** always appropriate to call sqlite3_unlock_notify(). There is however, -** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement, -** SQLite checks if there are any currently executing SELECT statements -** that belong to the same connection. If there are, SQLITE_LOCKED is -** returned. In this case there is no "blocking connection", so invoking -** sqlite3_unlock_notify() results in the unlock-notify callback being -** invoked immediately. If the application then re-attempts the "DROP TABLE" -** or "DROP INDEX" query, an infinite loop might be the result. -** -** One way around this problem is to check the extended error code returned -** by an sqlite3_step() call. ^(If there is a blocking connection, then the -** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in -** the special "DROP TABLE/INDEX" case, the extended error code is just -** SQLITE_LOCKED.)^ -*/ -SQLITE_API int sqlite3_unlock_notify( - sqlite3 *pBlocked, /* Waiting connection */ - void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */ - void *pNotifyArg /* Argument to pass to xNotify */ -); - - -/* -** CAPI3REF: String Comparison -** -** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications -** and extensions to compare the contents of two buffers containing UTF-8 -** strings in a case-independent fashion, using the same definition of "case -** independence" that SQLite uses internally when comparing identifiers. -*/ -SQLITE_API int sqlite3_stricmp(const char *, const char *); -SQLITE_API int sqlite3_strnicmp(const char *, const char *, int); - -/* -** CAPI3REF: String Globbing -* -** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if -** string X matches the [GLOB] pattern P. -** ^The definition of [GLOB] pattern matching used in -** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the -** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function -** is case sensitive. -** -** Note that this routine returns zero on a match and non-zero if the strings -** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()]. -** -** See also: [sqlite3_strlike()]. -*/ -SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr); - -/* -** CAPI3REF: String LIKE Matching -* -** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if -** string X matches the [LIKE] pattern P with escape character E. -** ^The definition of [LIKE] pattern matching used in -** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E" -** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without -** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0. -** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case -** insensitive - equivalent upper and lower case ASCII characters match -** one another. -** -** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though -** only ASCII characters are case folded. -** -** Note that this routine returns zero on a match and non-zero if the strings -** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()]. -** -** See also: [sqlite3_strglob()]. -*/ -SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc); - -/* -** CAPI3REF: Error Logging Interface -** -** ^The [sqlite3_log()] interface writes a message into the [error log] -** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()]. -** ^If logging is enabled, the zFormat string and subsequent arguments are -** used with [sqlite3_snprintf()] to generate the final output string. -** -** The sqlite3_log() interface is intended for use by extensions such as -** virtual tables, collating functions, and SQL functions. While there is -** nothing to prevent an application from calling sqlite3_log(), doing so -** is considered bad form. -** -** The zFormat string must not be NULL. -** -** To avoid deadlocks and other threading problems, the sqlite3_log() routine -** will not use dynamically allocated memory. The log message is stored in -** a fixed-length buffer on the stack. If the log message is longer than -** a few hundred characters, it will be truncated to the length of the -** buffer. -*/ -SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); - -/* -** CAPI3REF: Write-Ahead Log Commit Hook -** METHOD: sqlite3 -** -** ^The [sqlite3_wal_hook()] function is used to register a callback that -** is invoked each time data is committed to a database in wal mode. -** -** ^(The callback is invoked by SQLite after the commit has taken place and -** the associated write-lock on the database released)^, so the implementation -** may read, write or [checkpoint] the database as required. -** -** ^The first parameter passed to the callback function when it is invoked -** is a copy of the third parameter passed to sqlite3_wal_hook() when -** registering the callback. ^The second is a copy of the database handle. -** ^The third parameter is the name of the database that was written to - -** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter -** is the number of pages currently in the write-ahead log file, -** including those that were just committed. -** -** The callback function should normally return [SQLITE_OK]. ^If an error -** code is returned, that error will propagate back up through the -** SQLite code base to cause the statement that provoked the callback -** to report an error, though the commit will have still occurred. If the -** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value -** that does not correspond to any valid SQLite error code, the results -** are undefined. -** -** A single database handle may have at most a single write-ahead log callback -** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any -** previously registered write-ahead log callback. ^Note that the -** [sqlite3_wal_autocheckpoint()] interface and the -** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will -** overwrite any prior [sqlite3_wal_hook()] settings. -*/ -SQLITE_API void *sqlite3_wal_hook( - sqlite3*, - int(*)(void *,sqlite3*,const char*,int), - void* -); - -/* -** CAPI3REF: Configure an auto-checkpoint -** METHOD: sqlite3 -** -** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around -** [sqlite3_wal_hook()] that causes any database on [database connection] D -** to automatically [checkpoint] -** after committing a transaction if there are N or -** more frames in the [write-ahead log] file. ^Passing zero or -** a negative value as the nFrame parameter disables automatic -** checkpoints entirely. -** -** ^The callback registered by this function replaces any existing callback -** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback -** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism -** configured by this function. -** -** ^The [wal_autocheckpoint pragma] can be used to invoke this interface -** from SQL. -** -** ^Checkpoints initiated by this mechanism are -** [sqlite3_wal_checkpoint_v2|PASSIVE]. -** -** ^Every new [database connection] defaults to having the auto-checkpoint -** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT] -** pages. The use of this interface -** is only necessary if the default setting is found to be suboptimal -** for a particular application. -*/ -SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N); - -/* -** CAPI3REF: Checkpoint a database -** METHOD: sqlite3 -** -** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to -** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^ -** -** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the -** [write-ahead log] for database X on [database connection] D to be -** transferred into the database file and for the write-ahead log to -** be reset. See the [checkpointing] documentation for addition -** information. -** -** This interface used to be the only way to cause a checkpoint to -** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()] -** interface was added. This interface is retained for backwards -** compatibility and as a convenience for applications that need to manually -** start a callback but which do not need the full power (and corresponding -** complication) of [sqlite3_wal_checkpoint_v2()]. -*/ -SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); - -/* -** CAPI3REF: Checkpoint a database -** METHOD: sqlite3 -** -** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint -** operation on database X of [database connection] D in mode M. Status -** information is written back into integers pointed to by L and C.)^ -** ^(The M parameter must be a valid [checkpoint mode]:)^ -** -**
-**
SQLITE_CHECKPOINT_PASSIVE
-** ^Checkpoint as many frames as possible without waiting for any database -** readers or writers to finish, then sync the database file if all frames -** in the log were checkpointed. ^The [busy-handler callback] -** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode. -** ^On the other hand, passive mode might leave the checkpoint unfinished -** if there are concurrent readers or writers. -** -**
SQLITE_CHECKPOINT_FULL
-** ^This mode blocks (it invokes the -** [sqlite3_busy_handler|busy-handler callback]) until there is no -** database writer and all readers are reading from the most recent database -** snapshot. ^It then checkpoints all frames in the log file and syncs the -** database file. ^This mode blocks new database writers while it is pending, -** but new database readers are allowed to continue unimpeded. -** -**
SQLITE_CHECKPOINT_RESTART
-** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition -** that after checkpointing the log file it blocks (calls the -** [busy-handler callback]) -** until all readers are reading from the database file only. ^This ensures -** that the next writer will restart the log file from the beginning. -** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new -** database writer attempts while it is pending, but does not impede readers. -** -**
SQLITE_CHECKPOINT_TRUNCATE
-** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the -** addition that it also truncates the log file to zero bytes just prior -** to a successful return. -**
-** -** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in -** the log file or to -1 if the checkpoint could not run because -** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not -** NULL,then *pnCkpt is set to the total number of checkpointed frames in the -** log file (including any that were already checkpointed before the function -** was called) or to -1 if the checkpoint could not run due to an error or -** because the database is not in WAL mode. ^Note that upon successful -** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been -** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero. -** -** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If -** any other process is running a checkpoint operation at the same time, the -** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a -** busy-handler configured, it will not be invoked in this case. -** -** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the -** exclusive "writer" lock on the database file. ^If the writer lock cannot be -** obtained immediately, and a busy-handler is configured, it is invoked and -** the writer lock retried until either the busy-handler returns 0 or the lock -** is successfully obtained. ^The busy-handler is also invoked while waiting for -** database readers as described above. ^If the busy-handler returns 0 before -** the writer lock is obtained or while waiting for database readers, the -** checkpoint operation proceeds from that point in the same way as -** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible -** without blocking any further. ^SQLITE_BUSY is returned in this case. -** -** ^If parameter zDb is NULL or points to a zero length string, then the -** specified operation is attempted on all WAL databases [attached] to -** [database connection] db. In this case the -** values written to output parameters *pnLog and *pnCkpt are undefined. ^If -** an SQLITE_BUSY error is encountered when processing one or more of the -** attached WAL databases, the operation is still attempted on any remaining -** attached databases and SQLITE_BUSY is returned at the end. ^If any other -** error occurs while processing an attached database, processing is abandoned -** and the error code is returned to the caller immediately. ^If no error -** (SQLITE_BUSY or otherwise) is encountered while processing the attached -** databases, SQLITE_OK is returned. -** -** ^If database zDb is the name of an attached database that is not in WAL -** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If -** zDb is not NULL (or a zero length string) and is not the name of any -** attached database, SQLITE_ERROR is returned to the caller. -** -** ^Unless it returns SQLITE_MISUSE, -** the sqlite3_wal_checkpoint_v2() interface -** sets the error information that is queried by -** [sqlite3_errcode()] and [sqlite3_errmsg()]. -** -** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface -** from SQL. -*/ -SQLITE_API int sqlite3_wal_checkpoint_v2( - sqlite3 *db, /* Database handle */ - const char *zDb, /* Name of attached database (or NULL) */ - int eMode, /* SQLITE_CHECKPOINT_* value */ - int *pnLog, /* OUT: Size of WAL log in frames */ - int *pnCkpt /* OUT: Total number of frames checkpointed */ -); - -/* -** CAPI3REF: Checkpoint Mode Values -** KEYWORDS: {checkpoint mode} -** -** These constants define all valid values for the "checkpoint mode" passed -** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface. -** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the -** meaning of each of these checkpoint modes. -*/ -#define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */ -#define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */ -#define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */ -#define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */ - -/* -** CAPI3REF: Virtual Table Interface Configuration -** -** This function may be called by either the [xConnect] or [xCreate] method -** of a [virtual table] implementation to configure -** various facets of the virtual table interface. -** -** If this interface is invoked outside the context of an xConnect or -** xCreate virtual table method then the behavior is undefined. -** -** At present, there is only one option that may be configured using -** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options -** may be added in the future. -*/ -SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...); - -/* -** CAPI3REF: Virtual Table Configuration Options -** -** These macros define the various options to the -** [sqlite3_vtab_config()] interface that [virtual table] implementations -** can use to customize and optimize their behavior. -** -**
-**
SQLITE_VTAB_CONSTRAINT_SUPPORT -**
Calls of the form -** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported, -** where X is an integer. If X is zero, then the [virtual table] whose -** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not -** support constraints. In this configuration (which is the default) if -** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire -** statement is rolled back as if [ON CONFLICT | OR ABORT] had been -** specified as part of the users SQL statement, regardless of the actual -** ON CONFLICT mode specified. -** -** If X is non-zero, then the virtual table implementation guarantees -** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before -** any modifications to internal or persistent data structures have been made. -** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite -** is able to roll back a statement or database transaction, and abandon -** or continue processing the current SQL statement as appropriate. -** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns -** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode -** had been ABORT. -** -** Virtual table implementations that are required to handle OR REPLACE -** must do so within the [xUpdate] method. If a call to the -** [sqlite3_vtab_on_conflict()] function indicates that the current ON -** CONFLICT policy is REPLACE, the virtual table implementation should -** silently replace the appropriate rows within the xUpdate callback and -** return SQLITE_OK. Or, if this is not possible, it may return -** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT -** constraint handling. -**
-*/ -#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1 - -/* -** CAPI3REF: Determine The Virtual Table Conflict Policy -** -** This function may only be called from within a call to the [xUpdate] method -** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The -** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL], -** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode -** of the SQL statement that triggered the call to the [xUpdate] method of the -** [virtual table]. -*/ -SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *); - -/* -** CAPI3REF: Conflict resolution modes -** KEYWORDS: {conflict resolution mode} -** -** These constants are returned by [sqlite3_vtab_on_conflict()] to -** inform a [virtual table] implementation what the [ON CONFLICT] mode -** is for the SQL statement being evaluated. -** -** Note that the [SQLITE_IGNORE] constant is also used as a potential -** return value from the [sqlite3_set_authorizer()] callback and that -** [SQLITE_ABORT] is also a [result code]. -*/ -#define SQLITE_ROLLBACK 1 -/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */ -#define SQLITE_FAIL 3 -/* #define SQLITE_ABORT 4 // Also an error code */ -#define SQLITE_REPLACE 5 - -/* -** CAPI3REF: Prepared Statement Scan Status Opcodes -** KEYWORDS: {scanstatus options} -** -** The following constants can be used for the T parameter to the -** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a -** different metric for sqlite3_stmt_scanstatus() to return. -** -** When the value returned to V is a string, space to hold that string is -** managed by the prepared statement S and will be automatically freed when -** S is finalized. -** -**
-** [[SQLITE_SCANSTAT_NLOOP]]
SQLITE_SCANSTAT_NLOOP
-**
^The [sqlite3_int64] variable pointed to by the T parameter will be -** set to the total number of times that the X-th loop has run.
-** -** [[SQLITE_SCANSTAT_NVISIT]]
SQLITE_SCANSTAT_NVISIT
-**
^The [sqlite3_int64] variable pointed to by the T parameter will be set -** to the total number of rows examined by all iterations of the X-th loop.
-** -** [[SQLITE_SCANSTAT_EST]]
SQLITE_SCANSTAT_EST
-**
^The "double" variable pointed to by the T parameter will be set to the -** query planner's estimate for the average number of rows output from each -** iteration of the X-th loop. If the query planner's estimates was accurate, -** then this value will approximate the quotient NVISIT/NLOOP and the -** product of this value for all prior loops with the same SELECTID will -** be the NLOOP value for the current loop. -** -** [[SQLITE_SCANSTAT_NAME]]
SQLITE_SCANSTAT_NAME
-**
^The "const char *" variable pointed to by the T parameter will be set -** to a zero-terminated UTF-8 string containing the name of the index or table -** used for the X-th loop. -** -** [[SQLITE_SCANSTAT_EXPLAIN]]
SQLITE_SCANSTAT_EXPLAIN
-**
^The "const char *" variable pointed to by the T parameter will be set -** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN] -** description for the X-th loop. -** -** [[SQLITE_SCANSTAT_SELECTID]]
SQLITE_SCANSTAT_SELECT
-**
^The "int" variable pointed to by the T parameter will be set to the -** "select-id" for the X-th loop. The select-id identifies which query or -** subquery the loop is part of. The main query has a select-id of zero. -** The select-id is the same value as is output in the first column -** of an [EXPLAIN QUERY PLAN] query. -**
-*/ -#define SQLITE_SCANSTAT_NLOOP 0 -#define SQLITE_SCANSTAT_NVISIT 1 -#define SQLITE_SCANSTAT_EST 2 -#define SQLITE_SCANSTAT_NAME 3 -#define SQLITE_SCANSTAT_EXPLAIN 4 -#define SQLITE_SCANSTAT_SELECTID 5 - -/* -** CAPI3REF: Prepared Statement Scan Status -** METHOD: sqlite3_stmt -** -** This interface returns information about the predicted and measured -** performance for pStmt. Advanced applications can use this -** interface to compare the predicted and the measured performance and -** issue warnings and/or rerun [ANALYZE] if discrepancies are found. -** -** Since this interface is expected to be rarely used, it is only -** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS] -** compile-time option. -** -** The "iScanStatusOp" parameter determines which status information to return. -** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior -** of this interface is undefined. -** ^The requested measurement is written into a variable pointed to by -** the "pOut" parameter. -** Parameter "idx" identifies the specific loop to retrieve statistics for. -** Loops are numbered starting from zero. ^If idx is out of range - less than -** zero or greater than or equal to the total number of loops used to implement -** the statement - a non-zero value is returned and the variable that pOut -** points to is unchanged. -** -** ^Statistics might not be available for all loops in all statements. ^In cases -** where there exist loops with no available statistics, this function behaves -** as if the loop did not exist - it returns non-zero and leave the variable -** that pOut points to unchanged. -** -** See also: [sqlite3_stmt_scanstatus_reset()] -*/ -SQLITE_API int sqlite3_stmt_scanstatus( - sqlite3_stmt *pStmt, /* Prepared statement for which info desired */ - int idx, /* Index of loop to report on */ - int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */ - void *pOut /* Result written here */ -); - -/* -** CAPI3REF: Zero Scan-Status Counters -** METHOD: sqlite3_stmt -** -** ^Zero all [sqlite3_stmt_scanstatus()] related event counters. -** -** This API is only available if the library is built with pre-processor -** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined. -*/ -SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*); - -/* -** CAPI3REF: Flush caches to disk mid-transaction -** -** ^If a write-transaction is open on [database connection] D when the -** [sqlite3_db_cacheflush(D)] interface invoked, any dirty -** pages in the pager-cache that are not currently in use are written out -** to disk. A dirty page may be in use if a database cursor created by an -** active SQL statement is reading from it, or if it is page 1 of a database -** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)] -** interface flushes caches for all schemas - "main", "temp", and -** any [attached] databases. -** -** ^If this function needs to obtain extra database locks before dirty pages -** can be flushed to disk, it does so. ^If those locks cannot be obtained -** immediately and there is a busy-handler callback configured, it is invoked -** in the usual manner. ^If the required lock still cannot be obtained, then -** the database is skipped and an attempt made to flush any dirty pages -** belonging to the next (if any) database. ^If any databases are skipped -** because locks cannot be obtained, but no other error occurs, this -** function returns SQLITE_BUSY. -** -** ^If any other error occurs while flushing dirty pages to disk (for -** example an IO error or out-of-memory condition), then processing is -** abandoned and an SQLite [error code] is returned to the caller immediately. -** -** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK. -** -** ^This function does not set the database handle error code or message -** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions. -*/ -SQLITE_API int sqlite3_db_cacheflush(sqlite3*); - -/* -** CAPI3REF: The pre-update hook. -** -** ^These interfaces are only available if SQLite is compiled using the -** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option. -** -** ^The [sqlite3_preupdate_hook()] interface registers a callback function -** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation -** on a database table. -** ^At most one preupdate hook may be registered at a time on a single -** [database connection]; each call to [sqlite3_preupdate_hook()] overrides -** the previous setting. -** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()] -** with a NULL pointer as the second parameter. -** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as -** the first parameter to callbacks. -** -** ^The preupdate hook only fires for changes to real database tables; the -** preupdate hook is not invoked for changes to [virtual tables] or to -** system tables like sqlite_master or sqlite_stat1. -** -** ^The second parameter to the preupdate callback is a pointer to -** the [database connection] that registered the preupdate hook. -** ^The third parameter to the preupdate callback is one of the constants -** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the -** kind of update operation that is about to occur. -** ^(The fourth parameter to the preupdate callback is the name of the -** database within the database connection that is being modified. This -** will be "main" for the main database or "temp" for TEMP tables or -** the name given after the AS keyword in the [ATTACH] statement for attached -** databases.)^ -** ^The fifth parameter to the preupdate callback is the name of the -** table that is being modified. -** -** For an UPDATE or DELETE operation on a [rowid table], the sixth -** parameter passed to the preupdate callback is the initial [rowid] of the -** row being modified or deleted. For an INSERT operation on a rowid table, -** or any operation on a WITHOUT ROWID table, the value of the sixth -** parameter is undefined. For an INSERT or UPDATE on a rowid table the -** seventh parameter is the final rowid value of the row being inserted -** or updated. The value of the seventh parameter passed to the callback -** function is not defined for operations on WITHOUT ROWID tables, or for -** INSERT operations on rowid tables. -** -** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()], -** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces -** provide additional information about a preupdate event. These routines -** may only be called from within a preupdate callback. Invoking any of -** these routines from outside of a preupdate callback or with a -** [database connection] pointer that is different from the one supplied -** to the preupdate callback results in undefined and probably undesirable -** behavior. -** -** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns -** in the row that is being inserted, updated, or deleted. -** -** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to -** a [protected sqlite3_value] that contains the value of the Nth column of -** the table row before it is updated. The N parameter must be between 0 -** and one less than the number of columns or the behavior will be -** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE -** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the -** behavior is undefined. The [sqlite3_value] that P points to -** will be destroyed when the preupdate callback returns. -** -** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to -** a [protected sqlite3_value] that contains the value of the Nth column of -** the table row after it is updated. The N parameter must be between 0 -** and one less than the number of columns or the behavior will be -** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE -** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the -** behavior is undefined. The [sqlite3_value] that P points to -** will be destroyed when the preupdate callback returns. -** -** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate -** callback was invoked as a result of a direct insert, update, or delete -** operation; or 1 for inserts, updates, or deletes invoked by top-level -** triggers; or 2 for changes resulting from triggers called by top-level -** triggers; and so forth. -** -** See also: [sqlite3_update_hook()] -*/ -#if defined(SQLITE_ENABLE_PREUPDATE_HOOK) -SQLITE_API void *sqlite3_preupdate_hook( - sqlite3 *db, - void(*xPreUpdate)( - void *pCtx, /* Copy of third arg to preupdate_hook() */ - sqlite3 *db, /* Database handle */ - int op, /* SQLITE_UPDATE, DELETE or INSERT */ - char const *zDb, /* Database name */ - char const *zName, /* Table name */ - sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */ - sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */ - ), - void* -); -SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **); -SQLITE_API int sqlite3_preupdate_count(sqlite3 *); -SQLITE_API int sqlite3_preupdate_depth(sqlite3 *); -SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **); -#endif - -/* -** CAPI3REF: Low-level system error code -** -** ^Attempt to return the underlying operating system error code or error -** number that caused the most recent I/O error or failure to open a file. -** The return value is OS-dependent. For example, on unix systems, after -** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be -** called to get back the underlying "errno" that caused the problem, such -** as ENOSPC, EAUTH, EISDIR, and so forth. -*/ -SQLITE_API int sqlite3_system_errno(sqlite3*); - -/* -** CAPI3REF: Database Snapshot -** KEYWORDS: {snapshot} {sqlite3_snapshot} -** EXPERIMENTAL -** -** 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. -** -** The constructor for this object is [sqlite3_snapshot_get()]. The -** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer -** to an historical snapshot (if possible). The destructor for -** sqlite3_snapshot objects is [sqlite3_snapshot_free()]. -*/ -typedef struct sqlite3_snapshot { - unsigned char hidden[48]; -} sqlite3_snapshot; - -/* -** CAPI3REF: Record A Database Snapshot -** EXPERIMENTAL -** -** ^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 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 -** EXPERIMENTAL -** -** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a -** read transaction 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, a call to [sqlite3_snapshot_open(D,S,P)] must be -** the first operation following the [BEGIN] that takes the schema S -** out of [autocommit mode]. -** ^In other words, schema S must not currently be in -** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the -** database connection D must be out of [autocommit mode]. -** ^A [snapshot] will fail to open if it has been overwritten by a -** [checkpoint]. -** ^(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 -** EXPERIMENTAL -** -** ^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. -** EXPERIMENTAL -** -** 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. -*/ -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp( - sqlite3_snapshot *p1, - sqlite3_snapshot *p2 -); - -/* -** CAPI3REF: Recover snapshots from a wal file -** EXPERIMENTAL -** -** If all connections disconnect from a database file but do not perform -** a checkpoint, the existing wal file is opened along with the database -** file the next time the database is opened. At this point it is only -** possible to successfully call sqlite3_snapshot_open() to open the most -** recent snapshot of the database (the one at the head of the wal file), -** even though the wal file may contain other valid snapshots for which -** clients have sqlite3_snapshot handles. -** -** 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. -*/ -SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb); - -/* -** 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: Visiblity */ - 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 -*/ -typedef struct sqlite3_session sqlite3_session; - -/* -** CAPI3REF: Changeset Iterator Handle -*/ -typedef struct sqlite3_changeset_iter sqlite3_changeset_iter; - -/* -** CAPI3REF: Create A New Session Object -** -** 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 -** -** 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 -** -** 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 -** -** 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 -** -** 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. -*/ -SQLITE_API int sqlite3session_attach( - sqlite3_session *pSession, /* Session object */ - const char *zTab /* Table name */ -); - -/* -** CAPI3REF: Set a table filter on a Session Object. -** -** The second argument (xFilter) is the "filter callback". For changes to rows -** in tables that are not attached to the Session object, the filter is called -** to determine whether changes to the table's rows should be tracked or not. -** If xFilter returns 0, changes is not tracked. Note that once a table is -** attached, xFilter will not be called again. -*/ -SQLITE_API void sqlite3session_table_filter( - sqlite3_session *pSession, /* Session object */ - int(*xFilter)( - void *pCtx, /* Copy of third arg to _filter_table() */ - const char *zTab /* Table name */ - ), - void *pCtx /* First argument passed to xFilter */ -); - -/* -** CAPI3REF: Generate A Changeset From A Session Object -** -** 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 -** -** If it is not already attached to the session object passed as the first -** argument, this function attaches table zTbl in the same manner as the -** [sqlite3session_attach()] function. If zTbl does not exist, or if it -** does not have a primary key, this function is a no-op (but does not return -** an error). -** -** Argument zFromDb must be the name of a database ("main", "temp" etc.) -** attached to the same database handle as the session object that contains -** a table compatible with the table attached to the session by this function. -** A table is considered compatible if it: -** -**
    -**
  • Has the same name, -**
  • Has the same set of columns declared in the same order, and -**
  • Has the same PRIMARY KEY definition. -**
-** -** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables -** are compatible but do not have any PRIMARY KEY columns, it is not an error -** but no changes are added to the session object. As with other session -** APIs, tables without PRIMARY KEYs are simply ignored. -** -** This function adds a set of changes to the session object that could be -** used to update the table in database zFrom (call this the "from-table") -** so that its content is the same as the table attached to the session -** object (call this the "to-table"). Specifically: -** -**
    -**
  • For each row (primary key) that exists in the to-table but not in -** the from-table, an INSERT record is added to the session object. -** -**
  • For each row (primary key) that exists in the to-table but not in -** the from-table, a DELETE record is added to the session object. -** -**
  • For each row (primary key) that exists in both tables, but features -** different non-PK values in each, an UPDATE record is added to the -** session. -**
-** -** To clarify, if this function is called and then a changeset constructed -** using [sqlite3session_changeset()], then after applying that changeset to -** database zFrom the contents of the two compatible tables would be -** identical. -** -** It an error if database zFrom does not exist or does not contain the -** required compatible table. -** -** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite -** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg -** may be set to point to a buffer containing an English language error -** message. It is the responsibility of the caller to free this buffer using -** sqlite3_free(). -*/ -SQLITE_API int sqlite3session_diff( - sqlite3_session *pSession, - const char *zFromDb, - const char *zTbl, - char **pzErrMsg -); - - -/* -** CAPI3REF: Generate A Patchset From A Session Object -** -** 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 -** -** 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. -*/ -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 */ -); - - -/* -** CAPI3REF: Advance A Changeset Iterator -** -** This function may only be used with iterators created by function -** [sqlite3changeset_start()]. If it is called on an iterator passed to -** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE -** is returned and the call has no effect. -** -** Immediately after an iterator is created by sqlite3changeset_start(), it -** does not point to any change in the changeset. Assuming the changeset -** is not empty, the first call to this function advances the iterator to -** point to the first change in the changeset. Each subsequent call advances -** the iterator to point to the next change in the changeset (if any). If -** no error occurs and the iterator points to a valid change after a call -** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned. -** Otherwise, if all changes in the changeset have already been visited, -** SQLITE_DONE is returned. -** -** If an error occurs, an SQLite error code is returned. Possible error -** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or -** SQLITE_NOMEM. -*/ -SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter); - -/* -** CAPI3REF: Obtain The Current Operation From A Changeset Iterator -** -** 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 -** pbIncorrect 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 -** -** 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 -** -** 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 -** -** 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 -** -** 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 -** -** 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 -** -** 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 -*/ -typedef struct sqlite3_changegroup sqlite3_changegroup; - -/* -** CAPI3REF: Create A New Changegroup Object -** -** 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 -** -** Add all changes within the changeset (or patchset) in buffer pData (size -** nData bytes) to the changegroup. -** -** If the buffer contains a patchset, then all prior calls to this function -** on the same changegroup object must also have specified patchsets. Or, if -** the buffer contains a changeset, so must have the earlier calls to this -** function. Otherwise, SQLITE_ERROR is returned and no changes are added -** to the changegroup. -** -** Rows within the changeset and changegroup are identified by the values in -** their PRIMARY KEY columns. A change in the changeset is considered to -** apply to the same row as a change already present in the changegroup if -** the two rows have the same primary key. -** -** Changes to rows that do not already appear in the changegroup are -** simply copied into it. Or, if both the new changeset and the changegroup -** contain changes that apply to a single row, the final contents of the -** changegroup depends on the type of each change, as follows: -** -** -** -** -**
Existing Change New Change Output Change -**
INSERT INSERT -** The new change is ignored. This case does not occur if the new -** changeset was recorded immediately after the changesets already -** added to the changegroup. -**
INSERT UPDATE -** The INSERT change remains in the changegroup. The values in the -** INSERT change are modified as if the row was inserted by the -** existing change and then updated according to the new change. -**
INSERT DELETE -** The existing INSERT is removed from the changegroup. The DELETE is -** not added. -**
UPDATE INSERT -** The new change is ignored. This case does not occur if the new -** changeset was recorded immediately after the changesets already -** added to the changegroup. -**
UPDATE UPDATE -** The existing UPDATE remains within the changegroup. It is amended -** so that the accompanying values are as if the row was updated once -** by the existing change and then again by the new change. -**
UPDATE DELETE -** The existing UPDATE is replaced by the new DELETE within the -** changegroup. -**
DELETE INSERT -** If one or more of the column values in the row inserted by the -** new change differ from those in the row deleted by the existing -** change, the existing DELETE is replaced by an UPDATE within the -** changegroup. Otherwise, if the inserted row is exactly the same -** as the deleted row, the existing DELETE is simply discarded. -**
DELETE UPDATE -** The new change is ignored. This case does not occur if the new -** changeset was recorded immediately after the changesets already -** added to the changegroup. -**
DELETE DELETE -** The new change is ignored. This case does not occur if the new -** changeset was recorded immediately after the changesets already -** added to the changegroup. -**
-** -** If the new changeset contains changes to a table that is already present -** in the changegroup, then the number of columns and the position of the -** primary key columns for the table must be consistent. If this is not the -** case, this function fails with SQLITE_SCHEMA. If the input changeset -** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is -** returned. Or, if an out-of-memory condition occurs during processing, this -** function returns SQLITE_NOMEM. In all cases, if an error occurs the -** final contents of the changegroup is undefined. -** -** If no error occurs, SQLITE_OK is returned. -*/ -SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData); - -/* -** CAPI3REF: Obtain A Composite Changeset From A Changegroup -** -** 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 -*/ -SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*); - -/* -** CAPI3REF: Apply A Changeset To A Database -** -** Apply a changeset to a database. This function attempts 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 this function 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 to this function 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 this function 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, this 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, this function checks if the target database -** contains a row with the same primary key value (or values) as the -** original row values stored in the changeset. If it does, and the values -** stored in all modified non-primary key columns also match the values -** stored in the changeset the row is updated within the target database. -** -** If a row with matching primary key values is found, but one or more of -** the modified non-primary key fields contains a value different from an -** original row value stored in the changeset, the conflict-handler function -** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since -** UPDATE changes only contain values for non-primary key fields that are -** to be modified, only those fields need to match the original values to -** avoid the SQLITE_CHANGESET_DATA conflict-handler callback. -** -** If no row with matching primary key values is found in the database, -** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND] -** passed as the second argument. -** -** If the UPDATE operation is attempted, but SQLite returns -** SQLITE_CONSTRAINT, the conflict-handler function is invoked with -** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument. -** This includes the case where the UPDATE operation is attempted after -** an earlier call to the conflict handler function returned -** [SQLITE_CHANGESET_REPLACE]. -**
-** -** It is safe to execute SQL statements, including those that write to the -** table that the callback related to, from within the xConflict callback. -** This can be used to further customize the applications conflict -** resolution strategy. -** -** All changes made by this function 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. -*/ -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 */ -); - -/* -** 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: 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_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_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 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 -); - - -/* -** 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. The exception is if the table was created -** with the offsets=0 option specified. In this case *piOff is always -** set to -1. -** -** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM) -** if an error occurs. -** -** This API can be quite slow if used with an FTS5 table created with the -** "detail=none" or "detail=column" option. -** -** xRowid: -** Returns the rowid of the current row. -** -** xTokenize: -** Tokenize text using the tokenizer belonging to the FTS5 table. -** -** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback): -** This API function is used to query the FTS table for phrase iPhrase -** of the current query. Specifically, a query equivalent to: -** -** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid -** -** with $p set to a phrase equivalent to the phrase iPhrase of the -** current query is executed. Any column filter that applies to -** phrase iPhrase of the current query is included in $p. For each -** row visited, the callback function passed as the fourth argument -** is invoked. The context and API objects passed to the callback -** function may be used to access the properties of each matched row. -** Invoking Api.xUserData() returns a copy of the pointer passed as -** the third argument to pUserData. -** -** If the callback function returns any value other than SQLITE_OK, the -** query is abandoned and the xQueryPhrase function returns immediately. -** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK. -** Otherwise, the error code is propagated upwards. -** -** If the query runs to completion without incident, SQLITE_OK is returned. -** Or, if some error occurs before the query completes or is aborted by -** the callback, an SQLite error code is returned. -** -** -** xSetAuxdata(pFts5, pAux, xDelete) -** -** Save the pointer passed as the second argument as the extension functions -** "auxiliary data". The pointer may then be retrieved by the current or any -** future invocation of the same fts5 extension function made as part of -** 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, an -** 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, the -** In the above example, this means that the tokenizer returns the -** same token for inputs "first" and "1st". Say that token is in -** fact "first", so that when the user inserts the document "I won -** 1st place" entries are added to the index for tokens "i", "won", -** "first" and "place". If the user then queries for '1st + place', -** the tokenizer substitutes "first" for "1st" and the query works -** as expected. -** -**
  2. By adding multiple synonyms for a single term to the FTS index. -** 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 would be -** inefficient), it doesn't matter if the user queries for -** 'first + place' or '1st + place', as there are entires 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 subsituted for "1st" by the tokenizer, then the query: -** -** -** ... MATCH '1s*' -** -** will not match documents that contain the token "1st" (as the tokenizer -** will probably not map "1s" to any prefix of "first"). -** -** For full prefix support, method (3) may be preferred. In this case, -** because the index contains entries for both "first" and "1st", prefix -** queries such as 'fi*' or '1s*' will match correctly. However, because -** extra entries are added to the FTS index, this method uses more space -** within the database. -** -** Method (2) offers a midpoint between (1) and (3). Using this method, -** a query such as '1s*' will match documents that contain the literal -** token "1st", but not "first" (assuming the tokenizer is not able to -** provide synonyms for prefixes). However, a non-prefix query like '1st' -** will match against "1st" and "first". This method does not require -** extra disk space, as no extra entries are added to the FTS index. -** On the other hand, it may require more CPU cycles to run MATCH queries, -** as separate queries of the FTS index are required for each synonym. -** -** When using methods (2) or (3), it is important that the tokenizer only -** provide synonyms when tokenizing document text (method (2)) or query -** text (method (3)), not both. Doing so will not cause any errors, but is -** inefficient. -*/ -typedef struct Fts5Tokenizer Fts5Tokenizer; -typedef struct fts5_tokenizer fts5_tokenizer; -struct fts5_tokenizer { - int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut); - void (*xDelete)(Fts5Tokenizer*); - int (*xTokenize)(Fts5Tokenizer*, - void *pCtx, - int flags, /* Mask of FTS5_TOKENIZE_* flags */ - const char *pText, int nText, - int (*xToken)( - void *pCtx, /* Copy of 2nd argument to xTokenize() */ - int tflags, /* Mask of FTS5_TOKEN_* flags */ - const char *pToken, /* Pointer to buffer containing token */ - int nToken, /* Size of token in bytes */ - int iStart, /* Byte offset of token within input text */ - int iEnd /* Byte offset of end of token within input text */ - ) - ); -}; - -/* Flags that may be passed as the third argument to xTokenize() */ -#define FTS5_TOKENIZE_QUERY 0x0001 -#define FTS5_TOKENIZE_PREFIX 0x0002 -#define FTS5_TOKENIZE_DOCUMENT 0x0004 -#define FTS5_TOKENIZE_AUX 0x0008 - -/* Flags that may be passed by the tokenizer implementation back to FTS5 -** as the third argument to the supplied xToken callback. */ -#define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */ - -/* -** END OF CUSTOM TOKENIZERS -*************************************************************************/ - -/************************************************************************* -** FTS5 EXTENSION REGISTRATION API -*/ -typedef struct fts5_api fts5_api; -struct fts5_api { - int iVersion; /* Currently always set to 2 */ - - /* Create a new tokenizer */ - int (*xCreateTokenizer)( - fts5_api *pApi, - const char *zName, - void *pContext, - fts5_tokenizer *pTokenizer, - void (*xDestroy)(void*) - ); - - /* Find an existing tokenizer */ - int (*xFindTokenizer)( - fts5_api *pApi, - const char *zName, - void **ppContext, - fts5_tokenizer *pTokenizer - ); - - /* Create a new auxiliary function */ - int (*xCreateFunction)( - fts5_api *pApi, - const char *zName, - void *pContext, - fts5_extension_function xFunction, - void (*xDestroy)(void*) - ); -}; - -/* -** END OF REGISTRATION API -*************************************************************************/ - -#if 0 -} /* end of the 'extern "C"' block */ -#endif - -#endif /* _FTS5_H */ - -/******** End of fts5.h *********/ - -/************** End of sqlite3.h *********************************************/ -/************** Continuing where we left off in sqliteInt.h ******************/ - -/* -** Include the configuration header output by 'configure' if we're using the -** autoconf-based build -*/ -#if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H) -/* #include "config.h" */ -#define SQLITECONFIG_H 1 -#endif - -/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/ -/************** Begin file sqliteLimit.h *************************************/ -/* -** 2007 May 7 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file defines various limits of what SQLite can process. -*/ - -/* -** The maximum length of a TEXT or BLOB in bytes. This also -** limits the size of a row in a table or index. -** -** The hard limit is the ability of a 32-bit signed integer -** to count the size: 2^31-1 or 2147483647. -*/ -#ifndef SQLITE_MAX_LENGTH -# define SQLITE_MAX_LENGTH 1000000000 -#endif - -/* -** This is the maximum number of -** -** * Columns in a table -** * Columns in an index -** * Columns in a view -** * Terms in the SET clause of an UPDATE statement -** * Terms in the result set of a SELECT statement -** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement. -** * Terms in the VALUES clause of an INSERT statement -** -** The hard upper limit here is 32676. Most database people will -** tell you that in a well-normalized database, you usually should -** not have more than a dozen or so columns in any table. And if -** that is the case, there is no point in having more than a few -** dozen values in any of the other situations described above. -*/ -#ifndef SQLITE_MAX_COLUMN -# define SQLITE_MAX_COLUMN 2000 -#endif - -/* -** The maximum length of a single SQL statement in bytes. -** -** It used to be the case that setting this value to zero would -** turn the limit off. That is no longer true. It is not possible -** to turn this limit off. -*/ -#ifndef SQLITE_MAX_SQL_LENGTH -# define SQLITE_MAX_SQL_LENGTH 1000000000 -#endif - -/* -** The maximum depth of an expression tree. This is limited to -** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might -** want to place more severe limits on the complexity of an -** expression. -** -** A value of 0 used to mean that the limit was not enforced. -** But that is no longer true. The limit is now strictly enforced -** at all times. -*/ -#ifndef SQLITE_MAX_EXPR_DEPTH -# define SQLITE_MAX_EXPR_DEPTH 1000 -#endif - -/* -** The maximum number of terms in a compound SELECT statement. -** The code generator for compound SELECT statements does one -** level of recursion for each term. A stack overflow can result -** if the number of terms is too large. In practice, most SQL -** never has more than 3 or 4 terms. Use a value of 0 to disable -** any limit on the number of terms in a compount SELECT. -*/ -#ifndef SQLITE_MAX_COMPOUND_SELECT -# define SQLITE_MAX_COMPOUND_SELECT 500 -#endif - -/* -** The maximum number of opcodes in a VDBE program. -** Not currently enforced. -*/ -#ifndef SQLITE_MAX_VDBE_OP -# define SQLITE_MAX_VDBE_OP 250000000 -#endif - -/* -** The maximum number of arguments to an SQL function. -*/ -#ifndef SQLITE_MAX_FUNCTION_ARG -# define SQLITE_MAX_FUNCTION_ARG 127 -#endif - -/* -** The suggested maximum number of in-memory pages to use for -** the main database table and for temporary tables. -** -** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000, -** which means the cache size is limited to 2048000 bytes of memory. -** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be -** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options. -*/ -#ifndef SQLITE_DEFAULT_CACHE_SIZE -# define SQLITE_DEFAULT_CACHE_SIZE -2000 -#endif - -/* -** The default number of frames to accumulate in the log file before -** checkpointing the database in WAL mode. -*/ -#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT -# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000 -#endif - -/* -** The maximum number of attached databases. This must be between 0 -** and 125. The upper bound of 125 is because the attached databases are -** counted using a signed 8-bit integer which has a maximum value of 127 -** and we have to allow 2 extra counts for the "main" and "temp" databases. -*/ -#ifndef SQLITE_MAX_ATTACHED -# define SQLITE_MAX_ATTACHED 10 -#endif - - -/* -** The maximum value of a ?nnn wildcard that the parser will accept. -*/ -#ifndef SQLITE_MAX_VARIABLE_NUMBER -# define SQLITE_MAX_VARIABLE_NUMBER 999 -#endif - -/* Maximum page size. The upper bound on this value is 65536. This a limit -** imposed by the use of 16-bit offsets within each page. -** -** Earlier versions of SQLite allowed the user to change this value at -** compile time. This is no longer permitted, on the grounds that it creates -** a library that is technically incompatible with an SQLite library -** compiled with a different limit. If a process operating on a database -** with a page-size of 65536 bytes crashes, then an instance of SQLite -** compiled with the default page-size limit will not be able to rollback -** the aborted transaction. This could lead to database corruption. -*/ -#ifdef SQLITE_MAX_PAGE_SIZE -# undef SQLITE_MAX_PAGE_SIZE -#endif -#define SQLITE_MAX_PAGE_SIZE 65536 - - -/* -** The default size of a database page. -*/ -#ifndef SQLITE_DEFAULT_PAGE_SIZE -# define SQLITE_DEFAULT_PAGE_SIZE 4096 -#endif -#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE -# undef SQLITE_DEFAULT_PAGE_SIZE -# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE -#endif - -/* -** Ordinarily, if no value is explicitly provided, SQLite creates databases -** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain -** device characteristics (sector-size and atomic write() support), -** SQLite may choose a larger value. This constant is the maximum value -** SQLite will choose on its own. -*/ -#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE -# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192 -#endif -#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE -# undef SQLITE_MAX_DEFAULT_PAGE_SIZE -# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE -#endif - - -/* -** Maximum number of pages in one database file. -** -** This is really just the default value for the max_page_count pragma. -** This value can be lowered (or raised) at run-time using that the -** max_page_count macro. -*/ -#ifndef SQLITE_MAX_PAGE_COUNT -# define SQLITE_MAX_PAGE_COUNT 1073741823 -#endif - -/* -** Maximum length (in bytes) of the pattern in a LIKE or GLOB -** operator. -*/ -#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH -# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000 -#endif - -/* -** Maximum depth of recursion for triggers. -** -** A value of 1 means that a trigger program will not be able to itself -** fire any triggers. A value of 0 means that no trigger programs at all -** may be executed. -*/ -#ifndef SQLITE_MAX_TRIGGER_DEPTH -# define SQLITE_MAX_TRIGGER_DEPTH 1000 -#endif - -/************** End of sqliteLimit.h *****************************************/ -/************** Continuing where we left off in sqliteInt.h ******************/ - -/* Disable nuisance warnings on Borland compilers */ -#if defined(__BORLANDC__) -#pragma warn -rch /* unreachable code */ -#pragma warn -ccc /* Condition is always true or false */ -#pragma warn -aus /* Assigned value is never used */ -#pragma warn -csu /* Comparing signed and unsigned */ -#pragma warn -spa /* Suspicious pointer arithmetic */ -#endif - -/* -** Include standard header files as necessary -*/ -#ifdef HAVE_STDINT_H -#include -#endif -#ifdef HAVE_INTTYPES_H -#include -#endif - -/* -** The following macros are used to cast pointers to integers and -** integers to pointers. The way you do this varies from one compiler -** to the next, so we have developed the following set of #if statements -** to generate appropriate macros for a wide range of compilers. -** -** The correct "ANSI" way to do this is to use the intptr_t type. -** Unfortunately, that typedef is not available on all compilers, or -** if it is available, it requires an #include of specific headers -** that vary from one machine to the next. -** -** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on -** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)). -** So we have to define the macros in different ways depending on the -** compiler. -*/ -#if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */ -# define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X)) -# define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X)) -#elif !defined(__GNUC__) /* Works for compilers other than LLVM */ -# define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X]) -# define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0)) -#elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */ -# define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X)) -# define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X)) -#else /* Generates a warning - but it always works */ -# define SQLITE_INT_TO_PTR(X) ((void*)(X)) -# define SQLITE_PTR_TO_INT(X) ((int)(X)) -#endif - -/* -** A macro to hint to the compiler that a function should not be -** inlined. -*/ -#if defined(__GNUC__) -# define SQLITE_NOINLINE __attribute__((noinline)) -#elif defined(_MSC_VER) && _MSC_VER>=1310 -# define SQLITE_NOINLINE __declspec(noinline) -#else -# define SQLITE_NOINLINE -#endif - -/* -** Make sure that the compiler intrinsics we desire are enabled when -** compiling with an appropriate version of MSVC unless prevented by -** the SQLITE_DISABLE_INTRINSIC define. -*/ -#if !defined(SQLITE_DISABLE_INTRINSIC) -# if defined(_MSC_VER) && _MSC_VER>=1400 -# if !defined(_WIN32_WCE) -# include -# pragma intrinsic(_byteswap_ushort) -# pragma intrinsic(_byteswap_ulong) -# pragma intrinsic(_byteswap_uint64) -# pragma intrinsic(_ReadWriteBarrier) -# else -# include -# endif -# endif -#endif - -/* -** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2. -** 0 means mutexes are permanently disable and the library is never -** threadsafe. 1 means the library is serialized which is the highest -** level of threadsafety. 2 means the library is multithreaded - multiple -** threads can use SQLite as long as no two threads try to use the same -** database connection at the same time. -** -** Older versions of SQLite used an optional THREADSAFE macro. -** We support that for legacy. -** -** To ensure that the correct value of "THREADSAFE" is reported when querying -** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this -** logic is partially replicated in ctime.c. If it is updated here, it should -** also be updated there. -*/ -#if !defined(SQLITE_THREADSAFE) -# if defined(THREADSAFE) -# define SQLITE_THREADSAFE THREADSAFE -# else -# define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */ -# endif -#endif - -/* -** Powersafe overwrite is on by default. But can be turned off using -** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option. -*/ -#ifndef SQLITE_POWERSAFE_OVERWRITE -# define SQLITE_POWERSAFE_OVERWRITE 1 -#endif - -/* -** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by -** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in -** which case memory allocation statistics are disabled by default. -*/ -#if !defined(SQLITE_DEFAULT_MEMSTATUS) -# define SQLITE_DEFAULT_MEMSTATUS 1 -#endif - -/* -** Exactly one of the following macros must be defined in order to -** specify which memory allocation subsystem to use. -** -** SQLITE_SYSTEM_MALLOC // Use normal system malloc() -** SQLITE_WIN32_MALLOC // Use Win32 native heap API -** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails -** SQLITE_MEMDEBUG // Debugging version of system malloc() -** -** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the -** assert() macro is enabled, each call into the Win32 native heap subsystem -** will cause HeapValidate to be called. If heap validation should fail, an -** assertion will be triggered. -** -** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as -** the default. -*/ -#if defined(SQLITE_SYSTEM_MALLOC) \ - + defined(SQLITE_WIN32_MALLOC) \ - + defined(SQLITE_ZERO_MALLOC) \ - + defined(SQLITE_MEMDEBUG)>1 -# error "Two or more of the following compile-time configuration options\ - are defined but at most one is allowed:\ - SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\ - SQLITE_ZERO_MALLOC" -#endif -#if defined(SQLITE_SYSTEM_MALLOC) \ - + defined(SQLITE_WIN32_MALLOC) \ - + defined(SQLITE_ZERO_MALLOC) \ - + defined(SQLITE_MEMDEBUG)==0 -# define SQLITE_SYSTEM_MALLOC 1 -#endif - -/* -** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the -** sizes of memory allocations below this value where possible. -*/ -#if !defined(SQLITE_MALLOC_SOFT_LIMIT) -# define SQLITE_MALLOC_SOFT_LIMIT 1024 -#endif - -/* -** We need to define _XOPEN_SOURCE as follows in order to enable -** recursive mutexes on most Unix systems and fchmod() on OpenBSD. -** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit -** it. -*/ -#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) -# define _XOPEN_SOURCE 600 -#endif - -/* -** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that -** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true, -** make it true by defining or undefining NDEBUG. -** -** Setting NDEBUG makes the code smaller and faster by disabling the -** assert() statements in the code. So we want the default action -** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG -** is set. Thus NDEBUG becomes an opt-in rather than an opt-out -** feature. -*/ -#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) -# define NDEBUG 1 -#endif -#if defined(NDEBUG) && defined(SQLITE_DEBUG) -# undef NDEBUG -#endif - -/* -** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on. -*/ -#if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG) -# define SQLITE_ENABLE_EXPLAIN_COMMENTS 1 -#endif - -/* -** The testcase() macro is used to aid in coverage testing. When -** doing coverage testing, the condition inside the argument to -** testcase() must be evaluated both true and false in order to -** get full branch coverage. The testcase() macro is inserted -** to help ensure adequate test coverage in places where simple -** condition/decision coverage is inadequate. For example, testcase() -** can be used to make sure boundary values are tested. For -** bitmask tests, testcase() can be used to make sure each bit -** is significant and used at least once. On switch statements -** where multiple cases go to the same block of code, testcase() -** can insure that all cases are evaluated. -** -*/ -#ifdef SQLITE_COVERAGE_TEST -SQLITE_PRIVATE void sqlite3Coverage(int); -# define testcase(X) if( X ){ sqlite3Coverage(__LINE__); } -#else -# define testcase(X) -#endif - -/* -** The TESTONLY macro is used to enclose variable declarations or -** other bits of code that are needed to support the arguments -** within testcase() and assert() macros. -*/ -#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST) -# define TESTONLY(X) X -#else -# define TESTONLY(X) -#endif - -/* -** Sometimes we need a small amount of code such as a variable initialization -** to setup for a later assert() statement. We do not want this code to -** appear when assert() is disabled. The following macro is therefore -** used to contain that setup code. The "VVA" acronym stands for -** "Verification, Validation, and Accreditation". In other words, the -** code within VVA_ONLY() will only run during verification processes. -*/ -#ifndef NDEBUG -# define VVA_ONLY(X) X -#else -# define VVA_ONLY(X) -#endif - -/* -** The ALWAYS and NEVER macros surround boolean expressions which -** are intended to always be true or false, respectively. Such -** expressions could be omitted from the code completely. But they -** are included in a few cases in order to enhance the resilience -** of SQLite to unexpected behavior - to make the code "self-healing" -** or "ductile" rather than being "brittle" and crashing at the first -** hint of unplanned behavior. -** -** In other words, ALWAYS and NEVER are added for defensive code. -** -** When doing coverage testing ALWAYS and NEVER are hard-coded to -** be true and false so that the unreachable code they specify will -** not be counted as untested code. -*/ -#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST) -# define ALWAYS(X) (1) -# define NEVER(X) (0) -#elif !defined(NDEBUG) -# define ALWAYS(X) ((X)?1:(assert(0),0)) -# define NEVER(X) ((X)?(assert(0),1):0) -#else -# define ALWAYS(X) (X) -# define NEVER(X) (X) -#endif - -/* -** Some conditionals are optimizations only. In other words, if the -** conditionals are replaced with a constant 1 (true) or 0 (false) then -** the correct answer is still obtained, though perhaps not as quickly. -** -** The following macros mark these optimizations conditionals. -*/ -#if defined(SQLITE_MUTATION_TEST) -# define OK_IF_ALWAYS_TRUE(X) (1) -# define OK_IF_ALWAYS_FALSE(X) (0) -#else -# define OK_IF_ALWAYS_TRUE(X) (X) -# define OK_IF_ALWAYS_FALSE(X) (X) -#endif - -/* -** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is -** defined. We need to defend against those failures when testing with -** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches -** during a normal build. The following macro can be used to disable tests -** that are always false except when SQLITE_TEST_REALLOC_STRESS is set. -*/ -#if defined(SQLITE_TEST_REALLOC_STRESS) -# define ONLY_IF_REALLOC_STRESS(X) (X) -#elif !defined(NDEBUG) -# define ONLY_IF_REALLOC_STRESS(X) ((X)?(assert(0),1):0) -#else -# define ONLY_IF_REALLOC_STRESS(X) (0) -#endif - -/* -** Declarations used for tracing the operating system interfaces. -*/ -#if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \ - (defined(SQLITE_DEBUG) && SQLITE_OS_WIN) - extern int sqlite3OSTrace; -# define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X -# define SQLITE_HAVE_OS_TRACE -#else -# define OSTRACE(X) -# undef SQLITE_HAVE_OS_TRACE -#endif - -/* -** Is the sqlite3ErrName() function needed in the build? Currently, -** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when -** OSTRACE is enabled), and by several "test*.c" files (which are -** compiled using SQLITE_TEST). -*/ -#if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \ - (defined(SQLITE_DEBUG) && SQLITE_OS_WIN) -# define SQLITE_NEED_ERR_NAME -#else -# undef SQLITE_NEED_ERR_NAME -#endif - -/* -** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN -*/ -#ifdef SQLITE_OMIT_EXPLAIN -# undef SQLITE_ENABLE_EXPLAIN_COMMENTS -#endif - -/* -** Return true (non-zero) if the input is an integer that is too large -** to fit in 32-bits. This macro is used inside of various testcase() -** macros to verify that we have tested SQLite for large-file support. -*/ -#define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0) - -/* -** The macro unlikely() is a hint that surrounds a boolean -** expression that is usually false. Macro likely() surrounds -** a boolean expression that is usually true. These hints could, -** in theory, be used by the compiler to generate better code, but -** currently they are just comments for human readers. -*/ -#define likely(X) (X) -#define unlikely(X) (X) - -/************** Include hash.h in the middle of sqliteInt.h ******************/ -/************** Begin file hash.h ********************************************/ -/* -** 2001 September 22 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This is the header file for the generic hash-table implementation -** used in SQLite. -*/ -#ifndef SQLITE_HASH_H -#define SQLITE_HASH_H - -/* Forward declarations of structures. */ -typedef struct Hash Hash; -typedef struct HashElem HashElem; - -/* A complete hash table is an instance of the following structure. -** The internals of this structure are intended to be opaque -- client -** code should not attempt to access or modify the fields of this structure -** directly. Change this structure only by using the routines below. -** However, some of the "procedures" and "functions" for modifying and -** accessing this structure are really macros, so we can't really make -** this structure opaque. -** -** All elements of the hash table are on a single doubly-linked list. -** Hash.first points to the head of this list. -** -** There are Hash.htsize buckets. Each bucket points to a spot in -** the global doubly-linked list. The contents of the bucket are the -** element pointed to plus the next _ht.count-1 elements in the list. -** -** Hash.htsize and Hash.ht may be zero. In that case lookup is done -** by a linear search of the global list. For small tables, the -** Hash.ht table is never allocated because if there are few elements -** in the table, it is faster to do a linear search than to manage -** the hash table. -*/ -struct Hash { - unsigned int htsize; /* Number of buckets in the hash table */ - unsigned int count; /* Number of entries in this table */ - HashElem *first; /* The first element of the array */ - struct _ht { /* the hash table */ - 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_FOR 61 -#define TK_IGNORE 62 -#define TK_INITIALLY 63 -#define TK_INSTEAD 64 -#define TK_NO 65 -#define TK_KEY 66 -#define TK_OF 67 -#define TK_OFFSET 68 -#define TK_PRAGMA 69 -#define TK_RAISE 70 -#define TK_RECURSIVE 71 -#define TK_REPLACE 72 -#define TK_RESTRICT 73 -#define TK_ROW 74 -#define TK_TRIGGER 75 -#define TK_VACUUM 76 -#define TK_VIEW 77 -#define TK_VIRTUAL 78 -#define TK_WITH 79 -#define TK_REINDEX 80 -#define TK_RENAME 81 -#define TK_CTIME_KW 82 -#define TK_ANY 83 -#define TK_BITAND 84 -#define TK_BITOR 85 -#define TK_LSHIFT 86 -#define TK_RSHIFT 87 -#define TK_PLUS 88 -#define TK_MINUS 89 -#define TK_STAR 90 -#define TK_SLASH 91 -#define TK_REM 92 -#define TK_CONCAT 93 -#define TK_COLLATE 94 -#define TK_BITNOT 95 -#define TK_INDEXED 96 -#define TK_STRING 97 -#define TK_JOIN_KW 98 -#define TK_CONSTRAINT 99 -#define TK_DEFAULT 100 -#define TK_NULL 101 -#define TK_PRIMARY 102 -#define TK_UNIQUE 103 -#define TK_CHECK 104 -#define TK_REFERENCES 105 -#define TK_AUTOINCR 106 -#define TK_ON 107 -#define TK_INSERT 108 -#define TK_DELETE 109 -#define TK_UPDATE 110 -#define TK_SET 111 -#define TK_DEFERRABLE 112 -#define TK_FOREIGN 113 -#define TK_DROP 114 -#define TK_UNION 115 -#define TK_ALL 116 -#define TK_EXCEPT 117 -#define TK_INTERSECT 118 -#define TK_SELECT 119 -#define TK_VALUES 120 -#define TK_DISTINCT 121 -#define TK_DOT 122 -#define TK_FROM 123 -#define TK_JOIN 124 -#define TK_USING 125 -#define TK_ORDER 126 -#define TK_GROUP 127 -#define TK_HAVING 128 -#define TK_LIMIT 129 -#define TK_WHERE 130 -#define TK_INTO 131 -#define TK_FLOAT 132 -#define TK_BLOB 133 -#define TK_INTEGER 134 -#define TK_VARIABLE 135 -#define TK_CASE 136 -#define TK_WHEN 137 -#define TK_THEN 138 -#define TK_ELSE 139 -#define TK_INDEX 140 -#define TK_ALTER 141 -#define TK_ADD 142 -#define TK_ISNOT 143 -#define TK_FUNCTION 144 -#define TK_COLUMN 145 -#define TK_AGG_FUNCTION 146 -#define TK_AGG_COLUMN 147 -#define TK_UMINUS 148 -#define TK_UPLUS 149 -#define TK_REGISTER 150 -#define TK_VECTOR 151 -#define TK_SELECT_COLUMN 152 -#define TK_IF_NULL_ROW 153 -#define TK_ASTERISK 154 -#define TK_SPAN 155 -#define TK_END_OF_FILE 156 -#define TK_UNCLOSED_STRING 157 -#define TK_SPACE 158 -#define TK_ILLEGAL 159 - -/* The token codes above must all fit in 8 bits */ -#define TKFLG_MASK 0xff - -/* Flags that can be added to a token code when it is not -** being stored in a u8: */ -#define TKFLG_DONTFOLD 0x100 /* Omit constant folding optimizations */ - -/************** 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 - -/* -** 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) -# 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(__arm__) -# define SQLITE_BYTEORDER 1234 -# elif defined(sparc) || defined(__ppc__) -# define SQLITE_BYTEORDER 4321 -# else -# define SQLITE_BYTEORDER 0 -# endif -#endif -#if SQLITE_BYTEORDER==4321 -# define SQLITE_BIGENDIAN 1 -# define SQLITE_LITTLEENDIAN 0 -# define SQLITE_UTF16NATIVE SQLITE_UTF16BE -#elif SQLITE_BYTEORDER==1234 -# define SQLITE_BIGENDIAN 0 -# define SQLITE_LITTLEENDIAN 1 -# define SQLITE_UTF16NATIVE SQLITE_UTF16LE -#else -# ifdef SQLITE_AMALGAMATION - const int sqlite3one = 1; -# else - extern const int sqlite3one; -# endif -# define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0) -# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1) -# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE) -#endif - -/* -** Constants for the largest and smallest possible 64-bit signed integers. -** These macros are designed to work correctly on both 32-bit and 64-bit -** compilers. -*/ -#define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32)) -#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64) - -/* -** Round up a number to the next larger multiple of 8. This is used -** to force 8-byte alignment on 64-bit architectures. -*/ -#define ROUND8(x) (((x)+7)&~7) - -/* -** Round down to the nearest multiple of 8 -*/ -#define ROUNDDOWN8(x) ((x)&~7) - -/* -** Assert that the pointer X is aligned to an 8-byte boundary. This -** macro is used only within assert() to verify that the code gets -** all alignment restrictions correct. -** -** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the -** underlying malloc() implementation might return us 4-byte aligned -** pointers. In that case, only verify 4-byte alignment. -*/ -#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC -# define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0) -#else -# define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0) -#endif - -/* -** Disable MMAP on platforms where it is known to not work -*/ -#if defined(__OpenBSD__) || defined(__QNXNTO__) -# undef SQLITE_MAX_MMAP_SIZE -# define SQLITE_MAX_MMAP_SIZE 0 -#endif - -/* -** Default maximum size of memory used by memory-mapped I/O in the VFS -*/ -#ifdef __APPLE__ -# include -#endif -#ifndef SQLITE_MAX_MMAP_SIZE -# if defined(__linux__) \ - || defined(_WIN32) \ - || (defined(__APPLE__) && defined(__MACH__)) \ - || defined(__sun) \ - || defined(__FreeBSD__) \ - || defined(__DragonFly__) -# define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */ -# else -# define SQLITE_MAX_MMAP_SIZE 0 -# endif -#endif - -/* -** The default MMAP_SIZE is zero on all platforms. Or, even if a larger -** default MMAP_SIZE is specified at compile-time, make sure that it does -** not exceed the maximum mmap size. -*/ -#ifndef SQLITE_DEFAULT_MMAP_SIZE -# define SQLITE_DEFAULT_MMAP_SIZE 0 -#endif -#if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE -# undef SQLITE_DEFAULT_MMAP_SIZE -# define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE -#endif - -/* -** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined. -** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also -** define SQLITE_ENABLE_STAT3_OR_STAT4 -*/ -#ifdef SQLITE_ENABLE_STAT4 -# undef SQLITE_ENABLE_STAT3 -# define SQLITE_ENABLE_STAT3_OR_STAT4 1 -#elif SQLITE_ENABLE_STAT3 -# define SQLITE_ENABLE_STAT3_OR_STAT4 1 -#elif SQLITE_ENABLE_STAT3_OR_STAT4 -# undef SQLITE_ENABLE_STAT3_OR_STAT4 -#endif - -/* -** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not -** the Select query generator tracing logic is turned on. -*/ -#if defined(SQLITE_ENABLE_SELECTTRACE) -# define SELECTTRACE_ENABLED 1 -#else -# define SELECTTRACE_ENABLED 0 -#endif - -/* -** An instance of the following structure is used to store the busy-handler -** callback for a given sqlite handle. -** -** The sqlite.busyHandler member of the sqlite struct contains the busy -** callback for the database handle. Each pager opened via the sqlite -** handle is passed a pointer to sqlite.busyHandler. The busy-handler -** callback is currently invoked only from within pager.c. -*/ -typedef struct BusyHandler BusyHandler; -struct BusyHandler { - int (*xFunc)(void *,int); /* The busy callback */ - void *pArg; /* First arg to busy callback */ - int nBusy; /* Incremented with each busy call */ -}; - -/* -** Name of the master database table. The master database table -** is a special table that holds the names and attributes of all -** user tables and indices. -*/ -#define MASTER_NAME "sqlite_master" -#define TEMP_MASTER_NAME "sqlite_temp_master" - -/* -** The root-page of the master database table. -*/ -#define MASTER_ROOT 1 - -/* -** The name of the schema table. -*/ -#define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME) - -/* -** A convenience macro that returns the number of elements in -** an array. -*/ -#define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0]))) - -/* -** Determine if the argument is a power of two -*/ -#define IsPowerOfTwo(X) (((X)&((X)-1))==0) - -/* -** The following value as a destructor means to use sqlite3DbFree(). -** The sqlite3DbFree() routine requires two parameters instead of the -** one parameter that destructors normally want. So we have to introduce -** this magic value that the code knows to handle differently. Any -** pointer will work here as long as it is distinct from SQLITE_STATIC -** and SQLITE_TRANSIENT. -*/ -#define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize) - -/* -** When SQLITE_OMIT_WSD is defined, it means that the target platform does -** not support Writable Static Data (WSD) such as global and static variables. -** All variables must either be on the stack or dynamically allocated from -** the heap. When WSD is unsupported, the variable declarations scattered -** throughout the SQLite code must become constants instead. The SQLITE_WSD -** macro is used for this purpose. And instead of referencing the variable -** directly, we use its constant as a key to lookup the run-time allocated -** buffer that holds real variable. The constant is also the initializer -** for the run-time allocated buffer. -** -** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL -** macros become no-ops and have zero performance impact. -*/ -#ifdef SQLITE_OMIT_WSD - #define SQLITE_WSD const - #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v))) - #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config) -SQLITE_API int sqlite3_wsd_init(int N, int J); -SQLITE_API void *sqlite3_wsd_find(void *K, int L); -#else - #define SQLITE_WSD - #define GLOBAL(t,v) v - #define sqlite3GlobalConfig sqlite3Config -#endif - -/* -** The following macros are used to suppress compiler warnings and to -** make it clear to human readers when a function parameter is deliberately -** left unused within the body of a function. This usually happens when -** a function is called via a function pointer. For example the -** implementation of an SQL aggregate step callback may not use the -** parameter indicating the number of arguments passed to the aggregate, -** if it knows that this is enforced elsewhere. -** -** When a function parameter is not used at all within the body of a function, -** it is generally named "NotUsed" or "NotUsed2" to make things even clearer. -** However, these macros may also be used to suppress warnings related to -** parameters that may or may not be used depending on compilation options. -** For example those parameters only used in assert() statements. In these -** cases the parameters are named as per the usual conventions. -*/ -#define UNUSED_PARAMETER(x) (void)(x) -#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y) - -/* -** Forward references to structures -*/ -typedef struct AggInfo AggInfo; -typedef struct AuthContext AuthContext; -typedef struct AutoincInfo AutoincInfo; -typedef struct Bitvec Bitvec; -typedef struct CollSeq CollSeq; -typedef struct Column Column; -typedef struct Db Db; -typedef struct Schema Schema; -typedef struct Expr Expr; -typedef struct ExprList ExprList; -typedef struct ExprSpan ExprSpan; -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 RowSet RowSet; -typedef struct Savepoint Savepoint; -typedef struct Select Select; -typedef struct SQLiteThread SQLiteThread; -typedef struct SelectDest SelectDest; -typedef struct SrcList SrcList; -typedef struct StrAccum StrAccum; -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 VTable VTable; -typedef struct VtabCtx VtabCtx; -typedef struct Walker Walker; -typedef struct WhereInfo WhereInfo; -typedef struct With With; - -/* A VList object records a mapping between parameters/variables/wildcards -** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer -** variable number associated with that parameter. See the format description -** on the sqlite3VListAdd() routine for more information. A VList is really -** just an array of integers. -*/ -typedef int VList; - -/* -** Defer sourcing vdbe.h and btree.h until after the "u8" and -** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque -** pointer types (i.e. FuncDef) defined above. -*/ -/************** Include btree.h in the middle of sqliteInt.h *****************/ -/************** Begin file btree.h *******************************************/ -/* -** 2001 September 15 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This header file defines the interface that the sqlite B-Tree file -** subsystem. See comments in the source code for a detailed description -** of what each interface routine does. -*/ -#ifndef SQLITE_BTREE_H -#define SQLITE_BTREE_H - -/* TODO: This definition is just included so other modules compile. It -** needs to be revisited. -*/ -#define SQLITE_N_BTREE_META 16 - -/* -** If defined as non-zero, auto-vacuum is enabled by default. Otherwise -** it must be turned on for each database using "PRAGMA auto_vacuum = 1". -*/ -#ifndef SQLITE_DEFAULT_AUTOVACUUM - #define SQLITE_DEFAULT_AUTOVACUUM 0 -#endif - -#define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */ -#define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */ -#define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */ - -/* -** Forward declarations of structure -*/ -typedef struct Btree Btree; -typedef struct BtCursor BtCursor; -typedef struct BtShared BtShared; -typedef struct BtreePayload BtreePayload; - - -SQLITE_PRIVATE int sqlite3BtreeOpen( - sqlite3_vfs *pVfs, /* VFS to use with this b-tree */ - const char *zFilename, /* Name of database file to open */ - sqlite3 *db, /* Associated database connection */ - Btree **ppBtree, /* Return open Btree* here */ - int flags, /* Flags */ - int vfsFlags /* Flags passed through to VFS open */ -); - -/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the -** following values. -** -** NOTE: These values must match the corresponding PAGER_ values in -** pager.h. -*/ -#define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */ -#define BTREE_MEMORY 2 /* This is an in-memory DB */ -#define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */ -#define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */ - -SQLITE_PRIVATE int sqlite3BtreeClose(Btree*); -SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int); -SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int); -#if SQLITE_MAX_MMAP_SIZE>0 -SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64); -#endif -SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned); -SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix); -SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*); -SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int); -SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*); -SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int); -SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*); -SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p); -SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int); -SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *); -SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int); -SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster); -SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int); -SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*); -SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int); -SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int); -SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags); -SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*); -SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*); -SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*); -SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *)); -SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree); -#ifndef SQLITE_OMIT_SHARED_CACHE -SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock); -#endif -SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int); - -SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *); -SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *); -SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *); - -SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *); - -/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR -** of the flags shown below. -** -** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set. -** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data -** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With -** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored -** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL -** indices.) -*/ -#define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */ -#define BTREE_BLOBKEY 2 /* Table has keys only - no data */ - -SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*); -SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*); -SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*); -SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int); - -SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue); -SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value); - -SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p); - -/* -** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta -** should be one of the following values. The integer values are assigned -** to constants so that the offset of the corresponding field in an -** SQLite database header may be found using the following formula: -** -** offset = 36 + (idx * 4) -** -** For example, the free-page-count field is located at byte offset 36 of -** the database file header. The incr-vacuum-flag field is located at -** byte offset 64 (== 36+4*7). -** -** The BTREE_DATA_VERSION value is not really a value stored in the header. -** It is a read-only number computed by the pager. But we merge it with -** the header value access routines since its access pattern is the same. -** Call it a "virtual meta value". -*/ -#define BTREE_FREE_PAGE_COUNT 0 -#define BTREE_SCHEMA_VERSION 1 -#define BTREE_FILE_FORMAT 2 -#define BTREE_DEFAULT_CACHE_SIZE 3 -#define BTREE_LARGEST_ROOT_PAGE 4 -#define BTREE_TEXT_ENCODING 5 -#define BTREE_USER_VERSION 6 -#define BTREE_INCR_VACUUM 7 -#define BTREE_APPLICATION_ID 8 -#define BTREE_DATA_VERSION 15 /* A virtual meta-value */ - -/* -** Kinds of hints that can be passed into the sqlite3BtreeCursorHint() -** interface. -** -** BTREE_HINT_RANGE (arguments: Expr*, Mem*) -** -** The first argument is an Expr* (which is guaranteed to be constant for -** the lifetime of the cursor) that defines constraints on which rows -** might be fetched with this cursor. The Expr* tree may contain -** TK_REGISTER nodes that refer to values stored in the array of registers -** passed as the second parameter. In other words, if Expr.op==TK_REGISTER -** then the value of the node is the value in Mem[pExpr.iTable]. Any -** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th -** column of the b-tree of the cursor. The Expr tree will not contain -** any function calls nor subqueries nor references to b-trees other than -** the cursor being hinted. -** -** The design of the _RANGE hint is aid b-tree implementations that try -** to prefetch content from remote machines - to provide those -** implementations with limits on what needs to be prefetched and thereby -** reduce network bandwidth. -** -** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by -** standard SQLite. The other hints are provided for extentions that use -** the SQLite parser and code generator but substitute their own storage -** engine. -*/ -#define BTREE_HINT_RANGE 0 /* Range constraints on queries */ - -/* -** Values that may be OR'd together to form the argument to the -** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint(): -** -** The BTREE_BULKLOAD flag is set on index cursors when the index is going -** to be filled with content that is already in sorted order. -** -** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or -** OP_SeekLE opcodes for a range search, but where the range of entries -** selected will all have the same key. In other words, the cursor will -** be used only for equality key searches. -** -*/ -#define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */ -#define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */ - -/* -** Flags passed as the third argument to sqlite3BtreeCursor(). -** -** For read-only cursors the wrFlag argument is always zero. For read-write -** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just -** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will -** only be used by SQLite for the following: -** -** * to seek to and then delete specific entries, and/or -** -** * to read values that will be used to create keys that other -** BTREE_FORDELETE cursors will seek to and delete. -** -** The BTREE_FORDELETE flag is an optimization hint. It is not used by -** by this, the native b-tree engine of SQLite, but it is available to -** alternative storage engines that might be substituted in place of this -** b-tree system. For alternative storage engines in which a delete of -** the main table row automatically deletes corresponding index rows, -** the FORDELETE flag hint allows those alternative storage engines to -** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK -** and DELETE operations as no-ops, and any READ operation against a -** FORDELETE cursor may return a null row: 0x01 0x00. -*/ -#define BTREE_WRCSR 0x00000004 /* read-write cursor */ -#define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */ - -SQLITE_PRIVATE int sqlite3BtreeCursor( - Btree*, /* BTree containing table to open */ - int iTable, /* Index of root page */ - int wrFlag, /* 1 for writing. 0 for read-only */ - struct KeyInfo*, /* First argument to compare function */ - BtCursor *pCursor /* Space to write cursor structure */ -); -SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void); -SQLITE_PRIVATE int sqlite3BtreeCursorSize(void); -SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*); -SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned); -#ifdef SQLITE_ENABLE_CURSOR_HINTS -SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...); -#endif - -SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*); -SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked( - BtCursor*, - UnpackedRecord *pUnKey, - i64 intKey, - int bias, - int *pRes -); -SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*); -SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*); -SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags); - -/* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */ -#define BTREE_SAVEPOSITION 0x02 /* Leave cursor pointing at NEXT or PREV */ -#define BTREE_AUXDELETE 0x04 /* not the primary delete operation */ -#define BTREE_APPEND 0x08 /* Insert is likely an append */ - -/* An instance of the BtreePayload object describes the content of a single -** entry in either an index or table btree. -** -** Index btrees (used for indexes and also WITHOUT ROWID tables) contain -** an arbitrary key and no data. These btrees have pKey,nKey set to their -** key and pData,nData,nZero set to zero. -** -** 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. -** -** 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. NULL for indexes */ - 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 int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*); -SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt); -SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*); - -SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*); -SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*); -SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*); - -#ifndef SQLITE_OMIT_INCRBLOB -SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*); -SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*); -SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *); -#endif -SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *); -SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion); -SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask); -SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt); -SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void); - -#ifndef NDEBUG -SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*); -#endif -SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*); - -#ifndef SQLITE_OMIT_BTREECOUNT -SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *); -#endif - -#ifdef SQLITE_TEST -SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int); -SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*); -#endif - -#ifndef SQLITE_OMIT_WAL -SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *); -#endif - -/* -** If we are not using shared cache, then there is no need to -** use mutexes to access the BtShared structures. So make the -** Enter and Leave procedures no-ops. -*/ -#ifndef SQLITE_OMIT_SHARED_CACHE -SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*); -SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*); -SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*); -SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*); -SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree*); -#else -# define sqlite3BtreeEnter(X) -# define sqlite3BtreeEnterAll(X) -# define sqlite3BtreeSharable(X) 0 -# define sqlite3BtreeEnterCursor(X) -# define sqlite3BtreeConnectionCount(X) 1 -#endif - -#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE -SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*); -SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*); -SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*); -#ifndef NDEBUG - /* These routines are used inside assert() statements only. */ -SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*); -SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*); -SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*); -#endif -#else - -# define sqlite3BtreeLeave(X) -# define sqlite3BtreeLeaveCursor(X) -# define sqlite3BtreeLeaveAll(X) - -# define sqlite3BtreeHoldsMutex(X) 1 -# define sqlite3BtreeHoldsAllMutexes(X) 1 -# define sqlite3SchemaMutexHeld(X,Y,Z) 1 -#endif - - -#endif /* SQLITE_BTREE_H */ - -/************** End of btree.h ***********************************************/ -/************** Continuing where we left off in sqliteInt.h ******************/ -/************** Include vdbe.h in the middle of sqliteInt.h ******************/ -/************** Begin file vdbe.h ********************************************/ -/* -** 2001 September 15 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** Header file for the Virtual DataBase Engine (VDBE) -** -** This header defines the interface to the virtual database engine -** or VDBE. The VDBE implements an abstract machine that runs a -** simple program to access and modify the underlying database. -*/ -#ifndef SQLITE_VDBE_H -#define SQLITE_VDBE_H -/* #include */ - -/* -** A single VDBE is an opaque structure named "Vdbe". Only routines -** in the source file sqliteVdbe.c are allowed to see the insides -** of this structure. -*/ -typedef struct Vdbe Vdbe; - -/* -** The names of the following types declared in vdbeInt.h are required -** for the VdbeOp definition. -*/ -typedef struct sqlite3_value Mem; -typedef struct SubProgram SubProgram; - -/* -** A single instruction of the virtual machine has an opcode -** and as many as three operands. The instruction is recorded -** as an instance of the following structure: -*/ -struct VdbeOp { - u8 opcode; /* What operation to perform */ - signed char p4type; /* One of the P4_xxx constants for p4 */ - u16 p5; /* Fifth parameter is an unsigned 16-bit integer */ - int p1; /* First operand */ - int p2; /* Second parameter (often the jump destination) */ - int p3; /* The third parameter */ - union p4union { /* fourth parameter */ - int i; /* Integer value if p4type==P4_INT32 */ - void *p; /* Generic pointer */ - char *z; /* Pointer to data for string (char array) types */ - i64 *pI64; /* Used when p4type is P4_INT64 */ - double *pReal; /* Used when p4type is P4_REAL */ - FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */ - sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */ - CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */ - Mem *pMem; /* Used when p4type is P4_MEM */ - VTable *pVtab; /* Used when p4type is P4_VTAB */ - KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */ - int *ai; /* Used when p4type is P4_INTARRAY */ - SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */ - Table *pTab; /* Used when p4type is P4_TABLE */ -#ifdef SQLITE_ENABLE_CURSOR_HINTS - Expr *pExpr; /* Used when p4type is P4_EXPR */ -#endif - int (*xAdvance)(BtCursor *, int); - } p4; -#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS - char *zComment; /* Comment to improve readability */ -#endif -#ifdef VDBE_PROFILE - u32 cnt; /* Number of times this instruction was executed */ - u64 cycles; /* Total time spent executing this instruction */ -#endif -#ifdef SQLITE_VDBE_COVERAGE - int iSrcLine; /* Source-code line that generated this opcode */ -#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 */ - -/* 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 relative address in the p2 field -** of a VdbeOp structure into a negative number so that -** sqlite3VdbeAddOpList() knows that the address is relative. Calling -** the macro again restores the address. -*/ -#define ADDR(X) (-1-(X)) - -/* -** 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_PrevIfOpen 4 /* jump */ -#define OP_NextIfOpen 5 /* jump */ -#define OP_Prev 6 /* jump */ -#define OP_Next 7 /* jump */ -#define OP_Checkpoint 8 -#define OP_JournalMode 9 -#define OP_Vacuum 10 -#define OP_VFilter 11 /* jump, synopsis: iplan=r[P3] zplan='P4' */ -#define OP_VUpdate 12 /* synopsis: data=r[P3@P2] */ -#define OP_Goto 13 /* jump */ -#define OP_Gosub 14 /* jump */ -#define OP_InitCoroutine 15 /* jump */ -#define OP_Yield 16 /* jump */ -#define OP_MustBeInt 17 /* jump */ -#define OP_Jump 18 /* jump */ -#define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */ -#define OP_Once 20 /* jump */ -#define OP_If 21 /* jump */ -#define OP_IfNot 22 /* jump */ -#define OP_IfNullRow 23 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */ -#define OP_SeekLT 24 /* jump, synopsis: key=r[P3@P4] */ -#define OP_SeekLE 25 /* jump, synopsis: key=r[P3@P4] */ -#define OP_SeekGE 26 /* jump, synopsis: key=r[P3@P4] */ -#define OP_SeekGT 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_Return 63 -#define OP_EndCoroutine 64 -#define OP_HaltIfNull 65 /* synopsis: if r[P3]=null halt */ -#define OP_Halt 66 -#define OP_Integer 67 /* synopsis: r[P2]=P1 */ -#define OP_Int64 68 /* synopsis: r[P2]=P4 */ -#define OP_String 69 /* synopsis: r[P2]='P4' (len=P1) */ -#define OP_Null 70 /* synopsis: r[P2..P3]=NULL */ -#define OP_SoftNull 71 /* synopsis: r[P1]=NULL */ -#define OP_Blob 72 /* synopsis: r[P2]=P4 (len=P1) */ -#define OP_Variable 73 /* synopsis: r[P2]=parameter(P1,P4) */ -#define OP_Move 74 /* synopsis: r[P2@P3]=r[P1@P3] */ -#define OP_Copy 75 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */ -#define OP_SCopy 76 /* synopsis: r[P2]=r[P1] */ -#define OP_IntCopy 77 /* synopsis: r[P2]=r[P1] */ -#define OP_ResultRow 78 /* synopsis: output=r[P1@P2] */ -#define OP_CollSeq 79 -#define OP_AddImm 80 /* synopsis: r[P1]=r[P1]+P2 */ -#define OP_RealAffinity 81 -#define OP_Cast 82 /* synopsis: affinity(r[P1]) */ -#define OP_Permutation 83 -#define OP_BitAnd 84 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */ -#define OP_BitOr 85 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */ -#define OP_ShiftLeft 86 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<>r[P1] */ -#define OP_Add 88 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */ -#define OP_Subtract 89 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */ -#define OP_Multiply 90 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */ -#define OP_Divide 91 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */ -#define OP_Remainder 92 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */ -#define OP_Concat 93 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */ -#define OP_Compare 94 /* synopsis: r[P1@P3] <-> r[P2@P3] */ -#define OP_BitNot 95 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */ -#define OP_Column 96 /* synopsis: r[P3]=PX */ -#define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */ -#define OP_Affinity 98 /* synopsis: affinity(r[P1@P2]) */ -#define OP_MakeRecord 99 /* synopsis: r[P3]=mkrec(r[P1@P2]) */ -#define OP_Count 100 /* synopsis: r[P2]=count() */ -#define OP_ReadCookie 101 -#define OP_SetCookie 102 -#define OP_ReopenIdx 103 /* synopsis: root=P2 iDb=P3 */ -#define OP_OpenRead 104 /* synopsis: root=P2 iDb=P3 */ -#define OP_OpenWrite 105 /* synopsis: root=P2 iDb=P3 */ -#define OP_OpenDup 106 -#define OP_OpenAutoindex 107 /* synopsis: nColumn=P2 */ -#define OP_OpenEphemeral 108 /* synopsis: nColumn=P2 */ -#define OP_SorterOpen 109 -#define OP_SequenceTest 110 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */ -#define OP_OpenPseudo 111 /* synopsis: P3 columns in r[P2] */ -#define OP_Close 112 -#define OP_ColumnsUsed 113 -#define OP_Sequence 114 /* synopsis: r[P2]=cursor[P1].ctr++ */ -#define OP_NewRowid 115 /* synopsis: r[P2]=rowid */ -#define OP_Insert 116 /* synopsis: intkey=r[P3] data=r[P2] */ -#define OP_InsertInt 117 /* synopsis: intkey=P3 data=r[P2] */ -#define OP_Delete 118 -#define OP_ResetCount 119 -#define OP_SorterCompare 120 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */ -#define OP_SorterData 121 /* synopsis: r[P2]=data */ -#define OP_RowData 122 /* synopsis: r[P2]=data */ -#define OP_Rowid 123 /* synopsis: r[P2]=rowid */ -#define OP_NullRow 124 -#define OP_SeekEnd 125 -#define OP_SorterInsert 126 /* synopsis: key=r[P2] */ -#define OP_IdxInsert 127 /* synopsis: key=r[P2] */ -#define OP_IdxDelete 128 /* synopsis: key=r[P2@P3] */ -#define OP_DeferredSeek 129 /* synopsis: Move P3 to P1.rowid if needed */ -#define OP_IdxRowid 130 /* synopsis: r[P2]=rowid */ -#define OP_Destroy 131 -#define OP_Real 132 /* same as TK_FLOAT, synopsis: r[P2]=P4 */ -#define OP_Clear 133 -#define OP_ResetSorter 134 -#define OP_CreateBtree 135 /* synopsis: r[P2]=root iDb=P1 flags=P3 */ -#define OP_SqlExec 136 -#define OP_ParseSchema 137 -#define OP_LoadAnalysis 138 -#define OP_DropTable 139 -#define OP_DropIndex 140 -#define OP_DropTrigger 141 -#define OP_IntegrityCk 142 -#define OP_RowSetAdd 143 /* synopsis: rowset(P1)=r[P2] */ -#define OP_Param 144 -#define OP_FkCounter 145 /* synopsis: fkctr[P1]+=P2 */ -#define OP_MemMax 146 /* synopsis: r[P1]=max(r[P1],r[P2]) */ -#define OP_OffsetLimit 147 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */ -#define OP_AggStep0 148 /* synopsis: accum=r[P3] step(r[P2@P5]) */ -#define OP_AggStep 149 /* synopsis: accum=r[P3] step(r[P2@P5]) */ -#define OP_AggFinal 150 /* synopsis: accum=r[P1] N=P2 */ -#define OP_Expire 151 -#define OP_TableLock 152 /* synopsis: iDb=P1 root=P2 write=P3 */ -#define OP_VBegin 153 -#define OP_VCreate 154 -#define OP_VDestroy 155 -#define OP_VOpen 156 -#define OP_VColumn 157 /* synopsis: r[P3]=vcolumn(P2) */ -#define OP_VRename 158 -#define OP_Pagecount 159 -#define OP_MaxPgcnt 160 -#define OP_PureFunc0 161 -#define OP_Function0 162 /* synopsis: r[P3]=func(r[P2@P5]) */ -#define OP_PureFunc 163 -#define OP_Function 164 /* synopsis: r[P3]=func(r[P2@P5]) */ -#define OP_CursorHint 165 -#define OP_Noop 166 -#define OP_Explain 167 - -/* 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, 0x01, 0x01,\ -/* 8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,\ -/* 16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0x03, 0x03, 0x01,\ -/* 24 */ 0x09, 0x09, 0x09, 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, 0x02,\ -/* 64 */ 0x02, 0x08, 0x00, 0x10, 0x10, 0x10, 0x10, 0x00,\ -/* 72 */ 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\ -/* 80 */ 0x02, 0x02, 0x02, 0x00, 0x26, 0x26, 0x26, 0x26,\ -/* 88 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00, 0x12,\ -/* 96 */ 0x00, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\ -/* 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\ -/* 112 */ 0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00,\ -/* 120 */ 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x04, 0x04,\ -/* 128 */ 0x00, 0x00, 0x10, 0x10, 0x10, 0x00, 0x00, 0x10,\ -/* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06,\ -/* 144 */ 0x10, 0x00, 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00,\ -/* 152 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,\ -/* 160 */ 0x10, 0x00, 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 int sqlite3VdbeAddOp0(Vdbe*,int); -SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int); -SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int); -SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int); -SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*); -SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...); -SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int); -SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int); -SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int); -SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int); -SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int); -#if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS) -SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N); -SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p); -#else -# define sqlite3VdbeVerifyNoMallocRequired(A,B) -# define sqlite3VdbeVerifyNoResultRow(A) -#endif -SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno); -SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*); -SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8); -SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1); -SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2); -SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3); -SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5); -SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr); -SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr); -SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op); -SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N); -SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type); -SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*); -SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int); -SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int); -SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*); -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); -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 void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*); -SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*); -SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int); -SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*); - -typedef int (*RecordCompare)(int,const void*,UnpackedRecord*); -SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*); - -#ifndef SQLITE_OMIT_TRIGGER -SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *); -#endif - -SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*); - -/* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on -** each VDBE opcode. -** -** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op -** comments in VDBE programs that show key decision points in the code -** generator. -*/ -#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS -SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...); -# define VdbeComment(X) sqlite3VdbeComment X -SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...); -# define VdbeNoopComment(X) sqlite3VdbeNoopComment X -# ifdef SQLITE_ENABLE_MODULE_COMMENTS -# define VdbeModuleComment(X) sqlite3VdbeNoopComment X -# else -# define VdbeModuleComment(X) -# endif -#else -# define VdbeComment(X) -# define VdbeNoopComment(X) -# define VdbeModuleComment(X) -#endif - -/* -** The VdbeCoverage macros are used to set a coverage testing point -** for VDBE branch instructions. The coverage testing points are line -** numbers in the sqlite3.c source file. VDBE branch coverage testing -** only works with an amalagmation build. That's ok since a VDBE branch -** coverage build designed for testing the test suite only. No application -** should ever ship with VDBE branch coverage measuring turned on. -** -** VdbeCoverage(v) // Mark the previously coded instruction -** // as a branch -** -** VdbeCoverageIf(v, conditional) // Mark previous if conditional true -** -** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken -** -** VdbeCoverageNeverTaken(v) // Previous branch is never taken -** -** 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. -*/ -#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,2); -# define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1); -# define VDBE_OFFSET_LINENO(x) (__LINE__+x) -#else -# define VdbeCoverage(v) -# define VdbeCoverageIf(v,x) -# define VdbeCoverageAlwaysTaken(v) -# define VdbeCoverageNeverTaken(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 - -#endif /* SQLITE_VDBE_H */ - -/************** End of vdbe.h ************************************************/ -/************** Continuing where we left off in sqliteInt.h ******************/ -/************** Include pager.h in the middle of sqliteInt.h *****************/ -/************** Begin file pager.h *******************************************/ -/* -** 2001 September 15 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This header file defines the interface that the sqlite page cache -** subsystem. The page cache subsystem reads and writes a file a page -** at a time and provides a journal for rollback. -*/ - -#ifndef SQLITE_PAGER_H -#define SQLITE_PAGER_H - -/* -** Default maximum size for persistent journal files. A negative -** value means no limit. This value may be overridden using the -** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit". -*/ -#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT - #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1 -#endif - -/* -** The type used to represent a page number. The first page in a file -** is called page 1. 0 is used to represent "not a page". -*/ -typedef u32 Pgno; - -/* -** Each open file is managed by a separate instance of the "Pager" structure. -*/ -typedef struct Pager Pager; - -/* -** Handle type for pages. -*/ -typedef struct PgHdr DbPage; - -/* -** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is -** reserved for working around a windows/posix incompatibility). It is -** used in the journal to signify that the remainder of the journal file -** is devoted to storing a master journal name - there are no more pages to -** roll back. See comments for function writeMasterJournal() in pager.c -** for details. -*/ -#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1)) - -/* -** Allowed values for the flags parameter to sqlite3PagerOpen(). -** -** NOTE: These values must match the corresponding BTREE_ values in btree.h. -*/ -#define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */ -#define PAGER_MEMORY 0x0002 /* In-memory database */ - -/* -** Valid values for the second argument to sqlite3PagerLockingMode(). -*/ -#define PAGER_LOCKINGMODE_QUERY -1 -#define PAGER_LOCKINGMODE_NORMAL 0 -#define PAGER_LOCKINGMODE_EXCLUSIVE 1 - -/* -** Numeric constants that encode the journalmode. -** -** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY) -** are exposed in the API via the "PRAGMA journal_mode" command and -** therefore cannot be changed without a compatibility break. -*/ -#define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */ -#define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */ -#define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */ -#define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */ -#define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */ -#define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */ -#define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */ - -/* -** Flags that make up the mask passed to sqlite3PagerGet(). -*/ -#define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */ -#define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */ - -/* -** Flags for sqlite3PagerSetFlags() -** -** Value constraints (enforced via assert()): -** PAGER_FULLFSYNC == SQLITE_FullFSync -** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync -** PAGER_CACHE_SPILL == SQLITE_CacheSpill -*/ -#define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */ -#define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */ -#define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */ -#define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */ -#define PAGER_SYNCHRONOUS_MASK 0x07 /* Mask for four values above */ -#define PAGER_FULLFSYNC 0x08 /* PRAGMA fullfsync=ON */ -#define PAGER_CKPT_FULLFSYNC 0x10 /* PRAGMA checkpoint_fullfsync=ON */ -#define PAGER_CACHESPILL 0x20 /* PRAGMA cache_spill=ON */ -#define PAGER_FLAGS_MASK 0x38 /* All above except SYNCHRONOUS */ - -/* -** The remainder of this file contains the declarations of the functions -** that make up the Pager sub-system API. See source code comments for -** a detailed description of each routine. -*/ - -/* Open and close a Pager connection. */ -SQLITE_PRIVATE int sqlite3PagerOpen( - sqlite3_vfs*, - Pager **ppPager, - const char*, - int, - int, - int, - void(*)(DbPage*) -); -SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*); -SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*); - -/* Functions used to configure a Pager object. */ -SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *); -SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int); -#ifdef SQLITE_HAS_CODEC -SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*); -#endif -SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int); -SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int); -SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int); -SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64); -SQLITE_PRIVATE void sqlite3PagerShrink(Pager*); -SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned); -SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int); -SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int); -SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*); -SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*); -SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64); -SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*); -SQLITE_PRIVATE int sqlite3PagerFlush(Pager*); - -/* Functions used to obtain and release page references. */ -SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag); -SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno); -SQLITE_PRIVATE void sqlite3PagerRef(DbPage*); -SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*); -SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*); -SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage*); - -/* Operations on page references. */ -SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*); -SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*); -SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int); -SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*); -SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); -SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); - -/* Functions used to manage pager transactions and savepoints. */ -SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*); -SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int); -SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int); -SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*); -SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster); -SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*); -SQLITE_PRIVATE int sqlite3PagerRollback(Pager*); -SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n); -SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint); -SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager); - -#ifndef SQLITE_OMIT_WAL -SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*); -SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager); -SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager); -SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen); -SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3*); -# ifdef SQLITE_DIRECT_OVERFLOW_READ -SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager, Pgno); -# endif -# ifdef SQLITE_ENABLE_SNAPSHOT -SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot); -SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot); -SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager); -# endif -#else -# define sqlite3PagerUseWal(x,y) 0 -#endif - -#ifdef SQLITE_ENABLE_ZIPVFS -SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager); -#endif - -/* Functions used to query pager state and configuration. */ -SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*); -SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*); -#ifdef SQLITE_DEBUG -SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*); -#endif -SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*); -SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int); -SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*); -SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*); -SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*); -SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*); -SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*); -SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*); -SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *); -SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*); -SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *); - -/* Functions used to truncate the database file. */ -SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno); - -SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16); - -#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL) -SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *); -#endif - -/* Functions to support testing and debugging. */ -#if !defined(NDEBUG) || defined(SQLITE_TEST) -SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*); -SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*); -#endif -#ifdef SQLITE_TEST -SQLITE_PRIVATE int *sqlite3PagerStats(Pager*); -SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*); - void disable_simulated_io_errors(void); - void enable_simulated_io_errors(void); -#else -# define disable_simulated_io_errors() -# define enable_simulated_io_errors() -#endif - -#endif /* SQLITE_PAGER_H */ - -/************** End of pager.h ***********************************************/ -/************** Continuing where we left off in sqliteInt.h ******************/ -/************** Include pcache.h in the middle of sqliteInt.h ****************/ -/************** Begin file pcache.h ******************************************/ -/* -** 2008 August 05 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This header file defines the interface that the sqlite page cache -** subsystem. -*/ - -#ifndef _PCACHE_H_ - -typedef struct PgHdr PgHdr; -typedef struct PCache PCache; - -/* -** Every page in the cache is controlled by an instance of the following -** structure. -*/ -struct PgHdr { - sqlite3_pcache_page *pPage; /* Pcache object page handle */ - void *pData; /* Page data */ - void *pExtra; /* Extra content */ - PCache *pCache; /* PRIVATE: Cache that owns this page */ - PgHdr *pDirty; /* Transient list of dirty sorted by pgno */ - Pager *pPager; /* The pager this page is part of */ - Pgno pgno; /* Page number for this page */ -#ifdef SQLITE_CHECK_PAGES - u32 pageHash; /* Hash of page content */ -#endif - u16 flags; /* PGHDR flags defined below */ - - /********************************************************************** - ** Elements above, except pCache, are public. All that follow are - ** private to pcache.c and should not be accessed by other modules. - ** pCache is grouped with the public elements for efficiency. - */ - i16 nRef; /* Number of users of this page */ - PgHdr *pDirtyNext; /* Next element in list of dirty pages */ - PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */ - /* NB: pDirtyNext and pDirtyPrev are undefined if the - ** PgHdr object is not dirty */ -}; - -/* Bit values for PgHdr.flags */ -#define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */ -#define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */ -#define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */ -#define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before - ** writing this page to the database */ -#define PGHDR_DONT_WRITE 0x010 /* Do not write content to disk */ -#define PGHDR_MMAP 0x020 /* This is an mmap page object */ - -#define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */ - -/* Initialize and shutdown the page cache subsystem */ -SQLITE_PRIVATE int sqlite3PcacheInitialize(void); -SQLITE_PRIVATE void sqlite3PcacheShutdown(void); - -/* Page cache buffer management: -** These routines implement SQLITE_CONFIG_PAGECACHE. -*/ -SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n); - -/* Create a new pager cache. -** Under memory stress, invoke xStress to try to make pages clean. -** Only clean and unpinned pages can be reclaimed. -*/ -SQLITE_PRIVATE int sqlite3PcacheOpen( - int szPage, /* Size of every page */ - int szExtra, /* Extra space associated with each page */ - int bPurgeable, /* True if pages are on backing store */ - int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */ - void *pStress, /* Argument to xStress */ - PCache *pToInit /* Preallocated space for the PCache */ -); - -/* Modify the page-size after the cache has been created. */ -SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int); - -/* Return the size in bytes of a PCache object. Used to preallocate -** storage space. -*/ -SQLITE_PRIVATE int sqlite3PcacheSize(void); - -/* One release per successful fetch. Page is pinned until released. -** Reference counted. -*/ -SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag); -SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**); -SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage); -SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*); - -SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */ -SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */ -SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */ -SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */ -SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*); - -/* Change a page number. Used by incr-vacuum. */ -SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno); - -/* Remove all pages with pgno>x. Reset the cache if x==0 */ -SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x); - -/* Get a list of all dirty pages in the cache, sorted by page number */ -SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*); - -/* Reset and close the cache object */ -SQLITE_PRIVATE void sqlite3PcacheClose(PCache*); - -/* Clear flags from pages of the page cache */ -SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *); - -/* Discard the contents of the cache */ -SQLITE_PRIVATE void sqlite3PcacheClear(PCache*); - -/* Return the total number of outstanding page references */ -SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*); - -/* Increment the reference count of an existing page */ -SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*); - -SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*); - -/* Return the total number of pages stored in the cache */ -SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*); - -#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG) -/* Iterate through all dirty pages currently stored in the cache. This -** interface is only available if SQLITE_CHECK_PAGES is defined when the -** library is built. -*/ -SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)); -#endif - -#if defined(SQLITE_DEBUG) -/* Check invariants on a PgHdr object */ -SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*); -#endif - -/* Set and get the suggested cache-size for the specified pager-cache. -** -** If no global maximum is configured, then the system attempts to limit -** the total number of pages cached by purgeable pager-caches to the sum -** of the suggested cache-sizes. -*/ -SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int); -#ifdef SQLITE_TEST -SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *); -#endif - -/* Set or get the suggested spill-size for the specified pager-cache. -** -** The spill-size is the minimum number of pages in cache before the cache -** will attempt to spill dirty pages by calling xStress. -*/ -SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int); - -/* Free up as much memory as possible from the page cache */ -SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*); - -#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT -/* Try to return memory used by the pcache module to the main memory heap */ -SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int); -#endif - -#ifdef SQLITE_TEST -SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*); -#endif - -SQLITE_PRIVATE void sqlite3PCacheSetDefault(void); - -/* Return the header size */ -SQLITE_PRIVATE int sqlite3HeaderSizePcache(void); -SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void); - -/* Number of dirty pages as a percentage of the configured cache size */ -SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*); - -#endif /* _PCACHE_H_ */ - -/************** End of pcache.h **********************************************/ -/************** Continuing where we left off in sqliteInt.h ******************/ -/************** Include os.h in the middle of sqliteInt.h ********************/ -/************** Begin file os.h **********************************************/ -/* -** 2001 September 16 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This header file (together with is companion C source-code file -** "os.c") attempt to abstract the underlying operating system so that -** the SQLite library will work on both POSIX and windows systems. -** -** This header file is #include-ed by sqliteInt.h and thus ends up -** being included by every source file. -*/ -#ifndef _SQLITE_OS_H_ -#define _SQLITE_OS_H_ - -/* -** Attempt to automatically detect the operating system and setup the -** necessary pre-processor macros for it. -*/ -/************** Include os_setup.h in the middle of os.h *********************/ -/************** Begin file os_setup.h ****************************************/ -/* -** 2013 November 25 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This file contains pre-processor directives related to operating system -** detection and/or setup. -*/ -#ifndef SQLITE_OS_SETUP_H -#define SQLITE_OS_SETUP_H - -/* -** Figure out if we are dealing with Unix, Windows, or some other operating -** system. -** -** After the following block of preprocess macros, all of SQLITE_OS_UNIX, -** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of -** the three will be 1. The other two will be 0. -*/ -#if defined(SQLITE_OS_OTHER) -# if SQLITE_OS_OTHER==1 -# undef SQLITE_OS_UNIX -# define SQLITE_OS_UNIX 0 -# undef SQLITE_OS_WIN -# define SQLITE_OS_WIN 0 -# else -# undef SQLITE_OS_OTHER -# endif -#endif -#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER) -# define SQLITE_OS_OTHER 0 -# ifndef SQLITE_OS_WIN -# if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \ - defined(__MINGW32__) || defined(__BORLANDC__) -# define SQLITE_OS_WIN 1 -# define SQLITE_OS_UNIX 0 -# else -# define SQLITE_OS_WIN 0 -# define SQLITE_OS_UNIX 1 -# endif -# else -# define SQLITE_OS_UNIX 0 -# endif -#else -# ifndef SQLITE_OS_WIN -# define SQLITE_OS_WIN 0 -# endif -#endif - -#endif /* SQLITE_OS_SETUP_H */ - -/************** End of os_setup.h ********************************************/ -/************** Continuing where we left off in os.h *************************/ - -/* If the SET_FULLSYNC macro is not defined above, then make it -** a no-op -*/ -#ifndef SET_FULLSYNC -# define SET_FULLSYNC(x,y) -#endif - -/* -** The default size of a disk sector -*/ -#ifndef SQLITE_DEFAULT_SECTOR_SIZE -# define SQLITE_DEFAULT_SECTOR_SIZE 4096 -#endif - -/* -** Temporary files are named starting with this prefix followed by 16 random -** alphanumeric characters, and no file extension. They are stored in the -** OS's standard temporary file directory, and are deleted prior to exit. -** If sqlite is being embedded in another program, you may wish to change the -** prefix to reflect your program's name, so that if your program exits -** prematurely, old temporary files can be easily identified. This can be done -** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line. -** -** 2006-10-31: The default prefix used to be "sqlite_". But then -** Mcafee started using SQLite in their anti-virus product and it -** started putting files with the "sqlite" name in the c:/temp folder. -** This annoyed many windows users. Those users would then do a -** Google search for "sqlite", find the telephone numbers of the -** developers and call to wake them up at night and complain. -** For this reason, the default name prefix is changed to be "sqlite" -** spelled backwards. So the temp files are still identified, but -** anybody smart enough to figure out the code is also likely smart -** enough to know that calling the developer will not help get rid -** of the file. -*/ -#ifndef SQLITE_TEMP_FILE_PREFIX -# define SQLITE_TEMP_FILE_PREFIX "etilqs_" -#endif - -/* -** The following values may be passed as the second argument to -** sqlite3OsLock(). The various locks exhibit the following semantics: -** -** SHARED: Any number of processes may hold a SHARED lock simultaneously. -** RESERVED: A single process may hold a RESERVED lock on a file at -** any time. Other processes may hold and obtain new SHARED locks. -** PENDING: A single process may hold a PENDING lock on a file at -** any one time. Existing SHARED locks may persist, but no new -** SHARED locks may be obtained by other processes. -** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks. -** -** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a -** process that requests an EXCLUSIVE lock may actually obtain a PENDING -** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to -** sqlite3OsLock(). -*/ -#define NO_LOCK 0 -#define SHARED_LOCK 1 -#define RESERVED_LOCK 2 -#define PENDING_LOCK 3 -#define EXCLUSIVE_LOCK 4 - -/* -** File Locking Notes: (Mostly about windows but also some info for Unix) -** -** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because -** those functions are not available. So we use only LockFile() and -** UnlockFile(). -** -** LockFile() prevents not just writing but also reading by other processes. -** A SHARED_LOCK is obtained by locking a single randomly-chosen -** byte out of a specific range of bytes. The lock byte is obtained at -** random so two separate readers can probably access the file at the -** same time, unless they are unlucky and choose the same lock byte. -** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range. -** There can only be one writer. A RESERVED_LOCK is obtained by locking -** a single byte of the file that is designated as the reserved lock byte. -** A PENDING_LOCK is obtained by locking a designated byte different from -** the RESERVED_LOCK byte. -** -** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available, -** which means we can use reader/writer locks. When reader/writer locks -** are used, the lock is placed on the same range of bytes that is used -** for probabilistic locking in Win95/98/ME. Hence, the locking scheme -** will support two or more Win95 readers or two or more WinNT readers. -** But a single Win95 reader will lock out all WinNT readers and a single -** WinNT reader will lock out all other Win95 readers. -** -** The following #defines specify the range of bytes used for locking. -** SHARED_SIZE is the number of bytes available in the pool from which -** a random byte is selected for a shared lock. The pool of bytes for -** shared locks begins at SHARED_FIRST. -** -** The same locking strategy and -** byte ranges are used for Unix. This leaves open the possibility of having -** clients on win95, winNT, and unix all talking to the same shared file -** and all locking correctly. To do so would require that samba (or whatever -** tool is being used for file sharing) implements locks correctly between -** windows and unix. I'm guessing that isn't likely to happen, but by -** using the same locking range we are at least open to the possibility. -** -** Locking in windows is manditory. For this reason, we cannot store -** actual data in the bytes used for locking. The pager never allocates -** the pages involved in locking therefore. SHARED_SIZE is selected so -** that all locks will fit on a single page even at the minimum page size. -** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE -** is set high so that we don't have to allocate an unused page except -** for very large databases. But one should test the page skipping logic -** by setting PENDING_BYTE low and running the entire regression suite. -** -** Changing the value of PENDING_BYTE results in a subtly incompatible -** file format. Depending on how it is changed, you might not notice -** the incompatibility right away, even running a full regression test. -** The default location of PENDING_BYTE is the first byte past the -** 1GB boundary. -** -*/ -#ifdef SQLITE_OMIT_WSD -# define PENDING_BYTE (0x40000000) -#else -# define PENDING_BYTE sqlite3PendingByte -#endif -#define RESERVED_BYTE (PENDING_BYTE+1) -#define SHARED_FIRST (PENDING_BYTE+2) -#define SHARED_SIZE 510 - -/* -** Wrapper around OS specific sqlite3_os_init() function. -*/ -SQLITE_PRIVATE int sqlite3OsInit(void); - -/* -** Functions for accessing sqlite3_file methods -*/ -SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*); -SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset); -SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset); -SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size); -SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int); -SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize); -SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int); -SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int); -SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut); -SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*); -SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*); -#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0 -SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id); -SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id); -#ifndef SQLITE_OMIT_WAL -SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **); -SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int); -SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id); -SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int); -#endif /* SQLITE_OMIT_WAL */ -SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **); -SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *); - - -/* -** Functions for accessing sqlite3_vfs methods -*/ -SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *); -SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int); -SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut); -SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *); -#ifndef SQLITE_OMIT_LOAD_EXTENSION -SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *); -SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *); -SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void); -SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *); -#endif /* SQLITE_OMIT_LOAD_EXTENSION */ -SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *); -SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int); -SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*); -SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*); - -/* -** Convenience functions for opening and closing files using -** sqlite3_malloc() to obtain space for the file-handle structure. -*/ -SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*); -SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *); - -#endif /* _SQLITE_OS_H_ */ - -/************** End of os.h **************************************************/ -/************** Continuing where we left off in sqliteInt.h ******************/ -/************** Include mutex.h in the middle of sqliteInt.h *****************/ -/************** Begin file mutex.h *******************************************/ -/* -** 2007 August 28 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file contains the common header for all mutex implementations. -** The sqliteInt.h header #includes this file so that it is available -** to all source files. We break it out in an effort to keep the code -** better organized. -** -** NOTE: source files should *not* #include this header file directly. -** Source files should #include the sqliteInt.h file and let that file -** include this one indirectly. -*/ - - -/* -** Figure out what version of the code to use. The choices are -** -** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The -** mutexes implementation cannot be overridden -** at start-time. -** -** SQLITE_MUTEX_NOOP For single-threaded applications. No -** mutual exclusion is provided. But this -** implementation can be overridden at -** start-time. -** -** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix. -** -** SQLITE_MUTEX_W32 For multi-threaded applications on Win32. -*/ -#if !SQLITE_THREADSAFE -# define SQLITE_MUTEX_OMIT -#endif -#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP) -# if SQLITE_OS_UNIX -# define SQLITE_MUTEX_PTHREADS -# elif SQLITE_OS_WIN -# define SQLITE_MUTEX_W32 -# else -# define SQLITE_MUTEX_NOOP -# endif -#endif - -#ifdef SQLITE_MUTEX_OMIT -/* -** If this is a no-op implementation, implement everything as macros. -*/ -#define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8) -#define sqlite3_mutex_free(X) -#define sqlite3_mutex_enter(X) -#define sqlite3_mutex_try(X) SQLITE_OK -#define sqlite3_mutex_leave(X) -#define sqlite3_mutex_held(X) ((void)(X),1) -#define sqlite3_mutex_notheld(X) ((void)(X),1) -#define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8) -#define sqlite3MutexInit() SQLITE_OK -#define sqlite3MutexEnd() -#define MUTEX_LOGIC(X) -#else -#define MUTEX_LOGIC(X) X -#endif /* defined(SQLITE_MUTEX_OMIT) */ - -/************** End of mutex.h ***********************************************/ -/************** Continuing where we left off in sqliteInt.h ******************/ - -/* The SQLITE_EXTRA_DURABLE compile-time option used to set the default -** synchronous setting to EXTRA. It is no longer supported. -*/ -#ifdef SQLITE_EXTRA_DURABLE -# warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE -# define SQLITE_DEFAULT_SYNCHRONOUS 3 -#endif - -/* -** Default synchronous levels. -** -** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ -** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1. -** -** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS -** OFF 1 0 -** NORMAL 2 1 -** FULL 3 2 -** EXTRA 4 3 -** -** The "PRAGMA synchronous" statement also uses the zero-based numbers. -** In other words, the zero-based numbers are used for all external interfaces -** and the one-based values are used internally. -*/ -#ifndef SQLITE_DEFAULT_SYNCHRONOUS -# define SQLITE_DEFAULT_SYNCHRONOUS 2 -#endif -#ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS -# define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS -#endif - -/* -** Each database file to be accessed by the system is an instance -** of the following structure. There are normally two of these structures -** in the sqlite.aDb[] array. aDb[0] is the main database file and -** aDb[1] is the database file used to hold temporary tables. Additional -** databases may be attached. -*/ -struct Db { - char *zDbSName; /* Name of this database. (schema name, not filename) */ - Btree *pBt; /* The B*Tree structure for this database file */ - u8 safety_level; /* How aggressive at syncing data to disk */ - u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */ - Schema *pSchema; /* Pointer to database schema (possibly shared) */ -}; - -/* -** An instance of the following structure stores a database schema. -** -** Most Schema objects are associated with a Btree. The exception is -** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing. -** In shared cache mode, a single Schema object can be shared by multiple -** Btrees that refer to the same underlying BtShared object. -** -** Schema objects are automatically deallocated when the last Btree that -** references them is destroyed. The TEMP Schema is manually freed by -** sqlite3_close(). -* -** A thread must be holding a mutex on the corresponding Btree in order -** to access Schema content. This implies that the thread must also be -** holding a mutex on the sqlite3 connection pointer that owns the Btree. -** For a TEMP Schema, only the connection mutex is required. -*/ -struct Schema { - int schema_cookie; /* Database schema version number for this file */ - int iGeneration; /* Generation counter. Incremented with each change */ - Hash tblHash; /* All tables indexed by name */ - Hash idxHash; /* All (named) indices indexed by name */ - Hash trigHash; /* All triggers indexed by name */ - Hash fkeyHash; /* All foreign keys by referenced table name */ - Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */ - u8 file_format; /* Schema format version for this file */ - u8 enc; /* Text encoding used by this database */ - u16 schemaFlags; /* Flags associated with this schema */ - int cache_size; /* Number of pages to use in the cache */ -}; - -/* -** These macros can be used to test, set, or clear bits in the -** Db.pSchema->flags field. -*/ -#define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P)) -#define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0) -#define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P) -#define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P) - -/* -** Allowed values for the DB.pSchema->flags field. -** -** The DB_SchemaLoaded flag is set after the database schema has been -** read into internal hash tables. -** -** DB_UnresetViews means that one or more views have column names that -** have been filled out. If the schema changes, these column names might -** changes and so the view will need to be reset. -*/ -#define DB_SchemaLoaded 0x0001 /* The schema has been loaded */ -#define DB_UnresetViews 0x0002 /* Some views have defined column names */ -#define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */ -#define DB_ResetWanted 0x0008 /* Reset the schema when nSchemaLock==0 */ - -/* -** The number of different kinds of things that can be limited -** using the sqlite3_limit() interface. -*/ -#define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1) - -/* -** Lookaside malloc is a set of fixed-size buffers that can be used -** to satisfy small transient memory allocation requests for objects -** associated with a particular database connection. The use of -** lookaside malloc provides a significant performance enhancement -** (approx 10%) by avoiding numerous malloc/free requests while parsing -** SQL statements. -** -** The Lookaside structure holds configuration information about the -** lookaside malloc subsystem. Each available memory allocation in -** the lookaside subsystem is stored on a linked list of LookasideSlot -** objects. -** -** Lookaside allocations are only allowed for objects that are associated -** with a particular database connection. Hence, schema information cannot -** be stored in lookaside because in shared cache mode the schema information -** is shared by multiple database connections. Therefore, while parsing -** schema information, the Lookaside.bEnabled flag is cleared so that -** lookaside allocations are not used to construct the schema objects. -*/ -struct Lookaside { - u32 bDisable; /* Only operate the lookaside when zero */ - u16 sz; /* Size of each buffer in bytes */ - u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */ - u32 nSlot; /* Number of lookaside slots allocated */ - u32 anStat[3]; /* 0: hits. 1: size misses. 2: full misses */ - LookasideSlot *pInit; /* List of buffers not previously used */ - LookasideSlot *pFree; /* List of available buffers */ - void *pStart; /* First byte of available memory space */ - void *pEnd; /* First byte past end of available space */ -}; -struct LookasideSlot { - LookasideSlot *pNext; /* Next buffer in the list of free buffers */ -}; - -/* -** A hash table for built-in function definitions. (Application-defined -** functions use a regular table table from hash.h.) -** -** Hash each FuncDef structure into one of the FuncDefHash.a[] slots. -** Collisions are on the FuncDef.u.pHash chain. -*/ -#define SQLITE_FUNC_HASH_SZ 23 -struct FuncDefHash { - FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */ -}; - -#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 0x80 -#else -#define SQLITE_TRACE_LEGACY 0 -#endif /* SQLITE_OMIT_DEPRECATED */ - - -/* -** Each database connection is an instance of the following structure. -*/ -struct sqlite3 { - sqlite3_vfs *pVfs; /* OS Interface */ - struct Vdbe *pVdbe; /* List of active virtual machines */ - CollSeq *pDfltColl; /* The default collating sequence (BINARY) */ - sqlite3_mutex *mutex; /* Connection mutex */ - Db *aDb; /* All backends */ - int nDb; /* Number of backends currently in use */ - u32 mDbFlags; /* flags recording internal state */ - u32 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 skipBtreeMutex; /* True if no shared-cache backends */ - u8 nSqlExec; /* Number of pending OP_SqlExec opcodes */ - int nextPagesize; /* Pagesize after VACUUM if >0 */ - u32 magic; /* Magic number for detect library misuse */ - int nChange; /* Value returned by sqlite3_changes() */ - int nTotalChange; /* Value returned by sqlite3_total_changes() */ - int aLimit[SQLITE_N_LIMIT]; /* Limits */ - int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */ - struct sqlite3InitInfo { /* Information used during initialization */ - int newTnum; /* Rootpage of table being initialized */ - u8 iDb; /* Which db file is being initialized */ - u8 busy; /* TRUE if currently initializing */ - u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */ - u8 imposterTable; /* Building an imposter table */ - } init; - int nVdbeActive; /* Number of VDBEs currently running */ - int nVdbeRead; /* Number of active VDBEs that read or write */ - int nVdbeWrite; /* Number of active VDBEs that read and write */ - int nVdbeExec; /* Number of nested calls to VdbeExec() */ - int nVDestroy; /* Number of active OP_VDestroy operations */ - int nExtension; /* Number of loaded extensions */ - void **aExtension; /* Array of shared library handles */ - int (*xTrace)(u32,void*,void*,void*); /* Trace function */ - void *pTraceArg; /* Argument to the trace function */ - void (*xProfile)(void*,const char*,u64); /* Profiling function */ - void *pProfileArg; /* Argument to profile function */ - 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); -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK - void *pPreUpdateArg; /* First argument to xPreUpdateCallback */ - void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */ - void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64 - ); - PreUpdate *pPreUpdate; /* Context for active pre-update callback */ -#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */ -#ifndef SQLITE_OMIT_WAL - int (*xWalCallback)(void *, sqlite3 *, const char *, int); - void *pWalArg; -#endif - void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*); - void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*); - void *pCollNeededArg; - sqlite3_value *pErr; /* Most recent error message */ - union { - volatile int isInterrupted; /* True if sqlite3_interrupt has been called */ - double notUsed1; /* Spacer */ - } u1; - Lookaside lookaside; /* Lookaside malloc configuration */ -#ifndef SQLITE_OMIT_AUTHORIZATION - sqlite3_xauth xAuth; /* Access authorization function */ - void *pAuthArg; /* 1st argument to the access auth function */ -#endif -#ifndef SQLITE_OMIT_PROGRESS_CALLBACK - int (*xProgress)(void *); /* The progress callback */ - void *pProgressArg; /* Argument to the progress callback */ - unsigned nProgressOps; /* Number of opcodes for progress callback */ -#endif -#ifndef SQLITE_OMIT_VIRTUALTABLE - int nVTrans; /* Allocated size of aVTrans */ - Hash aModule; /* populated by sqlite3_create_module() */ - VtabCtx *pVtabCtx; /* Context for active vtab connect/create */ - VTable **aVTrans; /* Virtual tables with open transactions */ - VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */ -#endif - Hash aFunc; /* Hash table of connection functions */ - Hash aCollSeq; /* All collating sequences */ - BusyHandler busyHandler; /* Busy callback */ - Db aDbStatic[2]; /* Static space for the 2 default backends */ - Savepoint *pSavepoint; /* List of active savepoints */ - int busyTimeout; /* Busy handler timeout, in msec */ - int nSavepoint; /* Number of non-transaction savepoints */ - int nStatement; /* Number of nested statement-transactions */ - i64 nDeferredCons; /* Net deferred constraints this transaction. */ - i64 nDeferredImmCons; /* Net deferred immediate constraints */ - int *pnBytesFreed; /* If not NULL, increment this in DbFree() */ -#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY - /* The following variables are all protected by the STATIC_MASTER - ** mutex, not by sqlite3.mutex. They are used by code in notify.c. - ** - ** When X.pUnlockConnection==Y, that means that X is waiting for Y to - ** unlock so that it can proceed. - ** - ** When X.pBlockingConnection==Y, that means that something that X tried - ** tried to do recently failed with an SQLITE_LOCKED error due to locks - ** held by Y. - */ - sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */ - sqlite3 *pUnlockConnection; /* Connection to watch for unlock */ - void *pUnlockArg; /* Argument to xUnlockNotify */ - void (*xUnlockNotify)(void **, int); /* Unlock notify callback */ - sqlite3 *pNextBlocked; /* Next in list of all blocked connections */ -#endif -#ifdef SQLITE_USER_AUTHENTICATION - sqlite3_userauth auth; /* User authentication information */ -#endif -}; - -/* -** A macro to discover the encoding of a database. -*/ -#define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc) -#define ENC(db) ((db)->enc) - -/* -** Possible values for the sqlite3.flags. -** -** Value constraints (enforced via assert()): -** SQLITE_FullFSync == PAGER_FULLFSYNC -** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC -** SQLITE_CacheSpill == PAGER_CACHE_SPILL -*/ -#define SQLITE_WriteSchema 0x00000001 /* OK to update SQLITE_MASTER */ -#define SQLITE_LegacyFileFmt 0x00000002 /* Create new databases in format 1 */ -#define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */ -#define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */ -#define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */ -#define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */ -#define SQLITE_ShortColNames 0x00000040 /* Show short columns names */ -#define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */ - /* DELETE, or UPDATE and return */ - /* the count using a callback. */ -#define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */ - /* result set is empty */ -#define SQLITE_IgnoreChecks 0x00000200 /* Do not enforce check constraints */ -#define SQLITE_ReadUncommit 0x00000400 /* READ UNCOMMITTED in shared-cache */ -#define SQLITE_NoCkptOnClose 0x00000800 /* No checkpoint on close()/DETACH */ -#define SQLITE_ReverseOrder 0x00001000 /* Reverse unordered SELECTs */ -#define SQLITE_RecTriggers 0x00002000 /* Enable recursive triggers */ -#define SQLITE_ForeignKeys 0x00004000 /* Enforce foreign key constraints */ -#define SQLITE_AutoIndex 0x00008000 /* Enable automatic indexes */ -#define SQLITE_LoadExtension 0x00010000 /* Enable load_extension */ -#define SQLITE_LoadExtFunc 0x00020000 /* Enable load_extension() SQL func */ -#define SQLITE_EnableTrigger 0x00040000 /* True to enable triggers */ -#define SQLITE_DeferFKs 0x00080000 /* Defer all FK constraints */ -#define SQLITE_QueryOnly 0x00100000 /* Disable database changes */ -#define SQLITE_CellSizeCk 0x00200000 /* Check btree cell sizes on load */ -#define SQLITE_Fts3Tokenizer 0x00400000 /* Enable fts3_tokenizer(2) */ -#define SQLITE_EnableQPSG 0x00800000 /* Query Planner Stability Guarantee */ -/* Flags used only if debugging */ -#ifdef SQLITE_DEBUG -#define SQLITE_SqlTrace 0x08000000 /* Debug print SQL as it executes */ -#define SQLITE_VdbeListing 0x10000000 /* Debug listings of VDBE programs */ -#define SQLITE_VdbeTrace 0x20000000 /* True to trace VDBE execution */ -#define SQLITE_VdbeAddopTrace 0x40000000 /* Trace sqlite3VdbeAddOp() calls */ -#define SQLITE_VdbeEQP 0x80000000 /* Debug EXPLAIN QUERY PLAN */ -#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 */ - -/* -** 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_ColumnCache 0x0002 /* Column cache */ -#define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */ -#define SQLITE_FactorOutConst 0x0008 /* Constant factoring */ -#define SQLITE_DistinctOpt 0x0010 /* DISTINCT using indexes */ -#define SQLITE_CoverIdxScan 0x0020 /* Covering index scans */ -#define SQLITE_OrderByIdxJoin 0x0040 /* ORDER BY of joins via index */ -#define SQLITE_Transitive 0x0080 /* Transitive constraints */ -#define SQLITE_OmitNoopJoin 0x0100 /* Omit unused tables in joins */ -#define SQLITE_CountOfView 0x0200 /* The count-of-view optimization */ -#define SQLITE_CursorHints 0x0400 /* Add OP_CursorHint opcodes */ -#define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */ - /* TH3 expects the Stat34 ^^^^^^ value to be 0x0800. Don't change it */ -#define SQLITE_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 */ - u16 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 */ - const char *zName; /* SQL name of the function. */ - union { - FuncDef *pHash; /* Next with a different name but the same hash */ - FuncDestructor *pDestructor; /* Reference counted destructor function */ - } u; -}; - -/* -** This structure encapsulates a user-function destructor callback (as -** configured using create_function_v2()) and a reference counter. When -** create_function_v2() is called to create a function with a destructor, -** a single object of this type is allocated. FuncDestructor.nRef is set to -** the number of FuncDef objects created (either 1 or 3, depending on whether -** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor -** member of each of the new FuncDef objects is set to point to the allocated -** FuncDestructor. -** -** Thereafter, when one of the FuncDef objects is deleted, the reference -** count on this object is decremented. When it reaches 0, the destructor -** is invoked and the FuncDestructor structure freed. -*/ -struct FuncDestructor { - int nRef; - void (*xDestroy)(void *); - void *pUserData; -}; - -/* -** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF -** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And -** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There -** are assert() statements in the code to verify this. -** -** Value constraints (enforced via assert()): -** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg -** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG -** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG -** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API -** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API -*/ -#define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */ -#define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */ -#define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */ -#define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */ -#define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/ -#define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */ -#define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */ -#define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */ -#define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */ -#define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */ -#define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */ -#define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */ -#define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a - ** single query - might change over time */ -#define SQLITE_FUNC_AFFINITY 0x4000 /* Built-in affinity() function */ - -/* -** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are -** used to create the initializers for the FuncDef structures. -** -** FUNCTION(zName, nArg, iArg, bNC, xFunc) -** Used to create a scalar function definition of a function zName -** implemented by C function xFunc that accepts nArg arguments. The -** value passed as iArg is cast to a (void*) and made available -** as the user-data (sqlite3_user_data()) for the function. If -** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set. -** -** VFUNCTION(zName, nArg, iArg, bNC, xFunc) -** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag. -** -** DFUNCTION(zName, nArg, iArg, bNC, xFunc) -** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and -** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions -** and functions like sqlite_version() that can change, but not during -** a single query. The iArg is ignored. The user-data is always set -** to a NULL pointer. The bNC parameter is not used. -** -** PURE_DATE(zName, nArg, iArg, bNC, xFunc) -** Used for "pure" date/time functions, this macro is like DFUNCTION -** except that it does set the SQLITE_FUNC_CONSTANT flags. iArg is -** ignored and the user-data for these functions is set to an -** arbitrary non-NULL pointer. The bNC parameter is not used. -** -** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal) -** Used to create an aggregate function definition implemented by -** the C functions xStep and xFinal. The first four parameters -** are interpreted in the same way as the first 4 parameters to -** FUNCTION(). -** -** 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, #zName, {0} } -#define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \ - {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \ - SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} } -#define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \ - {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \ - 0, 0, xFunc, 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, #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, #zName, {0} } -#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \ - {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \ - pArg, 0, xFunc, 0, #zName, } -#define LIKEFUNC(zName, nArg, arg, flags) \ - {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \ - (void *)arg, 0, likeFunc, 0, #zName, {0} } -#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \ - {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \ - SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}} -#define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \ - {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \ - SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}} - -/* -** All current savepoints are stored in a linked list starting at -** sqlite3.pSavepoint. The first element in the list is the most recently -** opened savepoint. Savepoints are added to the list by the vdbe -** OP_Savepoint instruction. -*/ -struct Savepoint { - char *zName; /* Savepoint name (nul-terminated) */ - i64 nDeferredCons; /* Number of deferred fk violations */ - i64 nDeferredImmCons; /* Number of deferred imm fk. */ - Savepoint *pNext; /* Parent savepoint (if any) */ -}; - -/* -** The following are used as the second parameter to sqlite3Savepoint(), -** and as the P1 argument to the OP_Savepoint instruction. -*/ -#define SAVEPOINT_BEGIN 0 -#define SAVEPOINT_RELEASE 1 -#define SAVEPOINT_ROLLBACK 2 - - -/* -** Each SQLite module (virtual table definition) is defined by an -** instance of the following structure, stored in the sqlite3.aModule -** hash table. -*/ -struct Module { - const sqlite3_module *pModule; /* Callback pointers */ - const char *zName; /* Name passed to create_module() */ - void *pAux; /* pAux passed to create_module() */ - void (*xDestroy)(void *); /* Module destructor function */ - Table *pEpoTab; /* Eponymous table for this module */ -}; - -/* -** information about each column of an SQL table is held in an instance -** of this structure. -*/ -struct Column { - char *zName; /* Name of this column, \000, then the type */ - Expr *pDflt; /* Default value of this column */ - char *zColl; /* Collating sequence. If NULL, use the default */ - u8 notNull; /* An OE_ code for handling a NOT NULL constraint */ - char affinity; /* One of the SQLITE_AFF_... values */ - u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */ - u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */ -}; - -/* Allowed values for Column.colFlags: -*/ -#define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */ -#define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */ -#define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */ - -/* -** A "Collating Sequence" is defined by an instance of the following -** structure. Conceptually, a collating sequence consists of a name and -** a comparison routine that defines the order of that sequence. -** -** If CollSeq.xCmp is NULL, it means that the -** collating sequence is undefined. Indices built on an undefined -** collating sequence may not be read or written. -*/ -struct CollSeq { - char *zName; /* Name of the collating sequence, UTF-8 encoded */ - u8 enc; /* Text encoding handled by xCmp() */ - void *pUser; /* First argument to xCmp() */ - int (*xCmp)(void*,int, const void*, int, const void*); - void (*xDel)(void*); /* Destructor for pUser */ -}; - -/* -** A sort order can be either ASC or DESC. -*/ -#define SQLITE_SO_ASC 0 /* Sort in ascending order */ -#define SQLITE_SO_DESC 1 /* Sort in ascending order */ -#define SQLITE_SO_UNDEFINED -1 /* No sort order specified */ - -/* -** Column affinity types. -** -** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and -** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve -** the speed a little by numbering the values consecutively. -** -** But rather than start with 0 or 1, we begin with 'A'. That way, -** when multiple affinity types are concatenated into a string and -** used as the P4 operand, they will be more readable. -** -** Note also that the numeric types are grouped together so that testing -** for a numeric type is a single comparison. And the BLOB type is first. -*/ -#define SQLITE_AFF_BLOB 'A' -#define SQLITE_AFF_TEXT 'B' -#define SQLITE_AFF_NUMERIC 'C' -#define SQLITE_AFF_INTEGER 'D' -#define SQLITE_AFF_REAL 'E' - -#define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC) - -/* -** The SQLITE_AFF_MASK values masks off the significant bits of an -** affinity value. -*/ -#define SQLITE_AFF_MASK 0x47 - -/* -** Additional bit values that can be ORed with an affinity without -** changing the affinity. -** -** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL. -** It causes an assert() to fire if either operand to a comparison -** operator is NULL. It is added to certain comparison operators to -** prove that the operands are always NOT NULL. -*/ -#define SQLITE_KEEPNULL 0x08 /* Used by vector == or <> */ -#define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */ -#define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */ -#define SQLITE_NULLEQ 0x80 /* NULL=NULL */ -#define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */ - -/* -** An object of this type is created for each virtual table present in -** the database schema. -** -** If the database schema is shared, then there is one instance of this -** structure for each database connection (sqlite3*) that uses the shared -** schema. This is because each database connection requires its own unique -** instance of the sqlite3_vtab* handle used to access the virtual table -** implementation. sqlite3_vtab* handles can not be shared between -** database connections, even when the rest of the in-memory database -** schema is shared, as the implementation often stores the database -** connection handle passed to it via the xConnect() or xCreate() method -** during initialization internally. This database connection handle may -** then be used by the virtual table implementation to access real tables -** within the database. So that they appear as part of the callers -** transaction, these accesses need to be made via the same database -** connection as that used to execute SQL operations on the virtual table. -** -** All VTable objects that correspond to a single table in a shared -** database schema are initially stored in a linked-list pointed to by -** the Table.pVTable member variable of the corresponding Table object. -** When an sqlite3_prepare() operation is required to access the virtual -** table, it searches the list for the VTable that corresponds to the -** database connection doing the preparing so as to use the correct -** sqlite3_vtab* handle in the compiled query. -** -** When an in-memory Table object is deleted (for example when the -** schema is being reloaded for some reason), the VTable objects are not -** deleted and the sqlite3_vtab* handles are not xDisconnect()ed -** immediately. Instead, they are moved from the Table.pVTable list to -** another linked list headed by the sqlite3.pDisconnect member of the -** corresponding sqlite3 structure. They are then deleted/xDisconnected -** next time a statement is prepared using said sqlite3*. This is done -** to avoid deadlock issues involving multiple sqlite3.mutex mutexes. -** Refer to comments above function sqlite3VtabUnlockList() for an -** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect -** list without holding the corresponding sqlite3.mutex mutex. -** -** The memory for objects of this type is always allocated by -** sqlite3DbMalloc(), using the connection handle stored in VTable.db as -** the first argument. -*/ -struct VTable { - sqlite3 *db; /* Database connection associated with this table */ - Module *pMod; /* Pointer to module implementation */ - sqlite3_vtab *pVtab; /* Pointer to vtab instance */ - int nRef; /* Number of pointers to this structure */ - u8 bConstraint; /* True if constraints are supported */ - int iSavepoint; /* Depth of the SAVEPOINT stack */ - VTable *pNext; /* Next in linked list (see above) */ -}; - -/* -** The schema for each SQL table and view is represented in memory -** by an instance of the following structure. -*/ -struct Table { - char *zName; /* Name of the table or view */ - Column *aCol; /* Information about each column */ - Index *pIndex; /* List of SQL indexes on this table. */ - Select *pSelect; /* NULL for tables. Points to definition if a view. */ - FKey *pFKey; /* Linked list of all foreign keys in this table */ - char *zColAff; /* String defining the affinity of each column */ - ExprList *pCheck; /* All CHECK constraints */ - /* ... also used as column name list in a VIEW */ - int tnum; /* Root BTree page for this table */ - u32 nTabRef; /* Number of pointers to this Table */ - u32 tabFlags; /* Mask of TF_* values */ - i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */ - i16 nCol; /* Number of columns in this table */ - LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */ - LogEst szTabRow; /* Estimated size of each table row in bytes */ -#ifdef SQLITE_ENABLE_COSTMULT - LogEst costMult; /* Cost multiplier for using this table */ -#endif - u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */ -#ifndef SQLITE_OMIT_ALTERTABLE - int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */ -#endif -#ifndef SQLITE_OMIT_VIRTUALTABLE - int nModuleArg; /* Number of arguments to the module */ - char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */ - VTable *pVTable; /* List of VTable objects. */ -#endif - Trigger *pTrigger; /* List of triggers stored in pSchema */ - Schema *pSchema; /* Schema that contains this table */ - Table *pNextZombie; /* Next on the Parse.pZombieTab list */ -}; - -/* -** Allowed values for Table.tabFlags. -** -** TF_OOOHidden applies to tables or view that have hidden columns that are -** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING -** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden, -** the TF_OOOHidden attribute would apply in this case. Such tables require -** special handling during INSERT processing. -*/ -#define TF_Readonly 0x0001 /* Read-only system table */ -#define TF_Ephemeral 0x0002 /* An ephemeral table */ -#define TF_HasPrimaryKey 0x0004 /* Table has a primary key */ -#define TF_Autoincrement 0x0008 /* Integer primary key is autoincrement */ -#define TF_HasStat1 0x0010 /* nRowLogEst set from sqlite_stat1 */ -#define TF_WithoutRowid 0x0020 /* No rowid. PRIMARY KEY is the key */ -#define TF_NoVisibleRowid 0x0040 /* No user-visible "rowid" column */ -#define TF_OOOHidden 0x0080 /* Out-of-Order hidden columns */ -#define TF_StatsUsed 0x0100 /* Query planner decisions affected by - ** Index.aiRowLogEst[] values */ -#define TF_HasNotNull 0x0200 /* Contains NOT NULL constraints */ - -/* -** Test to see whether or not a table is a virtual table. This is -** done as a macro so that it will be optimized out when virtual -** table support is omitted from the build. -*/ -#ifndef SQLITE_OMIT_VIRTUALTABLE -# define IsVirtual(X) ((X)->nModuleArg) -#else -# define IsVirtual(X) 0 -#endif - -/* -** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn() -** only works for non-virtual tables (ordinary tables and views) and is -** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The -** IsHiddenColumn() macro is general purpose. -*/ -#if defined(SQLITE_ENABLE_HIDDEN_COLUMNS) -# define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0) -# define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0) -#elif !defined(SQLITE_OMIT_VIRTUALTABLE) -# define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0) -# define IsOrdinaryHiddenColumn(X) 0 -#else -# define IsHiddenColumn(X) 0 -# define IsOrdinaryHiddenColumn(X) 0 -#endif - - -/* Does the table have a rowid */ -#define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0) -#define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0) - -/* -** Each foreign key constraint is an instance of the following structure. -** -** A foreign key is associated with two tables. The "from" table is -** the table that contains the REFERENCES clause that creates the foreign -** key. The "to" table is the table that is named in the REFERENCES clause. -** Consider this example: -** -** CREATE TABLE ex1( -** a INTEGER PRIMARY KEY, -** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x) -** ); -** -** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2". -** Equivalent names: -** -** from-table == child-table -** to-table == parent-table -** -** Each REFERENCES clause generates an instance of the following structure -** which is attached to the from-table. The to-table need not exist when -** the from-table is created. The existence of the to-table is not checked. -** -** The list of all parents for child Table X is held at X.pFKey. -** -** A list of all children for a table named Z (which might not even exist) -** is held in Schema.fkeyHash with a hash key of Z. -*/ -struct FKey { - Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */ - FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */ - char *zTo; /* Name of table that the key points to (aka: Parent) */ - FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */ - FKey *pPrevTo; /* Previous with the same zTo */ - int nCol; /* Number of columns in this key */ - /* EV: R-30323-21917 */ - u8 isDeferred; /* True if constraint checking is deferred till COMMIT */ - u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */ - Trigger *apTrigger[2];/* Triggers for aAction[] actions */ - struct sColMap { /* Mapping of columns in pFrom to columns in zTo */ - int iFrom; /* Index of column in pFrom */ - char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */ - } aCol[1]; /* One entry for each of nCol columns */ -}; - -/* -** SQLite supports many different ways to resolve a constraint -** error. ROLLBACK processing means that a constraint violation -** causes the operation in process to fail and for the current transaction -** to be rolled back. ABORT processing means the operation in process -** fails and any prior changes from that one operation are backed out, -** but the transaction is not rolled back. FAIL processing means that -** the operation in progress stops and returns an error code. But prior -** changes due to the same operation are not backed out and no rollback -** occurs. IGNORE means that the particular row that caused the constraint -** error is not inserted or updated. Processing continues and no error -** is returned. REPLACE means that preexisting database rows that caused -** a UNIQUE constraint violation are removed so that the new insert or -** update can proceed. Processing continues and no error is reported. -** -** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys. -** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the -** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign -** key is set to NULL. CASCADE means that a DELETE or UPDATE of the -** referenced table row is propagated into the row that holds the -** foreign key. -** -** The following symbolic values are used to record which type -** of action to take. -*/ -#define OE_None 0 /* There is no constraint to check */ -#define OE_Rollback 1 /* Fail the operation and rollback the transaction */ -#define OE_Abort 2 /* Back out changes but do no rollback transaction */ -#define OE_Fail 3 /* Stop the operation but leave all prior changes */ -#define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */ -#define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */ - -#define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */ -#define OE_SetNull 7 /* Set the foreign key value to NULL */ -#define OE_SetDflt 8 /* Set the foreign key value to its default */ -#define OE_Cascade 9 /* Cascade the changes */ - -#define OE_Default 10 /* Do whatever the default action is */ - - -/* -** An instance of the following structure is passed as the first -** argument to sqlite3VdbeKeyCompare and is used to control the -** comparison of the two index keys. -** -** Note that aSortOrder[] and aColl[] have nField+1 slots. There -** are nField slots for the columns of an index then one extra slot -** for the rowid at the end. -*/ -struct KeyInfo { - u32 nRef; /* Number of references to this KeyInfo object */ - u8 enc; /* Text encoding - one of the SQLITE_UTF* values */ - u16 nKeyField; /* Number of key columns in the index */ - u16 nAllField; /* Total columns, including key plus others */ - sqlite3 *db; /* The database connection */ - u8 *aSortOrder; /* Sort order for each column. */ - CollSeq *aColl[1]; /* Collating sequence for each term of the key */ -}; - -/* -** This object holds a record which has been parsed out into individual -** fields, for the purposes of doing a comparison. -** -** A record is an object that contains one or more fields of data. -** Records are used to store the content of a table row and to store -** the key of an index. A blob encoding of a record is created by -** the OP_MakeRecord opcode of the VDBE and is disassembled by the -** OP_Column opcode. -** -** An instance of this object serves as a "key" for doing a search on -** an index b+tree. The goal of the search is to find the entry that -** is closed to the key described by this object. This object might hold -** just a prefix of the key. The number of fields is given by -** pKeyInfo->nField. -** -** The r1 and r2 fields are the values to return if this key is less than -** or greater than a key in the btree, respectively. These are normally -** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree -** is in DESC order. -** -** The key comparison functions actually return default_rc when they find -** an equals comparison. default_rc can be -1, 0, or +1. If there are -** multiple entries in the b-tree with the same key (when only looking -** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to -** cause the search to find the last match, or +1 to cause the search to -** find the first match. -** -** The key comparison functions will set eqSeen to true if they ever -** get and equal results when comparing this structure to a b-tree record. -** When default_rc!=0, the search might end up on the record immediately -** before the first match or immediately after the last match. The -** eqSeen field will indicate whether or not an exact match exists in the -** b-tree. -*/ -struct UnpackedRecord { - KeyInfo *pKeyInfo; /* Collation and sort-order information */ - Mem *aMem; /* Values */ - u16 nField; /* Number of entries in apMem[] */ - i8 default_rc; /* Comparison result if keys are equal */ - u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */ - i8 r1; /* Value to return if (lhs < rhs) */ - i8 r2; /* Value to return if (lhs > rhs) */ - u8 eqSeen; /* True if an equality comparison has been seen */ -}; - - -/* -** Each SQL index is represented in memory by an -** instance of the following structure. -** -** The columns of the table that are to be indexed are described -** by the aiColumn[] field of this structure. For example, suppose -** we have the following table and index: -** -** CREATE TABLE Ex1(c1 int, c2 int, c3 text); -** CREATE INDEX Ex2 ON Ex1(c3,c1); -** -** In the Table structure describing Ex1, nCol==3 because there are -** three columns in the table. In the Index structure describing -** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed. -** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the -** first column to be indexed (c3) has an index of 2 in Ex1.aCol[]. -** The second column to be indexed (c1) has an index of 0 in -** Ex1.aCol[], hence Ex2.aiColumn[1]==0. -** -** The Index.onError field determines whether or not the indexed columns -** must be unique and what to do if they are not. When Index.onError=OE_None, -** it means this is not a unique index. Otherwise it is a unique index -** and the value of Index.onError indicate the which conflict resolution -** algorithm to employ whenever an attempt is made to insert a non-unique -** element. -** -** While parsing a CREATE TABLE or CREATE INDEX statement in order to -** generate VDBE code (as opposed to parsing one read from an sqlite_master -** table as part of parsing an existing database schema), transient instances -** of this structure may be created. In this case the Index.tnum variable is -** used to store the address of a VDBE instruction, not a database page -** number (it cannot - the database page is not allocated until the VDBE -** program is executed). See convertToWithoutRowidTable() for details. -*/ -struct Index { - char *zName; /* Name of this index */ - i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */ - LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */ - Table *pTable; /* The SQL table being indexed */ - char *zColAff; /* String defining the affinity of each column */ - Index *pNext; /* The next index associated with the same table */ - Schema *pSchema; /* Schema containing this index */ - u8 *aSortOrder; /* for each column: True==DESC, False==ASC */ - const char **azColl; /* Array of collation sequence names for index */ - Expr *pPartIdxWhere; /* WHERE clause for partial indices */ - ExprList *aColExpr; /* Column expressions */ - int tnum; /* DB Page containing root of this index */ - LogEst szIdxRow; /* Estimated average row size in bytes */ - u16 nKeyCol; /* Number of columns forming the key */ - u16 nColumn; /* Number of columns stored in the index */ - u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ - unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */ - 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 */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - int nSample; /* Number of elements in aSample[] */ - int nSampleCol; /* Size of IndexSample.anEq[] and so on */ - tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */ - IndexSample *aSample; /* Samples of the left-most key */ - tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */ - tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */ -#endif -}; - -/* -** 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 */ - -/* Return true if index X is a PRIMARY KEY index */ -#define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY) - -/* Return true if index X is a UNIQUE index */ -#define IsUniqueIndex(X) ((X)->onError!=OE_None) - -/* The Index.aiColumn[] values are normally positive integer. But -** there are some negative values that have special meaning: -*/ -#define XN_ROWID (-1) /* Indexed column is the rowid */ -#define XN_EXPR (-2) /* Indexed column is an expression */ - -/* -** Each sample stored in the sqlite_stat3 table is represented in memory -** using a structure of this type. See documentation at the top of the -** analyze.c source file for additional information. -*/ -struct IndexSample { - void *p; /* Pointer to sampled record */ - int n; /* Size of record in bytes */ - tRowcnt *anEq; /* Est. number of rows where the key equals this sample */ - tRowcnt *anLt; /* Est. number of rows where key is less than this sample */ - tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */ -}; - -/* -** Each token coming out of the lexer is an instance of -** this structure. Tokens are also used as part of an expression. -** -** Note if Token.z==0 then Token.dyn and Token.n are undefined and -** may contain random values. Do not make any assumptions about Token.dyn -** and Token.n when Token.z==0. -*/ -struct Token { - const char *z; /* Text of the token. Not NULL-terminated! */ - unsigned int n; /* Number of characters in this token */ -}; - -/* -** An instance of this structure contains information needed to generate -** code for a SELECT that contains aggregate functions. -** -** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a -** pointer to this structure. The Expr.iColumn field is the index in -** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate -** code for that node. -** -** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the -** original Select structure that describes the SELECT statement. These -** fields do not need to be freed when deallocating the AggInfo structure. -*/ -struct AggInfo { - u8 directMode; /* Direct rendering mode means take data directly - ** from source tables rather than from accumulators */ - u8 useSortingIdx; /* In direct mode, reference the sorting index rather - ** than the source table */ - int sortingIdx; /* Cursor number of the sorting index */ - int sortingIdxPTab; /* Cursor number of pseudo-table */ - int nSortingColumn; /* Number of columns in the sorting index */ - int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */ - ExprList *pGroupBy; /* The group by clause */ - struct AggInfo_col { /* For each column used in source tables */ - Table *pTab; /* Source table */ - int iTable; /* Cursor number of the source table */ - int iColumn; /* Column number within the source table */ - int iSorterColumn; /* Column number in the sorting index */ - int iMem; /* Memory location that acts as accumulator */ - Expr *pExpr; /* The original expression */ - } *aCol; - int nColumn; /* Number of used entries in aCol[] */ - int nAccumulator; /* Number of columns that show through to the output. - ** Additional columns are used only as parameters to - ** aggregate functions */ - struct AggInfo_func { /* For each aggregate function */ - Expr *pExpr; /* Expression encoding the function */ - FuncDef *pFunc; /* The aggregate function implementation */ - int iMem; /* Memory location that acts as accumulator */ - int iDistinct; /* Ephemeral table used to enforce DISTINCT */ - } *aFunc; - int nFunc; /* Number of entries in aFunc[] */ -}; - -/* -** The datatype ynVar is a signed integer, either 16-bit or 32-bit. -** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater -** than 32767 we have to make it 32-bit. 16-bit is preferred because -** it uses less memory in the Expr object, which is a big memory user -** in systems with lots of prepared statements. And few applications -** need more than about 10 or 20 variables. But some extreme users want -** to have prepared statements with over 32767 variables, and for them -** the option is available (at compile-time). -*/ -#if SQLITE_MAX_VARIABLE_NUMBER<=32767 -typedef i16 ynVar; -#else -typedef int ynVar; -#endif - -/* -** Each node of an expression in the parse tree is an instance -** of this structure. -** -** Expr.op is the opcode. The integer parser token codes are reused -** as opcodes here. For example, the parser defines TK_GE to be an integer -** code representing the ">=" operator. This same integer code is reused -** to represent the greater-than-or-equal-to operator in the expression -** tree. -** -** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, -** or TK_STRING), then Expr.token contains the text of the SQL literal. If -** the expression is a variable (TK_VARIABLE), then Expr.token contains the -** variable name. Finally, if the expression is an SQL function (TK_FUNCTION), -** then Expr.token contains the name of the function. -** -** Expr.pRight and Expr.pLeft are the left and right subexpressions of a -** binary operator. Either or both may be NULL. -** -** Expr.x.pList is a list of arguments if the expression is an SQL function, -** a CASE expression or an IN expression of the form " IN (, ...)". -** Expr.x.pSelect is used if the expression is a sub-select or an expression of -** the form " IN (SELECT ...)". If the EP_xIsSelect bit is set in the -** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is -** valid. -** -** An expression of the form ID or ID.ID refers to a column in a table. -** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is -** the integer cursor number of a VDBE cursor pointing to that table and -** Expr.iColumn is the column number for the specific column. If the -** expression is used as a result in an aggregate SELECT, then the -** value is also stored in the Expr.iAgg column in the aggregate so that -** it can be accessed after all aggregates are computed. -** -** If the expression is an unbound variable marker (a question mark -** character '?' in the original SQL) then the Expr.iTable holds the index -** number for that variable. -** -** If the expression is a subquery then Expr.iColumn holds an integer -** register number containing the result of the subquery. If the -** subquery gives a constant result, then iTable is -1. If the subquery -** gives a different answer at different times during statement processing -** then iTable is the address of a subroutine that computes the subquery. -** -** If the Expr is of type OP_Column, and the table it is selecting from -** is a disk table or the "old.*" pseudo-table, then pTab points to the -** corresponding table definition. -** -** ALLOCATION NOTES: -** -** Expr objects can use a lot of memory space in database schema. To -** help reduce memory requirements, sometimes an Expr object will be -** truncated. And to reduce the number of memory allocations, sometimes -** two or more Expr objects will be stored in a single memory allocation, -** together with Expr.zToken strings. -** -** If the EP_Reduced and EP_TokenOnly flags are set when -** an Expr object is truncated. When EP_Reduced is set, then all -** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees -** are contained within the same memory allocation. Note, however, that -** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately -** allocated, regardless of whether or not EP_Reduced is set. -*/ -struct Expr { - u8 op; /* Operation performed by this node */ - char affinity; /* The affinity of the column or 0 if not a column */ - u32 flags; /* Various flags. EP_* See below */ - union { - char *zToken; /* Token value. Zero terminated and dequoted */ - int iValue; /* Non-negative integer value if EP_IntValue */ - } u; - - /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no - ** space is allocated for the fields below this point. An attempt to - ** access them will result in a segfault or malfunction. - *********************************************************************/ - - Expr *pLeft; /* Left subnode */ - Expr *pRight; /* Right subnode */ - union { - ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */ - Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */ - } x; - - /* If the EP_Reduced flag is set in the Expr.flags mask, then no - ** space is allocated for the fields below this point. An attempt to - ** access them will result in a segfault or malfunction. - *********************************************************************/ - -#if SQLITE_MAX_EXPR_DEPTH>0 - int nHeight; /* Height of the tree headed by this node */ -#endif - int iTable; /* TK_COLUMN: cursor number of table holding column - ** TK_REGISTER: register number - ** TK_TRIGGER: 1 -> new, 0 -> old - ** EP_Unlikely: 134217728 times likelihood - ** TK_SELECT: 1st register of result vector */ - ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid. - ** TK_VARIABLE: variable number (always >= 1). - ** TK_SELECT_COLUMN: column of the result vector */ - i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */ - i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */ - u8 op2; /* TK_REGISTER: original value of Expr.op - ** TK_COLUMN: the value of p5 for OP_Column - ** TK_AGG_FUNCTION: nesting depth */ - AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */ - Table *pTab; /* Table for TK_COLUMN expressions. Can be NULL - ** for a column of an index on an expression */ -}; - -/* -** The following are the meanings of bits in the Expr.flags field. -*/ -#define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */ -#define EP_Agg 0x000002 /* Contains one or more aggregate functions */ - /* 0x000004 // available for use */ - /* 0x000008 // available for use */ -#define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */ -#define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */ -#define EP_DblQuoted 0x000040 /* token.z was originally in "..." */ -#define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */ -#define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */ -#define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */ -#define EP_IntValue 0x000400 /* Integer value contained in u.iValue */ -#define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */ -#define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */ -#define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */ -#define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */ -#define EP_Static 0x008000 /* Held in memory not obtained from malloc() */ -#define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */ -#define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */ -#define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */ -#define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */ -#define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */ -#define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */ -#define EP_Alias 0x400000 /* Is an alias for a result set column */ -#define EP_Leaf 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */ - -/* -** Combinations of two or more EP_* flags -*/ -#define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */ - -/* -** 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) - -/* The ExprSetVVAProperty() macro is used for Verification, Validation, -** and Accreditation only. It works like ExprSetProperty() during VVA -** processes but is a no-op for delivery. -*/ -#ifdef SQLITE_DEBUG -# define ExprSetVVAProperty(E,P) (E)->flags|=(P) -#else -# define ExprSetVVAProperty(E,P) -#endif - -/* -** Macros to determine the number of bytes required by a normal Expr -** struct, an Expr struct with the EP_Reduced flag set in Expr.flags -** and an Expr struct with the EP_TokenOnly flag set. -*/ -#define EXPR_FULLSIZE sizeof(Expr) /* Full size */ -#define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */ -#define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */ - -/* -** Flags passed to the sqlite3ExprDup() function. See the header comment -** above sqlite3ExprDup() for details. -*/ -#define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */ - -/* -** A list of expressions. Each expression may optionally have a -** name. An expr/name combination can be used in several ways, such -** as the list of "expr AS ID" fields following a "SELECT" or in the -** list of "ID = expr" items in an UPDATE. A list of expressions can -** also be used as the argument to a function, in which case the a.zName -** field is not used. -** -** By default the Expr.zSpan field holds a human-readable description of -** the expression that is used in the generation of error messages and -** column labels. In this case, Expr.zSpan is typically the text of a -** column expression as it exists in a SELECT statement. However, if -** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name -** of the result column in the form: DATABASE.TABLE.COLUMN. This later -** form is used for name resolution with nested FROM clauses. -*/ -struct ExprList { - int nExpr; /* Number of expressions on the list */ - struct ExprList_item { /* For each expression in the list */ - Expr *pExpr; /* The parse tree for this expression */ - char *zName; /* Token associated with this expression */ - char *zSpan; /* Original text of the expression */ - u8 sortOrder; /* 1 for DESC or 0 for ASC */ - unsigned done :1; /* A flag to indicate when processing is finished */ - unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */ - unsigned reusable :1; /* Constant expression is reusable */ - union { - struct { - u16 iOrderByCol; /* For ORDER BY, column number in result set */ - u16 iAlias; /* Index into Parse.aAlias[] for zName */ - } x; - int iConstExprReg; /* Register in which Expr value is cached */ - } u; - } a[1]; /* One slot for each expression in the list */ -}; - -/* -** An instance of this structure is used by the parser to record both -** the parse tree for an expression and the span of input text for an -** expression. -*/ -struct ExprSpan { - Expr *pExpr; /* The expression parse tree */ - const char *zStart; /* First character of input text */ - const char *zEnd; /* One character past the end of input text */ -}; - -/* -** 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 bitmask datatype defined below is used for various optimizations. -** -** Changing this from a 64-bit to a 32-bit type limits the number of -** tables in a join to 32 instead of 64. But it also reduces the size -** of the library by 738 bytes on ix86. -*/ -#ifdef SQLITE_BITMASK_TYPE - typedef SQLITE_BITMASK_TYPE Bitmask; -#else - typedef u64 Bitmask; -#endif - -/* -** The number of bits in a Bitmask. "BMS" means "BitMask Size". -*/ -#define BMS ((int)(sizeof(Bitmask)*8)) - -/* -** A bit in a Bitmask -*/ -#define MASKBIT(n) (((Bitmask)1)<<(n)) -#define MASKBIT32(n) (((unsigned int)1)<<(n)) -#define ALLBITS ((Bitmask)-1) - -/* -** The following structure describes the FROM clause of a SELECT statement. -** Each table or subquery in the FROM clause is a separate element of -** the SrcList.a[] array. -** -** With the addition of multiple database support, the following structure -** can also be used to describe a particular table such as the table that -** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL, -** such a table must be a simple name: ID. But in SQLite, the table can -** now be identified by a database name, a dot, then the table name: ID.ID. -** -** The jointype starts out showing the join type between the current table -** and the next table on the list. The parser builds the list this way. -** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each -** jointype expresses the join between the table and the previous table. -** -** In the colUsed field, the high-order bit (bit 63) is set if the table -** contains more than 63 columns and the 64-th or later column is used. -*/ -struct SrcList { - int nSrc; /* Number of tables or subqueries in the FROM clause */ - u32 nAlloc; /* Number of entries allocated in a[] below */ - struct SrcList_item { - Schema *pSchema; /* Schema to which this item is fixed */ - char *zDatabase; /* Name of database holding this table */ - char *zName; /* Name of the table */ - char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */ - Table *pTab; /* An SQL table corresponding to zName */ - Select *pSelect; /* A SELECT statement used in place of a table name */ - int addrFillSub; /* Address of subroutine to manifest a subquery */ - int regReturn; /* Register holding return address of addrFillSub */ - int regResult; /* Registers holding results of a co-routine */ - struct { - u8 jointype; /* Type of join between this table and the previous */ - unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */ - unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */ - unsigned isTabFunc :1; /* True if table-valued-function syntax */ - unsigned isCorrelated :1; /* True if sub-query is correlated */ - unsigned viaCoroutine :1; /* Implemented as a co-routine */ - unsigned isRecursive :1; /* True for recursive reference in WITH */ - } fg; -#ifndef SQLITE_OMIT_EXPLAIN - u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */ -#endif - 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 */ - ExprList *pEList; /* Optional list of result-set columns */ - AggInfo *pAggInfo; /* Information about aggregates at this level */ - 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 */ - u16 ncFlags; /* Zero or more NC_* flags defined below */ -}; - -/* -** Allowed values for the NameContext, ncFlags field. -** -** Value constraints (all checked via assert()): -** NC_HasAgg == SF_HasAgg -** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX -** -*/ -#define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */ -#define NC_PartIdx 0x0002 /* True if resolving a partial index WHERE */ -#define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */ -#define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */ -#define NC_HasAgg 0x0010 /* One or more aggregate functions seen */ -#define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */ -#define NC_VarSelect 0x0040 /* A correlated subquery has been seen */ -#define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */ - -/* -** An instance of the following structure contains all information -** needed to generate code for a single SELECT statement. -** -** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0. -** If there is a LIMIT clause, the parser sets nLimit to the value of the -** limit and nOffset to the value of the offset (or 0 if there is not -** offset). But later on, nLimit and nOffset become the memory locations -** in the VDBE that record the limit and offset counters. -** -** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes. -** These addresses must be stored so that we can go back and fill in -** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor -** the number of columns in P2 can be computed at the same time -** as the OP_OpenEphm instruction is coded because not -** enough information about the compound query is known at that point. -** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences -** for the result set. The KeyInfo for addrOpenEphm[2] contains collating -** sequences for the ORDER BY clause. -*/ -struct Select { - ExprList *pEList; /* The fields of the result */ - u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */ - LogEst nSelectRow; /* Estimated number of result rows */ - u32 selFlags; /* Various SF_* values */ - int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */ -#if SELECTTRACE_ENABLED - char zSelName[12]; /* Symbolic name of this SELECT use for debugging */ -#endif - int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */ - SrcList *pSrc; /* The FROM clause */ - Expr *pWhere; /* The WHERE clause */ - ExprList *pGroupBy; /* The GROUP BY clause */ - Expr *pHaving; /* The HAVING clause */ - ExprList *pOrderBy; /* The ORDER BY clause */ - Select *pPrior; /* Prior select in a compound select statement */ - Select *pNext; /* Next select to the left in a compound */ - Expr *pLimit; /* LIMIT expression. NULL means not used. */ - Expr *pOffset; /* OFFSET expression. NULL means not used. */ - With *pWith; /* WITH clause attached to this select. Or NULL. */ -}; - -/* -** Allowed values for Select.selFlags. The "SF" prefix stands for -** "Select Flag". -** -** Value constraints (all checked via assert()) -** SF_HasAgg == NC_HasAgg -** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX -** SF_FixedLimit == WHERE_USE_LIMIT -*/ -#define SF_Distinct 0x00001 /* Output should be DISTINCT */ -#define SF_All 0x00002 /* Includes the ALL keyword */ -#define SF_Resolved 0x00004 /* Identifiers have been resolved */ -#define SF_Aggregate 0x00008 /* Contains agg functions or a GROUP BY */ -#define SF_HasAgg 0x00010 /* Contains aggregate functions */ -#define SF_UsesEphemeral 0x00020 /* Uses the OpenEphemeral opcode */ -#define SF_Expanded 0x00040 /* sqlite3SelectExpand() called on this */ -#define SF_HasTypeInfo 0x00080 /* FROM subqueries have Table metadata */ -#define SF_Compound 0x00100 /* Part of a compound query */ -#define SF_Values 0x00200 /* Synthesized from VALUES clause */ -#define SF_MultiValue 0x00400 /* Single VALUES term with multiple rows */ -#define SF_NestedFrom 0x00800 /* Part of a parenthesized FROM clause */ -#define SF_MinMaxAgg 0x01000 /* Aggregate containing min() or max() */ -#define SF_Recursive 0x02000 /* The recursive part of a recursive CTE */ -#define SF_FixedLimit 0x04000 /* nSelectRow set by a constant LIMIT */ -#define SF_MaybeConvert 0x08000 /* Need convertCompoundSelectToSubquery() */ -#define SF_Converted 0x10000 /* By convertCompoundSelectToSubquery() */ -#define SF_IncludeHidden 0x20000 /* Include hidden columns in output */ - - -/* -** The results of a SELECT can be distributed in several ways, as defined -** by one of the following macros. The "SRT" prefix means "SELECT Result -** Type". -** -** SRT_Union Store results as a key in a temporary index -** identified by pDest->iSDParm. -** -** SRT_Except Remove results from the temporary index pDest->iSDParm. -** -** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result -** set is not empty. -** -** SRT_Discard Throw the results away. This is used by SELECT -** statements within triggers whose only purpose is -** the side-effects of functions. -** -** All of the above are free to ignore their ORDER BY clause. Those that -** follow must honor the ORDER BY clause. -** -** SRT_Output Generate a row of output (using the OP_ResultRow -** opcode) for each row in the result set. -** -** SRT_Mem Only valid if the result is a single column. -** Store the first column of the first result row -** in register pDest->iSDParm then abandon the rest -** of the query. This destination implies "LIMIT 1". -** -** SRT_Set The result must be a single column. Store each -** row of result as the key in table pDest->iSDParm. -** Apply the affinity pDest->affSdst before storing -** results. Used to implement "IN (SELECT ...)". -** -** SRT_EphemTab Create an temporary table pDest->iSDParm and store -** the result there. The cursor is left open after -** returning. This is like SRT_Table except that -** this destination uses OP_OpenEphemeral to create -** the table first. -** -** SRT_Coroutine Generate a co-routine that returns a new row of -** results each time it is invoked. The entry point -** of the co-routine is stored in register pDest->iSDParm -** and the result row is stored in pDest->nDest registers -** starting with pDest->iSdst. -** -** SRT_Table Store results in temporary table pDest->iSDParm. -** SRT_Fifo This is like SRT_EphemTab except that the table -** is assumed to already be open. SRT_Fifo has -** the additional property of being able to ignore -** the ORDER BY clause. -** -** SRT_DistFifo Store results in a temporary table pDest->iSDParm. -** But also use temporary table pDest->iSDParm+1 as -** a record of all prior results and ignore any duplicate -** rows. Name means: "Distinct Fifo". -** -** SRT_Queue Store results in priority queue pDest->iSDParm (really -** an index). Append a sequence number so that all entries -** are distinct. -** -** SRT_DistQueue Store results in priority queue pDest->iSDParm only if -** the same record has never been stored before. The -** index at pDest->iSDParm+1 hold all prior stores. -*/ -#define SRT_Union 1 /* Store result as keys in an index */ -#define SRT_Except 2 /* Remove result from a UNION index */ -#define SRT_Exists 3 /* Store 1 if the result is not empty */ -#define SRT_Discard 4 /* Do not save the results anywhere */ -#define SRT_Fifo 5 /* Store result as data with an automatic rowid */ -#define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */ -#define SRT_Queue 7 /* Store result in an queue */ -#define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */ - -/* The ORDER BY clause is ignored for all of the above */ -#define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue) - -#define SRT_Output 9 /* Output each row of result */ -#define SRT_Mem 10 /* Store result in a memory cell */ -#define SRT_Set 11 /* Store results as keys in an index */ -#define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */ -#define SRT_Coroutine 13 /* Generate a single row of result */ -#define SRT_Table 14 /* Store result as data with an automatic rowid */ - -/* -** An instance of this object describes where to put of the results of -** a SELECT statement. -*/ -struct SelectDest { - u8 eDest; /* How to dispose of the results. On of SRT_* above. */ - int iSDParm; /* A parameter used by the eDest disposal method */ - int iSdst; /* Base register where results are written */ - int nSdst; /* Number of registers allocated */ - char *zAffSdst; /* Affinity used when eDest==SRT_Set */ - ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */ -}; - -/* -** During code generation of statements that do inserts into AUTOINCREMENT -** tables, the following information is attached to the Table.u.autoInc.p -** pointer of each autoincrement table to record some side information that -** the code generator needs. We have to keep per-table autoincrement -** information in case inserts are done within triggers. Triggers do not -** normally coordinate their activities, but we do need to coordinate the -** loading and saving of autoincrement information. -*/ -struct AutoincInfo { - AutoincInfo *pNext; /* Next info block in a list of them all */ - Table *pTab; /* Table this info block refers to */ - int iDb; /* Index in sqlite3.aDb[] of database holding pTab */ - int regCtr; /* Memory register holding the rowid counter */ -}; - -/* -** Size of the column cache -*/ -#ifndef SQLITE_N_COLCACHE -# define SQLITE_N_COLCACHE 10 -#endif - -/* -** 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 nColCache; /* Number of entries in aColCache[] */ - 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 nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */ - int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */ - int iSelfTab; /* Table for associated with an index on expr, or negative - ** of the base register during check-constraint eval */ - int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */ - int iCacheCnt; /* Counter used to generate aColCache[].lru values */ - int nLabel; /* Number of labels used */ - 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 */ -#if SELECTTRACE_ENABLED - int nSelect; /* Number of SELECT statements seen */ - int nSelectIndent; /* How far to indent SELECTTRACE() output */ -#endif -#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 */ - 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,aColCache). - **************************************************************************/ - - struct yColCache { - int iTable; /* Table cursor number */ - i16 iColumn; /* Table column number */ - u8 tempReg; /* iReg is a temp register that needs to be freed */ - int iLevel; /* Nesting level */ - int iReg; /* Reg with value of this column. 0 means none. */ - int lru; /* Least recently used entry has the smallest value */ - } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */ - 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 */ -#ifndef SQLITE_OMIT_VIRTUALTABLE - u8 declareVtab; /* True if inside sqlite3_declare_vtab() */ - int nVtabLock; /* Number of virtual tables to lock */ -#endif - int nHeight; /* Expression tree height of current sub-select */ -#ifndef SQLITE_OMIT_EXPLAIN - int iSelectId; /* ID of current select for EXPLAIN output */ - int iNextSelectId; /* Next available select ID for EXPLAIN output */ -#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 */ - 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 */ -}; - -/* -** Sizes and pointers of various parts of the Parse object. -*/ -#define PARSE_HDR_SZ offsetof(Parse,aColCache) /* 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->declareVtab) -#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_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 */ - -/* - * Each trigger present in the database schema is stored as an instance of - * struct Trigger. - * - * Pointers to instances of struct Trigger are stored in two ways. - * 1. In the "trigHash" hash table (part of the sqlite3* that represents the - * database). This allows Trigger structures to be retrieved by name. - * 2. All triggers associated with a single table form a linked list, using the - * pNext member of struct Trigger. A pointer to the first element of the - * linked list is stored as the "pTrigger" member of the associated - * struct Table. - * - * The "step_list" member points to the first element of a linked list - * containing the SQL statements specified as the trigger program. - */ -struct Trigger { - char *zName; /* The name of the trigger */ - char *table; /* The table or view to which the trigger applies */ - u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */ - u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */ - Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */ - IdList *pColumns; /* If this is an UPDATE OF trigger, - the is stored here */ - Schema *pSchema; /* Schema containing the trigger */ - Schema *pTabSchema; /* Schema containing the table */ - TriggerStep *step_list; /* Link list of trigger program steps */ - Trigger *pNext; /* Next trigger associated with the table */ -}; - -/* -** A trigger is either a BEFORE or an AFTER trigger. The following constants -** determine which. -** -** If there are multiple triggers, you might of some BEFORE and some AFTER. -** In that cases, the constants below can be ORed together. -*/ -#define TRIGGER_BEFORE 1 -#define TRIGGER_AFTER 2 - -/* - * An instance of struct TriggerStep is used to store a single SQL statement - * that is a part of a trigger-program. - * - * Instances of struct TriggerStep are stored in a singly linked list (linked - * using the "pNext" member) referenced by the "step_list" member of the - * associated struct Trigger instance. The first element of the linked list is - * the first step of the trigger-program. - * - * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or - * "SELECT" statement. The meanings of the other members is determined by the - * value of "op" as follows: - * - * (op == TK_INSERT) - * orconf -> stores the ON CONFLICT algorithm - * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then - * this stores a pointer to the SELECT statement. Otherwise NULL. - * zTarget -> Dequoted name of the table to insert into. - * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then - * this stores values to be inserted. Otherwise NULL. - * pIdList -> If this is an INSERT INTO ... () VALUES ... - * statement, then this stores the column-names to be - * inserted into. - * - * (op == TK_DELETE) - * zTarget -> Dequoted name of the table to delete from. - * pWhere -> The WHERE clause of the DELETE statement if one is specified. - * Otherwise NULL. - * - * (op == TK_UPDATE) - * zTarget -> Dequoted name of the table to update. - * pWhere -> The WHERE clause of the UPDATE statement if one is specified. - * Otherwise NULL. - * pExprList -> A list of the columns to update and the expressions to update - * them to. See sqlite3Update() documentation of "pChanges" - * argument. - * - */ -struct TriggerStep { - u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */ - u8 orconf; /* OE_Rollback etc. */ - Trigger *pTrig; /* The trigger that this step is a part of */ - Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */ - char *zTarget; /* Target table for DELETE, UPDATE, INSERT */ - Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */ - ExprList *pExprList; /* SET clause for UPDATE. */ - IdList *pIdList; /* Column names for INSERT */ - TriggerStep *pNext; /* Next in the link-list */ - TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */ -}; - -/* -** The following structure contains information used by the sqliteFix... -** routines as they walk the parse tree to make database references -** explicit. -*/ -typedef struct DbFixer DbFixer; -struct DbFixer { - Parse *pParse; /* The parsing context. Error messages written here */ - Schema *pSchema; /* Fix items to this schema */ - int bVarOnly; /* Check for variable references only */ - const char *zDb; /* Make sure all objects are contained in this database */ - const char *zType; /* Type of the container - used for error messages */ - const Token *pName; /* Name of the container - used for error messages */ -}; - -/* -** An objected used to accumulate the text of a string where we -** do not necessarily know how big the string will be in the end. -*/ -struct StrAccum { - 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; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */ - u8 printfFlags; /* SQLITE_PRINTF flags below */ -}; -#define STRACCUM_NOMEM 1 -#define STRACCUM_TOOBIG 2 -#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 */ -} InitData; - -/* -** Structure containing global configuration data for the SQLite library. -** -** This structure also contains some state information. -*/ -struct Sqlite3Config { - int bMemstat; /* True to enable memory status */ - int bCoreMutex; /* True to enable core mutexing */ - int bFullMutex; /* True to enable full mutexing */ - int bOpenUri; /* True to interpret filenames as URIs */ - int bUseCis; /* Use covering indices for full-scans */ - int bSmallMalloc; /* Avoid large memory allocations if true */ - int mxStrlen; /* Maximum string length */ - int neverCorrupt; /* Database is always well-formed */ - int szLookaside; /* Default lookaside buffer size */ - int nLookaside; /* Default lookaside buffer count */ - int nStmtSpill; /* Stmt-journal spill-to-disk threshold */ - sqlite3_mem_methods m; /* Low-level memory allocation interface */ - sqlite3_mutex_methods mutex; /* Low-level mutex interface */ - sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */ - void *pHeap; /* Heap storage space */ - int nHeap; /* Size of pHeap[] */ - int mnReq, mxReq; /* Min and max heap requests sizes */ - sqlite3_int64 szMmap; /* mmap() space per open file */ - sqlite3_int64 mxMmap; /* Maximum value for szMmap */ - void *pPage; /* Page cache memory */ - int szPage; /* Size of each page in pPage[] */ - int nPage; /* Number of pages in pPage[] */ - int mxParserStack; /* maximum depth of the parser stack */ - int sharedCacheEnabled; /* true if shared-cache mode enabled */ - u32 szPma; /* Maximum Sorter PMA size */ - /* The above might be initialized to non-zero. The following need to always - ** initially be zero, however. */ - int isInit; /* True after initialization has finished */ - int inProgress; /* True while initialization in progress */ - int isMutexInit; /* True after mutexes are initialized */ - int isMallocInit; /* True after malloc is initialized */ - int isPCacheInit; /* True after malloc is initialized */ - int nRefInitMutex; /* Number of users of pInitMutex */ - sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */ - void (*xLog)(void*,int,const char*); /* Function for logging */ - void *pLogArg; /* First argument to xLog() */ -#ifdef SQLITE_ENABLE_SQLLOG - void(*xSqllog)(void*,sqlite3*,const char*, int); - void *pSqllogArg; -#endif -#ifdef SQLITE_VDBE_COVERAGE - /* The following callback (if not NULL) is invoked on every VDBE branch - ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE. - */ - void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */ - void *pVdbeBranchArg; /* 1st argument */ -#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 */ -}; - -/* -** This macro is used inside of assert() statements to indicate that -** the assert is only valid on a well-formed database. Instead of: -** -** assert( X ); -** -** One writes: -** -** assert( X || CORRUPT_DB ); -** -** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate -** that the database is definitely corrupt, only that it might be corrupt. -** For most test cases, CORRUPT_DB is set to false using a special -** sqlite3_test_control(). This enables assert() statements to prove -** things that are always true for well-formed databases. -*/ -#define CORRUPT_DB (sqlite3Config.neverCorrupt==0) - -/* -** Context pointer passed down through the tree-walk. -*/ -struct Walker { - Parse *pParse; /* Parser context. */ - int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */ - int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */ - void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */ - int walkerDepth; /* Number of subqueries */ - u8 eCode; /* A small processing code */ - union { /* Extra data for callback */ - NameContext *pNC; /* Naming context */ - int n; /* A counter */ - int iCur; /* A cursor number */ - SrcList *pSrcList; /* FROM clause */ - struct SrcCount *pSrcCount; /* Counting column references */ - struct CCurHint *pCCurHint; /* Used by codeCursorHint() */ - int *aiCol; /* array of column indexes */ - struct IdxCover *pIdxCover; /* Check for index coverage */ - struct IdxExprTrans *pIdxTrans; /* Convert indexed expr to column */ - ExprList *pGroupBy; /* GROUP BY clause */ - struct HavingToWhereCtx *pHavingCtx; /* HAVING to WHERE clause ctx */ - } u; -}; - -/* Forward declarations */ -SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*); -SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*); -SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*); -SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*); -SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*); -SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*); -SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker*, Select*); -SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker*, Select*); -#ifdef SQLITE_DEBUG -SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker*, Select*); -#endif - -/* -** Return code from the parse-tree walking primitives and their -** callbacks. -*/ -#define WRC_Continue 0 /* Continue down into children */ -#define WRC_Prune 1 /* Omit children but continue walking siblings */ -#define WRC_Abort 2 /* Abandon the tree walk */ - -/* -** An instance of this structure represents a set of one or more CTEs -** (common table expressions) created by a single WITH clause. -*/ -struct With { - int nCte; /* Number of CTEs in the WITH clause */ - With *pOuter; /* Containing WITH clause, or NULL */ - struct Cte { /* For each CTE in the WITH clause.... */ - char *zName; /* Name of this CTE */ - ExprList *pCols; /* List of explicit column names, or NULL */ - Select *pSelect; /* The definition of this CTE */ - const char *zCteErr; /* Error message for circular references */ - } a[1]; -}; - -#ifdef SQLITE_DEBUG -/* -** An instance of the TreeView object is used for printing the content of -** data structures on sqlite3DebugPrintf() using a tree-like view. -*/ -struct TreeView { - int iLevel; /* Which level of the tree we are on */ - u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */ -}; -#endif /* SQLITE_DEBUG */ - -/* -** 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 sqlite3CorruptError(int); -SQLITE_PRIVATE int sqlite3MisuseError(int); -SQLITE_PRIVATE int sqlite3CantopenError(int); -#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__) -#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__) -#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__) -#ifdef SQLITE_DEBUG -SQLITE_PRIVATE int sqlite3NomemError(int); -SQLITE_PRIVATE int sqlite3IoerrnomemError(int); -SQLITE_PRIVATE int sqlite3CorruptPgnoError(int,Pgno); -# define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__) -# define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__) -# define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P)) -#else -# define SQLITE_NOMEM_BKPT SQLITE_NOMEM -# define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM -# define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__) -#endif - -/* -** FTS3 and FTS4 both require virtual table support -*/ -#if defined(SQLITE_OMIT_VIRTUALTABLE) -# undef SQLITE_ENABLE_FTS3 -# undef SQLITE_ENABLE_FTS4 -#endif - -/* -** FTS4 is really an extension for FTS3. It is enabled using the -** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call -** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3. -*/ -#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3) -# define SQLITE_ENABLE_FTS3 1 -#endif - -/* -** The ctype.h header is needed for non-ASCII systems. It is also -** needed by FTS3 when FTS3 is included in the amalgamation. -*/ -#if !defined(SQLITE_ASCII) || \ - (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION)) -# include -#endif - -/* -** The following macros mimic the standard library functions toupper(), -** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The -** sqlite versions only work for ASCII characters, regardless of locale. -*/ -#ifdef SQLITE_ASCII -# define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20)) -# define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01) -# define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06) -# define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02) -# define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04) -# define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08) -# define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)]) -# define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80) -#else -# define sqlite3Toupper(x) toupper((unsigned char)(x)) -# define sqlite3Isspace(x) isspace((unsigned char)(x)) -# define sqlite3Isalnum(x) isalnum((unsigned char)(x)) -# define sqlite3Isalpha(x) isalpha((unsigned char)(x)) -# define sqlite3Isdigit(x) isdigit((unsigned char)(x)) -# define sqlite3Isxdigit(x) isxdigit((unsigned char)(x)) -# define sqlite3Tolower(x) tolower((unsigned char)(x)) -# define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`') -#endif -#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS -SQLITE_PRIVATE int sqlite3IsIdChar(u8); -#endif - -/* -** Internal function prototypes -*/ -SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*); -SQLITE_PRIVATE int sqlite3Strlen30(const char*); -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 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); - -#ifndef SQLITE_OMIT_FLOATING_POINT -SQLITE_PRIVATE int sqlite3IsNaN(double); -#else -# 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 void sqlite3VXPrintf(StrAccum*, const char*, va_list); -SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...); -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 sqlite3TreeViewSelect(TreeView*, const Select*, u8); -SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8); -#endif - - -SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*); -SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...); -SQLITE_PRIVATE void sqlite3Dequote(char*); -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(sqlite3*,Expr*, Expr*); -SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*); -SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32); -SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*); -SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*); -SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*); -SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int); -SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int); -SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*); -SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*); -SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*); -SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**); -SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**); -SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int); -#ifndef SQLITE_OMIT_VIRTUALTABLE -SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName); -#endif -SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*); -SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int); -SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*); -SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*); -SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*); -SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**); -SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*); -SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*); -SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int); -SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*); -SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16); -SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int); -#if SQLITE_ENABLE_HIDDEN_COLUMNS -SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table*, Column*); -#else -# define sqlite3ColumnPropertiesFromName(T,C) /* no-op */ -#endif -SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*); -SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int); -SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int); -SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*); -SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*); -SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*); -SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*); -SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*, - sqlite3_vfs**,char**,char **); -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*, void*, unsigned int); -SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*); -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*); -#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); -SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*); -SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*); -SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*); -SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int); -SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, 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*,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*,Expr*,char*); -#endif -SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*); -SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int); -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 sqlite3WhereOrderedInnerLoop(WhereInfo*); -SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*); -SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*); -SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*); -SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*); -#define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */ -#define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */ -#define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */ -SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int); -SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8); -SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse*, Table*, int, int, int); -SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int); -SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int); -SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int); -SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*); -SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*); -SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int); -SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*); -SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int); -SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int); -SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int); -SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int); -SQLITE_PRIVATE int sqlite3ExprCodeAtInit(Parse*, Expr*, int); -SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*); -SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int); -SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int); -SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8); -#define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */ -#define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */ -#define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */ -#define SQLITE_ECEL_OMITREF 0x08 /* Omit if ExprList.u.x.iOrderByCol */ -SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int); -SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int); -SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int); -SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*); -#define LOCATE_VIEW 0x01 -#define LOCATE_NOERR 0x02 -SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*); -SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *); -SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*); -SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*); -SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*); -SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*); -SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int); -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 void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*); -SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*); -SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx); -SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*); -SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*); -#ifndef SQLITE_UNTESTABLE -SQLITE_PRIVATE void sqlite3PrngSaveState(void); -SQLITE_PRIVATE void sqlite3PrngRestoreState(void); -#endif -SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int); -SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int); -SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb); -SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int); -SQLITE_PRIVATE void sqlite3EndTransaction(Parse*,int); -SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*); -SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *); -SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*); -SQLITE_PRIVATE int 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 void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int, - u8,u8,int,int*,int*); -#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); -#if SELECTTRACE_ENABLED -SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*); -#else -# define sqlite3SelectSetName(A,B) -#endif -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*, 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*); -SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*, - Select*,u8); -SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8); -SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*); -SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*); -SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*); -SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int); -# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p)) -# define sqlite3IsToplevel(p) ((p)->pToplevel==0) -#else -# define sqlite3TriggersExist(B,C,D,E,F) 0 -# define sqlite3DeleteTrigger(A,B) -# define sqlite3DropTriggerPtr(A,B) -# define sqlite3UnlinkAndDeleteTrigger(A,B,C) -# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I) -# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F) -# define sqlite3TriggerList(X, Y) 0 -# define sqlite3ParseToplevel(p) p -# define sqlite3IsToplevel(p) 1 -# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0 -#endif - -SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*); -SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int); -SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int); -#ifndef SQLITE_OMIT_AUTHORIZATION -SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*); -SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*); -SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*); -SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*); -SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int); -#else -# define sqlite3AuthRead(a,b,c,d) -# define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK -# define sqlite3AuthContextPush(a,b,c) -# define sqlite3AuthContextPop(a) ((void)(a)) -#endif -SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*); -SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*); -SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*); -SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*); -SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*); -SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*); -SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*); -SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*); -SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8); -SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*); -SQLITE_PRIVATE int sqlite3Atoi(const char*); -#ifndef SQLITE_OMIT_UTF16 -SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar); -#endif -SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte); -SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**); -SQLITE_PRIVATE LogEst sqlite3LogEst(u64); -SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst); -#ifndef SQLITE_OMIT_VIRTUALTABLE -SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double); -#endif -#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \ - defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \ - defined(SQLITE_EXPLAIN_ESTIMATED_ROWS) -SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst); -#endif -SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int); -SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int); -SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int); - -/* -** Routines to read and write variable-length integers. These used to -** be defined locally, but now we use the varint routines in the util.c -** file. -*/ -SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64); -SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *); -SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *); -SQLITE_PRIVATE int sqlite3VarintLen(u64 v); - -/* -** The common case is for a varint to be a single byte. They following -** macros handle the common case without a procedure call, but then call -** the procedure for larger varints. -*/ -#define getVarint32(A,B) \ - (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B))) -#define putVarint32(A,B) \ - (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\ - sqlite3PutVarint((A),(B))) -#define getVarint sqlite3GetVarint -#define putVarint sqlite3PutVarint - - -SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*); -SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int); -SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2); -SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity); -SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int); -SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr); -SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8); -SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*); -SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...); -SQLITE_PRIVATE void sqlite3Error(sqlite3*,int); -SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int); -SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n); -SQLITE_PRIVATE u8 sqlite3HexToInt(int h); -SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **); - -#if defined(SQLITE_NEED_ERR_NAME) -SQLITE_PRIVATE const char *sqlite3ErrName(int); -#endif - -SQLITE_PRIVATE const char *sqlite3ErrStr(int); -SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse); -SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int); -SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName); -SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr); -SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr); -SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,Expr*,Expr*); -SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int); -SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*); -SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*); -SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *); -SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *); -SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int); -SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64); -SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64); -SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64); -SQLITE_PRIVATE int sqlite3AbsInt32(int); -#ifdef SQLITE_ENABLE_8_3_NAMES -SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*); -#else -# define sqlite3FileSuffix3(X,Y) -#endif -SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8); - -SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8); -SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8); -SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, - void(*)(void*)); -SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*); -SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*); -SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *); -#ifndef SQLITE_OMIT_UTF16 -SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8); -#endif -SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **); -SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8); -#ifndef SQLITE_AMALGAMATION -SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[]; -SQLITE_PRIVATE const char sqlite3StrBINARY[]; -SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[]; -SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[]; -SQLITE_PRIVATE const Token sqlite3IntTokens[]; -SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config; -SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions; -#ifndef SQLITE_OMIT_WSD -SQLITE_PRIVATE int sqlite3PendingByte; -#endif -#endif -SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int); -SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*); -SQLITE_PRIVATE void sqlite3AlterFunctions(void); -SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*); -SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *); -SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...); -SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*); -SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr *, int, int); -SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*); -SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p); -SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*); -SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*); -SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*); -SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*); -SQLITE_PRIVATE void 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 CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*); -SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*); -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*); -#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*), - FuncDestructor *pDestructor -); -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 void sqlite3StrAccumAppend(StrAccum*,const char*,int); -SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*); -SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char); -SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*); -SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*); -SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int); -SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int); - -SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *); -SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *); - -#ifndef SQLITE_OMIT_SUBQUERY -SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*); -#else -# define sqlite3ExprCheckIN(x,y) SQLITE_OK -#endif - -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 -SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void); -SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue( - Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*); -SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**); -SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*); -SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**); -SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int); -#endif - -/* -** The interface to the LEMON-generated parser -*/ -#ifndef SQLITE_AMALGAMATION -SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64)); -SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*)); -#endif -SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*); -#ifdef YYTRACKMAXSTACKDEPTH -SQLITE_PRIVATE int sqlite3ParserStackPeak(void*); -#endif - -SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*); -#ifndef SQLITE_OMIT_LOAD_EXTENSION -SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*); -#else -# define sqlite3CloseExtensions(X) -#endif - -#ifndef SQLITE_OMIT_SHARED_CACHE -SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *); -#else - #define sqlite3TableLock(v,w,x,y,z) -#endif - -#ifdef SQLITE_TEST -SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*); -#endif - -#ifdef SQLITE_OMIT_VIRTUALTABLE -# define sqlite3VtabClear(Y) -# define sqlite3VtabSync(X,Y) SQLITE_OK -# define sqlite3VtabRollback(X) -# define sqlite3VtabCommit(X) -# define sqlite3VtabInSync(db) 0 -# define sqlite3VtabLock(X) -# define sqlite3VtabUnlock(X) -# define sqlite3VtabUnlockList(X) -# define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK -# define sqlite3GetVTable(X,Y) ((VTable*)0) -#else -SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*); -SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p); -SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*); -SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db); -SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db); -SQLITE_PRIVATE void sqlite3VtabLock(VTable *); -SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *); -SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*); -SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int); -SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*); -SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*); -SQLITE_PRIVATE Module *sqlite3VtabCreateModule( - sqlite3*, - const char*, - const sqlite3_module*, - void*, - void(*)(void*) - ); -# define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0) -#endif -SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*); -SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*); -SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*); -SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int); -SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*); -SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*); -SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*); -SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **); -SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*); -SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *); -SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *); -SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*); -SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**); -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*); -SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*); -SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*); -SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *); -SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*); -SQLITE_PRIVATE const char *sqlite3JournalModename(int); -#ifndef SQLITE_OMIT_WAL -SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*); -SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int); -#endif -#ifndef SQLITE_OMIT_CTE -SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*); -SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*); -SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8); -#else -#define sqlite3WithPush(x,y,z) -#define sqlite3WithDelete(x,y) -#endif - -/* 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*); - -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 the SQLITE_ENABLE IOTRACE exists then the global variable -** sqlite3IoTrace is a pointer to a printf-like routine used to -** print I/O tracing messages. -*/ -#ifdef SQLITE_ENABLE_IOTRACE -# define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; } -SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*); -SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...); -#else -# define IOTRACE(A) -# define sqlite3VdbeIOTraceSql(X) -#endif - -/* -** These routines are available for the mem2.c debugging memory allocator -** only. They are used to verify that different "types" of memory -** allocations are properly tracked by the system. -** -** sqlite3MemdebugSetType() sets the "type" of an allocation to one of -** the MEMTYPE_* macros defined below. The type must be a bitmask with -** a single bit set. -** -** sqlite3MemdebugHasType() returns true if any of the bits in its second -** argument match the type set by the previous sqlite3MemdebugSetType(). -** sqlite3MemdebugHasType() is intended for use inside assert() statements. -** -** sqlite3MemdebugNoType() returns true if none of the bits in its second -** argument match the type set by the previous sqlite3MemdebugSetType(). -** -** Perhaps the most important point is the difference between MEMTYPE_HEAP -** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means -** it might have been allocated by lookaside, except the allocation was -** too large or lookaside was already full. It is important to verify -** that allocations that might have been satisfied by lookaside are not -** passed back to non-lookaside free() routines. Asserts such as the -** example above are placed on the non-lookaside free() routines to verify -** this constraint. -** -** All of this is no-op for a production build. It only comes into -** play when the SQLITE_MEMDEBUG compile-time option is used. -*/ -#ifdef SQLITE_MEMDEBUG -SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8); -SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8); -SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8); -#else -# define sqlite3MemdebugSetType(X,Y) /* no-op */ -# define sqlite3MemdebugHasType(X,Y) 1 -# define sqlite3MemdebugNoType(X,Y) 1 -#endif -#define MEMTYPE_HEAP 0x01 /* General heap allocations */ -#define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */ -#define MEMTYPE_PCACHE 0x04 /* Page cache allocations */ - -/* -** Threading interface -*/ -#if SQLITE_MAX_WORKER_THREADS>0 -SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*); -SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**); -#endif - -#if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST) -SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3*); -#endif -#if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST) -SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*); -#endif - -SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr); -SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr); -SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int); -SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int); -SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*); - -#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS -SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt); -#endif - -#endif /* SQLITEINT_H */ - -/************** End of sqliteInt.h *******************************************/ -/************** Begin file global.c ******************************************/ -/* -** 2008 June 13 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file contains definitions of global variables and constants. -*/ -/* #include "sqliteInt.h" */ - -/* An array to map all upper-case characters into their corresponding -** lower-case character. -** -** SQLite only considers US-ASCII (or EBCDIC) characters. We do not -** handle case conversions for the UTF character set since the tables -** involved are nearly as big or bigger than SQLite itself. -*/ -SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = { -#ifdef SQLITE_ASCII - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, - 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, - 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103, - 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121, - 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107, - 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125, - 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, - 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161, - 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179, - 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197, - 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215, - 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233, - 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251, - 252,253,254,255 -#endif -#ifdef SQLITE_EBCDIC - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */ - 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */ - 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */ - 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */ - 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */ - 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */ - 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */ - 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */ - 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */ - 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */ - 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */ - 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */ - 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */ - 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */ - 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */ - 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */ -#endif -}; - -/* -** The following 256 byte lookup table is used to support SQLites built-in -** equivalents to the following standard library functions: -** -** isspace() 0x01 -** isalpha() 0x02 -** isdigit() 0x04 -** isalnum() 0x06 -** isxdigit() 0x08 -** toupper() 0x20 -** SQLite identifier character 0x40 -** Quote character 0x80 -** -** Bit 0x20 is set if the mapped character requires translation to upper -** case. i.e. if the character is a lower-case ASCII character. -** If x is a lower-case ASCII character, then its upper-case equivalent -** is (x - 0x20). Therefore toupper() can be implemented as: -** -** (x & ~(map[x]&0x20)) -** -** The equivalent of tolower() is implemented using the sqlite3UpperToLower[] -** array. tolower() is used more often than toupper() by SQLite. -** -** Bit 0x40 is set if the character is non-alphanumeric and can be used in an -** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any -** non-ASCII UTF character. Hence the test for whether or not a character is -** part of an identifier is 0x46. -*/ -#ifdef SQLITE_ASCII -SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */ - 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */ - 0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */ - 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */ - 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */ - - 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */ - 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */ - 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */ - 0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */ - 0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */ - 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */ - 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */ - 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */ - - 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */ - 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */ - 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */ - 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */ - 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */ - 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */ - 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */ - 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */ - - 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */ - 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */ - 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */ - 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */ - 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */ - 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */ - 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */ - 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */ -}; -#endif - -/* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards -** compatibility for legacy applications, the URI filename capability is -** disabled by default. -** -** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled -** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options. -** -** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally -** disabled. The default value may be changed by compiling with the -** SQLITE_USE_URI symbol defined. -** -** URI filenames are enabled by default if SQLITE_HAS_CODEC is -** enabled. -*/ -#ifndef SQLITE_USE_URI -# ifdef SQLITE_HAS_CODEC -# define SQLITE_USE_URI 1 -# else -# define SQLITE_USE_URI 0 -# endif -#endif - -/* EVIDENCE-OF: R-38720-18127 The default setting is determined by the -** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if -** that compile-time option is omitted. -*/ -#ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN -# define SQLITE_ALLOW_COVERING_INDEX_SCAN 1 -#endif - -/* The minimum PMA size is set to this value multiplied by the database -** page size in bytes. -*/ -#ifndef SQLITE_SORTER_PMASZ -# define SQLITE_SORTER_PMASZ 250 -#endif - -/* Statement journals spill to disk when their size exceeds the following -** threshold (in bytes). 0 means that statement journals are created and -** written to disk immediately (the default behavior for SQLite versions -** before 3.12.0). -1 means always keep the entire statement journal in -** memory. (The statement journal is also always held entirely in memory -** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this -** setting.) -*/ -#ifndef SQLITE_STMTJRNL_SPILL -# define SQLITE_STMTJRNL_SPILL (64*1024) -#endif - -/* -** The default lookaside-configuration, the format "SZ,N". SZ is the -** number of bytes in each lookaside slot (should be a multiple of 8) -** and N is the number of slots. The lookaside-configuration can be -** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE) -** or at run-time for an individual database connection using -** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE); -*/ -#ifndef SQLITE_DEFAULT_LOOKASIDE -# define SQLITE_DEFAULT_LOOKASIDE 1200,100 -#endif - - -/* -** The following singleton contains the global configuration for -** the SQLite library. -*/ -SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = { - SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */ - 1, /* bCoreMutex */ - SQLITE_THREADSAFE==1, /* bFullMutex */ - SQLITE_USE_URI, /* bOpenUri */ - SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */ - 0, /* bSmallMalloc */ - 0x7ffffffe, /* mxStrlen */ - 0, /* neverCorrupt */ - SQLITE_DEFAULT_LOOKASIDE, /* szLookaside, nLookaside */ - SQLITE_STMTJRNL_SPILL, /* nStmtSpill */ - {0,0,0,0,0,0,0,0}, /* m */ - {0,0,0,0,0,0,0,0,0}, /* mutex */ - {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */ - (void*)0, /* pHeap */ - 0, /* nHeap */ - 0, 0, /* mnHeap, mxHeap */ - SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */ - SQLITE_MAX_MMAP_SIZE, /* mxMmap */ - (void*)0, /* pPage */ - 0, /* szPage */ - SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */ - 0, /* mxParserStack */ - 0, /* sharedCacheEnabled */ - SQLITE_SORTER_PMASZ, /* szPma */ - /* All the rest should always be initialized to zero */ - 0, /* isInit */ - 0, /* inProgress */ - 0, /* isMutexInit */ - 0, /* isMallocInit */ - 0, /* isPCacheInit */ - 0, /* nRefInitMutex */ - 0, /* pInitMutex */ - 0, /* xLog */ - 0, /* pLogArg */ -#ifdef SQLITE_ENABLE_SQLLOG - 0, /* xSqllog */ - 0, /* pSqllogArg */ -#endif -#ifdef SQLITE_VDBE_COVERAGE - 0, /* xVdbeBranch */ - 0, /* pVbeBranchArg */ -#endif -#ifndef SQLITE_UNTESTABLE - 0, /* xTestCallback */ -#endif - 0, /* bLocaltimeFault */ - 0x7ffffffe /* iOnceResetThreshold */ -}; - -/* -** Hash table for global functions - functions common to all -** database connections. After initialization, this table is -** read-only. -*/ -SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions; - -/* -** Constant tokens for values 0 and 1. -*/ -SQLITE_PRIVATE const Token sqlite3IntTokens[] = { - { "0", 1 }, - { "1", 1 } -}; - - -/* -** The value of the "pending" byte must be 0x40000000 (1 byte past the -** 1-gibabyte boundary) in a compatible database. SQLite never uses -** the database page that contains the pending byte. It never attempts -** to read or write that page. The pending byte page is set aside -** for use by the VFS layers as space for managing file locks. -** -** During testing, it is often desirable to move the pending byte to -** a different position in the file. This allows code that has to -** deal with the pending byte to run on files that are much smaller -** than 1 GiB. The sqlite3_test_control() interface can be used to -** move the pending byte. -** -** IMPORTANT: Changing the pending byte to any value other than -** 0x40000000 results in an incompatible database file format! -** Changing the pending byte during operation will result in undefined -** and incorrect behavior. -*/ -#ifndef SQLITE_OMIT_WSD -SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000; -#endif - -/* #include "opcodes.h" */ -/* -** Properties of opcodes. The OPFLG_INITIALIZER macro is -** created by mkopcodeh.awk during compilation. Data is obtained -** from the comments following the "case OP_xxxx:" statements in -** the vdbe.c file. -*/ -SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER; - -/* -** Name of the default collating sequence -*/ -SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY"; - -/************** End of global.c **********************************************/ -/************** Begin file status.c ******************************************/ -/* -** 2008 June 18 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This module implements the sqlite3_status() interface and related -** functionality. -*/ -/* #include "sqliteInt.h" */ -/************** Include vdbeInt.h in the middle of status.c ******************/ -/************** Begin file vdbeInt.h *****************************************/ -/* -** 2003 September 6 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This is the header file for information that is private to the -** VDBE. This information used to all be at the top of the single -** source code file "vdbe.c". When that file became too big (over -** 6000 lines long) it was split up into several smaller files and -** this header information was factored out. -*/ -#ifndef SQLITE_VDBEINT_H -#define SQLITE_VDBEINT_H - -/* -** The maximum number of times that a statement will try to reparse -** itself before giving up and returning SQLITE_SCHEMA. -*/ -#ifndef SQLITE_MAX_SCHEMA_RETRY -# define SQLITE_MAX_SCHEMA_RETRY 50 -#endif - -/* -** VDBE_DISPLAY_P4 is true or false depending on whether or not the -** "explain" P4 display logic is enabled. -*/ -#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \ - || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG) -# define VDBE_DISPLAY_P4 1 -#else -# define VDBE_DISPLAY_P4 0 -#endif - -/* -** SQL is translated into a sequence of instructions to be -** executed by a virtual machine. Each instruction is an instance -** of the following structure. -*/ -typedef struct VdbeOp Op; - -/* -** Boolean values -*/ -typedef unsigned Bool; - -/* Opaque type used by code in vdbesort.c */ -typedef struct VdbeSorter VdbeSorter; - -/* Elements of the linked list at Vdbe.pAuxData */ -typedef struct AuxData AuxData; - -/* Types of VDBE cursors */ -#define CURTYPE_BTREE 0 -#define CURTYPE_SORTER 1 -#define CURTYPE_VTAB 2 -#define CURTYPE_PSEUDO 3 - -/* -** A VdbeCursor is an superclass (a wrapper) for various cursor objects: -** -** * A b-tree cursor -** - In the main database or in an ephemeral database -** - On either an index or a table -** * A sorter -** * A virtual table -** * A one-row "pseudotable" stored in a single register -*/ -typedef struct VdbeCursor VdbeCursor; -struct VdbeCursor { - u8 eCurType; /* One of the CURTYPE_* values above */ - i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */ - u8 nullRow; /* True if pointing to a row with no data */ - u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */ - u8 isTable; /* True for rowid tables. False for indexes */ -#ifdef SQLITE_DEBUG - u8 seekOp; /* Most recent seek operation on this cursor */ - u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */ -#endif - Bool isEphemeral:1; /* True for an ephemeral table */ - Bool useRandomRowid:1; /* Generate new record numbers semi-randomly */ - Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */ - Btree *pBtx; /* Separate file holding temporary table */ - i64 seqCount; /* Sequence counter */ - int *aAltMap; /* Mapping from table to index column numbers */ - - /* Cached OP_Column parse information is only valid if cacheStatus matches - ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of - ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that - ** the cache is out of date. */ - u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */ - int seekResult; /* Result of previous sqlite3BtreeMoveto() or 0 - ** if there have been no prior seeks on the cursor. */ - /* seekResult does not distinguish between "no seeks have ever occurred - ** on this cursor" and "the most recent seek was an exact match". - ** For CURTYPE_PSEUDO, seekResult is the register holding the record */ - - /* When a new VdbeCursor is allocated, only the fields above are zeroed. - ** The fields that follow are uninitialized, and must be individually - ** initialized prior to first use. */ - VdbeCursor *pAltCursor; /* Associated index cursor from which to read */ - union { - BtCursor *pCursor; /* CURTYPE_BTREE or _PSEUDO. Btree cursor */ - sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */ - VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */ - } uc; - KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */ - u32 iHdrOffset; /* Offset to next unparsed byte of the header */ - Pgno pgnoRoot; /* Root page of the open btree cursor */ - i16 nField; /* Number of fields in the header */ - u16 nHdrParsed; /* Number of header fields parsed so far */ - i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */ - u32 *aOffset; /* Pointer to aType[nField] */ - const u8 *aRow; /* Data for the current row, if all on one page */ - u32 payloadSize; /* Total number of bytes in the record */ - u32 szRow; /* Byte available in aRow */ -#ifdef SQLITE_ENABLE_COLUMN_USED_MASK - u64 maskUsed; /* Mask of columns used by this cursor */ -#endif - - /* 2*nField extra array elements allocated for aType[], beyond the one - ** static element declared in the structure. nField total array slots for - ** aType[] and nField+1 array slots for aOffset[] */ - u32 aType[1]; /* Type values record decode. MUST BE LAST */ -}; - - -/* -** A value for VdbeCursor.cacheStatus that means the cache is always invalid. -*/ -#define CACHE_STALE 0 - -/* -** When a sub-program is executed (OP_Program), a structure of this type -** is allocated to store the current value of the program counter, as -** well as the current memory cell array and various other frame specific -** values stored in the Vdbe struct. When the sub-program is finished, -** these values are copied back to the Vdbe from the VdbeFrame structure, -** restoring the state of the VM to as it was before the sub-program -** began executing. -** -** The memory for a VdbeFrame object is allocated and managed by a memory -** cell in the parent (calling) frame. When the memory cell is deleted or -** overwritten, the VdbeFrame object is not freed immediately. Instead, it -** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame -** list is deleted when the VM is reset in VdbeHalt(). The reason for doing -** this instead of deleting the VdbeFrame immediately is to avoid recursive -** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the -** child frame are released. -** -** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is -** set to NULL if the currently executing frame is the main program. -*/ -typedef struct VdbeFrame VdbeFrame; -struct VdbeFrame { - Vdbe *v; /* VM this frame belongs to */ - VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */ - Op *aOp; /* Program instructions for parent frame */ - i64 *anExec; /* Event counters from parent frame */ - Mem *aMem; /* Array of memory cells for parent frame */ - VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */ - u8 *aOnce; /* Bitmask used by OP_Once */ - void *token; /* Copy of SubProgram.token */ - i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */ - AuxData *pAuxData; /* Linked list of auxdata allocations */ - 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 */ -}; - -#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 */ - RowSet *pRowSet; /* Used only when flags==MEM_RowSet */ - VdbeFrame *pFrame; /* Used when flags==MEM_Frame */ - } 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 */ - void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */ -#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_AffMask 0x001f /* Mask of affinity bits */ -#define MEM_RowSet 0x0020 /* Value is a RowSet object */ -#define MEM_Frame 0x0040 /* Value is a VdbeFrame object */ -#define MEM_Undefined 0x0080 /* Value is undefined */ -#define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */ -#define MEM_TypeMask 0xc1ff /* 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|MEM_RowSet|MEM_Frame))!=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) - -/* -** 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 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */ - 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 */ - -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 */ -}; - -/* -** 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 not 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 */ - - /* 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 */ - Mem *aMem; /* The memory locations */ - Mem **apArg; /* Arguments to currently executing user function */ - Mem *aColName; /* Column names to return */ - Mem *pResultSet; /* Pointer to an array of results */ - char *zErrMsg; /* Error message written here */ - VdbeCursor **apCsr; /* One element of this array for each open cursor */ - Mem *aVar; /* Values for the OP_Variable opcode. */ - VList *pVList; /* Name of variables */ -#ifndef SQLITE_OMIT_TRACE - i64 startTime; /* Time when query started - used for profiling */ -#endif - int nOp; /* Number of instructions in the program */ -#ifdef SQLITE_DEBUG - int rcApp; /* errcode set by sqlite3_result_error_code() */ -#endif - u16 nResColumn; /* Number of columns in one row of the result set */ - u8 errorAction; /* Recovery action to do in case of an error */ - u8 minWriteFileFormat; /* Minimum file format for writable database files */ - u8 prepFlags; /* SQLITE_PREPARE_* flags */ - bft expired:1; /* True if the VM needs to be recompiled */ - bft doingRerun:1; /* True if rerunning after an auto-reprepare */ - 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 */ - void *pFree; /* Free this when deleting the vdbe */ - VdbeFrame *pFrame; /* Parent frame */ - VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */ - int nFrame; /* Number of frames in pFrame list */ - u32 expmask; /* Binding to these vars invalidates VM */ - SubProgram *pProgram; /* Linked list of all sub-programs used by VM */ - AuxData *pAuxData; /* Linked list of auxdata allocations */ -#ifdef SQLITE_ENABLE_STMT_SCANSTATUS - i64 *anExec; /* Number of times each op has been executed */ - int nScan; /* Entries in aScan[] */ - ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */ -#endif -}; - -/* -** The following are allowed values for Vdbe.magic -*/ -#define VDBE_MAGIC_INIT 0x16bceaa5 /* Building a VDBE program */ -#define VDBE_MAGIC_RUN 0x2df20da3 /* VDBE is ready to execute */ -#define VDBE_MAGIC_HALT 0x319c2973 /* VDBE has completed execution */ -#define VDBE_MAGIC_RESET 0x48fa9f76 /* Reset and ready to run again */ -#define VDBE_MAGIC_DEAD 0x5606c3c8 /* The VDBE has been deallocated */ - -/* -** Structure used to store the context required by the -** sqlite3_preupdate_*() API functions. -*/ -struct PreUpdate { - Vdbe *v; - VdbeCursor *pCsr; /* Cursor to read old values from */ - int op; /* One of SQLITE_INSERT, UPDATE, DELETE */ - u8 *aRecord; /* old.* database record */ - KeyInfo keyinfo; - UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */ - UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */ - int iNewReg; /* Register for new.* values */ - i64 iKey1; /* First key value passed to hook */ - i64 iKey2; /* Second key value passed to hook */ - Mem *aNew; /* Array of new.* values */ - Table *pTab; /* Schema object being upated */ - Index *pPk; /* PK index if pTab is WITHOUT ROWID */ -}; - -/* -** Function prototypes -*/ -SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...); -SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*); -void sqliteVdbePopStack(Vdbe*,int); -SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*); -SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*); -#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) -SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*); -#endif -SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32); -SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8); -SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*); -SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32); -SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*); -SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int); - -int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *); -SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*); -SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*); -SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*); -SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*); -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); -SQLITE_PRIVATE void 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 void sqlite3VdbeIntegerAffinity(Mem*); -SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*); -SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*); -SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8); -SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*); -SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p); -SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*); -SQLITE_PRIVATE const char *sqlite3OpcodeName(int); -SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve); -SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n); -SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int); -SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*); -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 *); - -#if !defined(SQLITE_OMIT_SHARED_CACHE) -SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*); -#else -# define sqlite3VdbeEnter(X) -#endif - -#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0 -SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*); -#else -# define sqlite3VdbeLeave(X) -#endif - -#ifdef SQLITE_DEBUG -SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*); -SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*); -#endif - -#ifndef SQLITE_OMIT_FOREIGN_KEY -SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int); -#else -# define sqlite3VdbeCheckFk(p,i) 0 -#endif - -#ifdef SQLITE_DEBUG -SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*); -SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf); -#endif -#ifndef SQLITE_OMIT_UTF16 -SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8); -SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem); -#endif - -#ifndef SQLITE_OMIT_INCRBLOB -SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *); - #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0) -#else - #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK - #define ExpandBlob(P) SQLITE_OK -#endif - -#endif /* !defined(SQLITE_VDBEINT_H) */ - -/************** End of vdbeInt.h *********************************************/ -/************** Continuing where we left off in status.c *********************/ - -/* -** Variables in which to record status information. -*/ -#if SQLITE_PTRSIZE>4 -typedef sqlite3_int64 sqlite3StatValueType; -#else -typedef u32 sqlite3StatValueType; -#endif -typedef struct sqlite3StatType sqlite3StatType; -static SQLITE_WSD struct sqlite3StatType { - sqlite3StatValueType nowValue[10]; /* Current value */ - sqlite3StatValueType mxValue[10]; /* Maximum value */ -} sqlite3Stat = { {0,}, {0,} }; - -/* -** Elements of sqlite3Stat[] are protected by either the memory allocator -** mutex, or by the pcache1 mutex. The following array determines which. -*/ -static const char statMutex[] = { - 0, /* SQLITE_STATUS_MEMORY_USED */ - 1, /* SQLITE_STATUS_PAGECACHE_USED */ - 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */ - 0, /* SQLITE_STATUS_SCRATCH_USED */ - 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */ - 0, /* SQLITE_STATUS_MALLOC_SIZE */ - 0, /* SQLITE_STATUS_PARSER_STACK */ - 1, /* SQLITE_STATUS_PAGECACHE_SIZE */ - 0, /* SQLITE_STATUS_SCRATCH_SIZE */ - 0, /* SQLITE_STATUS_MALLOC_COUNT */ -}; - - -/* The "wsdStat" macro will resolve to the status information -** state vector. If writable static data is unsupported on the target, -** we have to locate the state vector at run-time. In the more common -** case where writable static data is supported, wsdStat can refer directly -** to the "sqlite3Stat" state vector declared above. -*/ -#ifdef SQLITE_OMIT_WSD -# define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat) -# define wsdStat x[0] -#else -# define wsdStatInit -# define wsdStat sqlite3Stat -#endif - -/* -** Return the current value of a status parameter. The caller must -** be holding the appropriate mutex. -*/ -SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){ - wsdStatInit; - assert( op>=0 && op=0 && op=0 && op=0 && opwsdStat.mxValue[op] ){ - wsdStat.mxValue[op] = wsdStat.nowValue[op]; - } -} -SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){ - wsdStatInit; - assert( N>=0 ); - assert( op>=0 && op=0 && op=0 ); - newValue = (sqlite3StatValueType)X; - assert( op>=0 && op=0 && opwsdStat.mxValue[op] ){ - wsdStat.mxValue[op] = newValue; - } -} - -/* -** Query status information. -*/ -SQLITE_API int sqlite3_status64( - int op, - sqlite3_int64 *pCurrent, - sqlite3_int64 *pHighwater, - int resetFlag -){ - sqlite3_mutex *pMutex; - wsdStatInit; - if( op<0 || op>=ArraySize(wsdStat.nowValue) ){ - return SQLITE_MISUSE_BKPT; - } -#ifdef SQLITE_ENABLE_API_ARMOR - if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT; -#endif - pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex(); - sqlite3_mutex_enter(pMutex); - *pCurrent = wsdStat.nowValue[op]; - *pHighwater = wsdStat.mxValue[op]; - if( resetFlag ){ - wsdStat.mxValue[op] = wsdStat.nowValue[op]; - } - sqlite3_mutex_leave(pMutex); - (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */ - return SQLITE_OK; -} -SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){ - sqlite3_int64 iCur = 0, iHwtr = 0; - int rc; -#ifdef SQLITE_ENABLE_API_ARMOR - if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT; -#endif - rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag); - if( rc==0 ){ - *pCurrent = (int)iCur; - *pHighwater = (int)iHwtr; - } - return rc; -} - -/* -** Return the number of LookasideSlot elements on the linked list -*/ -static u32 countLookasideSlots(LookasideSlot *p){ - u32 cnt = 0; - while( p ){ - p = p->pNext; - cnt++; - } - return cnt; -} - -/* -** Count the number of slots of lookaside memory that are outstanding -*/ -SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3 *db, int *pHighwater){ - u32 nInit = countLookasideSlots(db->lookaside.pInit); - u32 nFree = countLookasideSlots(db->lookaside.pFree); - if( pHighwater ) *pHighwater = db->lookaside.nSlot - nInit; - return db->lookaside.nSlot - (nInit+nFree); -} - -/* -** Query status information for a single database connection -*/ -SQLITE_API int sqlite3_db_status( - sqlite3 *db, /* The database connection whose status is desired */ - int op, /* Status verb */ - int *pCurrent, /* Write current value here */ - int *pHighwater, /* Write high-water mark here */ - int resetFlag /* Reset high-water mark if true */ -){ - int rc = SQLITE_OK; /* Return code */ -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){ - return SQLITE_MISUSE_BKPT; - } -#endif - sqlite3_mutex_enter(db->mutex); - switch( op ){ - case SQLITE_DBSTATUS_LOOKASIDE_USED: { - *pCurrent = sqlite3LookasideUsed(db, pHighwater); - if( resetFlag ){ - LookasideSlot *p = db->lookaside.pFree; - if( p ){ - while( p->pNext ) p = p->pNext; - p->pNext = db->lookaside.pInit; - db->lookaside.pInit = db->lookaside.pFree; - db->lookaside.pFree = 0; - } - } - break; - } - - case SQLITE_DBSTATUS_LOOKASIDE_HIT: - case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE: - case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: { - testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT ); - testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE ); - testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL ); - assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 ); - assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 ); - *pCurrent = 0; - *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT]; - if( resetFlag ){ - db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0; - } - break; - } - - /* - ** Return an approximation for the amount of memory currently used - ** by all pagers associated with the given database connection. The - ** highwater mark is meaningless and is returned as zero. - */ - case SQLITE_DBSTATUS_CACHE_USED_SHARED: - case SQLITE_DBSTATUS_CACHE_USED: { - int totalUsed = 0; - int i; - sqlite3BtreeEnterAll(db); - for(i=0; inDb; i++){ - Btree *pBt = db->aDb[i].pBt; - if( pBt ){ - Pager *pPager = sqlite3BtreePager(pBt); - int nByte = sqlite3PagerMemUsed(pPager); - if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){ - nByte = nByte / sqlite3BtreeConnectionCount(pBt); - } - totalUsed += nByte; - } - } - sqlite3BtreeLeaveAll(db); - *pCurrent = totalUsed; - *pHighwater = 0; - break; - } - - /* - ** *pCurrent gets an accurate estimate of the amount of memory used - ** to store the schema for all databases (main, temp, and any ATTACHed - ** databases. *pHighwater is set to zero. - */ - case SQLITE_DBSTATUS_SCHEMA_USED: { - int i; /* Used to iterate through schemas */ - int nByte = 0; /* Used to accumulate return value */ - - sqlite3BtreeEnterAll(db); - db->pnBytesFreed = &nByte; - for(i=0; inDb; i++){ - Schema *pSchema = db->aDb[i].pSchema; - if( ALWAYS(pSchema!=0) ){ - HashElem *p; - - nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * ( - pSchema->tblHash.count - + pSchema->trigHash.count - + pSchema->idxHash.count - + pSchema->fkeyHash.count - ); - nByte += sqlite3_msize(pSchema->tblHash.ht); - nByte += sqlite3_msize(pSchema->trigHash.ht); - nByte += sqlite3_msize(pSchema->idxHash.ht); - nByte += sqlite3_msize(pSchema->fkeyHash.ht); - - for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){ - sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p)); - } - for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){ - sqlite3DeleteTable(db, (Table *)sqliteHashData(p)); - } - } - } - db->pnBytesFreed = 0; - sqlite3BtreeLeaveAll(db); - - *pHighwater = 0; - *pCurrent = nByte; - break; - } - - /* - ** *pCurrent gets an accurate estimate of the amount of memory used - ** to store all prepared statements. - ** *pHighwater is set to zero. - */ - case SQLITE_DBSTATUS_STMT_USED: { - struct Vdbe *pVdbe; /* Used to iterate through VMs */ - int nByte = 0; /* Used to accumulate return value */ - - db->pnBytesFreed = &nByte; - for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){ - sqlite3VdbeClearObject(db, pVdbe); - sqlite3DbFree(db, pVdbe); - } - db->pnBytesFreed = 0; - - *pHighwater = 0; /* IMP: R-64479-57858 */ - *pCurrent = nByte; - - break; - } - - /* - ** Set *pCurrent to the total cache hits or misses encountered by all - ** pagers the database handle is connected to. *pHighwater is always set - ** to zero. - */ - case SQLITE_DBSTATUS_CACHE_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 -** ISBM 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) ){ - setRawDateNumber(p, r); - return 0; - } - return 1; -} - -/* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999. -** Multiplying this by 86400000 gives 464269060799999 as the maximum value -** for DateTime.iJD. -** -** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with -** such a large integer literal, so we have to encode it. -*/ -#define INT_464269060799999 ((((i64)0x1a640)<<32)|0x1072fdff) - -/* -** Return TRUE if the given julian day number is within range. -** -** The input is the JulianDay times 86400000. -*/ -static int validJulianDay(sqlite3_int64 iJD){ - return iJD>=0 && iJD<=INT_464269060799999; -} - -/* -** Compute the Year, Month, and Day from the julian day number. -*/ -static void computeYMD(DateTime *p){ - int Z, A, B, C, D, E, X1; - if( p->validYMD ) return; - if( !p->validJD ){ - p->Y = 2000; - p->M = 1; - p->D = 1; - }else if( !validJulianDay(p->iJD) ){ - datetimeError(p); - return; - }else{ - Z = (int)((p->iJD + 43200000)/86400000); - A = (int)((Z - 1867216.25)/36524.25); - A = Z + 1 + A - (A/4); - B = A + 1524; - C = (int)((B - 122.1)/365.25); - D = (36525*(C&32767))/100; - E = (int)((B-D)/30.6001); - X1 = (int)(30.6001*E); - p->D = B - D - X1; - p->M = E<14 ? E-1 : E-13; - p->Y = p->M>2 ? C - 4716 : C - 4715; - } - p->validYMD = 1; -} - -/* -** Compute the Hour, Minute, and Seconds from the julian day number. -*/ -static void computeHMS(DateTime *p){ - int s; - if( p->validHMS ) return; - computeJD(p); - s = (int)((p->iJD + 43200000) % 86400000); - p->s = s/1000.0; - s = (int)p->s; - p->s -= s; - p->h = s/3600; - s -= p->h*3600; - p->m = s/60; - p->s += s - p->m*60; - p->rawS = 0; - p->validHMS = 1; -} - -/* -** Compute both YMD and HMS -*/ -static void computeYMD_HMS(DateTime *p){ - computeYMD(p); - computeHMS(p); -} - -/* -** Clear the YMD and HMS and the TZ -*/ -static void clearYMD_HMS_TZ(DateTime *p){ - p->validYMD = 0; - p->validHMS = 0; - p->validTZ = 0; -} - -#ifndef SQLITE_OMIT_LOCALTIME -/* -** On recent Windows platforms, the localtime_s() function is available -** as part of the "Secure CRT". It is essentially equivalent to -** localtime_r() available under most POSIX platforms, except that the -** order of the parameters is reversed. -** -** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx. -** -** If the user has not indicated to use localtime_r() or localtime_s() -** already, check for an MSVC build environment that provides -** localtime_s(). -*/ -#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \ - && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE) -#undef HAVE_LOCALTIME_S -#define HAVE_LOCALTIME_S 1 -#endif - -/* -** The following routine implements the rough equivalent of localtime_r() -** using whatever operating-system specific localtime facility that -** is available. This routine returns 0 on success and -** non-zero on any kind of error. -** -** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this -** routine will always fail. -** -** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C -** library function localtime_r() is used to assist in the calculation of -** local time. -*/ -static int osLocaltime(time_t *t, struct tm *pTm){ - int rc; -#if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S - struct tm *pX; -#if SQLITE_THREADSAFE>0 - sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); -#endif - sqlite3_mutex_enter(mutex); - pX = localtime(t); -#ifndef SQLITE_UNTESTABLE - if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0; -#endif - if( pX ) *pTm = *pX; - sqlite3_mutex_leave(mutex); - rc = pX==0; -#else -#ifndef SQLITE_UNTESTABLE - if( sqlite3GlobalConfig.bLocaltimeFault ) return 1; -#endif -#if HAVE_LOCALTIME_R - rc = localtime_r(t, pTm)==0; -#else - rc = localtime_s(pTm, t); -#endif /* HAVE_LOCALTIME_R */ -#endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */ - return rc; -} -#endif /* SQLITE_OMIT_LOCALTIME */ - - -#ifndef SQLITE_OMIT_LOCALTIME -/* -** Compute the difference (in milliseconds) between localtime and UTC -** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs, -** return this value and set *pRc to SQLITE_OK. -** -** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value -** is undefined in this case. -*/ -static sqlite3_int64 localtimeOffset( - DateTime *p, /* Date at which to calculate offset */ - sqlite3_context *pCtx, /* Write error here if one occurs */ - int *pRc /* OUT: Error code. SQLITE_OK or ERROR */ -){ - DateTime x, y; - time_t t; - struct tm sLocal; - - /* Initialize the contents of sLocal to avoid a compiler warning. */ - memset(&sLocal, 0, sizeof(sLocal)); - - x = *p; - computeYMD_HMS(&x); - if( x.Y<1971 || x.Y>=2038 ){ - /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only - ** works for years between 1970 and 2037. For dates outside this range, - ** SQLite attempts to map the year into an equivalent year within this - ** range, do the calculation, then map the year back. - */ - x.Y = 2000; - x.M = 1; - x.D = 1; - x.h = 0; - x.m = 0; - x.s = 0.0; - } else { - int s = (int)(x.s + 0.5); - x.s = s; - } - x.tz = 0; - x.validJD = 0; - computeJD(&x); - t = (time_t)(x.iJD/1000 - 21086676*(i64)10000); - if( osLocaltime(&t, &sLocal) ){ - sqlite3_result_error(pCtx, "local time unavailable", -1); - *pRc = SQLITE_ERROR; - return 0; - } - y.Y = sLocal.tm_year + 1900; - y.M = sLocal.tm_mon + 1; - y.D = sLocal.tm_mday; - y.h = sLocal.tm_hour; - y.m = sLocal.tm_min; - y.s = sLocal.tm_sec; - y.validYMD = 1; - y.validHMS = 1; - y.validJD = 0; - y.rawS = 0; - y.validTZ = 0; - y.isError = 0; - computeJD(&y); - *pRc = SQLITE_OK; - return y.iJD - x.iJD; -} -#endif /* SQLITE_OMIT_LOCALTIME */ - -/* -** The following table defines various date transformations of the form -** -** 'NNN days' -** -** Where NNN is an arbitrary floating-point number and "days" can be one -** of several units of time. -*/ -static const struct { - u8 eType; /* Transformation type code */ - u8 nName; /* Length of th name */ - char *zName; /* Name of the transformation */ - double rLimit; /* Maximum NNN value for this transform */ - double rXform; /* Constant used for this transform */ -} aXformType[] = { - { 0, 6, "second", 464269060800.0, 86400000.0/(24.0*60.0*60.0) }, - { 0, 6, "minute", 7737817680.0, 86400000.0/(24.0*60.0) }, - { 0, 4, "hour", 128963628.0, 86400000.0/24.0 }, - { 0, 3, "day", 5373485.0, 86400000.0 }, - { 1, 5, "month", 176546.0, 30.0*86400000.0 }, - { 2, 4, "year", 14713.0, 365.0*86400000.0 }, -}; - -/* -** Process a modifier to a date-time stamp. The modifiers are -** as follows: -** -** NNN days -** NNN hours -** NNN minutes -** NNN.NNNN seconds -** NNN months -** NNN years -** start of month -** start of year -** start of week -** start of day -** weekday N -** unixepoch -** localtime -** utc -** -** Return 0 on success and 1 if there is any kind of error. If the error -** is in a system call (i.e. localtime()), then an error message is written -** to context pCtx. If the error is an unrecognized modifier, no error is -** written to pCtx. -*/ -static int parseModifier( - sqlite3_context *pCtx, /* Function context */ - const char *z, /* The text of the modifier */ - int n, /* Length of zMod in bytes */ - DateTime *p /* The date/time value to be modified */ -){ - int rc = 1; - double r; - switch(sqlite3UpperToLower[(u8)z[0]] ){ -#ifndef SQLITE_OMIT_LOCALTIME - case 'l': { - /* localtime - ** - ** Assuming the current time value is UTC (a.k.a. GMT), shift it to - ** show local time. - */ - if( sqlite3_stricmp(z, "localtime")==0 && sqlite3NotPureFunc(pCtx) ){ - computeJD(p); - p->iJD += localtimeOffset(p, pCtx, &rc); - clearYMD_HMS_TZ(p); - } - break; - } -#endif - case 'u': { - /* - ** unixepoch - ** - ** Treat the current value of p->s as the number of - ** seconds since 1970. Convert to a real julian day number. - */ - if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){ - r = p->s*1000.0 + 210866760000000.0; - if( r>=0.0 && r<464269060800000.0 ){ - clearYMD_HMS_TZ(p); - p->iJD = (sqlite3_int64)r; - p->validJD = 1; - p->rawS = 0; - rc = 0; - } - } -#ifndef SQLITE_OMIT_LOCALTIME - else if( sqlite3_stricmp(z, "utc")==0 && sqlite3NotPureFunc(pCtx) ){ - if( p->tzSet==0 ){ - sqlite3_int64 c1; - computeJD(p); - c1 = localtimeOffset(p, pCtx, &rc); - if( rc==SQLITE_OK ){ - p->iJD -= c1; - clearYMD_HMS_TZ(p); - p->iJD += c1 - localtimeOffset(p, pCtx, &rc); - } - p->tzSet = 1; - }else{ - rc = SQLITE_OK; - } - } -#endif - break; - } - case 'w': { - /* - ** weekday N - ** - ** Move the date to the same time on the next occurrence of - ** weekday N where 0==Sunday, 1==Monday, and so forth. If the - ** date is already on the appropriate weekday, this is a no-op. - */ - if( sqlite3_strnicmp(z, "weekday ", 8)==0 - && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8) - && (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) ){ - rc = 1; - break; - } - if( z[n]==':' ){ - /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the - ** specified number of hours, minutes, seconds, and fractional seconds - ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be - ** omitted. - */ - const char *z2 = z; - DateTime tx; - sqlite3_int64 day; - if( !sqlite3Isdigit(*z2) ) z2++; - memset(&tx, 0, sizeof(tx)); - if( parseHhMmSs(z2, &tx) ) break; - computeJD(&tx); - tx.iJD -= 43200000; - day = tx.iJD/86400000; - tx.iJD -= day*86400000; - if( z[0]=='-' ) tx.iJD = -tx.iJD; - computeJD(p); - clearYMD_HMS_TZ(p); - p->iJD += tx.iJD; - rc = 0; - break; - } - - /* If control reaches this point, it means the transformation is - ** one of the forms like "+NNN days". */ - z += n; - while( sqlite3Isspace(*z) ) z++; - n = sqlite3Strlen30(z); - if( n>10 || n<3 ) break; - if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--; - computeJD(p); - rc = 1; - rRounder = r<0 ? -0.5 : +0.5; - for(i=0; i-aXformType[i].rLimit && rM += (int)r; - x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12; - p->Y += x; - p->M -= x*12; - p->validJD = 0; - r -= (int)r; - break; - } - case 2: { /* Special processing to add years */ - int y = (int)r; - computeYMD_HMS(p); - p->Y += y; - p->validJD = 0; - r -= (int)r; - break; - } - } - computeJD(p); - p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder); - rc = 0; - break; - } - } - clearYMD_HMS_TZ(p); - break; - } - default: { - break; - } - } - return rc; -} - -/* -** Process time function arguments. argv[0] is a date-time stamp. -** argv[1] and following are modifiers. Parse them all and write -** the resulting time into the DateTime structure p. Return 0 -** on success and 1 if there are any errors. -** -** If there are zero parameters (if even argv[0] is undefined) -** then assume a default value of "now" for argv[0]. -*/ -static int isDate( - sqlite3_context *context, - int argc, - sqlite3_value **argv, - DateTime *p -){ - int i, n; - const unsigned char *z; - int eType; - memset(p, 0, sizeof(*p)); - if( argc==0 ){ - return setDateTimeToCurrent(context, p); - } - if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT - || eType==SQLITE_INTEGER ){ - setRawDateNumber(p, sqlite3_value_double(argv[0])); - }else{ - z = sqlite3_value_text(argv[0]); - if( !z || parseDateOrTime(context, (char*)z, p) ){ - return 1; - } - } - for(i=1; iisError || !validJulianDay(p->iJD) ) return 1; - return 0; -} - - -/* -** The following routines implement the various date and time functions -** of SQLite. -*/ - -/* -** julianday( TIMESTRING, MOD, MOD, ...) -** -** Return the julian day number of the date specified in the arguments -*/ -static void juliandayFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - DateTime x; - if( isDate(context, argc, argv, &x)==0 ){ - computeJD(&x); - sqlite3_result_double(context, x.iJD/86400000.0); - } -} - -/* -** datetime( TIMESTRING, MOD, MOD, ...) -** -** Return YYYY-MM-DD HH:MM:SS -*/ -static void datetimeFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - DateTime x; - if( isDate(context, argc, argv, &x)==0 ){ - char zBuf[100]; - computeYMD_HMS(&x); - sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d", - x.Y, x.M, x.D, x.h, x.m, (int)(x.s)); - sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); - } -} - -/* -** time( TIMESTRING, MOD, MOD, ...) -** -** Return HH:MM:SS -*/ -static void timeFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - DateTime x; - if( isDate(context, argc, argv, &x)==0 ){ - char zBuf[100]; - computeHMS(&x); - sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s); - sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); - } -} - -/* -** date( TIMESTRING, MOD, MOD, ...) -** -** Return YYYY-MM-DD -*/ -static void dateFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - DateTime x; - if( isDate(context, argc, argv, &x)==0 ){ - char zBuf[100]; - computeYMD(&x); - sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D); - sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); - } -} - -/* -** strftime( FORMAT, TIMESTRING, MOD, MOD, ...) -** -** Return a string described by FORMAT. Conversions as follows: -** -** %d day of month -** %f ** fractional seconds SS.SSS -** %H hour 00-24 -** %j day of year 000-366 -** %J ** julian day number -** %m month 01-12 -** %M minute 00-59 -** %s seconds since 1970-01-01 -** %S seconds 00-59 -** %w day of week 0-6 sunday==0 -** %W week of year 00-53 -** %Y year 0000-9999 -** %% % -*/ -static void strftimeFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - DateTime x; - u64 n; - size_t i,j; - char *z; - sqlite3 *db; - const char *zFmt; - char zBuf[100]; - if( argc==0 ) return; - zFmt = (const char*)sqlite3_value_text(argv[0]); - if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return; - db = sqlite3_context_db_handle(context); - for(i=0, n=1; zFmt[i]; i++, n++){ - if( zFmt[i]=='%' ){ - switch( zFmt[i+1] ){ - case 'd': - case 'H': - case 'm': - case 'M': - case 'S': - case 'W': - n++; - /* fall thru */ - case 'w': - case '%': - break; - case 'f': - n += 8; - break; - case 'j': - n += 3; - break; - case 'Y': - n += 8; - break; - case 's': - case 'J': - n += 50; - break; - default: - return; /* ERROR. return a NULL */ - } - i++; - } - } - testcase( n==sizeof(zBuf)-1 ); - testcase( n==sizeof(zBuf) ); - testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 ); - testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ); - if( n(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){ - sqlite3_result_error_toobig(context); - return; - }else{ - z = sqlite3DbMallocRawNN(db, (int)n); - if( z==0 ){ - sqlite3_result_error_nomem(context); - return; - } - } - computeJD(&x); - computeYMD_HMS(&x); - for(i=j=0; zFmt[i]; i++){ - if( zFmt[i]!='%' ){ - z[j++] = zFmt[i]; - }else{ - i++; - switch( zFmt[i] ){ - case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break; - case 'f': { - double s = x.s; - if( s>59.999 ) s = 59.999; - sqlite3_snprintf(7, &z[j],"%06.3f", s); - j += sqlite3Strlen30(&z[j]); - break; - } - case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break; - case 'W': /* Fall thru */ - case 'j': { - int nDay; /* Number of days since 1st day of year */ - DateTime y = x; - y.validJD = 0; - y.M = 1; - y.D = 1; - computeJD(&y); - nDay = (int)((x.iJD-y.iJD+43200000)/86400000); - if( zFmt[i]=='W' ){ - int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */ - wd = (int)(((x.iJD+43200000)/86400000)%7); - sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7); - j += 2; - }else{ - sqlite3_snprintf(4, &z[j],"%03d",nDay+1); - j += 3; - } - break; - } - case 'J': { - sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0); - j+=sqlite3Strlen30(&z[j]); - break; - } - case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break; - case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break; - case 's': { - sqlite3_snprintf(30,&z[j],"%lld", - (i64)(x.iJD/1000 - 21086676*(i64)10000)); - j += sqlite3Strlen30(&z[j]); - break; - } - case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break; - case 'w': { - z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0'; - break; - } - case 'Y': { - sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]); - break; - } - default: z[j++] = '%'; break; - } - } - } - z[j] = 0; - sqlite3_result_text(context, z, -1, - z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC); -} - -/* -** current_time() -** -** This function returns the same value as time('now'). -*/ -static void ctimeFunc( - sqlite3_context *context, - int NotUsed, - sqlite3_value **NotUsed2 -){ - UNUSED_PARAMETER2(NotUsed, NotUsed2); - timeFunc(context, 0, 0); -} - -/* -** current_date() -** -** This function returns the same value as date('now'). -*/ -static void cdateFunc( - sqlite3_context *context, - int NotUsed, - sqlite3_value **NotUsed2 -){ - UNUSED_PARAMETER2(NotUsed, NotUsed2); - dateFunc(context, 0, 0); -} - -/* -** current_timestamp() -** -** This function returns the same value as datetime('now'). -*/ -static void ctimestampFunc( - sqlite3_context *context, - int NotUsed, - sqlite3_value **NotUsed2 -){ - UNUSED_PARAMETER2(NotUsed, NotUsed2); - datetimeFunc(context, 0, 0); -} -#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */ - -#ifdef SQLITE_OMIT_DATETIME_FUNCS -/* -** If the library is compiled to omit the full-scale date and time -** handling (to get a smaller binary), the following minimal version -** of the functions current_time(), current_date() and current_timestamp() -** are included instead. This is to support column declarations that -** include "DEFAULT CURRENT_TIME" etc. -** -** This function uses the C-library functions time(), gmtime() -** and strftime(). The format string to pass to strftime() is supplied -** as the user-data for the function. -*/ -static void currentTimeFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - time_t t; - char *zFormat = (char *)sqlite3_user_data(context); - sqlite3_int64 iT; - struct tm *pTm; - struct tm sNow; - char zBuf[20]; - - UNUSED_PARAMETER(argc); - UNUSED_PARAMETER(argv); - - iT = sqlite3StmtCurrentTime(context); - if( iT<=0 ) return; - t = iT/1000 - 10000*(sqlite3_int64)21086676; -#if HAVE_GMTIME_R - pTm = gmtime_r(&t, &sNow); -#else - sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); - pTm = gmtime(&t); - if( pTm ) memcpy(&sNow, pTm, sizeof(sNow)); - sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); -#endif - if( pTm ){ - strftime(zBuf, 20, zFormat, &sNow); - sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); - } -} -#endif - -/* -** This function registered all of the above C functions as SQL -** functions. This should be the only routine in this file with -** external linkage. -*/ -SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){ - static FuncDef aDateTimeFuncs[] = { -#ifndef SQLITE_OMIT_DATETIME_FUNCS - PURE_DATE(julianday, -1, 0, 0, juliandayFunc ), - PURE_DATE(date, -1, 0, 0, dateFunc ), - PURE_DATE(time, -1, 0, 0, timeFunc ), - PURE_DATE(datetime, -1, 0, 0, datetimeFunc ), - PURE_DATE(strftime, -1, 0, 0, strftimeFunc ), - DFUNCTION(current_time, 0, 0, 0, ctimeFunc ), - DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc), - DFUNCTION(current_date, 0, 0, 0, cdateFunc ), -#else - STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc), - STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc), - STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc), -#endif - }; - sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs)); -} - -/************** End of date.c ************************************************/ -/************** Begin file os.c **********************************************/ -/* -** 2005 November 29 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This file contains OS interface code that is common to all -** architectures. -*/ -/* #include "sqliteInt.h" */ - -/* -** If we compile with the SQLITE_TEST macro set, then the following block -** of code will give us the ability to simulate a disk I/O error. This -** is used for testing the I/O recovery logic. -*/ -#if defined(SQLITE_TEST) -SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */ -SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */ -SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */ -SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */ -SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */ -SQLITE_API int sqlite3_diskfull_pending = 0; -SQLITE_API int sqlite3_diskfull = 0; -#endif /* defined(SQLITE_TEST) */ - -/* -** When testing, also keep a count of the number of open files. -*/ -#if defined(SQLITE_TEST) -SQLITE_API int sqlite3_open_file_count = 0; -#endif /* defined(SQLITE_TEST) */ - -/* -** The default SQLite sqlite3_vfs implementations do not allocate -** memory (actually, os_unix.c allocates a small amount of memory -** from within OsOpen()), but some third-party implementations may. -** So we test the effects of a malloc() failing and the sqlite3OsXXX() -** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro. -** -** The following functions are instrumented for malloc() failure -** testing: -** -** sqlite3OsRead() -** sqlite3OsWrite() -** sqlite3OsSync() -** sqlite3OsFileSize() -** sqlite3OsLock() -** sqlite3OsCheckReservedLock() -** sqlite3OsFileControl() -** sqlite3OsShmMap() -** sqlite3OsOpen() -** sqlite3OsDelete() -** sqlite3OsAccess() -** sqlite3OsFullPathname() -** -*/ -#if defined(SQLITE_TEST) -SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1; - #define DO_OS_MALLOC_TEST(x) \ - if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \ - void *pTstAlloc = sqlite3Malloc(10); \ - if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT; \ - sqlite3_free(pTstAlloc); \ - } -#else - #define DO_OS_MALLOC_TEST(x) -#endif - -/* -** The following routines are convenience wrappers around methods -** of the sqlite3_file object. This is mostly just syntactic sugar. All -** of this would be completely automatic if SQLite were coded using -** C++ instead of plain old C. -*/ -SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){ - if( pId->pMethods ){ - pId->pMethods->xClose(pId); - pId->pMethods = 0; - } -} -SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){ - DO_OS_MALLOC_TEST(id); - return id->pMethods->xRead(id, pBuf, amt, offset); -} -SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){ - DO_OS_MALLOC_TEST(id); - return id->pMethods->xWrite(id, pBuf, amt, offset); -} -SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){ - return id->pMethods->xTruncate(id, size); -} -SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){ - DO_OS_MALLOC_TEST(id); - return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK; -} -SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){ - DO_OS_MALLOC_TEST(id); - return id->pMethods->xFileSize(id, pSize); -} -SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){ - DO_OS_MALLOC_TEST(id); - return id->pMethods->xLock(id, lockType); -} -SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){ - return id->pMethods->xUnlock(id, lockType); -} -SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){ - DO_OS_MALLOC_TEST(id); - return id->pMethods->xCheckReservedLock(id, pResOut); -} - -/* -** Use sqlite3OsFileControl() when we are doing something that might fail -** and we need to know about the failures. Use sqlite3OsFileControlHint() -** when simply tossing information over the wall to the VFS and we do not -** really care if the VFS receives and understands the information since it -** is only a hint and can be safely ignored. The sqlite3OsFileControlHint() -** routine has no return value since the return value would be meaningless. -*/ -SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){ -#ifdef SQLITE_TEST - if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){ - /* 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){ - (void)id->pMethods->xFileControl(id, op, pArg); -} - -SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){ - int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize; - return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE); -} -SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){ - return id->pMethods->xDeviceCharacteristics(id); -} -#ifndef SQLITE_OMIT_WAL -SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){ - return id->pMethods->xShmLock(id, offset, n, flags); -} -SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){ - id->pMethods->xShmBarrier(id); -} -SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){ - return id->pMethods->xShmUnmap(id, deleteFlag); -} -SQLITE_PRIVATE int sqlite3OsShmMap( - sqlite3_file *id, /* Database file handle */ - int iPage, - int pgsz, - int bExtend, /* True to extend file if necessary */ - void volatile **pp /* OUT: Pointer to mapping */ -){ - DO_OS_MALLOC_TEST(id); - return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp); -} -#endif /* SQLITE_OMIT_WAL */ - -#if SQLITE_MAX_MMAP_SIZE>0 -/* The real implementation of xFetch and xUnfetch */ -SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){ - DO_OS_MALLOC_TEST(id); - return id->pMethods->xFetch(id, iOff, iAmt, pp); -} -SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){ - return id->pMethods->xUnfetch(id, iOff, p); -} -#else -/* No-op stubs to use when memory-mapped I/O is disabled */ -SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){ - *pp = 0; - return SQLITE_OK; -} -SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){ - return SQLITE_OK; -} -#endif - -/* -** The next group of routines are convenience wrappers around the -** VFS methods. -*/ -SQLITE_PRIVATE int sqlite3OsOpen( - sqlite3_vfs *pVfs, - const char *zPath, - sqlite3_file *pFile, - int flags, - int *pFlagsOut -){ - int rc; - DO_OS_MALLOC_TEST(0); - /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed - ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example, - ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before - ** reaching the VFS. */ - rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut); - assert( rc==SQLITE_OK || pFile->pMethods==0 ); - return rc; -} -SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){ - DO_OS_MALLOC_TEST(0); - assert( dirSync==0 || dirSync==1 ); - return pVfs->xDelete(pVfs, zPath, dirSync); -} -SQLITE_PRIVATE int sqlite3OsAccess( - sqlite3_vfs *pVfs, - const char *zPath, - int flags, - int *pResOut -){ - DO_OS_MALLOC_TEST(0); - return pVfs->xAccess(pVfs, zPath, flags, pResOut); -} -SQLITE_PRIVATE int sqlite3OsFullPathname( - sqlite3_vfs *pVfs, - const char *zPath, - int nPathOut, - char *zPathOut -){ - DO_OS_MALLOC_TEST(0); - zPathOut[0] = 0; - return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut); -} -#ifndef SQLITE_OMIT_LOAD_EXTENSION -SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){ - return pVfs->xDlOpen(pVfs, zPath); -} -SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ - pVfs->xDlError(pVfs, nByte, zBufOut); -} -SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){ - return pVfs->xDlSym(pVfs, pHdle, zSym); -} -SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){ - pVfs->xDlClose(pVfs, pHandle); -} -#endif /* SQLITE_OMIT_LOAD_EXTENSION */ -SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){ - return pVfs->xRandomness(pVfs, nByte, zBufOut); -} -SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){ - return pVfs->xSleep(pVfs, nMicro); -} -SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){ - return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0; -} -SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){ - int rc; - /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64() - ** method to get the current date and time if that method is available - ** (if iVersion is 2 or greater and the function pointer is not NULL) and - ** will fall back to xCurrentTime() if xCurrentTimeInt64() is - ** unavailable. - */ - if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){ - rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut); - }else{ - double r; - rc = pVfs->xCurrentTime(pVfs, &r); - *pTimeOut = (sqlite3_int64)(r*86400000.0); - } - return rc; -} - -SQLITE_PRIVATE int sqlite3OsOpenMalloc( - sqlite3_vfs *pVfs, - const char *zFile, - sqlite3_file **ppFile, - int flags, - int *pOutFlags -){ - int rc; - sqlite3_file *pFile; - pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile); - if( pFile ){ - rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags); - if( rc!=SQLITE_OK ){ - sqlite3_free(pFile); - }else{ - *ppFile = pFile; - } - }else{ - rc = SQLITE_NOMEM_BKPT; - } - return rc; -} -SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){ - assert( pFile ); - sqlite3OsClose(pFile); - sqlite3_free(pFile); -} - -/* -** This function is a wrapper around the OS specific implementation of -** sqlite3_os_init(). The purpose of the wrapper is to provide the -** ability to simulate a malloc failure, so that the handling of an -** error in sqlite3_os_init() by the upper layers can be tested. -*/ -SQLITE_PRIVATE int sqlite3OsInit(void){ - void *p = sqlite3_malloc(10); - if( p==0 ) return SQLITE_NOMEM_BKPT; - sqlite3_free(p); - return sqlite3_os_init(); -} - -/* -** The list of all registered VFS implementations. -*/ -static sqlite3_vfs * SQLITE_WSD vfsList = 0; -#define vfsList GLOBAL(sqlite3_vfs *, vfsList) - -/* -** Locate a VFS by name. If no name is given, simply return the -** first VFS on the list. -*/ -SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){ - sqlite3_vfs *pVfs = 0; -#if SQLITE_THREADSAFE - sqlite3_mutex *mutex; -#endif -#ifndef SQLITE_OMIT_AUTOINIT - int rc = sqlite3_initialize(); - if( rc ) return 0; -#endif -#if SQLITE_THREADSAFE - mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); -#endif - sqlite3_mutex_enter(mutex); - for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){ - if( zVfs==0 ) break; - if( strcmp(zVfs, pVfs->zName)==0 ) break; - } - sqlite3_mutex_leave(mutex); - return pVfs; -} - -/* -** Unlink a VFS from the linked list -*/ -static void vfsUnlink(sqlite3_vfs *pVfs){ - assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) ); - if( pVfs==0 ){ - /* No-op */ - }else if( vfsList==pVfs ){ - vfsList = pVfs->pNext; - }else if( vfsList ){ - sqlite3_vfs *p = vfsList; - while( p->pNext && p->pNext!=pVfs ){ - p = p->pNext; - } - if( p->pNext==pVfs ){ - p->pNext = pVfs->pNext; - } - } -} - -/* -** Register a VFS with the system. It is harmless to register the same -** VFS multiple times. The new VFS becomes the default if makeDflt is -** true. -*/ -SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){ - MUTEX_LOGIC(sqlite3_mutex *mutex;) -#ifndef SQLITE_OMIT_AUTOINIT - int rc = sqlite3_initialize(); - if( rc ) return rc; -#endif -#ifdef SQLITE_ENABLE_API_ARMOR - if( pVfs==0 ) return SQLITE_MISUSE_BKPT; -#endif - - MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) - sqlite3_mutex_enter(mutex); - vfsUnlink(pVfs); - if( makeDflt || vfsList==0 ){ - pVfs->pNext = vfsList; - vfsList = pVfs; - }else{ - pVfs->pNext = vfsList->pNext; - vfsList->pNext = pVfs; - } - assert(vfsList); - sqlite3_mutex_leave(mutex); - return SQLITE_OK; -} - -/* -** Unregister a VFS so that it is no longer accessible. -*/ -SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){ -#if SQLITE_THREADSAFE - sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); -#endif - sqlite3_mutex_enter(mutex); - vfsUnlink(pVfs); - sqlite3_mutex_leave(mutex); - return SQLITE_OK; -} - -/************** End of os.c **************************************************/ -/************** Begin file fault.c *******************************************/ -/* -** 2008 Jan 22 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file contains code to support the concept of "benign" -** malloc failures (when the xMalloc() or xRealloc() method of the -** sqlite3_mem_methods structure fails to allocate a block of memory -** and returns 0). -** -** Most malloc failures are non-benign. After they occur, SQLite -** abandons the current operation and returns an error code (usually -** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily -** fatal. For example, if a malloc fails while resizing a hash table, this -** is completely recoverable simply by not carrying out the resize. The -** hash table will continue to function normally. So a malloc failure -** during a hash table resize is a benign fault. -*/ - -/* #include "sqliteInt.h" */ - -#ifndef SQLITE_UNTESTABLE - -/* -** Global variables. -*/ -typedef struct BenignMallocHooks BenignMallocHooks; -static SQLITE_WSD struct BenignMallocHooks { - void (*xBenignBegin)(void); - void (*xBenignEnd)(void); -} sqlite3Hooks = { 0, 0 }; - -/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks -** structure. If writable static data is unsupported on the target, -** we have to locate the state vector at run-time. In the more common -** case where writable static data is supported, wsdHooks can refer directly -** to the "sqlite3Hooks" state vector declared above. -*/ -#ifdef SQLITE_OMIT_WSD -# define wsdHooksInit \ - BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks) -# define wsdHooks x[0] -#else -# define wsdHooksInit -# define wsdHooks sqlite3Hooks -#endif - - -/* -** Register hooks to call when sqlite3BeginBenignMalloc() and -** sqlite3EndBenignMalloc() are called, respectively. -*/ -SQLITE_PRIVATE void sqlite3BenignMallocHooks( - void (*xBenignBegin)(void), - void (*xBenignEnd)(void) -){ - wsdHooksInit; - wsdHooks.xBenignBegin = xBenignBegin; - wsdHooks.xBenignEnd = xBenignEnd; -} - -/* -** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that -** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc() -** indicates that subsequent malloc failures are non-benign. -*/ -SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){ - wsdHooksInit; - if( wsdHooks.xBenignBegin ){ - wsdHooks.xBenignBegin(); - } -} -SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){ - wsdHooksInit; - if( wsdHooks.xBenignEnd ){ - wsdHooks.xBenignEnd(); - } -} - -#endif /* #ifndef SQLITE_UNTESTABLE */ - -/************** End of fault.c ***********************************************/ -/************** Begin file mem0.c ********************************************/ -/* -** 2008 October 28 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file contains a no-op memory allocation drivers for use when -** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented -** here always fail. SQLite will not operate with these drivers. These -** are merely placeholders. Real drivers must be substituted using -** sqlite3_config() before SQLite will operate. -*/ -/* #include "sqliteInt.h" */ - -/* -** This version of the memory allocator is the default. It is -** used when no other memory allocator is specified using compile-time -** macros. -*/ -#ifdef SQLITE_ZERO_MALLOC - -/* -** No-op versions of all memory allocation routines -*/ -static void *sqlite3MemMalloc(int nByte){ return 0; } -static void sqlite3MemFree(void *pPrior){ return; } -static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; } -static int sqlite3MemSize(void *pPrior){ return 0; } -static int sqlite3MemRoundup(int n){ return n; } -static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; } -static void sqlite3MemShutdown(void *NotUsed){ return; } - -/* -** This routine is the only routine in this file with external linkage. -** -** Populate the low-level memory allocation function pointers in -** sqlite3GlobalConfig.m with pointers to the routines in this file. -*/ -SQLITE_PRIVATE void sqlite3MemSetDefault(void){ - static const sqlite3_mem_methods defaultMethods = { - sqlite3MemMalloc, - sqlite3MemFree, - sqlite3MemRealloc, - sqlite3MemSize, - sqlite3MemRoundup, - sqlite3MemInit, - sqlite3MemShutdown, - 0 - }; - sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); -} - -#endif /* SQLITE_ZERO_MALLOC */ - -/************** End of mem0.c ************************************************/ -/************** Begin file mem1.c ********************************************/ -/* -** 2007 August 14 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file contains low-level memory allocation drivers for when -** SQLite will use the standard C-library malloc/realloc/free interface -** to obtain the memory it needs. -** -** This file contains implementations of the low-level memory allocation -** routines specified in the sqlite3_mem_methods object. The content of -** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The -** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the -** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The -** default configuration is to use memory allocation routines in this -** file. -** -** C-preprocessor macro summary: -** -** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if -** the malloc_usable_size() interface exists -** on the target platform. Or, this symbol -** can be set manually, if desired. -** If an equivalent interface exists by -** a different name, using a separate -D -** option to rename it. -** -** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone -** memory allocator. Set this symbol to enable -** building on older macs. -** -** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of -** _msize() on windows systems. This might -** be necessary when compiling for Delphi, -** for example. -*/ -/* #include "sqliteInt.h" */ - -/* -** This version of the memory allocator is the default. It is -** used when no other memory allocator is specified using compile-time -** macros. -*/ -#ifdef SQLITE_SYSTEM_MALLOC -#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) - -/* -** Use the zone allocator available on apple products unless the -** SQLITE_WITHOUT_ZONEMALLOC symbol is defined. -*/ -#include -#include -#ifdef SQLITE_MIGHT_BE_SINGLE_CORE -#include -#endif /* SQLITE_MIGHT_BE_SINGLE_CORE */ -static malloc_zone_t* _sqliteZone_; -#define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x)) -#define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x)); -#define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y)) -#define SQLITE_MALLOCSIZE(x) \ - (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x)) - -#else /* if not __APPLE__ */ - -/* -** Use standard C library malloc and free on non-Apple systems. -** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined. -*/ -#define SQLITE_MALLOC(x) malloc(x) -#define SQLITE_FREE(x) free(x) -#define SQLITE_REALLOC(x,y) realloc((x),(y)) - -/* -** The malloc.h header file is needed for malloc_usable_size() function -** on some systems (e.g. Linux). -*/ -#if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE -# define SQLITE_USE_MALLOC_H 1 -# define SQLITE_USE_MALLOC_USABLE_SIZE 1 -/* -** The MSVCRT has malloc_usable_size(), but it is called _msize(). The -** use of _msize() is automatic, but can be disabled by compiling with -** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires -** the malloc.h header file. -*/ -#elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE) -# define SQLITE_USE_MALLOC_H -# define SQLITE_USE_MSIZE -#endif - -/* -** Include the malloc.h header file, if necessary. Also set define macro -** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize() -** for MSVC and malloc_usable_size() for most other systems (e.g. Linux). -** The memory size function can always be overridden manually by defining -** the macro SQLITE_MALLOCSIZE to the desired function name. -*/ -#if defined(SQLITE_USE_MALLOC_H) -# include -# if defined(SQLITE_USE_MALLOC_USABLE_SIZE) -# if !defined(SQLITE_MALLOCSIZE) -# define SQLITE_MALLOCSIZE(x) malloc_usable_size(x) -# endif -# elif defined(SQLITE_USE_MSIZE) -# if !defined(SQLITE_MALLOCSIZE) -# define SQLITE_MALLOCSIZE _msize -# endif -# endif -#endif /* defined(SQLITE_USE_MALLOC_H) */ - -#endif /* __APPLE__ or not __APPLE__ */ - -/* -** Like malloc(), but remember the size of the allocation -** so that we can find it later using sqlite3MemSize(). -** -** For this low-level routine, we are guaranteed that nByte>0 because -** cases of nByte<=0 will be intercepted and dealt with by higher level -** routines. -*/ -static void *sqlite3MemMalloc(int nByte){ -#ifdef SQLITE_MALLOCSIZE - void *p; - testcase( ROUND8(nByte)==nByte ); - p = SQLITE_MALLOC( nByte ); - if( p==0 ){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte); - } - return p; -#else - sqlite3_int64 *p; - assert( nByte>0 ); - testcase( ROUND8(nByte)!=nByte ); - p = SQLITE_MALLOC( nByte+8 ); - if( p ){ - p[0] = nByte; - p++; - }else{ - testcase( sqlite3GlobalConfig.xLog!=0 ); - sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte); - } - return (void *)p; -#endif -} - -/* -** Like free() but works for allocations obtained from sqlite3MemMalloc() -** or sqlite3MemRealloc(). -** -** For this low-level routine, we already know that pPrior!=0 since -** cases where pPrior==0 will have been intecepted and dealt with -** by higher-level routines. -*/ -static void sqlite3MemFree(void *pPrior){ -#ifdef SQLITE_MALLOCSIZE - SQLITE_FREE(pPrior); -#else - sqlite3_int64 *p = (sqlite3_int64*)pPrior; - assert( pPrior!=0 ); - p--; - SQLITE_FREE(p); -#endif -} - -/* -** Report the allocated size of a prior return from xMalloc() -** or xRealloc(). -*/ -static int sqlite3MemSize(void *pPrior){ -#ifdef SQLITE_MALLOCSIZE - assert( pPrior!=0 ); - return (int)SQLITE_MALLOCSIZE(pPrior); -#else - sqlite3_int64 *p; - assert( pPrior!=0 ); - p = (sqlite3_int64*)pPrior; - p--; - return (int)p[0]; -#endif -} - -/* -** Like realloc(). Resize an allocation previously obtained from -** sqlite3MemMalloc(). -** -** For this low-level interface, we know that pPrior!=0. Cases where -** pPrior==0 while have been intercepted by higher-level routine and -** redirected to xMalloc. Similarly, we know that nByte>0 because -** cases where nByte<=0 will have been intercepted by higher-level -** routines and redirected to xFree. -*/ -static void *sqlite3MemRealloc(void *pPrior, int nByte){ -#ifdef SQLITE_MALLOCSIZE - void *p = SQLITE_REALLOC(pPrior, nByte); - if( p==0 ){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - sqlite3_log(SQLITE_NOMEM, - "failed memory resize %u to %u bytes", - SQLITE_MALLOCSIZE(pPrior), nByte); - } - return p; -#else - sqlite3_int64 *p = (sqlite3_int64*)pPrior; - assert( pPrior!=0 && nByte>0 ); - assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */ - p--; - p = SQLITE_REALLOC(p, nByte+8 ); - if( p ){ - p[0] = nByte; - p++; - }else{ - testcase( sqlite3GlobalConfig.xLog!=0 ); - sqlite3_log(SQLITE_NOMEM, - "failed memory resize %u to %u bytes", - sqlite3MemSize(pPrior), nByte); - } - return (void*)p; -#endif -} - -/* -** Round up a request size to the next valid allocation size. -*/ -static int sqlite3MemRoundup(int n){ - return ROUND8(n); -} - -/* -** Initialize this module. -*/ -static int sqlite3MemInit(void *NotUsed){ -#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) - int cpuCount; - size_t len; - if( _sqliteZone_ ){ - return SQLITE_OK; - } - len = sizeof(cpuCount); - /* One usually wants to use hw.acctivecpu for MT decisions, but not here */ - sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0); - if( cpuCount>1 ){ - /* defer MT decisions to system malloc */ - _sqliteZone_ = malloc_default_zone(); - }else{ - /* only 1 core, use our own zone to contention over global locks, - ** e.g. we have our own dedicated locks */ - _sqliteZone_ = malloc_create_zone(4096, 0); - malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap"); - } -#endif /* defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */ - UNUSED_PARAMETER(NotUsed); - return SQLITE_OK; -} - -/* -** Deinitialize this module. -*/ -static void sqlite3MemShutdown(void *NotUsed){ - UNUSED_PARAMETER(NotUsed); - return; -} - -/* -** This routine is the only routine in this file with external linkage. -** -** Populate the low-level memory allocation function pointers in -** sqlite3GlobalConfig.m with pointers to the routines in this file. -*/ -SQLITE_PRIVATE void sqlite3MemSetDefault(void){ - static const sqlite3_mem_methods defaultMethods = { - sqlite3MemMalloc, - sqlite3MemFree, - sqlite3MemRealloc, - sqlite3MemSize, - sqlite3MemRoundup, - sqlite3MemInit, - sqlite3MemShutdown, - 0 - }; - sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); -} - -#endif /* SQLITE_SYSTEM_MALLOC */ - -/************** End of mem1.c ************************************************/ -/************** Begin file mem2.c ********************************************/ -/* -** 2007 August 15 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** This file contains low-level memory allocation drivers for when -** SQLite will use the standard C-library malloc/realloc/free interface -** to obtain the memory it needs while adding lots of additional debugging -** information to each allocation in order to help detect and fix memory -** leaks and memory usage errors. -** -** This file contains implementations of the low-level memory allocation -** routines specified in the sqlite3_mem_methods object. -*/ -/* #include "sqliteInt.h" */ - -/* -** This version of the memory allocator is used only if the -** SQLITE_MEMDEBUG macro is defined -*/ -#ifdef SQLITE_MEMDEBUG - -/* -** The backtrace functionality is only available with GLIBC -*/ -#ifdef __GLIBC__ - extern int backtrace(void**,int); - extern void backtrace_symbols_fd(void*const*,int,int); -#else -# define backtrace(A,B) 1 -# define backtrace_symbols_fd(A,B,C) -#endif -/* #include */ - -/* -** Each memory allocation looks like this: -** -** ------------------------------------------------------------------------ -** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard | -** ------------------------------------------------------------------------ -** -** The application code sees only a pointer to the allocation. We have -** to back up from the allocation pointer to find the MemBlockHdr. The -** MemBlockHdr tells us the size of the allocation and the number of -** backtrace pointers. There is also a guard word at the end of the -** MemBlockHdr. -*/ -struct MemBlockHdr { - i64 iSize; /* Size of this allocation */ - struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */ - char nBacktrace; /* Number of backtraces on this alloc */ - char nBacktraceSlots; /* Available backtrace slots */ - u8 nTitle; /* Bytes of title; includes '\0' */ - u8 eType; /* Allocation type code */ - int iForeGuard; /* Guard word for sanity */ -}; - -/* -** Guard words -*/ -#define FOREGUARD 0x80F5E153 -#define REARGUARD 0xE4676B53 - -/* -** Number of malloc size increments to track. -*/ -#define NCSIZE 1000 - -/* -** All of the static variables used by this module are collected -** into a single structure named "mem". This is to keep the -** static variables organized and to reduce namespace pollution -** when this module is combined with other in the amalgamation. -*/ -static struct { - - /* - ** Mutex to control access to the memory allocation subsystem. - */ - sqlite3_mutex *mutex; - - /* - ** Head and tail of a linked list of all outstanding allocations - */ - struct MemBlockHdr *pFirst; - struct MemBlockHdr *pLast; - - /* - ** The number of levels of backtrace to save in new allocations. - */ - int nBacktrace; - void (*xBacktrace)(int, int, void **); - - /* - ** Title text to insert in front of each block - */ - int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */ - char zTitle[100]; /* The title text */ - - /* - ** sqlite3MallocDisallow() increments the following counter. - ** sqlite3MallocAllow() decrements it. - */ - int disallow; /* Do not allow memory allocation */ - - /* - ** Gather statistics on the sizes of memory allocations. - ** nAlloc[i] is the number of allocation attempts of i*8 - ** bytes. i==NCSIZE is the number of allocation attempts for - ** sizes more than NCSIZE*8 bytes. - */ - int nAlloc[NCSIZE]; /* Total number of allocations */ - int nCurrent[NCSIZE]; /* Current number of allocations */ - int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */ - -} mem; - - -/* -** Adjust memory usage statistics -*/ -static void adjustStats(int iSize, int increment){ - int i = ROUND8(iSize)/8; - if( i>NCSIZE-1 ){ - i = NCSIZE - 1; - } - if( increment>0 ){ - mem.nAlloc[i]++; - mem.nCurrent[i]++; - if( mem.nCurrent[i]>mem.mxCurrent[i] ){ - mem.mxCurrent[i] = mem.nCurrent[i]; - } - }else{ - mem.nCurrent[i]--; - assert( mem.nCurrent[i]>=0 ); - } -} - -/* -** Given an allocation, find the MemBlockHdr for that allocation. -** -** This routine checks the guards at either end of the allocation and -** if they are incorrect it asserts. -*/ -static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){ - struct MemBlockHdr *p; - int *pInt; - u8 *pU8; - int nReserve; - - p = (struct MemBlockHdr*)pAllocation; - p--; - assert( p->iForeGuard==(int)FOREGUARD ); - nReserve = ROUND8(p->iSize); - pInt = (int*)pAllocation; - pU8 = (u8*)pAllocation; - assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD ); - /* This checks any of the "extra" bytes allocated due - ** to rounding up to an 8 byte boundary to ensure - ** they haven't been overwritten. - */ - while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 ); - return p; -} - -/* -** Return the number of bytes currently allocated at address p. -*/ -static int sqlite3MemSize(void *p){ - struct MemBlockHdr *pHdr; - if( !p ){ - return 0; - } - pHdr = sqlite3MemsysGetHeader(p); - return (int)pHdr->iSize; -} - -/* -** Initialize the memory allocation subsystem. -*/ -static int sqlite3MemInit(void *NotUsed){ - UNUSED_PARAMETER(NotUsed); - assert( (sizeof(struct MemBlockHdr)&7) == 0 ); - if( !sqlite3GlobalConfig.bMemstat ){ - /* If memory status is enabled, then the malloc.c wrapper will already - ** hold the STATIC_MEM mutex when the routines here are invoked. */ - mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); - } - return SQLITE_OK; -} - -/* -** Deinitialize the memory allocation subsystem. -*/ -static void sqlite3MemShutdown(void *NotUsed){ - UNUSED_PARAMETER(NotUsed); - mem.mutex = 0; -} - -/* -** Round up a request size to the next valid allocation size. -*/ -static int sqlite3MemRoundup(int n){ - return ROUND8(n); -} - -/* -** Fill a buffer with pseudo-random bytes. This is used to preset -** the content of a new memory allocation to unpredictable values and -** to clear the content of a freed allocation to unpredictable values. -*/ -static void randomFill(char *pBuf, int nByte){ - unsigned int x, y, r; - x = SQLITE_PTR_TO_INT(pBuf); - y = nByte | 1; - while( nByte >= 4 ){ - x = (x>>1) ^ (-(int)(x&1) & 0xd0000001); - y = y*1103515245 + 12345; - r = x ^ y; - *(int*)pBuf = r; - pBuf += 4; - nByte -= 4; - } - while( nByte-- > 0 ){ - x = (x>>1) ^ (-(int)(x&1) & 0xd0000001); - y = y*1103515245 + 12345; - r = x ^ y; - *(pBuf++) = r & 0xff; - } -} - -/* -** Allocate nByte bytes of memory. -*/ -static void *sqlite3MemMalloc(int nByte){ - struct MemBlockHdr *pHdr; - void **pBt; - char *z; - int *pInt; - void *p = 0; - int totalSize; - int nReserve; - sqlite3_mutex_enter(mem.mutex); - assert( mem.disallow==0 ); - nReserve = ROUND8(nByte); - totalSize = nReserve + sizeof(*pHdr) + sizeof(int) + - mem.nBacktrace*sizeof(void*) + mem.nTitle; - p = malloc(totalSize); - if( p ){ - z = p; - pBt = (void**)&z[mem.nTitle]; - pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace]; - pHdr->pNext = 0; - pHdr->pPrev = mem.pLast; - if( mem.pLast ){ - mem.pLast->pNext = pHdr; - }else{ - mem.pFirst = pHdr; - } - mem.pLast = pHdr; - pHdr->iForeGuard = FOREGUARD; - pHdr->eType = MEMTYPE_HEAP; - pHdr->nBacktraceSlots = mem.nBacktrace; - pHdr->nTitle = mem.nTitle; - if( mem.nBacktrace ){ - void *aAddr[40]; - pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1; - memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*)); - assert(pBt[0]); - if( mem.xBacktrace ){ - mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]); - } - }else{ - pHdr->nBacktrace = 0; - } - if( mem.nTitle ){ - memcpy(z, mem.zTitle, mem.nTitle); - } - pHdr->iSize = nByte; - adjustStats(nByte, +1); - pInt = (int*)&pHdr[1]; - pInt[nReserve/sizeof(int)] = REARGUARD; - randomFill((char*)pInt, nByte); - memset(((char*)pInt)+nByte, 0x65, nReserve-nByte); - p = (void*)pInt; - } - sqlite3_mutex_leave(mem.mutex); - return p; -} - -/* -** Free memory. -*/ -static void sqlite3MemFree(void *pPrior){ - struct MemBlockHdr *pHdr; - void **pBt; - char *z; - assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 - || mem.mutex!=0 ); - pHdr = sqlite3MemsysGetHeader(pPrior); - pBt = (void**)pHdr; - pBt -= pHdr->nBacktraceSlots; - sqlite3_mutex_enter(mem.mutex); - if( pHdr->pPrev ){ - assert( pHdr->pPrev->pNext==pHdr ); - pHdr->pPrev->pNext = pHdr->pNext; - }else{ - assert( mem.pFirst==pHdr ); - mem.pFirst = pHdr->pNext; - } - if( pHdr->pNext ){ - assert( pHdr->pNext->pPrev==pHdr ); - pHdr->pNext->pPrev = pHdr->pPrev; - }else{ - assert( mem.pLast==pHdr ); - mem.pLast = pHdr->pPrev; - } - z = (char*)pBt; - z -= pHdr->nTitle; - adjustStats((int)pHdr->iSize, -1); - randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) + - (int)pHdr->iSize + sizeof(int) + pHdr->nTitle); - free(z); - sqlite3_mutex_leave(mem.mutex); -} - -/* -** Change the size of an existing memory allocation. -** -** For this debugging implementation, we *always* make a copy of the -** allocation into a new place in memory. In this way, if the -** higher level code is using pointer to the old allocation, it is -** much more likely to break and we are much more liking to find -** the error. -*/ -static void *sqlite3MemRealloc(void *pPrior, int nByte){ - struct MemBlockHdr *pOldHdr; - void *pNew; - assert( mem.disallow==0 ); - assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */ - pOldHdr = sqlite3MemsysGetHeader(pPrior); - pNew = sqlite3MemMalloc(nByte); - if( pNew ){ - memcpy(pNew, pPrior, (int)(nByteiSize ? nByte : pOldHdr->iSize)); - if( nByte>pOldHdr->iSize ){ - randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize); - } - sqlite3MemFree(pPrior); - } - return pNew; -} - -/* -** Populate the low-level memory allocation function pointers in -** sqlite3GlobalConfig.m with pointers to the routines in this file. -*/ -SQLITE_PRIVATE void sqlite3MemSetDefault(void){ - static const sqlite3_mem_methods defaultMethods = { - sqlite3MemMalloc, - sqlite3MemFree, - sqlite3MemRealloc, - sqlite3MemSize, - sqlite3MemRoundup, - sqlite3MemInit, - sqlite3MemShutdown, - 0 - }; - sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods); -} - -/* -** Set the "type" of an allocation. -*/ -SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){ - if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){ - struct MemBlockHdr *pHdr; - pHdr = sqlite3MemsysGetHeader(p); - assert( pHdr->iForeGuard==FOREGUARD ); - pHdr->eType = eType; - } -} - -/* -** Return TRUE if the mask of type in eType matches the type of the -** allocation p. Also return true if p==NULL. -** -** This routine is designed for use within an assert() statement, to -** verify the type of an allocation. For example: -** -** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); -*/ -SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){ - int rc = 1; - if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){ - struct MemBlockHdr *pHdr; - pHdr = sqlite3MemsysGetHeader(p); - assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */ - if( (pHdr->eType&eType)==0 ){ - rc = 0; - } - } - return rc; -} - -/* -** Return TRUE if the mask of type in eType matches no bits of the type of the -** allocation p. Also return true if p==NULL. -** -** This routine is designed for use within an assert() statement, to -** verify the type of an allocation. For example: -** -** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) ); -*/ -SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){ - int rc = 1; - if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){ - struct MemBlockHdr *pHdr; - pHdr = sqlite3MemsysGetHeader(p); - assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */ - if( (pHdr->eType&eType)!=0 ){ - rc = 0; - } - } - return rc; -} - -/* -** Set the number of backtrace levels kept for each allocation. -** A value of zero turns off backtracing. The number is always rounded -** up to a multiple of 2. -*/ -SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){ - if( depth<0 ){ depth = 0; } - if( depth>20 ){ depth = 20; } - depth = (depth+1)&0xfe; - mem.nBacktrace = depth; -} - -SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){ - mem.xBacktrace = xBacktrace; -} - -/* -** Set the title string for subsequent allocations. -*/ -SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){ - unsigned int n = sqlite3Strlen30(zTitle) + 1; - sqlite3_mutex_enter(mem.mutex); - if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1; - memcpy(mem.zTitle, zTitle, n); - mem.zTitle[n] = 0; - mem.nTitle = ROUND8(n); - sqlite3_mutex_leave(mem.mutex); -} - -SQLITE_PRIVATE void sqlite3MemdebugSync(){ - struct MemBlockHdr *pHdr; - for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){ - void **pBt = (void**)pHdr; - pBt -= pHdr->nBacktraceSlots; - mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]); - } -} - -/* -** Open the file indicated and write a log of all unfreed memory -** allocations into that log. -*/ -SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){ - FILE *out; - struct MemBlockHdr *pHdr; - void **pBt; - int i; - out = fopen(zFilename, "w"); - if( out==0 ){ - fprintf(stderr, "** Unable to output memory debug output log: %s **\n", - zFilename); - return; - } - for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){ - char *z = (char*)pHdr; - z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle; - fprintf(out, "**** %lld bytes at %p from %s ****\n", - pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???"); - if( pHdr->nBacktrace ){ - fflush(out); - pBt = (void**)pHdr; - pBt -= pHdr->nBacktraceSlots; - backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out)); - fprintf(out, "\n"); - } - } - fprintf(out, "COUNTS:\n"); - for(i=0; i=1 ); - size = mem3.aPool[i-1].u.hdr.size4x/4; - assert( size==mem3.aPool[i+size-1].u.hdr.prevSize ); - assert( size>=2 ); - if( size <= MX_SMALL ){ - memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]); - }else{ - hash = size % N_HASH; - memsys3UnlinkFromList(i, &mem3.aiHash[hash]); - } -} - -/* -** Link the chunk at mem3.aPool[i] so that is on the list rooted -** at *pRoot. -*/ -static void memsys3LinkIntoList(u32 i, u32 *pRoot){ - assert( sqlite3_mutex_held(mem3.mutex) ); - mem3.aPool[i].u.list.next = *pRoot; - mem3.aPool[i].u.list.prev = 0; - if( *pRoot ){ - mem3.aPool[*pRoot].u.list.prev = i; - } - *pRoot = i; -} - -/* -** Link the chunk at index i into either the appropriate -** small chunk list, or into the large chunk hash table. -*/ -static void memsys3Link(u32 i){ - u32 size, hash; - assert( sqlite3_mutex_held(mem3.mutex) ); - assert( i>=1 ); - assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 ); - size = mem3.aPool[i-1].u.hdr.size4x/4; - assert( size==mem3.aPool[i+size-1].u.hdr.prevSize ); - assert( size>=2 ); - if( size <= MX_SMALL ){ - memsys3LinkIntoList(i, &mem3.aiSmall[size-2]); - }else{ - hash = size % N_HASH; - memsys3LinkIntoList(i, &mem3.aiHash[hash]); - } -} - -/* -** If the STATIC_MEM mutex is not already held, obtain it now. The mutex -** will already be held (obtained by code in malloc.c) if -** sqlite3GlobalConfig.bMemStat is true. -*/ -static void memsys3Enter(void){ - if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){ - mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); - } - sqlite3_mutex_enter(mem3.mutex); -} -static void memsys3Leave(void){ - sqlite3_mutex_leave(mem3.mutex); -} - -/* -** Called when we are unable to satisfy an allocation of nBytes. -*/ -static void memsys3OutOfMemory(int nByte){ - if( !mem3.alarmBusy ){ - mem3.alarmBusy = 1; - assert( sqlite3_mutex_held(mem3.mutex) ); - sqlite3_mutex_leave(mem3.mutex); - sqlite3_release_memory(nByte); - sqlite3_mutex_enter(mem3.mutex); - mem3.alarmBusy = 0; - } -} - - -/* -** Chunk i is a free chunk that has been unlinked. Adjust its -** size parameters for check-out and return a pointer to the -** user portion of the chunk. -*/ -static void *memsys3Checkout(u32 i, u32 nBlock){ - u32 x; - assert( sqlite3_mutex_held(mem3.mutex) ); - assert( i>=1 ); - assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ); - assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock ); - x = mem3.aPool[i-1].u.hdr.size4x; - mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2); - mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock; - mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2; - return &mem3.aPool[i]; -} - -/* -** Carve a piece off of the end of the mem3.iMaster free chunk. -** Return a pointer to the new allocation. Or, if the master chunk -** is not large enough, return 0. -*/ -static void *memsys3FromMaster(u32 nBlock){ - assert( sqlite3_mutex_held(mem3.mutex) ); - assert( mem3.szMaster>=nBlock ); - if( nBlock>=mem3.szMaster-1 ){ - /* Use the entire master */ - void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster); - mem3.iMaster = 0; - mem3.szMaster = 0; - mem3.mnMaster = 0; - return p; - }else{ - /* Split the master block. Return the tail. */ - u32 newi, x; - newi = mem3.iMaster + mem3.szMaster - nBlock; - assert( newi > mem3.iMaster+1 ); - mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock; - mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2; - mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1; - mem3.szMaster -= nBlock; - mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster; - x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2; - mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x; - if( mem3.szMaster < mem3.mnMaster ){ - mem3.mnMaster = mem3.szMaster; - } - return (void*)&mem3.aPool[newi]; - } -} - -/* -** *pRoot is the head of a list of free chunks of the same size -** or same size hash. In other words, *pRoot is an entry in either -** mem3.aiSmall[] or mem3.aiHash[]. -** -** This routine examines all entries on the given list and tries -** to coalesce each entries with adjacent free chunks. -** -** If it sees a chunk that is larger than mem3.iMaster, it replaces -** the current mem3.iMaster with the new larger chunk. In order for -** this mem3.iMaster replacement to work, the master chunk must be -** linked into the hash tables. That is not the normal state of -** affairs, of course. The calling routine must link the master -** chunk before invoking this routine, then must unlink the (possibly -** changed) master chunk once this routine has finished. -*/ -static void memsys3Merge(u32 *pRoot){ - u32 iNext, prev, size, i, x; - - assert( sqlite3_mutex_held(mem3.mutex) ); - for(i=*pRoot; i>0; i=iNext){ - iNext = mem3.aPool[i].u.list.next; - size = mem3.aPool[i-1].u.hdr.size4x; - assert( (size&1)==0 ); - if( (size&2)==0 ){ - memsys3UnlinkFromList(i, pRoot); - assert( i > mem3.aPool[i-1].u.hdr.prevSize ); - prev = i - mem3.aPool[i-1].u.hdr.prevSize; - if( prev==iNext ){ - iNext = mem3.aPool[prev].u.list.next; - } - memsys3Unlink(prev); - size = i + size/4 - prev; - x = mem3.aPool[prev-1].u.hdr.size4x & 2; - mem3.aPool[prev-1].u.hdr.size4x = size*4 | x; - mem3.aPool[prev+size-1].u.hdr.prevSize = size; - memsys3Link(prev); - i = prev; - }else{ - size /= 4; - } - if( size>mem3.szMaster ){ - mem3.iMaster = i; - mem3.szMaster = size; - } - } -} - -/* -** Return a block of memory of at least nBytes in size. -** Return NULL if unable. -** -** This function assumes that the necessary mutexes, if any, are -** already held by the caller. Hence "Unsafe". -*/ -static void *memsys3MallocUnsafe(int nByte){ - u32 i; - u32 nBlock; - u32 toFree; - - assert( sqlite3_mutex_held(mem3.mutex) ); - assert( sizeof(Mem3Block)==8 ); - if( nByte<=12 ){ - nBlock = 2; - }else{ - nBlock = (nByte + 11)/8; - } - assert( nBlock>=2 ); - - /* STEP 1: - ** Look for an entry of the correct size in either the small - ** chunk table or in the large chunk hash table. This is - ** successful most of the time (about 9 times out of 10). - */ - if( nBlock <= MX_SMALL ){ - i = mem3.aiSmall[nBlock-2]; - if( i>0 ){ - memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]); - return memsys3Checkout(i, nBlock); - } - }else{ - int hash = nBlock % N_HASH; - for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){ - if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){ - memsys3UnlinkFromList(i, &mem3.aiHash[hash]); - return memsys3Checkout(i, nBlock); - } - } - } - - /* STEP 2: - ** Try to satisfy the allocation by carving a piece off of the end - ** of the master chunk. This step usually works if step 1 fails. - */ - if( mem3.szMaster>=nBlock ){ - return memsys3FromMaster(nBlock); - } - - - /* STEP 3: - ** Loop through the entire memory pool. Coalesce adjacent free - ** chunks. Recompute the master chunk as the largest free chunk. - ** Then try again to satisfy the allocation by carving a piece off - ** of the end of the master chunk. This step happens very - ** rarely (we hope!) - */ - for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){ - memsys3OutOfMemory(toFree); - if( mem3.iMaster ){ - memsys3Link(mem3.iMaster); - mem3.iMaster = 0; - mem3.szMaster = 0; - } - for(i=0; i=nBlock ){ - return memsys3FromMaster(nBlock); - } - } - } - - /* If none of the above worked, then we fail. */ - return 0; -} - -/* -** Free an outstanding memory allocation. -** -** This function assumes that the necessary mutexes, if any, are -** already held by the caller. Hence "Unsafe". -*/ -static void memsys3FreeUnsafe(void *pOld){ - Mem3Block *p = (Mem3Block*)pOld; - int i; - u32 size, x; - assert( sqlite3_mutex_held(mem3.mutex) ); - assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] ); - i = p - mem3.aPool; - assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 ); - size = mem3.aPool[i-1].u.hdr.size4x/4; - assert( i+size<=mem3.nPool+1 ); - mem3.aPool[i-1].u.hdr.size4x &= ~1; - mem3.aPool[i+size-1].u.hdr.prevSize = size; - mem3.aPool[i+size-1].u.hdr.size4x &= ~2; - memsys3Link(i); - - /* Try to expand the master using the newly freed chunk */ - if( mem3.iMaster ){ - while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){ - size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize; - mem3.iMaster -= size; - mem3.szMaster += size; - memsys3Unlink(mem3.iMaster); - x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2; - mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x; - mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster; - } - x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2; - while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){ - memsys3Unlink(mem3.iMaster+mem3.szMaster); - mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4; - mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x; - mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster; - } - } -} - -/* -** Return the size of an outstanding allocation, in bytes. The -** size returned omits the 8-byte header overhead. This only -** works for chunks that are currently checked out. -*/ -static int memsys3Size(void *p){ - Mem3Block *pBlock; - assert( p!=0 ); - pBlock = (Mem3Block*)p; - assert( (pBlock[-1].u.hdr.size4x&1)!=0 ); - return (pBlock[-1].u.hdr.size4x&~3)*2 - 4; -} - -/* -** Round up a request size to the next valid allocation size. -*/ -static int memsys3Roundup(int n){ - if( n<=12 ){ - return 12; - }else{ - return ((n+11)&~7) - 4; - } -} - -/* -** Allocate nBytes of memory. -*/ -static void *memsys3Malloc(int nBytes){ - sqlite3_int64 *p; - assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */ - memsys3Enter(); - p = memsys3MallocUnsafe(nBytes); - memsys3Leave(); - return (void*)p; -} - -/* -** Free memory. -*/ -static void memsys3Free(void *pPrior){ - assert( pPrior ); - memsys3Enter(); - memsys3FreeUnsafe(pPrior); - memsys3Leave(); -} - -/* -** Change the size of an existing memory allocation -*/ -static void *memsys3Realloc(void *pPrior, int nBytes){ - int nOld; - void *p; - if( pPrior==0 ){ - return sqlite3_malloc(nBytes); - } - if( nBytes<=0 ){ - sqlite3_free(pPrior); - return 0; - } - nOld = memsys3Size(pPrior); - if( nBytes<=nOld && nBytes>=nOld-128 ){ - return pPrior; - } - memsys3Enter(); - p = memsys3MallocUnsafe(nBytes); - if( p ){ - if( nOld>1)!=(size&1) ){ - fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]); - assert( 0 ); - break; - } - if( size&1 ){ - fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8); - }else{ - fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8, - i==mem3.iMaster ? " **master**" : ""); - } - } - for(i=0; i0; j=mem3.aPool[j].u.list.next){ - fprintf(out, " %p(%d)", &mem3.aPool[j], - (mem3.aPool[j-1].u.hdr.size4x/4)*8-8); - } - fprintf(out, "\n"); - } - for(i=0; i0; j=mem3.aPool[j].u.list.next){ - fprintf(out, " %p(%d)", &mem3.aPool[j], - (mem3.aPool[j-1].u.hdr.size4x/4)*8-8); - } - fprintf(out, "\n"); - } - fprintf(out, "master=%d\n", mem3.iMaster); - fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8); - fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8); - sqlite3_mutex_leave(mem3.mutex); - if( out==stdout ){ - fflush(stdout); - }else{ - fclose(out); - } -#else - UNUSED_PARAMETER(zFilename); -#endif -} - -/* -** This routine is the only routine in this file with external -** linkage. -** -** Populate the low-level memory allocation function pointers in -** sqlite3GlobalConfig.m with pointers to the routines in this file. The -** arguments specify the block of memory to manage. -** -** This routine is only called by sqlite3_config(), and therefore -** is not required to be threadsafe (it is not). -*/ -SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){ - static const sqlite3_mem_methods mempoolMethods = { - memsys3Malloc, - memsys3Free, - memsys3Realloc, - memsys3Size, - memsys3Roundup, - memsys3Init, - memsys3Shutdown, - 0 - }; - return &mempoolMethods; -} - -#endif /* SQLITE_ENABLE_MEMSYS3 */ - -/************** End of mem3.c ************************************************/ -/************** Begin file mem5.c ********************************************/ -/* -** 2007 October 14 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file contains the C functions that implement a memory -** allocation subsystem for use by SQLite. -** -** This version of the memory allocation subsystem omits all -** use of malloc(). The application gives SQLite a block of memory -** before calling sqlite3_initialize() from which allocations -** are made and returned by the xMalloc() and xRealloc() -** implementations. Once sqlite3_initialize() has been called, -** the amount of memory available to SQLite is fixed and cannot -** be changed. -** -** This version of the memory allocation subsystem is included -** in the build only if SQLITE_ENABLE_MEMSYS5 is defined. -** -** This memory allocator uses the following algorithm: -** -** 1. All memory allocation sizes are rounded up to a power of 2. -** -** 2. If two adjacent free blocks are the halves of a larger block, -** then the two blocks are coalesced into the single larger block. -** -** 3. New memory is allocated from the first available free block. -** -** This algorithm is described in: J. M. Robson. "Bounds for Some Functions -** Concerning Dynamic Storage Allocation". Journal of the Association for -** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499. -** -** Let n be the size of the largest allocation divided by the minimum -** allocation size (after rounding all sizes up to a power of 2.) Let M -** be the maximum amount of memory ever outstanding at one time. Let -** N be the total amount of memory available for allocation. Robson -** proved that this memory allocator will never breakdown due to -** fragmentation as long as the following constraint holds: -** -** N >= M*(1 + log2(n)/2) - n + 1 -** -** The sqlite3_status() logic tracks the maximum values of n and M so -** that an application can, at any time, verify this constraint. -*/ -/* #include "sqliteInt.h" */ - -/* -** This version of the memory allocator is used only when -** SQLITE_ENABLE_MEMSYS5 is defined. -*/ -#ifdef SQLITE_ENABLE_MEMSYS5 - -/* -** A minimum allocation is an instance of the following structure. -** Larger allocations are an array of these structures where the -** size of the array is a power of 2. -** -** The size of this object must be a power of two. That fact is -** verified in memsys5Init(). -*/ -typedef struct Mem5Link Mem5Link; -struct Mem5Link { - int next; /* Index of next free chunk */ - int prev; /* Index of previous free chunk */ -}; - -/* -** Maximum size of any allocation is ((1<=0 && i=0 && iLogsize<=LOGMAX ); - assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize ); - - next = MEM5LINK(i)->next; - prev = MEM5LINK(i)->prev; - if( prev<0 ){ - mem5.aiFreelist[iLogsize] = next; - }else{ - MEM5LINK(prev)->next = next; - } - if( next>=0 ){ - MEM5LINK(next)->prev = prev; - } -} - -/* -** Link the chunk at mem5.aPool[i] so that is on the iLogsize -** free list. -*/ -static void memsys5Link(int i, int iLogsize){ - int x; - assert( sqlite3_mutex_held(mem5.mutex) ); - assert( i>=0 && i=0 && iLogsize<=LOGMAX ); - assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize ); - - x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize]; - MEM5LINK(i)->prev = -1; - if( x>=0 ){ - assert( xprev = i; - } - mem5.aiFreelist[iLogsize] = i; -} - -/* -** Obtain or release the mutex needed to access global data structures. -*/ -static void memsys5Enter(void){ - sqlite3_mutex_enter(mem5.mutex); -} -static void memsys5Leave(void){ - sqlite3_mutex_leave(mem5.mutex); -} - -/* -** Return the size of an outstanding allocation, in bytes. -** This only works for chunks that are currently checked out. -*/ -static int memsys5Size(void *p){ - int iSize, i; - assert( p!=0 ); - i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom); - assert( i>=0 && i0 ); - - /* No more than 1GiB per allocation */ - if( nByte > 0x40000000 ) return 0; - -#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) - /* Keep track of the maximum allocation request. Even unfulfilled - ** requests are counted */ - if( (u32)nByte>mem5.maxRequest ){ - mem5.maxRequest = nByte; - } -#endif - - - /* Round nByte up to the next valid power of two */ - for(iFullSz=mem5.szAtom,iLogsize=0; iFullSzLOGMAX ){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte); - return 0; - } - i = mem5.aiFreelist[iBin]; - memsys5Unlink(i, iBin); - while( iBin>iLogsize ){ - int newSize; - - iBin--; - newSize = 1 << iBin; - mem5.aCtrl[i+newSize] = CTRL_FREE | iBin; - memsys5Link(i+newSize, iBin); - } - mem5.aCtrl[i] = iLogsize; - -#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) - /* Update allocator performance statistics. */ - mem5.nAlloc++; - mem5.totalAlloc += iFullSz; - mem5.totalExcess += iFullSz - nByte; - mem5.currentCount++; - mem5.currentOut += iFullSz; - if( mem5.maxCount=0 && iBlock0 ); - assert( mem5.currentOut>=(size*mem5.szAtom) ); - mem5.currentCount--; - mem5.currentOut -= size*mem5.szAtom; - assert( mem5.currentOut>0 || mem5.currentCount==0 ); - assert( mem5.currentCount>0 || mem5.currentOut==0 ); -#endif - - mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize; - while( ALWAYS(iLogsize>iLogsize) & 1 ){ - iBuddy = iBlock - size; - assert( iBuddy>=0 ); - }else{ - iBuddy = iBlock + size; - if( iBuddy>=mem5.nBlock ) break; - } - if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break; - memsys5Unlink(iBuddy, iLogsize); - iLogsize++; - if( iBuddy0 ){ - memsys5Enter(); - p = memsys5MallocUnsafe(nBytes); - memsys5Leave(); - } - return (void*)p; -} - -/* -** Free memory. -** -** The outer layer memory allocator prevents this routine from -** being called with pPrior==0. -*/ -static void memsys5Free(void *pPrior){ - assert( pPrior!=0 ); - memsys5Enter(); - memsys5FreeUnsafe(pPrior); - memsys5Leave(); -} - -/* -** Change the size of an existing memory allocation. -** -** The outer layer memory allocator prevents this routine from -** being called with pPrior==0. -** -** nBytes is always a value obtained from a prior call to -** memsys5Round(). Hence nBytes is always a non-negative power -** of two. If nBytes==0 that means that an oversize allocation -** (an allocation larger than 0x40000000) was requested and this -** routine should return 0 without freeing pPrior. -*/ -static void *memsys5Realloc(void *pPrior, int nBytes){ - int nOld; - void *p; - assert( pPrior!=0 ); - assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */ - assert( nBytes>=0 ); - if( nBytes==0 ){ - return 0; - } - nOld = memsys5Size(pPrior); - if( nBytes<=nOld ){ - return pPrior; - } - p = memsys5Malloc(nBytes); - if( p ){ - memcpy(p, pPrior, nOld); - memsys5Free(pPrior); - } - return p; -} - -/* -** Round up a request size to the next valid allocation size. If -** the allocation is too large to be handled by this allocation system, -** return 0. -** -** All allocations must be a power of two and must be expressed by a -** 32-bit signed integer. Hence the largest allocation is 0x40000000 -** or 1073741824 bytes. -*/ -static int memsys5Roundup(int n){ - int iFullSz; - if( n > 0x40000000 ) return 0; - for(iFullSz=mem5.szAtom; iFullSz 0 -** memsys5Log(2) -> 1 -** memsys5Log(4) -> 2 -** memsys5Log(5) -> 3 -** memsys5Log(8) -> 3 -** memsys5Log(9) -> 4 -*/ -static int memsys5Log(int iValue){ - int iLog; - for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<mem5.szAtom ){ - mem5.szAtom = mem5.szAtom << 1; - } - - mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8))); - mem5.zPool = zByte; - mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom]; - - for(ii=0; ii<=LOGMAX; ii++){ - mem5.aiFreelist[ii] = -1; - } - - iOffset = 0; - for(ii=LOGMAX; ii>=0; ii--){ - int nAlloc = (1<mem5.nBlock); - } - - /* If a mutex is required for normal operation, allocate one */ - if( sqlite3GlobalConfig.bMemstat==0 ){ - mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); - } - - return SQLITE_OK; -} - -/* -** Deinitialize this module. -*/ -static void memsys5Shutdown(void *NotUsed){ - UNUSED_PARAMETER(NotUsed); - mem5.mutex = 0; - return; -} - -#ifdef SQLITE_TEST -/* -** Open the file indicated and write a log of all unfreed memory -** allocations into that log. -*/ -SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){ - FILE *out; - int i, j, n; - int nMinLog; - - if( zFilename==0 || zFilename[0]==0 ){ - out = stdout; - }else{ - out = fopen(zFilename, "w"); - if( out==0 ){ - fprintf(stderr, "** Unable to output memory debug output log: %s **\n", - zFilename); - return; - } - } - memsys5Enter(); - nMinLog = memsys5Log(mem5.szAtom); - for(i=0; i<=LOGMAX && i+nMinLog<32; i++){ - for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){} - fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n); - } - fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc); - fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc); - fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess); - fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut); - fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount); - fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut); - fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount); - fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest); - memsys5Leave(); - if( out==stdout ){ - fflush(stdout); - }else{ - fclose(out); - } -} -#endif - -/* -** This routine is the only routine in this file with external -** linkage. It returns a pointer to a static sqlite3_mem_methods -** struct populated with the memsys5 methods. -*/ -SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){ - static const sqlite3_mem_methods memsys5Methods = { - memsys5Malloc, - memsys5Free, - memsys5Realloc, - memsys5Size, - memsys5Roundup, - memsys5Init, - memsys5Shutdown, - 0 - }; - return &memsys5Methods; -} - -#endif /* SQLITE_ENABLE_MEMSYS5 */ - -/************** End of mem5.c ************************************************/ -/************** Begin file mutex.c *******************************************/ -/* -** 2007 August 14 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file contains the C functions that implement mutexes. -** -** This file contains code that is common across all mutex implementations. -*/ -/* #include "sqliteInt.h" */ - -#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT) -/* -** For debugging purposes, record when the mutex subsystem is initialized -** and uninitialized so that we can assert() if there is an attempt to -** allocate a mutex while the system is uninitialized. -*/ -static SQLITE_WSD int mutexIsInit = 0; -#endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */ - - -#ifndef SQLITE_MUTEX_OMIT -/* -** 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 ){ - pFrom = sqlite3DefaultMutex(); - }else{ - pFrom = sqlite3NoopMutex(); - } - pTo->xMutexInit = pFrom->xMutexInit; - pTo->xMutexEnd = pFrom->xMutexEnd; - pTo->xMutexFree = pFrom->xMutexFree; - pTo->xMutexEnter = pFrom->xMutexEnter; - pTo->xMutexTry = pFrom->xMutexTry; - pTo->xMutexLeave = pFrom->xMutexLeave; - pTo->xMutexHeld = pFrom->xMutexHeld; - pTo->xMutexNotheld = pFrom->xMutexNotheld; - sqlite3MemoryBarrier(); - pTo->xMutexAlloc = pFrom->xMutexAlloc; - } - assert( sqlite3GlobalConfig.mutex.xMutexInit ); - rc = sqlite3GlobalConfig.mutex.xMutexInit(); - -#ifdef SQLITE_DEBUG - GLOBAL(int, mutexIsInit) = 1; -#endif - - return rc; -} - -/* -** Shutdown the mutex system. This call frees resources allocated by -** sqlite3MutexInit(). -*/ -SQLITE_PRIVATE int sqlite3MutexEnd(void){ - int rc = SQLITE_OK; - if( sqlite3GlobalConfig.mutex.xMutexEnd ){ - rc = sqlite3GlobalConfig.mutex.xMutexEnd(); - } - -#ifdef SQLITE_DEBUG - GLOBAL(int, mutexIsInit) = 0; -#endif - - return rc; -} - -/* -** Retrieve a pointer to a static mutex or allocate a new dynamic one. -*/ -SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){ -#ifndef SQLITE_OMIT_AUTOINIT - if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0; - if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0; -#endif - assert( sqlite3GlobalConfig.mutex.xMutexAlloc ); - return sqlite3GlobalConfig.mutex.xMutexAlloc(id); -} - -SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){ - if( !sqlite3GlobalConfig.bCoreMutex ){ - return 0; - } - assert( GLOBAL(int, mutexIsInit) ); - assert( sqlite3GlobalConfig.mutex.xMutexAlloc ); - return sqlite3GlobalConfig.mutex.xMutexAlloc(id); -} - -/* -** Free a dynamic mutex. -*/ -SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){ - if( p ){ - assert( sqlite3GlobalConfig.mutex.xMutexFree ); - sqlite3GlobalConfig.mutex.xMutexFree(p); - } -} - -/* -** Obtain the mutex p. If some other thread already has the mutex, block -** until it can be obtained. -*/ -SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){ - if( p ){ - assert( sqlite3GlobalConfig.mutex.xMutexEnter ); - sqlite3GlobalConfig.mutex.xMutexEnter(p); - } -} - -/* -** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another -** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY. -*/ -SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){ - int rc = SQLITE_OK; - if( p ){ - assert( sqlite3GlobalConfig.mutex.xMutexTry ); - return sqlite3GlobalConfig.mutex.xMutexTry(p); - } - return rc; -} - -/* -** The sqlite3_mutex_leave() routine exits a mutex that was previously -** entered by the same thread. The behavior is undefined if the mutex -** is not currently entered. If a NULL pointer is passed as an argument -** this function is a no-op. -*/ -SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){ - if( p ){ - assert( sqlite3GlobalConfig.mutex.xMutexLeave ); - sqlite3GlobalConfig.mutex.xMutexLeave(p); - } -} - -#ifndef NDEBUG -/* -** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are -** intended for use inside assert() statements. -*/ -SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){ - assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld ); - return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p); -} -SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){ - assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld ); - return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p); -} -#endif - -#endif /* !defined(SQLITE_MUTEX_OMIT) */ - -/************** End of mutex.c ***********************************************/ -/************** Begin file mutex_noop.c **************************************/ -/* -** 2008 October 07 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file contains the C functions that implement mutexes. -** -** This implementation in this file does not provide any mutual -** exclusion and is thus suitable for use only in applications -** that use SQLite in a single thread. The routines defined -** here are place-holders. Applications can substitute working -** mutex routines at start-time using the -** -** sqlite3_config(SQLITE_CONFIG_MUTEX,...) -** -** interface. -** -** If compiled with SQLITE_DEBUG, then additional logic is inserted -** that does error checking on mutexes to make sure they are being -** called correctly. -*/ -/* #include "sqliteInt.h" */ - -#ifndef SQLITE_MUTEX_OMIT - -#ifndef SQLITE_DEBUG -/* -** Stub routines for all mutex methods. -** -** This routines provide no mutual exclusion or error checking. -*/ -static int noopMutexInit(void){ return SQLITE_OK; } -static int noopMutexEnd(void){ return SQLITE_OK; } -static sqlite3_mutex *noopMutexAlloc(int id){ - UNUSED_PARAMETER(id); - return (sqlite3_mutex*)8; -} -static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; } -static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; } -static int noopMutexTry(sqlite3_mutex *p){ - UNUSED_PARAMETER(p); - return SQLITE_OK; -} -static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; } - -SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){ - static const sqlite3_mutex_methods sMutex = { - noopMutexInit, - noopMutexEnd, - noopMutexAlloc, - noopMutexFree, - noopMutexEnter, - noopMutexTry, - noopMutexLeave, - - 0, - 0, - }; - - return &sMutex; -} -#endif /* !SQLITE_DEBUG */ - -#ifdef SQLITE_DEBUG -/* -** In this implementation, error checking is provided for testing -** and debugging purposes. The mutexes still do not provide any -** mutual exclusion. -*/ - -/* -** The mutex object -*/ -typedef struct sqlite3_debug_mutex { - int id; /* The mutex type */ - int cnt; /* Number of entries without a matching leave */ -} sqlite3_debug_mutex; - -/* -** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are -** intended for use inside assert() statements. -*/ -static int debugMutexHeld(sqlite3_mutex *pX){ - sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; - return p==0 || p->cnt>0; -} -static int debugMutexNotheld(sqlite3_mutex *pX){ - sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; - return p==0 || p->cnt==0; -} - -/* -** Initialize and deinitialize the mutex subsystem. -*/ -static int debugMutexInit(void){ return SQLITE_OK; } -static int debugMutexEnd(void){ return SQLITE_OK; } - -/* -** The sqlite3_mutex_alloc() routine allocates a new -** mutex and returns a pointer to it. If it returns NULL -** that means that a mutex could not be allocated. -*/ -static sqlite3_mutex *debugMutexAlloc(int id){ - static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1]; - sqlite3_debug_mutex *pNew = 0; - switch( id ){ - case SQLITE_MUTEX_FAST: - case SQLITE_MUTEX_RECURSIVE: { - pNew = sqlite3Malloc(sizeof(*pNew)); - if( pNew ){ - pNew->id = id; - pNew->cnt = 0; - } - break; - } - default: { -#ifdef SQLITE_ENABLE_API_ARMOR - if( id-2<0 || id-2>=ArraySize(aStatic) ){ - (void)SQLITE_MISUSE_BKPT; - return 0; - } -#endif - pNew = &aStatic[id-2]; - pNew->id = id; - break; - } - } - return (sqlite3_mutex*)pNew; -} - -/* -** This routine deallocates a previously allocated mutex. -*/ -static void debugMutexFree(sqlite3_mutex *pX){ - sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; - assert( p->cnt==0 ); - if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){ - sqlite3_free(p); - }else{ -#ifdef SQLITE_ENABLE_API_ARMOR - (void)SQLITE_MISUSE_BKPT; -#endif - } -} - -/* -** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt -** to enter a mutex. If another thread is already within the mutex, -** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return -** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK -** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can -** be entered multiple times by the same thread. In such cases the, -** mutex must be exited an equal number of times before another thread -** can enter. If the same thread tries to enter any other kind of mutex -** more than once, the behavior is undefined. -*/ -static void debugMutexEnter(sqlite3_mutex *pX){ - sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; - assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) ); - p->cnt++; -} -static int debugMutexTry(sqlite3_mutex *pX){ - sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; - assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) ); - p->cnt++; - return SQLITE_OK; -} - -/* -** The sqlite3_mutex_leave() routine exits a mutex that was -** previously entered by the same thread. The behavior -** is undefined if the mutex is not currently entered or -** is not currently allocated. SQLite will never do either. -*/ -static void debugMutexLeave(sqlite3_mutex *pX){ - sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX; - assert( debugMutexHeld(pX) ); - p->cnt--; - assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) ); -} - -SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){ - static const sqlite3_mutex_methods sMutex = { - debugMutexInit, - debugMutexEnd, - debugMutexAlloc, - debugMutexFree, - debugMutexEnter, - debugMutexTry, - debugMutexLeave, - - debugMutexHeld, - debugMutexNotheld - }; - - return &sMutex; -} -#endif /* SQLITE_DEBUG */ - -/* -** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation -** is used regardless of the run-time threadsafety setting. -*/ -#ifdef SQLITE_MUTEX_NOOP -SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ - return sqlite3NoopMutex(); -} -#endif /* defined(SQLITE_MUTEX_NOOP) */ -#endif /* !defined(SQLITE_MUTEX_OMIT) */ - -/************** End of mutex_noop.c ******************************************/ -/************** Begin file mutex_unix.c **************************************/ -/* -** 2007 August 28 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file contains the C functions that implement mutexes for pthreads -*/ -/* #include "sqliteInt.h" */ - -/* -** The code in this file is only used if we are compiling threadsafe -** under unix with pthreads. -** -** Note that this implementation requires a version of pthreads that -** supports recursive mutexes. -*/ -#ifdef SQLITE_MUTEX_PTHREADS - -#include - -/* -** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields -** are necessary under two condidtions: (1) Debug builds and (2) using -** home-grown mutexes. Encapsulate these conditions into a single #define. -*/ -#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX) -# define SQLITE_MUTEX_NREF 1 -#else -# define SQLITE_MUTEX_NREF 0 -#endif - -/* -** Each recursive mutex is an instance of the following structure. -*/ -struct sqlite3_mutex { - pthread_mutex_t mutex; /* Mutex controlling the lock */ -#if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR) - int id; /* Mutex type */ -#endif -#if SQLITE_MUTEX_NREF - volatile int nRef; /* Number of entrances */ - volatile pthread_t owner; /* Thread that is within this mutex */ - int trace; /* True to trace changes */ -#endif -}; -#if SQLITE_MUTEX_NREF -#define SQLITE3_MUTEX_INITIALIZER {PTHREAD_MUTEX_INITIALIZER,0,0,(pthread_t)0,0} -#elif defined(SQLITE_ENABLE_API_ARMOR) -#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0 } -#else -#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER } -#endif - -/* -** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are -** intended for use only inside assert() statements. On some platforms, -** there might be race conditions that can cause these routines to -** deliver incorrect results. In particular, if pthread_equal() is -** not an atomic operation, then these routines might delivery -** incorrect results. On most platforms, pthread_equal() is a -** comparison of two integers and is therefore atomic. But we are -** told that HPUX is not such a platform. If so, then these routines -** will not always work correctly on HPUX. -** -** On those platforms where pthread_equal() is not atomic, SQLite -** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to -** make sure no assert() statements are evaluated and hence these -** routines are never called. -*/ -#if !defined(NDEBUG) || defined(SQLITE_DEBUG) -static int pthreadMutexHeld(sqlite3_mutex *p){ - return (p->nRef!=0 && pthread_equal(p->owner, pthread_self())); -} -static int pthreadMutexNotheld(sqlite3_mutex *p){ - return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0; -} -#endif - -/* -** Try to provide a memory barrier operation, needed for initialization -** and also for the implementation of xShmBarrier in the VFS in cases -** where SQLite is compiled without mutexes. -*/ -SQLITE_PRIVATE void sqlite3MemoryBarrier(void){ -#if defined(SQLITE_MEMORY_BARRIER) - SQLITE_MEMORY_BARRIER; -#elif defined(__GNUC__) && GCC_VERSION>=4001000 - __sync_synchronize(); -#endif -} - -/* -** Initialize and deinitialize the mutex subsystem. -*/ -static int pthreadMutexInit(void){ return SQLITE_OK; } -static int pthreadMutexEnd(void){ return SQLITE_OK; } - -/* -** The sqlite3_mutex_alloc() routine allocates a new -** mutex and returns a pointer to it. If it returns NULL -** that means that a mutex could not be allocated. SQLite -** will unwind its stack and return an error. The argument -** to sqlite3_mutex_alloc() is one of these integer constants: -** -**
    -**
  • SQLITE_MUTEX_FAST -**
  • SQLITE_MUTEX_RECURSIVE -**
  • SQLITE_MUTEX_STATIC_MASTER -**
  • SQLITE_MUTEX_STATIC_MEM -**
  • SQLITE_MUTEX_STATIC_OPEN -**
  • SQLITE_MUTEX_STATIC_PRNG -**
  • SQLITE_MUTEX_STATIC_LRU -**
  • SQLITE_MUTEX_STATIC_PMEM -**
  • SQLITE_MUTEX_STATIC_APP1 -**
  • SQLITE_MUTEX_STATIC_APP2 -**
  • SQLITE_MUTEX_STATIC_APP3 -**
  • SQLITE_MUTEX_STATIC_VFS1 -**
  • SQLITE_MUTEX_STATIC_VFS2 -**
  • SQLITE_MUTEX_STATIC_VFS3 -**
-** -** The first two constants cause sqlite3_mutex_alloc() to create -** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE -** is used but not necessarily so when SQLITE_MUTEX_FAST is used. -** The mutex implementation does not need to make a distinction -** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does -** not want to. But SQLite will only request a recursive mutex in -** cases where it really needs one. If a faster non-recursive mutex -** implementation is available on the host platform, the mutex subsystem -** might return such a mutex in response to SQLITE_MUTEX_FAST. -** -** The other allowed parameters to sqlite3_mutex_alloc() each return -** a pointer to a static preexisting mutex. Six static mutexes are -** used by the current version of SQLite. Future versions of SQLite -** may add additional static mutexes. Static mutexes are for internal -** use by SQLite only. Applications that use SQLite mutexes should -** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or -** SQLITE_MUTEX_RECURSIVE. -** -** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST -** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() -** returns a different mutex on every call. But for the static -** mutex types, the same mutex is returned on every call that has -** the same type number. -*/ -static sqlite3_mutex *pthreadMutexAlloc(int iType){ - static sqlite3_mutex staticMutexes[] = { - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER - }; - 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 - } - break; - } - case SQLITE_MUTEX_FAST: { - p = sqlite3MallocZero( sizeof(*p) ); - if( p ){ - pthread_mutex_init(&p->mutex, 0); - } - 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) - if( p ) p->id = iType; -#endif - return p; -} - - -/* -** This routine deallocates a previously -** allocated mutex. SQLite is careful to deallocate every -** mutex that it allocates. -*/ -static void pthreadMutexFree(sqlite3_mutex *p){ - assert( p->nRef==0 ); -#if SQLITE_ENABLE_API_ARMOR - if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ) -#endif - { - pthread_mutex_destroy(&p->mutex); - sqlite3_free(p); - } -#ifdef SQLITE_ENABLE_API_ARMOR - else{ - (void)SQLITE_MISUSE_BKPT; - } -#endif -} - -/* -** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt -** to enter a mutex. If another thread is already within the mutex, -** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return -** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK -** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can -** be entered multiple times by the same thread. In such cases the, -** mutex must be exited an equal number of times before another thread -** can enter. If the same thread tries to enter any other kind of mutex -** more than once, the behavior is undefined. -*/ -static void pthreadMutexEnter(sqlite3_mutex *p){ - assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) ); - -#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX - /* If recursive mutexes are not available, then we have to grow - ** our own. This implementation assumes that pthread_equal() - ** is atomic - that it cannot be deceived into thinking self - ** and p->owner are equal if p->owner changes between two values - ** that are not equal to self while the comparison is taking place. - ** This implementation also assumes a coherent cache - that - ** separate processes cannot read different values from the same - ** address at the same time. If either of these two conditions - ** are not met, then the mutexes will fail and problems will result. - */ - { - pthread_t self = pthread_self(); - if( p->nRef>0 && pthread_equal(p->owner, self) ){ - p->nRef++; - }else{ - pthread_mutex_lock(&p->mutex); - assert( p->nRef==0 ); - p->owner = self; - p->nRef = 1; - } - } -#else - /* Use the built-in recursive mutexes if they are available. - */ - pthread_mutex_lock(&p->mutex); -#if SQLITE_MUTEX_NREF - assert( p->nRef>0 || p->owner==0 ); - p->owner = pthread_self(); - p->nRef++; -#endif -#endif - -#ifdef SQLITE_DEBUG - if( p->trace ){ - printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); - } -#endif -} -static int pthreadMutexTry(sqlite3_mutex *p){ - int rc; - assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) ); - -#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX - /* If recursive mutexes are not available, then we have to grow - ** our own. This implementation assumes that pthread_equal() - ** is atomic - that it cannot be deceived into thinking self - ** and p->owner are equal if p->owner changes between two values - ** that are not equal to self while the comparison is taking place. - ** This implementation also assumes a coherent cache - that - ** separate processes cannot read different values from the same - ** address at the same time. If either of these two conditions - ** are not met, then the mutexes will fail and problems will result. - */ - { - pthread_t self = pthread_self(); - if( p->nRef>0 && pthread_equal(p->owner, self) ){ - p->nRef++; - rc = SQLITE_OK; - }else if( pthread_mutex_trylock(&p->mutex)==0 ){ - assert( p->nRef==0 ); - p->owner = self; - p->nRef = 1; - rc = SQLITE_OK; - }else{ - rc = SQLITE_BUSY; - } - } -#else - /* Use the built-in recursive mutexes if they are available. - */ - if( pthread_mutex_trylock(&p->mutex)==0 ){ -#if SQLITE_MUTEX_NREF - p->owner = pthread_self(); - p->nRef++; -#endif - rc = SQLITE_OK; - }else{ - rc = SQLITE_BUSY; - } -#endif - -#ifdef SQLITE_DEBUG - if( rc==SQLITE_OK && p->trace ){ - printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); - } -#endif - return rc; -} - -/* -** The sqlite3_mutex_leave() routine exits a mutex that was -** previously entered by the same thread. The behavior -** is undefined if the mutex is not currently entered or -** is not currently allocated. SQLite will never do either. -*/ -static void pthreadMutexLeave(sqlite3_mutex *p){ - assert( pthreadMutexHeld(p) ); -#if SQLITE_MUTEX_NREF - p->nRef--; - if( p->nRef==0 ) p->owner = 0; -#endif - assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE ); - -#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX - if( p->nRef==0 ){ - pthread_mutex_unlock(&p->mutex); - } -#else - pthread_mutex_unlock(&p->mutex); -#endif - -#ifdef SQLITE_DEBUG - if( p->trace ){ - printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); - } -#endif -} - -SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ - static const sqlite3_mutex_methods sMutex = { - pthreadMutexInit, - pthreadMutexEnd, - pthreadMutexAlloc, - pthreadMutexFree, - pthreadMutexEnter, - pthreadMutexTry, - pthreadMutexLeave, -#ifdef SQLITE_DEBUG - pthreadMutexHeld, - pthreadMutexNotheld -#else - 0, - 0 -#endif - }; - - return &sMutex; -} - -#endif /* SQLITE_MUTEX_PTHREADS */ - -/************** End of mutex_unix.c ******************************************/ -/************** Begin file mutex_w32.c ***************************************/ -/* -** 2007 August 14 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file contains the C functions that implement mutexes for Win32. -*/ -/* #include "sqliteInt.h" */ - -#if SQLITE_OS_WIN -/* -** Include code that is common to all os_*.c files -*/ -/************** Include os_common.h in the middle of mutex_w32.c *************/ -/************** Begin file os_common.h ***************************************/ -/* -** 2004 May 22 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This file contains macros and a little bit of code that is common to -** all of the platform-specific files (os_*.c) and is #included into those -** files. -** -** This file should be #included by the os_*.c files only. It is not a -** general purpose header file. -*/ -#ifndef _OS_COMMON_H_ -#define _OS_COMMON_H_ - -/* -** At least two bugs have slipped in because we changed the MEMORY_DEBUG -** macro to SQLITE_DEBUG and some older makefiles have not yet made the -** switch. The following code should catch this problem at compile-time. -*/ -#ifdef MEMORY_DEBUG -# error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead." -#endif - -/* -** Macros for performance tracing. Normally turned off. Only works -** on i486 hardware. -*/ -#ifdef SQLITE_PERFORMANCE_TRACE - -/* -** hwtime.h contains inline assembler code for implementing -** high-performance timing routines. -*/ -/************** Include hwtime.h in the middle of os_common.h ****************/ -/************** Begin file hwtime.h ******************************************/ -/* -** 2008 May 27 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This file contains inline asm code for retrieving "high-performance" -** counters for x86 class CPUs. -*/ -#ifndef SQLITE_HWTIME_H -#define SQLITE_HWTIME_H - -/* -** The following routine only works on pentium-class (or newer) processors. -** It uses the RDTSC opcode to read the cycle count value out of the -** processor and returns that value. This can be used for high-res -** profiling. -*/ -#if (defined(__GNUC__) || defined(_MSC_VER)) && \ - (defined(i386) || defined(__i386__) || defined(_M_IX86)) - - #if defined(__GNUC__) - - __inline__ sqlite_uint64 sqlite3Hwtime(void){ - unsigned int lo, hi; - __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); - return (sqlite_uint64)hi << 32 | lo; - } - - #elif defined(_MSC_VER) - - __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){ - __asm { - rdtsc - ret ; return value at EDX:EAX - } - } - - #endif - -#elif (defined(__GNUC__) && defined(__x86_64__)) - - __inline__ sqlite_uint64 sqlite3Hwtime(void){ - unsigned long val; - __asm__ __volatile__ ("rdtsc" : "=A" (val)); - return val; - } - -#elif (defined(__GNUC__) && defined(__ppc__)) - - __inline__ sqlite_uint64 sqlite3Hwtime(void){ - unsigned long long retval; - unsigned long junk; - __asm__ __volatile__ ("\n\ - 1: mftbu %1\n\ - mftb %L0\n\ - mftbu %0\n\ - cmpw %0,%1\n\ - bne 1b" - : "=r" (retval), "=r" (junk)); - return retval; - } - -#else - - #error Need implementation of sqlite3Hwtime() for your platform. - - /* - ** To compile without implementing sqlite3Hwtime() for your platform, - ** you can remove the above #error and use the following - ** stub function. You will lose timing support for many - ** of the debugging and testing utilities, but it should at - ** least compile and run. - */ -SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } - -#endif - -#endif /* !defined(SQLITE_HWTIME_H) */ - -/************** End of hwtime.h **********************************************/ -/************** Continuing where we left off in os_common.h ******************/ - -static sqlite_uint64 g_start; -static sqlite_uint64 g_elapsed; -#define TIMER_START g_start=sqlite3Hwtime() -#define TIMER_END g_elapsed=sqlite3Hwtime()-g_start -#define TIMER_ELAPSED g_elapsed -#else -#define TIMER_START -#define TIMER_END -#define TIMER_ELAPSED ((sqlite_uint64)0) -#endif - -/* -** If we compile with the SQLITE_TEST macro set, then the following block -** of code will give us the ability to simulate a disk I/O error. This -** is used for testing the I/O recovery logic. -*/ -#if defined(SQLITE_TEST) -SQLITE_API extern int sqlite3_io_error_hit; -SQLITE_API extern int sqlite3_io_error_hardhit; -SQLITE_API extern int sqlite3_io_error_pending; -SQLITE_API extern int sqlite3_io_error_persist; -SQLITE_API extern int sqlite3_io_error_benign; -SQLITE_API extern int sqlite3_diskfull_pending; -SQLITE_API extern int sqlite3_diskfull; -#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X) -#define SimulateIOError(CODE) \ - if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \ - || sqlite3_io_error_pending-- == 1 ) \ - { local_ioerr(); CODE; } -static void local_ioerr(){ - IOTRACE(("IOERR\n")); - sqlite3_io_error_hit++; - if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++; -} -#define SimulateDiskfullError(CODE) \ - if( sqlite3_diskfull_pending ){ \ - if( sqlite3_diskfull_pending == 1 ){ \ - local_ioerr(); \ - sqlite3_diskfull = 1; \ - sqlite3_io_error_hit = 1; \ - CODE; \ - }else{ \ - sqlite3_diskfull_pending--; \ - } \ - } -#else -#define SimulateIOErrorBenign(X) -#define SimulateIOError(A) -#define SimulateDiskfullError(A) -#endif /* defined(SQLITE_TEST) */ - -/* -** When testing, keep a count of the number of open files. -*/ -#if defined(SQLITE_TEST) -SQLITE_API extern int sqlite3_open_file_count; -#define OpenCounter(X) sqlite3_open_file_count+=(X) -#else -#define OpenCounter(X) -#endif /* defined(SQLITE_TEST) */ - -#endif /* !defined(_OS_COMMON_H_) */ - -/************** End of os_common.h *******************************************/ -/************** Continuing where we left off in mutex_w32.c ******************/ - -/* -** Include the header file for the Windows VFS. -*/ -/************** Include os_win.h in the middle of mutex_w32.c ****************/ -/************** Begin file os_win.h ******************************************/ -/* -** 2013 November 25 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This file contains code that is specific to Windows. -*/ -#ifndef SQLITE_OS_WIN_H -#define SQLITE_OS_WIN_H - -/* -** Include the primary Windows SDK header file. -*/ -#include "windows.h" - -#ifdef __CYGWIN__ -# include -# include /* amalgamator: dontcache */ -#endif - -/* -** Determine if we are dealing with Windows NT. -** -** We ought to be able to determine if we are compiling for Windows 9x or -** Windows NT using the _WIN32_WINNT macro as follows: -** -** #if defined(_WIN32_WINNT) -** # define SQLITE_OS_WINNT 1 -** #else -** # define SQLITE_OS_WINNT 0 -** #endif -** -** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as -** it ought to, so the above test does not work. We'll just assume that -** everything is Windows NT unless the programmer explicitly says otherwise -** by setting SQLITE_OS_WINNT to 0. -*/ -#if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT) -# define SQLITE_OS_WINNT 1 -#endif - -/* -** Determine if we are dealing with Windows CE - which has a much reduced -** API. -*/ -#if defined(_WIN32_WCE) -# define SQLITE_OS_WINCE 1 -#else -# define SQLITE_OS_WINCE 0 -#endif - -/* -** Determine if we are dealing with WinRT, which provides only a subset of -** the full Win32 API. -*/ -#if !defined(SQLITE_OS_WINRT) -# define SQLITE_OS_WINRT 0 -#endif - -/* -** For WinCE, some API function parameters do not appear to be declared as -** volatile. -*/ -#if SQLITE_OS_WINCE -# define SQLITE_WIN32_VOLATILE -#else -# define SQLITE_WIN32_VOLATILE volatile -#endif - -/* -** For some Windows sub-platforms, the _beginthreadex() / _endthreadex() -** functions are not available (e.g. those not using MSVC, Cygwin, etc). -*/ -#if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \ - SQLITE_THREADSAFE>0 && !defined(__CYGWIN__) -# define SQLITE_OS_WIN_THREADS 1 -#else -# define SQLITE_OS_WIN_THREADS 0 -#endif - -#endif /* SQLITE_OS_WIN_H */ - -/************** End of os_win.h **********************************************/ -/************** Continuing where we left off in mutex_w32.c ******************/ -#endif - -/* -** The code in this file is only used if we are compiling multithreaded -** on a Win32 system. -*/ -#ifdef SQLITE_MUTEX_W32 - -/* -** Each recursive mutex is an instance of the following structure. -*/ -struct sqlite3_mutex { - CRITICAL_SECTION mutex; /* Mutex controlling the lock */ - int id; /* Mutex type */ -#ifdef SQLITE_DEBUG - volatile int nRef; /* Number of enterances */ - volatile DWORD owner; /* Thread holding this mutex */ - volatile int 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 { SQLITE_W32_MUTEX_INITIALIZER, 0, \ - 0L, (DWORD)0, 0 } -#else -#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 } -#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, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER, - SQLITE3_MUTEX_INITIALIZER -}; - -static int winMutex_isInit = 0; -static int winMutex_isNt = -1; /* <0 means "need to query" */ - -/* As the winMutexInit() and winMutexEnd() functions are called as part -** of the sqlite3_initialize() and sqlite3_shutdown() processing, the -** "interlocked" magic used here is probably not strictly necessary. -*/ -static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0; - -SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */ -SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */ - -static int winMutexInit(void){ - /* The first to increment to 1 does actual initialization */ - if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){ - int i; - for(i=0; i -**
  • SQLITE_MUTEX_FAST -**
  • SQLITE_MUTEX_RECURSIVE -**
  • SQLITE_MUTEX_STATIC_MASTER -**
  • SQLITE_MUTEX_STATIC_MEM -**
  • SQLITE_MUTEX_STATIC_OPEN -**
  • SQLITE_MUTEX_STATIC_PRNG -**
  • SQLITE_MUTEX_STATIC_LRU -**
  • SQLITE_MUTEX_STATIC_PMEM -**
  • SQLITE_MUTEX_STATIC_APP1 -**
  • SQLITE_MUTEX_STATIC_APP2 -**
  • SQLITE_MUTEX_STATIC_APP3 -**
  • SQLITE_MUTEX_STATIC_VFS1 -**
  • SQLITE_MUTEX_STATIC_VFS2 -**
  • SQLITE_MUTEX_STATIC_VFS3 -** -** -** The first two constants cause sqlite3_mutex_alloc() to create -** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE -** is used but not necessarily so when SQLITE_MUTEX_FAST is used. -** The mutex implementation does not need to make a distinction -** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does -** not want to. But SQLite will only request a recursive mutex in -** cases where it really needs one. If a faster non-recursive mutex -** implementation is available on the host platform, the mutex subsystem -** might return such a mutex in response to SQLITE_MUTEX_FAST. -** -** The other allowed parameters to sqlite3_mutex_alloc() each return -** a pointer to a static preexisting mutex. Six static mutexes are -** used by the current version of SQLite. Future versions of SQLite -** may add additional static mutexes. Static mutexes are for internal -** use by SQLite only. Applications that use SQLite mutexes should -** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or -** SQLITE_MUTEX_RECURSIVE. -** -** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST -** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() -** returns a different mutex on every call. But for the static -** mutex types, the same mutex is returned on every call that has -** the same type number. -*/ -static sqlite3_mutex *winMutexAlloc(int iType){ - sqlite3_mutex *p; - - switch( iType ){ - case SQLITE_MUTEX_FAST: - case SQLITE_MUTEX_RECURSIVE: { - p = sqlite3MallocZero( sizeof(*p) ); - if( p ){ - p->id = iType; -#ifdef SQLITE_DEBUG -#ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC - p->trace = 1; -#endif -#endif -#if SQLITE_OS_WINRT - InitializeCriticalSectionEx(&p->mutex, 0, 0); -#else - InitializeCriticalSection(&p->mutex); -#endif - } - break; - } - default: { -#ifdef SQLITE_ENABLE_API_ARMOR - if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){ - (void)SQLITE_MISUSE_BKPT; - return 0; - } -#endif - p = &winMutex_staticMutexes[iType-2]; - p->id = iType; -#ifdef SQLITE_DEBUG -#ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC - p->trace = 1; -#endif -#endif - break; - } - } - return p; -} - - -/* -** This routine deallocates a previously -** allocated mutex. SQLite is careful to deallocate every -** mutex that it allocates. -*/ -static void winMutexFree(sqlite3_mutex *p){ - assert( p ); - assert( p->nRef==0 && p->owner==0 ); - if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){ - DeleteCriticalSection(&p->mutex); - sqlite3_free(p); - }else{ -#ifdef SQLITE_ENABLE_API_ARMOR - (void)SQLITE_MISUSE_BKPT; -#endif - } -} - -/* -** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt -** to enter a mutex. If another thread is already within the mutex, -** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return -** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK -** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can -** be entered multiple times by the same thread. In such cases the, -** mutex must be exited an equal number of times before another thread -** can enter. If the same thread tries to enter any other kind of mutex -** more than once, the behavior is undefined. -*/ -static void winMutexEnter(sqlite3_mutex *p){ -#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) - DWORD tid = GetCurrentThreadId(); -#endif -#ifdef SQLITE_DEBUG - assert( p ); - assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) ); -#else - assert( p ); -#endif - assert( winMutex_isInit==1 ); - EnterCriticalSection(&p->mutex); -#ifdef SQLITE_DEBUG - assert( p->nRef>0 || p->owner==0 ); - p->owner = tid; - p->nRef++; - if( p->trace ){ - OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n", - tid, p->id, p, p->trace, p->nRef)); - } -#endif -} - -static int winMutexTry(sqlite3_mutex *p){ -#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) - DWORD tid = GetCurrentThreadId(); -#endif - int rc = SQLITE_BUSY; - assert( p ); - assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) ); - /* - ** The sqlite3_mutex_try() routine is very rarely used, and when it - ** is used it is merely an optimization. So it is OK for it to always - ** fail. - ** - ** The TryEnterCriticalSection() interface is only available on WinNT. - ** And some windows compilers complain if you try to use it without - ** first doing some #defines that prevent SQLite from building on Win98. - ** For that reason, we will omit this optimization for now. See - ** ticket #2685. - */ -#if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400 - assert( winMutex_isInit==1 ); - assert( winMutex_isNt>=-1 && winMutex_isNt<=1 ); - if( winMutex_isNt<0 ){ - winMutex_isNt = sqlite3_win32_is_nt(); - } - assert( winMutex_isNt==0 || winMutex_isNt==1 ); - if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){ -#ifdef SQLITE_DEBUG - p->owner = tid; - p->nRef++; -#endif - rc = SQLITE_OK; - } -#else - UNUSED_PARAMETER(p); -#endif -#ifdef SQLITE_DEBUG - if( p->trace ){ - OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n", - tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc))); - } -#endif - return rc; -} - -/* -** The sqlite3_mutex_leave() routine exits a mutex that was -** previously entered by the same thread. The behavior -** is undefined if the mutex is not currently entered or -** is not currently allocated. SQLite will never do either. -*/ -static void winMutexLeave(sqlite3_mutex *p){ -#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) - DWORD tid = GetCurrentThreadId(); -#endif - assert( p ); -#ifdef SQLITE_DEBUG - assert( p->nRef>0 ); - assert( p->owner==tid ); - p->nRef--; - if( p->nRef==0 ) p->owner = 0; - assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE ); -#endif - assert( winMutex_isInit==1 ); - LeaveCriticalSection(&p->mutex); -#ifdef SQLITE_DEBUG - if( p->trace ){ - OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n", - tid, p->id, p, p->trace, p->nRef)); - } -#endif -} - -SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){ - static const sqlite3_mutex_methods sMutex = { - winMutexInit, - winMutexEnd, - winMutexAlloc, - winMutexFree, - winMutexEnter, - winMutexTry, - winMutexLeave, -#ifdef SQLITE_DEBUG - winMutexHeld, - winMutexNotheld -#else - 0, - 0 -#endif - }; - return &sMutex; -} - -#endif /* SQLITE_MUTEX_W32 */ - -/************** End of mutex_w32.c *******************************************/ -/************** Begin file malloc.c ******************************************/ -/* -** 2001 September 15 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** -** Memory allocation functions used throughout sqlite. -*/ -/* #include "sqliteInt.h" */ -/* #include */ - -/* -** Attempt to release up to n bytes of non-essential memory currently -** held by SQLite. An example of non-essential memory is memory used to -** cache database pages that are not currently in use. -*/ -SQLITE_API int sqlite3_release_memory(int n){ -#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT - return sqlite3PcacheReleaseMemory(n); -#else - /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine - ** is a no-op returning zero if SQLite is not compiled with - ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */ - UNUSED_PARAMETER(n); - return 0; -#endif -} - -/* -** State information local to the memory allocation subsystem. -*/ -static SQLITE_WSD struct Mem0Global { - sqlite3_mutex *mutex; /* Mutex to serialize access */ - sqlite3_int64 alarmThreshold; /* The soft heap limit */ - - /* - ** True if heap is nearly "full" where "full" is defined by the - ** sqlite3_soft_heap_limit() setting. - */ - int nearlyFull; -} mem0 = { 0, 0, 0 }; - -#define mem0 GLOBAL(struct Mem0Global, mem0) - -/* -** Return the memory allocator mutex. sqlite3_status() needs it. -*/ -SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){ - return mem0.mutex; -} - -#ifndef SQLITE_OMIT_DEPRECATED -/* -** Deprecated external interface. It used to set an alarm callback -** that was invoked when memory usage grew too large. Now it is a -** no-op. -*/ -SQLITE_API int sqlite3_memory_alarm( - void(*xCallback)(void *pArg, sqlite3_int64 used,int N), - void *pArg, - sqlite3_int64 iThreshold -){ - (void)xCallback; - (void)pArg; - (void)iThreshold; - return SQLITE_OK; -} -#endif - -/* -** Set the soft heap-size limit for the library. Passing a zero or -** negative value indicates no limit. -*/ -SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){ - sqlite3_int64 priorLimit; - sqlite3_int64 excess; - sqlite3_int64 nUsed; -#ifndef SQLITE_OMIT_AUTOINIT - int rc = sqlite3_initialize(); - if( rc ) return -1; -#endif - sqlite3_mutex_enter(mem0.mutex); - priorLimit = mem0.alarmThreshold; - if( n<0 ){ - sqlite3_mutex_leave(mem0.mutex); - return priorLimit; - } - mem0.alarmThreshold = n; - nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); - mem0.nearlyFull = (n>0 && n<=nUsed); - sqlite3_mutex_leave(mem0.mutex); - excess = sqlite3_memory_used() - n; - if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff)); - return priorLimit; -} -SQLITE_API void sqlite3_soft_heap_limit(int n){ - if( n<0 ) n = 0; - sqlite3_soft_heap_limit64(n); -} - -/* -** Initialize the memory allocation subsystem. -*/ -SQLITE_PRIVATE int sqlite3MallocInit(void){ - int rc; - if( sqlite3GlobalConfig.m.xMalloc==0 ){ - sqlite3MemSetDefault(); - } - memset(&mem0, 0, sizeof(mem0)); - mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); - if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512 - || sqlite3GlobalConfig.nPage<=0 ){ - sqlite3GlobalConfig.pPage = 0; - sqlite3GlobalConfig.szPage = 0; - } - rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData); - if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0)); - return rc; -} - -/* -** Return true if the heap is currently under memory pressure - in other -** words if the amount of heap used is close to the limit set by -** sqlite3_soft_heap_limit(). -*/ -SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){ - return mem0.nearlyFull; -} - -/* -** Deinitialize the memory allocation subsystem. -*/ -SQLITE_PRIVATE void sqlite3MallocEnd(void){ - if( sqlite3GlobalConfig.m.xShutdown ){ - sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData); - } - memset(&mem0, 0, sizeof(mem0)); -} - -/* -** Return the amount of memory currently checked out. -*/ -SQLITE_API sqlite3_int64 sqlite3_memory_used(void){ - sqlite3_int64 res, mx; - sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0); - return res; -} - -/* -** Return the maximum amount of memory that has ever been -** checked out since either the beginning of this process -** or since the most recent reset. -*/ -SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){ - sqlite3_int64 res, mx; - sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag); - return mx; -} - -/* -** Trigger the alarm -*/ -static void sqlite3MallocAlarm(int nByte){ - if( mem0.alarmThreshold<=0 ) return; - sqlite3_mutex_leave(mem0.mutex); - sqlite3_release_memory(nByte); - sqlite3_mutex_enter(mem0.mutex); -} - -/* -** Do a memory allocation with statistics and alarms. Assume the -** lock is already held. -*/ -static void mallocWithAlarm(int n, void **pp){ - void *p; - int nFull; - assert( sqlite3_mutex_held(mem0.mutex) ); - assert( n>0 ); - - /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal - ** implementation of malloc_good_size(), which must be called in debug - ** mode and specifically when the DMD "Dark Matter Detector" is enabled - ** or else a crash results. Hence, do not attempt to optimize out the - ** following xRoundup() call. */ - nFull = sqlite3GlobalConfig.m.xRoundup(n); - -#ifdef SQLITE_MAX_MEMORY - if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nFull>SQLITE_MAX_MEMORY ){ - *pp = 0; - return; - } -#endif - - sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n); - if( mem0.alarmThreshold>0 ){ - sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED); - if( nUsed >= mem0.alarmThreshold - nFull ){ - mem0.nearlyFull = 1; - sqlite3MallocAlarm(nFull); - }else{ - mem0.nearlyFull = 0; - } - } - p = sqlite3GlobalConfig.m.xMalloc(nFull); -#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT - if( p==0 && mem0.alarmThreshold>0 ){ - sqlite3MallocAlarm(nFull); - p = sqlite3GlobalConfig.m.xMalloc(nFull); - } -#endif - if( p ){ - nFull = sqlite3MallocSize(p); - sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull); - sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1); - } - *pp = p; -} - -/* -** Allocate memory. This routine is like sqlite3_malloc() except that it -** assumes the memory subsystem has already been initialized. -*/ -SQLITE_PRIVATE void *sqlite3Malloc(u64 n){ - void *p; - if( n==0 || n>=0x7fffff00 ){ - /* A memory allocation of a number of bytes which is near the maximum - ** signed integer value might cause an integer overflow inside of the - ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving - ** 255 bytes of overhead. SQLite itself will never use anything near - ** this amount. The only way to reach the limit is with sqlite3_malloc() */ - p = 0; - }else if( sqlite3GlobalConfig.bMemstat ){ - sqlite3_mutex_enter(mem0.mutex); - mallocWithAlarm((int)n, &p); - sqlite3_mutex_leave(mem0.mutex); - }else{ - p = sqlite3GlobalConfig.m.xMalloc((int)n); - } - assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */ - return p; -} - -/* -** This version of the memory allocation is for use by the application. -** First make sure the memory subsystem is initialized, then do the -** allocation. -*/ -SQLITE_API void *sqlite3_malloc(int n){ -#ifndef SQLITE_OMIT_AUTOINIT - if( sqlite3_initialize() ) return 0; -#endif - return n<=0 ? 0 : sqlite3Malloc(n); -} -SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){ -#ifndef SQLITE_OMIT_AUTOINIT - if( sqlite3_initialize() ) return 0; -#endif - return sqlite3Malloc(n); -} - -/* -** TRUE if p is a lookaside memory allocation from db -*/ -#ifndef SQLITE_OMIT_LOOKASIDE -static int isLookaside(sqlite3 *db, void *p){ - return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd); -} -#else -#define isLookaside(A,B) 0 -#endif - -/* -** Return the size of a memory allocation previously obtained from -** sqlite3Malloc() or sqlite3_malloc(). -*/ -SQLITE_PRIVATE int sqlite3MallocSize(void *p){ - assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); - return sqlite3GlobalConfig.m.xSize(p); -} -SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){ - assert( p!=0 ); - if( db==0 || !isLookaside(db,p) ){ -#ifdef SQLITE_DEBUG - if( db==0 ){ - assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) ); - assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); - }else{ - assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); - assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); - } -#endif - return sqlite3GlobalConfig.m.xSize(p); - }else{ - assert( sqlite3_mutex_held(db->mutex) ); - return db->lookaside.sz; - } -} -SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){ - assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) ); - assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); - return p ? sqlite3GlobalConfig.m.xSize(p) : 0; -} - -/* -** Free memory previously obtained from sqlite3Malloc(). -*/ -SQLITE_API void sqlite3_free(void *p){ - if( p==0 ) return; /* IMP: R-49053-54554 */ - assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) ); - assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) ); - if( sqlite3GlobalConfig.bMemstat ){ - sqlite3_mutex_enter(mem0.mutex); - sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p)); - sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1); - sqlite3GlobalConfig.m.xFree(p); - sqlite3_mutex_leave(mem0.mutex); - }else{ - sqlite3GlobalConfig.m.xFree(p); - } -} - -/* -** Add the size of memory allocation "p" to the count in -** *db->pnBytesFreed. -*/ -static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){ - *db->pnBytesFreed += sqlite3DbMallocSize(db,p); -} - -/* -** Free memory that might be associated with a particular database -** connection. Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op. -** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL. -*/ -SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3 *db, void *p){ - assert( db==0 || sqlite3_mutex_held(db->mutex) ); - assert( p!=0 ); - if( db ){ - if( db->pnBytesFreed ){ - measureAllocationSize(db, p); - return; - } - if( isLookaside(db, p) ){ - LookasideSlot *pBuf = (LookasideSlot*)p; -#ifdef SQLITE_DEBUG - /* Trash all content in the buffer being freed */ - memset(p, 0xaa, db->lookaside.sz); -#endif - pBuf->pNext = db->lookaside.pFree; - db->lookaside.pFree = pBuf; - return; - } - } - assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); - assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); - assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) ); - sqlite3MemdebugSetType(p, MEMTYPE_HEAP); - sqlite3_free(p); -} -SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){ - assert( db==0 || sqlite3_mutex_held(db->mutex) ); - if( p ) sqlite3DbFreeNN(db, p); -} - -/* -** Change the size of an existing memory allocation -*/ -SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){ - int nOld, nNew, nDiff; - void *pNew; - assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) ); - assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) ); - if( pOld==0 ){ - return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */ - } - if( nBytes==0 ){ - sqlite3_free(pOld); /* IMP: R-26507-47431 */ - return 0; - } - if( nBytes>=0x7fffff00 ){ - /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */ - return 0; - } - nOld = sqlite3MallocSize(pOld); - /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second - ** argument to xRealloc is always a value returned by a prior call to - ** xRoundup. */ - nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes); - if( nOld==nNew ){ - pNew = pOld; - }else if( sqlite3GlobalConfig.bMemstat ){ - sqlite3_mutex_enter(mem0.mutex); - sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes); - nDiff = nNew - nOld; - if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= - mem0.alarmThreshold-nDiff ){ - sqlite3MallocAlarm(nDiff); - } - pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); - if( pNew==0 && mem0.alarmThreshold>0 ){ - sqlite3MallocAlarm((int)nBytes); - pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); - } - if( pNew ){ - nNew = sqlite3MallocSize(pNew); - sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld); - } - sqlite3_mutex_leave(mem0.mutex); - }else{ - pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew); - } - assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */ - return pNew; -} - -/* -** The public interface to sqlite3Realloc. Make sure that the memory -** subsystem is initialized prior to invoking sqliteRealloc. -*/ -SQLITE_API void *sqlite3_realloc(void *pOld, int n){ -#ifndef SQLITE_OMIT_AUTOINIT - if( sqlite3_initialize() ) return 0; -#endif - if( n<0 ) n = 0; /* IMP: R-26507-47431 */ - return sqlite3Realloc(pOld, n); -} -SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){ -#ifndef SQLITE_OMIT_AUTOINIT - if( sqlite3_initialize() ) return 0; -#endif - return sqlite3Realloc(pOld, n); -} - - -/* -** Allocate and zero memory. -*/ -SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){ - void *p = sqlite3Malloc(n); - if( p ){ - memset(p, 0, (size_t)n); - } - return p; -} - -/* -** Allocate and zero memory. If the allocation fails, make -** the mallocFailed flag in the connection pointer. -*/ -SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){ - void *p; - testcase( db==0 ); - p = sqlite3DbMallocRaw(db, n); - if( p ) memset(p, 0, (size_t)n); - return p; -} - - -/* Finish the work of sqlite3DbMallocRawNN for the unusual and -** slower case when the allocation cannot be fulfilled using lookaside. -*/ -static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){ - void *p; - assert( db!=0 ); - p = sqlite3Malloc(n); - if( !p ) sqlite3OomFault(db); - sqlite3MemdebugSetType(p, - (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP); - return p; -} - -/* -** Allocate memory, either lookaside (if possible) or heap. -** If the allocation fails, set the mallocFailed flag in -** the connection pointer. -** -** If db!=0 and db->mallocFailed is true (indicating a prior malloc -** failure on the same database connection) then always return 0. -** Hence for a particular database connection, once malloc starts -** failing, it fails consistently until mallocFailed is reset. -** This is an important assumption. There are many places in the -** code that do things like this: -** -** int *a = (int*)sqlite3DbMallocRaw(db, 100); -** int *b = (int*)sqlite3DbMallocRaw(db, 200); -** if( b ) a[10] = 9; -** -** In other words, if a subsequent malloc (ex: "b") worked, it is assumed -** that all prior mallocs (ex: "a") worked too. -** -** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is -** not a NULL pointer. -*/ -SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){ - void *p; - if( db ) return sqlite3DbMallocRawNN(db, n); - p = sqlite3Malloc(n); - sqlite3MemdebugSetType(p, MEMTYPE_HEAP); - return p; -} -SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){ -#ifndef SQLITE_OMIT_LOOKASIDE - LookasideSlot *pBuf; - assert( db!=0 ); - assert( sqlite3_mutex_held(db->mutex) ); - assert( db->pnBytesFreed==0 ); - if( db->lookaside.bDisable==0 ){ - assert( db->mallocFailed==0 ); - if( n>db->lookaside.sz ){ - db->lookaside.anStat[1]++; - }else if( (pBuf = db->lookaside.pFree)!=0 ){ - db->lookaside.pFree = pBuf->pNext; - db->lookaside.anStat[0]++; - return (void*)pBuf; - }else if( (pBuf = db->lookaside.pInit)!=0 ){ - db->lookaside.pInit = pBuf->pNext; - db->lookaside.anStat[0]++; - return (void*)pBuf; - }else{ - db->lookaside.anStat[2]++; - } - }else if( db->mallocFailed ){ - return 0; - } -#else - assert( db!=0 ); - assert( sqlite3_mutex_held(db->mutex) ); - assert( db->pnBytesFreed==0 ); - if( db->mallocFailed ){ - return 0; - } -#endif - return dbMallocRawFinish(db, n); -} - -/* Forward declaration */ -static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n); - -/* -** Resize the block of memory pointed to by p to n bytes. If the -** resize fails, set the mallocFailed flag in the connection object. -*/ -SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){ - assert( db!=0 ); - if( p==0 ) return sqlite3DbMallocRawNN(db, n); - assert( sqlite3_mutex_held(db->mutex) ); - if( isLookaside(db,p) && n<=db->lookaside.sz ) return p; - return dbReallocFinish(db, p, n); -} -static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){ - void *pNew = 0; - assert( db!=0 ); - assert( p!=0 ); - if( db->mallocFailed==0 ){ - if( isLookaside(db, p) ){ - pNew = sqlite3DbMallocRawNN(db, n); - if( pNew ){ - memcpy(pNew, p, db->lookaside.sz); - sqlite3DbFree(db, p); - } - }else{ - assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); - assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) ); - sqlite3MemdebugSetType(p, MEMTYPE_HEAP); - pNew = sqlite3_realloc64(p, n); - if( !pNew ){ - sqlite3OomFault(db); - } - sqlite3MemdebugSetType(pNew, - (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP)); - } - } - return pNew; -} - -/* -** Attempt to reallocate p. If the reallocation fails, then free p -** and set the mallocFailed flag in the database connection. -*/ -SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){ - void *pNew; - pNew = sqlite3DbRealloc(db, p, n); - if( !pNew ){ - sqlite3DbFree(db, p); - } - return pNew; -} - -/* -** Make a copy of a string in memory obtained from sqliteMalloc(). These -** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This -** is because when memory debugging is turned on, these two functions are -** called via macros that record the current file and line number in the -** ThreadData structure. -*/ -SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){ - char *zNew; - size_t n; - if( z==0 ){ - return 0; - } - n = strlen(z) + 1; - zNew = sqlite3DbMallocRaw(db, n); - if( zNew ){ - memcpy(zNew, z, n); - } - return zNew; -} -SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){ - char *zNew; - assert( db!=0 ); - if( z==0 ){ - return 0; - } - assert( (n&0x7fffffff)==n ); - zNew = sqlite3DbMallocRawNN(db, n+1); - if( zNew ){ - memcpy(zNew, z, (size_t)n); - zNew[n] = 0; - } - return zNew; -} - -/* -** Free any prior content in *pz and replace it with a copy of zNew. -*/ -SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){ - sqlite3DbFree(db, *pz); - *pz = sqlite3DbStrDup(db, zNew); -} - -/* -** Call this routine to record the fact that an OOM (out-of-memory) error -** has happened. This routine will set db->mallocFailed, and also -** temporarily disable the lookaside memory allocator and interrupt -** any running VDBEs. -*/ -SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){ - if( db->mallocFailed==0 && db->bBenignMalloc==0 ){ - db->mallocFailed = 1; - if( db->nVdbeExec>0 ){ - db->u1.isInterrupted = 1; - } - db->lookaside.bDisable++; - } -} - -/* -** This routine reactivates the memory allocator and clears the -** db->mallocFailed flag as necessary. -** -** The memory allocator is not restarted if there are running -** VDBEs. -*/ -SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){ - if( db->mallocFailed && db->nVdbeExec==0 ){ - db->mallocFailed = 0; - db->u1.isInterrupted = 0; - assert( db->lookaside.bDisable>0 ); - db->lookaside.bDisable--; - } -} - -/* -** Take actions at the end of an API call to indicate an OOM error -*/ -static SQLITE_NOINLINE int apiOomError(sqlite3 *db){ - sqlite3OomClear(db); - sqlite3Error(db, SQLITE_NOMEM); - return SQLITE_NOMEM_BKPT; -} - -/* -** This function must be called before exiting any API function (i.e. -** returning control to the user) that has called sqlite3_malloc or -** sqlite3_realloc. -** -** The returned value is normally a copy of the second argument to this -** function. However, if a malloc() failure has occurred since the previous -** invocation SQLITE_NOMEM is returned instead. -** -** If an OOM as occurred, then the connection error-code (the value -** returned by sqlite3_errcode()) is set to SQLITE_NOMEM. -*/ -SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){ - /* If the db handle must hold the connection handle mutex here. - ** Otherwise the read (and possible write) of db->mallocFailed - ** is unsafe, as is the call to sqlite3Error(). - */ - assert( db!=0 ); - assert( sqlite3_mutex_held(db->mutex) ); - if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){ - return apiOomError(db); - } - return rc & db->errMask; -} - -/************** End of malloc.c **********************************************/ -/************** Begin file printf.c ******************************************/ -/* -** The "printf" code that follows dates from the 1980's. It is in -** the public domain. -** -************************************************************************** -** -** This file contains code for a set of "printf"-like routines. These -** routines format strings much like the printf() from the standard C -** library, though the implementation here has enhancements to support -** SQLite. -*/ -/* #include "sqliteInt.h" */ - -/* -** Conversion types fall into various categories as defined by the -** following enumeration. -*/ -#define etRADIX 0 /* non-decimal integer types. %x %o */ -#define etFLOAT 1 /* Floating point. %f */ -#define etEXP 2 /* Exponentional notation. %e and %E */ -#define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */ -#define etSIZE 4 /* Return number of characters processed so far. %n */ -#define etSTRING 5 /* Strings. %s */ -#define etDYNSTRING 6 /* Dynamically allocated strings. %z */ -#define etPERCENT 7 /* Percent symbol. %% */ -#define etCHARX 8 /* Characters. %c */ -/* The rest are extensions, not normally found in printf() */ -#define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */ -#define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '', - NULL pointers replaced by SQL NULL. %Q */ -#define etTOKEN 11 /* a pointer to a Token structure */ -#define etSRCLIST 12 /* a pointer to a SrcList */ -#define etPOINTER 13 /* The %p conversion */ -#define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */ -#define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */ -#define etDECIMAL 16 /* %d or %u, but not %x, %o */ - -#define etINVALID 17 /* Any unrecognized conversion type */ - - -/* -** An "etByte" is an 8-bit unsigned value. -*/ -typedef unsigned char etByte; - -/* -** Each builtin conversion character (ex: the 'd' in "%d") is described -** by an instance of the following structure -*/ -typedef struct et_info { /* Information about each format field */ - char fmttype; /* The format field code letter */ - etByte base; /* The base for radix conversion */ - etByte flags; /* One or more of FLAG_ constants below */ - etByte type; /* Conversion paradigm */ - etByte charset; /* Offset into aDigits[] of the digits string */ - etByte prefix; /* Offset into aPrefix[] of the prefix string */ -} et_info; - -/* -** Allowed values for et_info.flags -*/ -#define FLAG_SIGNED 1 /* True if the value to convert is signed */ -#define FLAG_STRING 4 /* Allow infinite precision */ - - -/* -** The following table is searched linearly, so it is good to put the -** most frequently used conversion types first. -*/ -static const char aDigits[] = "0123456789ABCDEF0123456789abcdef"; -static const char aPrefix[] = "-x0\000X0"; -static const et_info fmtinfo[] = { - { 'd', 10, 1, etDECIMAL, 0, 0 }, - { 's', 0, 4, etSTRING, 0, 0 }, - { 'g', 0, 1, etGENERIC, 30, 0 }, - { 'z', 0, 4, etDYNSTRING, 0, 0 }, - { 'q', 0, 4, etSQLESCAPE, 0, 0 }, - { 'Q', 0, 4, etSQLESCAPE2, 0, 0 }, - { 'w', 0, 4, etSQLESCAPE3, 0, 0 }, - { 'c', 0, 0, etCHARX, 0, 0 }, - { 'o', 8, 0, etRADIX, 0, 2 }, - { 'u', 10, 0, etDECIMAL, 0, 0 }, - { 'x', 16, 0, etRADIX, 16, 1 }, - { 'X', 16, 0, etRADIX, 0, 4 }, -#ifndef SQLITE_OMIT_FLOATING_POINT - { 'f', 0, 1, etFLOAT, 0, 0 }, - { 'e', 0, 1, etEXP, 30, 0 }, - { 'E', 0, 1, etEXP, 14, 0 }, - { 'G', 0, 1, etGENERIC, 14, 0 }, -#endif - { 'i', 10, 1, etDECIMAL, 0, 0 }, - { 'n', 0, 0, etSIZE, 0, 0 }, - { '%', 0, 0, etPERCENT, 0, 0 }, - { 'p', 16, 0, etPOINTER, 0, 1 }, - - /* All the rest are undocumented and are for internal use only */ - { 'T', 0, 0, etTOKEN, 0, 0 }, - { 'S', 0, 0, etSRCLIST, 0, 0 }, - { 'r', 10, 1, etORDINAL, 0, 0 }, -}; - -/* -** 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==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG ); - p->accError = eError; - p->nAlloc = 0; -} - -/* -** 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++]); -} - - -/* -** On machines with a small stack size, you can redefine the -** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired. -*/ -#ifndef SQLITE_PRINT_BUF_SIZE -# define SQLITE_PRINT_BUF_SIZE 70 -#endif -#define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */ - -/* -** Render a string given by "fmt" into the StrAccum object. -*/ -SQLITE_PRIVATE void sqlite3VXPrintf( - StrAccum *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 */ - - 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 - sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt)); - if( *fmt==0 ) break; - } - if( (c=(*++fmt))==0 ){ - sqlite3StrAccumAppend(pAccum, "%", 1); - break; - } - /* Find out what flags are present */ - flag_leftjustify = flag_prefix = cThousand = - flag_alternateform = flag_altform2 = flag_zeropad = 0; - done = 0; - 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; - } - }while( !done && (c=(*++fmt))!=0 ); - /* Get the field width */ - if( c=='*' ){ - if( bArgList ){ - width = (int)getIntArg(pArgList); - }else{ - width = va_arg(ap,int); - } - if( width<0 ){ - flag_leftjustify = 1; - width = width >= -2147483647 ? -width : 0; - } - c = *++fmt; - }else{ - unsigned wx = 0; - while( c>='0' && c<='9' ){ - wx = wx*10 + c - '0'; - c = *++fmt; - } - testcase( wx>0x7fffffff ); - width = wx & 0x7fffffff; - } - assert( width>=0 ); -#ifdef SQLITE_PRINTF_PRECISION_LIMIT - if( width>SQLITE_PRINTF_PRECISION_LIMIT ){ - width = SQLITE_PRINTF_PRECISION_LIMIT; - } -#endif - - /* Get the precision */ - if( c=='.' ){ - c = *++fmt; - if( c=='*' ){ - if( bArgList ){ - precision = (int)getIntArg(pArgList); - }else{ - precision = va_arg(ap,int); - } - c = *++fmt; - if( precision<0 ){ - precision = precision >= -2147483647 ? -precision : -1; - } - }else{ - unsigned px = 0; - while( c>='0' && c<='9' ){ - px = px*10 + c - '0'; - c = *++fmt; - } - testcase( px>0x7fffffff ); - precision = px & 0x7fffffff; - } - }else{ - precision = -1; - } - assert( precision>=(-1) ); -#ifdef SQLITE_PRINTF_PRECISION_LIMIT - if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){ - precision = SQLITE_PRINTF_PRECISION_LIMIT; - } -#endif - - - /* Get the conversion type modifier */ - if( c=='l' ){ - flag_long = 1; - c = *++fmt; - if( c=='l' ){ - flag_long = 2; - c = *++fmt; - } - }else{ - flag_long = 0; - } - /* Fetch the info entry for the field */ - infop = &fmtinfo[0]; - xtype = etINVALID; - for(idx=0; idxtype; - break; - } - } - - /* - ** At this point, variables are initialized as follows: - ** - ** flag_alternateform TRUE if a '#' is present. - ** flag_altform2 TRUE if a '!' is present. - ** flag_prefix '+' or ' ' or zero - ** flag_leftjustify TRUE if a '-' is present or if the - ** field width was negative. - ** flag_zeropad TRUE if the width began with 0. - ** flag_long 1 for "l", 2 for "ll" - ** width The specified field width. This is - ** always non-negative. Zero is the default. - ** precision The specified precision. The default - ** is -1. - ** xtype The class of the conversion. - ** infop Pointer to the appropriate info struct. - */ - switch( xtype ){ - case etPOINTER: - flag_long = sizeof(char*)==sizeof(i64) ? 2 : - sizeof(char*)==sizeof(long int) ? 1 : 0; - /* Fall through into the next case */ - case etORDINAL: - case etRADIX: - cThousand = 0; - /* Fall through into the next case */ - case etDECIMAL: - if( infop->flags & FLAG_SIGNED ){ - i64 v; - if( bArgList ){ - v = getIntArg(pArgList); - }else if( flag_long ){ - if( flag_long==2 ){ - v = va_arg(ap,i64) ; - }else{ - v = va_arg(ap,long int); - } - }else{ - v = va_arg(ap,int); - } - if( v<0 ){ - if( v==SMALLEST_INT64 ){ - longvalue = ((u64)1)<<63; - }else{ - longvalue = -v; - } - prefix = '-'; - }else{ - longvalue = v; - prefix = flag_prefix; - } - }else{ - if( bArgList ){ - longvalue = (u64)getIntArg(pArgList); - }else if( flag_long ){ - if( flag_long==2 ){ - longvalue = va_arg(ap,u64); - }else{ - longvalue = va_arg(ap,unsigned long int); - } - }else{ - longvalue = va_arg(ap,unsigned int); - } - prefix = 0; - } - if( longvalue==0 ) flag_alternateform = 0; - if( flag_zeropad && precision=4 || (longvalue/10)%10==1 ){ - x = 0; - } - *(--bufpt) = zOrd[x*2+1]; - *(--bufpt) = zOrd[x*2]; - } - { - const char *cset = &aDigits[infop->charset]; - u8 base = infop->base; - do{ /* Convert to ascii */ - *(--bufpt) = cset[longvalue%base]; - longvalue = longvalue/base; - }while( longvalue>0 ); - } - length = (int)(&zOut[nOut-1]-bufpt); - while( precision>length ){ - *(--bufpt) = '0'; /* Zero pad */ - length++; - } - if( cThousand ){ - int nn = (length - 1)/3; /* Number of "," to insert */ - int ix = (length - 1)%3 + 1; - bufpt -= nn; - for(idx=0; nn>0; idx++){ - bufpt[idx] = bufpt[idx+nn]; - ix--; - if( ix==0 ){ - bufpt[++idx] = cThousand; - nn--; - ix = 3; - } - } - } - if( prefix ) *(--bufpt) = prefix; /* Add sign */ - if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */ - const char *pre; - char x; - pre = &aPrefix[infop->prefix]; - for(; (x=(*pre))!=0; pre++) *(--bufpt) = x; - } - length = (int)(&zOut[nOut-1]-bufpt); - break; - case etFLOAT: - case etEXP: - case etGENERIC: - if( bArgList ){ - realvalue = getDoubleArg(pArgList); - }else{ - realvalue = va_arg(ap,double); - } -#ifdef SQLITE_OMIT_FLOATING_POINT - length = 0; -#else - if( precision<0 ) precision = 6; /* Set default precision */ - if( realvalue<0.0 ){ - realvalue = -realvalue; - prefix = '-'; - }else{ - prefix = flag_prefix; - } - if( xtype==etGENERIC && precision>0 ) precision--; - testcase( precision>0xfff ); - for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){} - if( xtype==etFLOAT ) 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; - } - if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){ - bufpt = zExtra - = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 ); - if( bufpt==0 ){ - setStrAccumError(pAccum, STRACCUM_NOMEM); - 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); - c = bufpt ? bufpt[0] : 0; - }else{ - c = va_arg(ap,int); - } - if( precision>1 ){ - width -= precision-1; - if( width>1 && !flag_leftjustify ){ - sqlite3AppendChar(pAccum, width-1, ' '); - width = 0; - } - sqlite3AppendChar(pAccum, precision-1, c); - } - length = 1; - buf[0] = c; - bufpt = buf; - break; - 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 ){ - zExtra = bufpt; - } - if( precision>=0 ){ - for(length=0; lengthetBUFSIZE ){ - bufpt = zExtra = sqlite3Malloc( n ); - if( bufpt==0 ){ - setStrAccumError(pAccum, STRACCUM_NOMEM); - return; - } - }else{ - bufpt = buf; - } - j = 0; - if( needQuote ) bufpt[j++] = q; - k = i; - for(i=0; i=0 && precisionprintfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return; - pToken = va_arg(ap, Token*); - assert( bArgList==0 ); - if( pToken && pToken->n ){ - sqlite3StrAccumAppend(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 ){ - sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase); - sqlite3StrAccumAppend(pAccum, ".", 1); - } - sqlite3StrAccumAppendAll(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. - */ - width -= length; - if( width>0 ){ - if( !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' '); - sqlite3StrAccumAppend(pAccum, bufpt, length); - if( flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' '); - }else{ - sqlite3StrAccumAppend(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==STRACCUM_TOOBIG); - testcase(p->accError==STRACCUM_NOMEM); - return 0; - } - if( p->mxAlloc==0 ){ - N = p->nAlloc - p->nChar - 1; - setStrAccumError(p, STRACCUM_TOOBIG); - return N; - }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 ){ - sqlite3StrAccumReset(p); - setStrAccumError(p, STRACCUM_TOOBIG); - return 0; - }else{ - p->nAlloc = (int)szNew; - } - if( p->db ){ - zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc); - }else{ - zNew = sqlite3_realloc64(zOld, p->nAlloc); - } - if( zNew ){ - assert( p->zText!=0 || p->nChar==0 ); - if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar); - p->zText = zNew; - p->nAlloc = sqlite3DbMallocSize(p->db, zNew); - p->printfFlags |= SQLITE_PRINTF_MALLOCED; - }else{ - sqlite3StrAccumReset(p); - setStrAccumError(p, STRACCUM_NOMEM); - return 0; - } - } - return N; -} - -/* -** Append N copies of character c to the given string buffer. -*/ -SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *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 sqlite3StrAccumAppend() that does special-case -** work (enlarging the buffer) using tail recursion, so that the -** sqlite3StrAccumAppend() 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_PRIVATE void sqlite3StrAccumAppend(StrAccum *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 ); - 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_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){ - sqlite3StrAccumAppend(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, STRACCUM_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; -} - -/* -** Reset an StrAccum string. Reclaim all malloced memory. -*/ -SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){ - if( isMalloced(p) ){ - sqlite3DbFree(p->db, p->zText); - p->printfFlags &= ~SQLITE_PRINTF_MALLOCED; - } - 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; -} - -/* -** 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; - sqlite3VXPrintf(&acc, zFormat, ap); - z = sqlite3StrAccumFinish(&acc); - if( acc.accError==STRACCUM_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); - sqlite3VXPrintf(&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); - sqlite3VXPrintf(&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. -** -** sqlite3VXPrintf() 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); - sqlite3VXPrintf(&acc, zFormat, ap); - sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode, - sqlite3StrAccumFinish(&acc)); -} - -/* -** Format and write a message to the log if logging is enabled. -*/ -SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){ - va_list ap; /* Vararg list */ - if( sqlite3GlobalConfig.xLog ){ - va_start(ap, zFormat); - renderLogMsg(iErrCode, zFormat, ap); - va_end(ap); - } -} - -#if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) -/* -** A version of printf() that understands %lld. Used for debugging. -** The printf() built into some versions of windows does not understand %lld -** and segfaults if you give it a long long int. -*/ -SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){ - va_list ap; - StrAccum acc; - char zBuf[500]; - sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); - va_start(ap,zFormat); - sqlite3VXPrintf(&acc, zFormat, ap); - va_end(ap); - sqlite3StrAccumFinish(&acc); - fprintf(stdout,"%s", zBuf); - fflush(stdout); -} -#endif - - -/* -** variable-argument wrapper around sqlite3VXPrintf(). The bFlags argument -** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats. -*/ -SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){ - va_list ap; - va_start(ap,zFormat); - sqlite3VXPrintf(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++){ - sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4); - } - sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4); - } - va_start(ap, zFormat); - sqlite3VXPrintf(&acc, zFormat, ap); - va_end(ap); - assert( acc.nChar>0 ); - if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&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); - sqlite3XPrintf(&x, "%s", pCte->zName); - if( pCte->pCols && pCte->pCols->nExpr>0 ){ - char cSep = '('; - int j; - for(j=0; jpCols->nExpr; j++){ - sqlite3XPrintf(&x, "%c%s", cSep, pCte->pCols->a[j].zName); - cSep = ','; - } - sqlite3XPrintf(&x, ")"); - } - sqlite3XPrintf(&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 Select object. -*/ -SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){ - int n = 0; - int cnt = 0; - if( p==0 ){ - sqlite3TreeViewLine(pView, "nil-SELECT"); - return; - } - pView = sqlite3TreeViewPush(pView, moreToFollow); - if( p->pWith ){ - sqlite3TreeViewWith(pView, p->pWith, 1); - cnt = 1; - sqlite3TreeViewPush(pView, 1); - } - do{ - sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d", - ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""), - ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), 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++; - if( p->pOffset ) n++; - } - sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set"); - if( p->pSrc && p->pSrc->nSrc ){ - int i; - pView = sqlite3TreeViewPush(pView, (n--)>0); - sqlite3TreeViewLine(pView, "FROM"); - for(i=0; ipSrc->nSrc; i++){ - struct SrcList_item *pItem = &p->pSrc->a[i]; - StrAccum x; - char zLine[100]; - sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0); - sqlite3XPrintf(&x, "{%d,*}", pItem->iCursor); - if( pItem->zDatabase ){ - sqlite3XPrintf(&x, " %s.%s", pItem->zDatabase, pItem->zName); - }else if( pItem->zName ){ - sqlite3XPrintf(&x, " %s", pItem->zName); - } - if( pItem->pTab ){ - sqlite3XPrintf(&x, " tabname=%Q", pItem->pTab->zName); - } - if( pItem->zAlias ){ - sqlite3XPrintf(&x, " (AS %s)", pItem->zAlias); - } - if( pItem->fg.jointype & JT_LEFT ){ - sqlite3XPrintf(&x, " LEFT-JOIN"); - } - sqlite3StrAccumFinish(&x); - sqlite3TreeViewItem(pView, zLine, ipSrc->nSrc-1); - if( pItem->pSelect ){ - sqlite3TreeViewSelect(pView, pItem->pSelect, 0); - } - if( pItem->fg.isTabFunc ){ - sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:"); - } - sqlite3TreeViewPop(pView); - } - 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); - } - if( p->pOrderBy ){ - sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY"); - } - if( p->pLimit ){ - sqlite3TreeViewItem(pView, "LIMIT", (n--)>0); - sqlite3TreeViewExpr(pView, p->pLimit, 0); - sqlite3TreeViewPop(pView); - } - if( p->pOffset ){ - sqlite3TreeViewItem(pView, "OFFSET", (n--)>0); - sqlite3TreeViewExpr(pView, p->pOffset, 0); - 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); -} - -/* -** Generate a human-readable explanation of an expression tree. -*/ -SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){ - const char *zBinOp = 0; /* Binary operator */ - const char *zUniOp = 0; /* Unary operator */ - char zFlgs[60]; - pView = sqlite3TreeViewPush(pView, moreToFollow); - if( pExpr==0 ){ - sqlite3TreeViewLine(pView, "nil"); - sqlite3TreeViewPop(pView); - return; - } - if( pExpr->flags ){ - if( ExprHasProperty(pExpr, EP_FromJoin) ){ - sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x iRJT=%d", - pExpr->flags, pExpr->iRightJoinTable); - }else{ - sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x",pExpr->flags); - } - }else{ - zFlgs[0] = 0; - } - switch( pExpr->op ){ - case TK_AGG_COLUMN: { - sqlite3TreeViewLine(pView, "AGG{%d:%d}%s", - pExpr->iTable, pExpr->iColumn, zFlgs); - break; - } - case TK_COLUMN: { - if( pExpr->iTable<0 ){ - /* This only happens when coding check constraints */ - sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs); - }else{ - sqlite3TreeViewLine(pView, "{%d:%d}%s", - pExpr->iTable, pExpr->iColumn, zFlgs); - } - 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; - } -#ifndef SQLITE_OMIT_BLOB_LITERAL - case TK_BLOB: { - sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken); - break; - } -#endif - case TK_VARIABLE: { - sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)", - pExpr->u.zToken, pExpr->iColumn); - break; - } - case TK_REGISTER: { - sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable); - break; - } - case TK_ID: { - sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken); - break; - } -#ifndef SQLITE_OMIT_CAST - case TK_CAST: { - /* Expressions of the form: CAST(pLeft AS token) */ - sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken); - sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); - break; - } -#endif /* SQLITE_OMIT_CAST */ - case TK_LT: zBinOp = "LT"; break; - case TK_LE: zBinOp = "LE"; break; - case TK_GT: zBinOp = "GT"; break; - case TK_GE: zBinOp = "GE"; break; - case TK_NE: zBinOp = "NE"; break; - case TK_EQ: zBinOp = "EQ"; break; - case TK_IS: zBinOp = "IS"; break; - case TK_ISNOT: zBinOp = "ISNOT"; break; - case TK_AND: zBinOp = "AND"; break; - case TK_OR: zBinOp = "OR"; break; - case TK_PLUS: zBinOp = "ADD"; break; - case TK_STAR: zBinOp = "MUL"; break; - case TK_MINUS: zBinOp = "SUB"; break; - case TK_REM: zBinOp = "REM"; break; - case TK_BITAND: zBinOp = "BITAND"; break; - case TK_BITOR: zBinOp = "BITOR"; break; - case TK_SLASH: zBinOp = "DIV"; break; - case TK_LSHIFT: zBinOp = "LSHIFT"; break; - case TK_RSHIFT: zBinOp = "RSHIFT"; break; - case TK_CONCAT: zBinOp = "CONCAT"; break; - case TK_DOT: zBinOp = "DOT"; break; - - case TK_UMINUS: zUniOp = "UMINUS"; break; - case TK_UPLUS: zUniOp = "UPLUS"; break; - case TK_BITNOT: zUniOp = "BITNOT"; break; - case TK_NOT: zUniOp = "NOT"; break; - case TK_ISNULL: zUniOp = "ISNULL"; break; - case TK_NOTNULL: zUniOp = "NOTNULL"; break; - - case TK_SPAN: { - sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken); - sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); - break; - } - - case TK_COLLATE: { - sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken); - sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); - break; - } - - case TK_AGG_FUNCTION: - case TK_FUNCTION: { - ExprList *pFarg; /* List of function arguments */ - if( ExprHasProperty(pExpr, EP_TokenOnly) ){ - pFarg = 0; - }else{ - pFarg = pExpr->x.pList; - } - if( pExpr->op==TK_AGG_FUNCTION ){ - sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q", - pExpr->op2, pExpr->u.zToken); - }else{ - sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken); - } - if( pFarg ){ - sqlite3TreeViewExprList(pView, pFarg, 0, 0); - } - break; - } -#ifndef SQLITE_OMIT_SUBQUERY - case TK_EXISTS: { - sqlite3TreeViewLine(pView, "EXISTS-expr flags=0x%x", pExpr->flags); - sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0); - break; - } - case TK_SELECT: { - sqlite3TreeViewLine(pView, "SELECT-expr flags=0x%x", pExpr->flags); - sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0); - break; - } - case TK_IN: { - sqlite3TreeViewLine(pView, "IN flags=0x%x", pExpr->flags); - sqlite3TreeViewExpr(pView, pExpr->pLeft, 1); - if( ExprHasProperty(pExpr, EP_xIsSelect) ){ - sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0); - }else{ - sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0); - } - break; - } -#endif /* SQLITE_OMIT_SUBQUERY */ - - /* - ** x BETWEEN y AND z - ** - ** This is equivalent to - ** - ** x>=y AND x<=z - ** - ** X is stored in pExpr->pLeft. - ** Y is stored in pExpr->pList->a[0].pExpr. - ** Z is stored in pExpr->pList->a[1].pExpr. - */ - case TK_BETWEEN: { - Expr *pX = pExpr->pLeft; - Expr *pY = pExpr->x.pList->a[0].pExpr; - Expr *pZ = pExpr->x.pList->a[1].pExpr; - sqlite3TreeViewLine(pView, "BETWEEN"); - sqlite3TreeViewExpr(pView, pX, 1); - sqlite3TreeViewExpr(pView, pY, 1); - sqlite3TreeViewExpr(pView, pZ, 0); - break; - } - case TK_TRIGGER: { - /* If the opcode is TK_TRIGGER, then the expression is a reference - ** to a column in the new.* or old.* pseudo-tables available to - ** trigger programs. In this case Expr.iTable is set to 1 for the - ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn - ** is set to the column of the pseudo-table to read, or to -1 to - ** read the rowid field. - */ - sqlite3TreeViewLine(pView, "%s(%d)", - pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn); - break; - } - case TK_CASE: { - sqlite3TreeViewLine(pView, "CASE"); - sqlite3TreeViewExpr(pView, pExpr->pLeft, 1); - sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0); - break; - } -#ifndef SQLITE_OMIT_TRIGGER - case TK_RAISE: { - const char *zType = "unk"; - switch( pExpr->affinity ){ - case OE_Rollback: zType = "rollback"; break; - case OE_Abort: zType = "abort"; break; - case OE_Fail: zType = "fail"; break; - case OE_Ignore: zType = "ignore"; break; - } - sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken); - break; - } -#endif - case TK_MATCH: { - sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s", - pExpr->iTable, pExpr->iColumn, zFlgs); - sqlite3TreeViewExpr(pView, pExpr->pRight, 0); - break; - } - case TK_VECTOR: { - sqlite3TreeViewBareExprList(pView, pExpr->x.pList, "VECTOR"); - break; - } - case TK_SELECT_COLUMN: { - sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn); - sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0); - break; - } - case TK_IF_NULL_ROW: { - sqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable); - sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); - break; - } - default: { - sqlite3TreeViewLine(pView, "op=%d", pExpr->op); - break; - } - } - if( zBinOp ){ - sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs); - sqlite3TreeViewExpr(pView, pExpr->pLeft, 1); - sqlite3TreeViewExpr(pView, pExpr->pRight, 0); - }else if( zUniOp ){ - sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs); - sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); - } - sqlite3TreeViewPop(pView); -} - - -/* -** Generate a human-readable explanation of an expression list. -*/ -SQLITE_PRIVATE void sqlite3TreeViewBareExprList( - TreeView *pView, - const ExprList *pList, - const char *zLabel -){ - if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST"; - if( pList==0 ){ - sqlite3TreeViewLine(pView, "%s (empty)", zLabel); - }else{ - int i; - sqlite3TreeViewLine(pView, "%s", zLabel); - for(i=0; inExpr; i++){ - int j = pList->a[i].u.x.iOrderByCol; - if( j ){ - sqlite3TreeViewPush(pView, 0); - sqlite3TreeViewLine(pView, "iOrderByCol=%d", j); - } - sqlite3TreeViewExpr(pView, pList->a[i].pExpr, inExpr-1); - if( j ) sqlite3TreeViewPop(pView); - } - } -} -SQLITE_PRIVATE void sqlite3TreeViewExprList( - TreeView *pView, - const ExprList *pList, - u8 moreToFollow, - const char *zLabel -){ - pView = sqlite3TreeViewPush(pView, moreToFollow); - sqlite3TreeViewBareExprList(pView, pList, zLabel); - sqlite3TreeViewPop(pView); -} - -#endif /* SQLITE_DEBUG */ - -/************** End of treeview.c ********************************************/ -/************** Begin file random.c ******************************************/ -/* -** 2001 September 15 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file contains code to implement a pseudo-random number -** generator (PRNG) for SQLite. -** -** Random numbers are used by some of the database backends in order -** to generate random integer keys for tables or random filenames. -*/ -/* #include "sqliteInt.h" */ - - -/* All threads share a single random number generator. -** This structure is the current state of the generator. -*/ -static SQLITE_WSD struct sqlite3PrngType { - unsigned char isInit; /* True if initialized */ - unsigned char i, j; /* State variables */ - unsigned char s[256]; /* State variables */ -} sqlite3Prng; - -/* -** Return N random bytes. -*/ -SQLITE_API void sqlite3_randomness(int N, void *pBuf){ - unsigned char t; - unsigned char *zBuf = pBuf; - - /* The "wsdPrng" macro will resolve to the pseudo-random number generator - ** state vector. If writable static data is unsupported on the target, - ** we have to locate the state vector at run-time. In the more common - ** case where writable static data is supported, wsdPrng can refer directly - ** to the "sqlite3Prng" state vector declared above. - */ -#ifdef SQLITE_OMIT_WSD - struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng); -# define wsdPrng p[0] -#else -# define wsdPrng sqlite3Prng -#endif - -#if SQLITE_THREADSAFE - sqlite3_mutex *mutex; -#endif - -#ifndef SQLITE_OMIT_AUTOINIT - if( sqlite3_initialize() ) return; -#endif - -#if SQLITE_THREADSAFE - mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG); -#endif - - sqlite3_mutex_enter(mutex); - if( N<=0 || pBuf==0 ){ - wsdPrng.isInit = 0; - sqlite3_mutex_leave(mutex); - return; - } - - /* Initialize the state of the random number generator once, - ** the first time this routine is called. The seed value does - ** not need to contain a lot of randomness since we are not - ** trying to do secure encryption or anything like that... - ** - ** Nothing in this file or anywhere else in SQLite does any kind of - ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random - ** number generator) not as an encryption device. - */ - if( !wsdPrng.isInit ){ - int i; - char k[256]; - wsdPrng.j = 0; - wsdPrng.i = 0; - sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k); - for(i=0; i<256; i++){ - wsdPrng.s[i] = (u8)i; - } - for(i=0; i<256; i++){ - wsdPrng.j += wsdPrng.s[i] + k[i]; - t = wsdPrng.s[wsdPrng.j]; - wsdPrng.s[wsdPrng.j] = wsdPrng.s[i]; - wsdPrng.s[i] = t; - } - wsdPrng.isInit = 1; - } - - assert( N>0 ); - do{ - wsdPrng.i++; - t = wsdPrng.s[wsdPrng.i]; - wsdPrng.j += t; - wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j]; - wsdPrng.s[wsdPrng.j] = t; - t += wsdPrng.s[wsdPrng.i]; - *(zBuf++) = wsdPrng.s[t]; - }while( --N ); - sqlite3_mutex_leave(mutex); -} - -#ifndef SQLITE_UNTESTABLE -/* -** For testing purposes, we sometimes want to preserve the state of -** PRNG and restore the PRNG to its saved state at a later time, or -** to reset the PRNG to its initial state. These routines accomplish -** those tasks. -** -** The sqlite3_test_control() interface calls these routines to -** control the PRNG. -*/ -static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng; -SQLITE_PRIVATE void sqlite3PrngSaveState(void){ - memcpy( - &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng), - &GLOBAL(struct sqlite3PrngType, sqlite3Prng), - sizeof(sqlite3Prng) - ); -} -SQLITE_PRIVATE void sqlite3PrngRestoreState(void){ - memcpy( - &GLOBAL(struct sqlite3PrngType, sqlite3Prng), - &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng), - sizeof(sqlite3Prng) - ); -} -#endif /* SQLITE_UNTESTABLE */ - -/************** End of random.c **********************************************/ -/************** Begin file threads.c *****************************************/ -/* -** 2012 July 21 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This file presents a simple cross-platform threading interface for -** use internally by SQLite. -** -** A "thread" can be created using sqlite3ThreadCreate(). This thread -** runs independently of its creator until it is joined using -** sqlite3ThreadJoin(), at which point it terminates. -** -** Threads do not have to be real. It could be that the work of the -** "thread" is done by the main thread at either the sqlite3ThreadCreate() -** or sqlite3ThreadJoin() call. This is, in fact, what happens in -** single threaded systems. Nothing in SQLite requires multiple threads. -** This interface exists so that applications that want to take advantage -** of multiple cores can do so, while also allowing applications to stay -** single-threaded if desired. -*/ -/* #include "sqliteInt.h" */ -#if SQLITE_OS_WIN -/* # include "os_win.h" */ -#endif - -#if SQLITE_MAX_WORKER_THREADS>0 - -/********************************* Unix Pthreads ****************************/ -#if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0 - -#define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */ -/* #include */ - -/* A running thread */ -struct SQLiteThread { - pthread_t tid; /* Thread ID */ - int done; /* Set to true when thread finishes */ - void *pOut; /* Result returned by the thread */ - void *(*xTask)(void*); /* The thread routine */ - void *pIn; /* Argument to the thread */ -}; - -/* Create a new thread */ -SQLITE_PRIVATE int sqlite3ThreadCreate( - SQLiteThread **ppThread, /* OUT: Write the thread object here */ - void *(*xTask)(void*), /* Routine to run in a separate thread */ - void *pIn /* Argument passed into xTask() */ -){ - SQLiteThread *p; - int rc; - - assert( ppThread!=0 ); - assert( xTask!=0 ); - /* This routine is never used in single-threaded mode */ - assert( sqlite3GlobalConfig.bCoreMutex!=0 ); - - *ppThread = 0; - p = sqlite3Malloc(sizeof(*p)); - if( p==0 ) return SQLITE_NOMEM_BKPT; - memset(p, 0, sizeof(*p)); - p->xTask = xTask; - p->pIn = pIn; - /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a - ** function that returns SQLITE_ERROR when passed the argument 200, that - ** forces worker threads to run sequentially and deterministically - ** for testing purposes. */ - if( sqlite3FaultSim(200) ){ - rc = 1; - }else{ - rc = pthread_create(&p->tid, 0, xTask, pIn); - } - if( rc ){ - p->done = 1; - p->pOut = xTask(pIn); - } - *ppThread = p; - return SQLITE_OK; -} - -/* Get the results of the thread */ -SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ - int rc; - - assert( ppOut!=0 ); - if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT; - if( p->done ){ - *ppOut = p->pOut; - rc = SQLITE_OK; - }else{ - rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK; - } - sqlite3_free(p); - return rc; -} - -#endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */ -/******************************** End Unix Pthreads *************************/ - - -/********************************* Win32 Threads ****************************/ -#if SQLITE_OS_WIN_THREADS - -#define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */ -#include - -/* A running thread */ -struct SQLiteThread { - void *tid; /* The thread handle */ - unsigned id; /* The thread identifier */ - void *(*xTask)(void*); /* The routine to run as a thread */ - void *pIn; /* Argument to xTask */ - void *pResult; /* Result of xTask */ -}; - -/* Thread procedure Win32 compatibility shim */ -static unsigned __stdcall sqlite3ThreadProc( - void *pArg /* IN: Pointer to the SQLiteThread structure */ -){ - SQLiteThread *p = (SQLiteThread *)pArg; - - assert( p!=0 ); -#if 0 - /* - ** This assert appears to trigger spuriously on certain - ** versions of Windows, possibly due to _beginthreadex() - ** and/or CreateThread() not fully setting their thread - ** ID parameter before starting the thread. - */ - assert( p->id==GetCurrentThreadId() ); -#endif - assert( p->xTask!=0 ); - p->pResult = p->xTask(p->pIn); - - _endthreadex(0); - return 0; /* NOT REACHED */ -} - -/* Create a new thread */ -SQLITE_PRIVATE int sqlite3ThreadCreate( - SQLiteThread **ppThread, /* OUT: Write the thread object here */ - void *(*xTask)(void*), /* Routine to run in a separate thread */ - void *pIn /* Argument passed into xTask() */ -){ - SQLiteThread *p; - - assert( ppThread!=0 ); - assert( xTask!=0 ); - *ppThread = 0; - p = sqlite3Malloc(sizeof(*p)); - if( p==0 ) return SQLITE_NOMEM_BKPT; - /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a - ** function that returns SQLITE_ERROR when passed the argument 200, that - ** forces worker threads to run sequentially and deterministically - ** (via the sqlite3FaultSim() term of the conditional) for testing - ** purposes. */ - if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){ - memset(p, 0, sizeof(*p)); - }else{ - p->xTask = xTask; - p->pIn = pIn; - p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id); - if( p->tid==0 ){ - memset(p, 0, sizeof(*p)); - } - } - if( p->xTask==0 ){ - p->id = GetCurrentThreadId(); - p->pResult = xTask(pIn); - } - *ppThread = p; - return SQLITE_OK; -} - -SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */ - -/* Get the results of the thread */ -SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ - DWORD rc; - BOOL bRc; - - assert( ppOut!=0 ); - if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT; - if( p->xTask==0 ){ - /* assert( p->id==GetCurrentThreadId() ); */ - rc = WAIT_OBJECT_0; - assert( p->tid==0 ); - }else{ - assert( p->id!=0 && p->id!=GetCurrentThreadId() ); - rc = sqlite3Win32Wait((HANDLE)p->tid); - assert( rc!=WAIT_IO_COMPLETION ); - bRc = CloseHandle((HANDLE)p->tid); - assert( bRc ); - } - if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult; - sqlite3_free(p); - return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR; -} - -#endif /* SQLITE_OS_WIN_THREADS */ -/******************************** End Win32 Threads *************************/ - - -/********************************* Single-Threaded **************************/ -#ifndef SQLITE_THREADS_IMPLEMENTED -/* -** This implementation does not actually create a new thread. It does the -** work of the thread in the main thread, when either the thread is created -** or when it is joined -*/ - -/* A running thread */ -struct SQLiteThread { - void *(*xTask)(void*); /* The routine to run as a thread */ - void *pIn; /* Argument to xTask */ - void *pResult; /* Result of xTask */ -}; - -/* Create a new thread */ -SQLITE_PRIVATE int sqlite3ThreadCreate( - SQLiteThread **ppThread, /* OUT: Write the thread object here */ - void *(*xTask)(void*), /* Routine to run in a separate thread */ - void *pIn /* Argument passed into xTask() */ -){ - SQLiteThread *p; - - assert( ppThread!=0 ); - assert( xTask!=0 ); - *ppThread = 0; - p = sqlite3Malloc(sizeof(*p)); - if( p==0 ) return SQLITE_NOMEM_BKPT; - if( (SQLITE_PTR_TO_INT(p)/17)&1 ){ - p->xTask = xTask; - p->pIn = pIn; - }else{ - p->xTask = 0; - p->pResult = xTask(pIn); - } - *ppThread = p; - return SQLITE_OK; -} - -/* Get the results of the thread */ -SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ - - assert( ppOut!=0 ); - if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT; - if( p->xTask ){ - *ppOut = p->xTask(p->pIn); - }else{ - *ppOut = p->pResult; - } - sqlite3_free(p); - -#if defined(SQLITE_TEST) - { - void *pTstAlloc = sqlite3Malloc(10); - if (!pTstAlloc) return SQLITE_NOMEM_BKPT; - sqlite3_free(pTstAlloc); - } -#endif - - return SQLITE_OK; -} - -#endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */ -/****************************** End Single-Threaded *************************/ -#endif /* SQLITE_MAX_WORKER_THREADS>0 */ - -/************** End of threads.c *********************************************/ -/************** Begin file utf.c *********************************************/ -/* -** 2004 April 13 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file contains routines used to translate between UTF-8, -** UTF-16, UTF-16BE, and UTF-16LE. -** -** Notes on UTF-8: -** -** Byte-0 Byte-1 Byte-2 Byte-3 Value -** 0xxxxxxx 00000000 00000000 0xxxxxxx -** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx -** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx -** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx -** -** -** Notes on UTF-16: (with wwww+1==uuuuu) -** -** Word-0 Word-1 Value -** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx -** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx -** -** -** BOM or Byte Order Mark: -** 0xff 0xfe little-endian utf-16 follows -** 0xfe 0xff big-endian utf-16 follows -** -*/ -/* #include "sqliteInt.h" */ -/* #include */ -/* #include "vdbeInt.h" */ - -#if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0 -/* -** The following constant value is used by the SQLITE_BIGENDIAN and -** SQLITE_LITTLEENDIAN macros. -*/ -SQLITE_PRIVATE const int sqlite3one = 1; -#endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */ - -/* -** This lookup table is used to help decode the first byte of -** a multi-byte UTF8 character. -*/ -static const unsigned char sqlite3Utf8Trans1[] = { - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, - 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, - 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00, -}; - - -#define WRITE_UTF8(zOut, c) { \ - if( c<0x00080 ){ \ - *zOut++ = (u8)(c&0xFF); \ - } \ - else if( c<0x00800 ){ \ - *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \ - *zOut++ = 0x80 + (u8)(c & 0x3F); \ - } \ - else if( c<0x10000 ){ \ - *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \ - *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ - *zOut++ = 0x80 + (u8)(c & 0x3F); \ - }else{ \ - *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \ - *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \ - *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ - *zOut++ = 0x80 + (u8)(c & 0x3F); \ - } \ -} - -#define WRITE_UTF16LE(zOut, c) { \ - if( c<=0xFFFF ){ \ - *zOut++ = (u8)(c&0x00FF); \ - *zOut++ = (u8)((c>>8)&0x00FF); \ - }else{ \ - *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \ - *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \ - *zOut++ = (u8)(c&0x00FF); \ - *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \ - } \ -} - -#define WRITE_UTF16BE(zOut, c) { \ - if( c<=0xFFFF ){ \ - *zOut++ = (u8)((c>>8)&0x00FF); \ - *zOut++ = (u8)(c&0x00FF); \ - }else{ \ - *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \ - *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \ - *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \ - *zOut++ = (u8)(c&0x00FF); \ - } \ -} - -#define READ_UTF16LE(zIn, TERM, c){ \ - c = (*zIn++); \ - c += ((*zIn++)<<8); \ - if( c>=0xD800 && c<0xE000 && TERM ){ \ - int c2 = (*zIn++); \ - c2 += ((*zIn++)<<8); \ - c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \ - } \ -} - -#define READ_UTF16BE(zIn, TERM, c){ \ - c = ((*zIn++)<<8); \ - c += (*zIn++); \ - if( c>=0xD800 && c<0xE000 && TERM ){ \ - int c2 = ((*zIn++)<<8); \ - c2 += (*zIn++); \ - c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \ - } \ -} - -/* -** Translate a single UTF-8 character. Return the unicode value. -** -** During translation, assume that the byte that zTerm points -** is a 0x00. -** -** Write a pointer to the next unread byte back into *pzNext. -** -** Notes On Invalid UTF-8: -** -** * This routine never allows a 7-bit character (0x00 through 0x7f) to -** be encoded as a multi-byte character. Any multi-byte character that -** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd. -** -** * This routine never allows a UTF16 surrogate value to be encoded. -** If a multi-byte character attempts to encode a value between -** 0xd800 and 0xe000 then it is rendered as 0xfffd. -** -** * Bytes in the range of 0x80 through 0xbf which occur as the first -** byte of a character are interpreted as single-byte characters -** and rendered as themselves even though they are technically -** invalid characters. -** -** * This routine accepts over-length UTF8 encodings -** for unicode values 0x80 and greater. It does not change over-length -** encodings to 0xfffd as some systems recommend. -*/ -#define READ_UTF8(zIn, zTerm, c) \ - c = *(zIn++); \ - if( c>=0xc0 ){ \ - c = sqlite3Utf8Trans1[c-0xc0]; \ - while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \ - c = (c<<6) + (0x3f & *(zIn++)); \ - } \ - if( c<0x80 \ - || (c&0xFFFFF800)==0xD800 \ - || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ - } -SQLITE_PRIVATE u32 sqlite3Utf8Read( - const unsigned char **pz /* Pointer to string from which to read char */ -){ - unsigned int c; - - /* Same as READ_UTF8() above but without the zTerm parameter. - ** For this routine, we assume the UTF8 string is always zero-terminated. - */ - c = *((*pz)++); - if( c>=0xc0 ){ - c = sqlite3Utf8Trans1[c-0xc0]; - while( (*(*pz) & 0xc0)==0x80 ){ - c = (c<<6) + (0x3f & *((*pz)++)); - } - if( c<0x80 - || (c&0xFFFFF800)==0xD800 - || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } - } - return c; -} - - - - -/* -** If the TRANSLATE_TRACE macro is defined, the value of each Mem is -** printed on stderr on the way into and out of sqlite3VdbeMemTranslate(). -*/ -/* #define TRANSLATE_TRACE 1 */ - -#ifndef SQLITE_OMIT_UTF16 -/* -** This routine transforms the internal text encoding used by pMem to -** desiredEnc. It is an error if the string is already of the desired -** encoding, or if *pMem does not contain a string value. -*/ -SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){ - int len; /* Maximum length of output string in bytes */ - unsigned char *zOut; /* Output buffer */ - unsigned char *zIn; /* Input iterator */ - unsigned char *zTerm; /* End of input */ - unsigned char *z; /* Output iterator */ - unsigned int c; - - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - assert( pMem->flags&MEM_Str ); - assert( pMem->enc!=desiredEnc ); - assert( pMem->enc!=0 ); - assert( pMem->n>=0 ); - -#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG) - { - char zBuf[100]; - sqlite3VdbeMemPrettyPrint(pMem, zBuf); - fprintf(stderr, "INPUT: %s\n", zBuf); - } -#endif - - /* If the translation is between UTF-16 little and big endian, then - ** all that is required is to swap the byte order. This case is handled - ** differently from the others. - */ - if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){ - u8 temp; - int rc; - rc = sqlite3VdbeMemMakeWriteable(pMem); - if( rc!=SQLITE_OK ){ - assert( rc==SQLITE_NOMEM ); - return SQLITE_NOMEM_BKPT; - } - zIn = (u8*)pMem->z; - zTerm = &zIn[pMem->n&~1]; - while( zInenc = desiredEnc; - goto translate_out; - } - - /* Set len to the maximum number of bytes required in the output buffer. */ - if( desiredEnc==SQLITE_UTF8 ){ - /* When converting from UTF-16, the maximum growth results from - ** translating a 2-byte character to a 4-byte UTF-8 character. - ** A single byte is required for the output string - ** nul-terminator. - */ - pMem->n &= ~1; - len = pMem->n * 2 + 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 = pMem->n * 2 + 2; - } - - /* Set zIn to point at the start of the input buffer and zTerm to point 1 - ** byte past the end. - ** - ** Variable zOut is set to point at the output buffer, space obtained - ** from sqlite3_malloc(). - */ - zIn = (u8*)pMem->z; - zTerm = &zIn[pMem->n]; - zOut = sqlite3DbMallocRaw(pMem->db, len); - if( !zOut ){ - return SQLITE_NOMEM_BKPT; - } - z = zOut; - - if( pMem->enc==SQLITE_UTF8 ){ - if( desiredEnc==SQLITE_UTF16LE ){ - /* UTF-8 -> UTF-16 Little-endian */ - while( zIn UTF-16 Big-endian */ - while( zInn = (int)(z - zOut); - *z++ = 0; - }else{ - assert( desiredEnc==SQLITE_UTF8 ); - if( pMem->enc==SQLITE_UTF16LE ){ - /* UTF-16 Little-endian -> UTF-8 */ - while( zIn UTF-8 */ - while( zInn = (int)(z - zOut); - } - *z = 0; - assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len ); - - c = pMem->flags; - sqlite3VdbeMemRelease(pMem); - pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype)); - pMem->enc = desiredEnc; - pMem->z = (char*)zOut; - pMem->zMalloc = pMem->z; - pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z); - -translate_out: -#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG) - { - char zBuf[100]; - sqlite3VdbeMemPrettyPrint(pMem, zBuf); - fprintf(stderr, "OUTPUT: %s\n", zBuf); - } -#endif - return SQLITE_OK; -} -#endif /* SQLITE_OMIT_UTF16 */ - -#ifndef SQLITE_OMIT_UTF16 -/* -** This routine checks for a byte-order mark at the beginning of the -** UTF-16 string stored in *pMem. If one is present, it is removed and -** the encoding of the Mem adjusted. This routine does not do any -** byte-swapping, it just sets Mem.enc appropriately. -** -** The allocation (static, dynamic etc.) and encoding of the Mem may be -** changed by this function. -*/ -SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){ - int rc = SQLITE_OK; - u8 bom = 0; - - assert( pMem->n>=0 ); - if( pMem->n>1 ){ - u8 b1 = *(u8 *)pMem->z; - u8 b2 = *(((u8 *)pMem->z) + 1); - if( b1==0xFE && b2==0xFF ){ - bom = SQLITE_UTF16BE; - } - if( b1==0xFF && b2==0xFE ){ - bom = SQLITE_UTF16LE; - } - } - - if( bom ){ - rc = sqlite3VdbeMemMakeWriteable(pMem); - if( rc==SQLITE_OK ){ - pMem->n -= 2; - memmove(pMem->z, &pMem->z[2], pMem->n); - pMem->z[pMem->n] = '\0'; - pMem->z[pMem->n+1] = '\0'; - pMem->flags |= MEM_Term; - pMem->enc = bom; - } - } - return rc; -} -#endif /* SQLITE_OMIT_UTF16 */ - -/* -** pZ is a UTF-8 encoded unicode string. If nByte is less than zero, -** return the number of unicode characters in pZ up to (but not including) -** the first 0x00 byte. If nByte is not less than zero, return the -** number of unicode characters in the first nByte of pZ (or up to -** the first 0x00, whichever comes first). -*/ -SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){ - int r = 0; - const u8 *z = (const u8*)zIn; - const u8 *zTerm; - if( nByte>=0 ){ - zTerm = &z[nByte]; - }else{ - zTerm = (const u8*)(-1); - } - assert( z<=zTerm ); - while( *z!=0 && zmallocFailed ){ - sqlite3VdbeMemRelease(&m); - m.z = 0; - } - assert( (m.flags & MEM_Term)!=0 || db->mallocFailed ); - assert( (m.flags & MEM_Str)!=0 || db->mallocFailed ); - assert( m.z || db->mallocFailed ); - return m.z; -} - -/* -** zIn is a UTF-16 encoded unicode string at least nChar characters long. -** Return the number of bytes in the first nChar unicode characters -** in pZ. nChar must be non-negative. -*/ -SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){ - int c; - unsigned char const *z = zIn; - int n = 0; - - if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){ - while( n0 && n<=4 ); - z[0] = 0; - z = zBuf; - c = sqlite3Utf8Read((const u8**)&z); - t = i; - if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD; - if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD; - assert( c==t ); - assert( (z-zBuf)==n ); - } - for(i=0; i<0x00110000; i++){ - if( i>=0xD800 && i<0xE000 ) continue; - z = zBuf; - WRITE_UTF16LE(z, i); - n = (int)(z-zBuf); - assert( n>0 && n<=4 ); - z[0] = 0; - z = zBuf; - READ_UTF16LE(z, 1, c); - assert( c==i ); - assert( (z-zBuf)==n ); - } - for(i=0; i<0x00110000; i++){ - if( i>=0xD800 && i<0xE000 ) continue; - z = zBuf; - WRITE_UTF16BE(z, i); - n = (int)(z-zBuf); - assert( n>0 && n<=4 ); - z[0] = 0; - z = zBuf; - READ_UTF16BE(z, 1, c); - assert( c==i ); - assert( (z-zBuf)==n ); - } -} -#endif /* SQLITE_TEST */ -#endif /* SQLITE_OMIT_UTF16 */ - -/************** End of utf.c *************************************************/ -/************** Begin file util.c ********************************************/ -/* -** 2001 September 15 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** Utility functions used throughout sqlite. -** -** This file contains functions for allocating memory, comparing -** strings, and stuff like that. -** -*/ -/* #include "sqliteInt.h" */ -/* #include */ -#if HAVE_ISNAN || SQLITE_HAVE_ISNAN -# 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 - -/* -** Give a callback to the test harness that can be used to simulate faults -** in places where it is difficult or expensive to do so purely by means -** of inputs. -** -** The intent of the integer argument is to let the fault simulator know -** which of multiple sqlite3FaultSim() calls has been hit. -** -** Return whatever integer value the test callback returns, or return -** SQLITE_OK if no test callback is installed. -*/ -#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). -** -** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN. -** Otherwise, we have our own implementation that works on most systems. -*/ -SQLITE_PRIVATE int sqlite3IsNaN(double x){ - int rc; /* The value return */ -#if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN - /* - ** Systems that support the isnan() library function should probably - ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have - ** found that many systems do not have a working isnan() function so - ** this implementation is provided as an alternative. - ** - ** This NaN test sometimes fails if compiled on GCC with -ffast-math. - ** On the other hand, the use of -ffast-math comes with the following - ** warning: - ** - ** This option [-ffast-math] should never be turned on by any - ** -O option since it can result in incorrect output for programs - ** which depend on an exact implementation of IEEE or ISO - ** rules/specifications for math functions. - ** - ** Under MSVC, this NaN test may fail if compiled with a floating- - ** point precision mode other than /fp:precise. From the MSDN - ** documentation: - ** - ** The compiler [with /fp:precise] will properly handle comparisons - ** involving NaN. For example, x != x evaluates to true if x is NaN - ** ... - */ -#ifdef __FAST_MATH__ -# error SQLite will not work correctly with the -ffast-math option of GCC. -#endif - volatile double y = x; - volatile double z = y; - rc = (y!=z); -#else /* if HAVE_ISNAN */ - rc = isnan(x); -#endif /* HAVE_ISNAN */ - testcase( rc ); - return rc; -} -#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; - } -} - -/* -** 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-Feb-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; -} - -/* -** 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; - a = (unsigned char *)zLeft; - b = (unsigned char *)zRight; - for(;;){ - c = (int)UpperToLower[*a] - (int)UpperToLower[*b]; - if( c || *a==0 ) 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]; -} - -/* -** 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. Valid numbers -** are in one of these formats: -** -** [+-]digits[E[+-]digits] -** [+-]digits.[digits][E[+-]digits] -** [+-].digits[E[+-]digits] -** -** Leading and trailing whitespace is ignored for the purpose of determining -** validity. -** -** If some prefix of the input string is a valid number, this routine -** returns FALSE but it still converts the prefix and writes the result -** into *pResult. -*/ -SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){ -#ifndef SQLITE_OMIT_FLOATING_POINT - int incr; - const char *zEnd = z + length; - /* sign * significand * (10 ^ (esign * exponent)) */ - int sign = 1; /* sign of significand */ - i64 s = 0; /* significand */ - int d = 0; /* adjust exponent for shifting decimal point */ - int esign = 1; /* sign of exponent */ - int e = 0; /* exponent */ - int eValid = 1; /* True exponent is either not used or is well-formed */ - double result; - int nDigits = 0; - int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */ - - assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE ); - *pResult = 0.0; /* Default return value, in case of an error */ - - if( enc==SQLITE_UTF8 ){ - incr = 1; - }else{ - int i; - incr = 2; - assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 ); - 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=zEnd ) goto do_atof_calc; - - /* if decimal point is present */ - if( *z=='.' ){ - z+=incr; - /* 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; - - /* 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{ - LONGDOUBLE_TYPE scale = 1.0; - /* attempt to handle extremely small/large numbers better */ - if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/ - if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/ - while( e%308 ) { scale *= 1.0e+1; e -= 1; } - 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{ - /* 1.0e+22 is the largest power of 10 than can be - ** represented exactly. */ - while( e%22 ) { scale *= 1.0e+1; e -= 1; } - while( e>0 ) { scale *= 1.0e+22; e -= 22; } - 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 */ - return z==zEnd && nDigits>0 && eValid && nonNum==0; -#else - return !sqlite3Atoi64(z, pResult, length, enc); -#endif /* SQLITE_OMIT_FLOATING_POINT */ -} - -/* -** Compare the 19-character string zNum against the text representation -** value 2^63: 9223372036854775808. Return negative, zero, or positive -** if zNum is less than, equal to, or greater than the string. -** Note that zNum must contain exactly 19 characters. -** -** Unlike memcmp() this routine is guaranteed to return the difference -** in the values of the last digit if the only difference is in the -** last digit. So, for example, -** -** compare2pow63("9223372036854775800", 1) -** -** will return -8. -*/ -static int compare2pow63(const char *zNum, int incr){ - int c = 0; - int i; - /* 012345678901234567 */ - const char *pow63 = "922337203685477580"; - for(i=0; c==0 && i<18; i++){ - c = (zNum[i*incr]-pow63[i])*10; - } - if( c==0 ){ - c = zNum[18*incr] - '8'; - testcase( c==(-1) ); - testcase( c==0 ); - testcase( c==(+1) ); - } - return c; -} - -/* -** Convert zNum to a 64-bit signed integer. zNum must be decimal. This -** routine does *not* accept hexadecimal notation. -** -** Returns: -** -** 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 -** -** 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'; - } - if( u>LARGEST_INT64 ){ - *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64; - }else if( neg ){ - *pNum = -(i64)u; - }else{ - *pNum = (i64)u; - } - testcase( i==18 ); - testcase( i==19 ); - testcase( i==20 ); - if( &zNum[i]19*incr ){ /* Too many digits */ - /* zNum is empty or contains non-numeric text or is longer - ** than 19 digits (thus guaranteeing that it is too large) */ - return 2; - }else if( i<19*incr ){ - /* Less than 19 digits, so we know that it fits in 64 bits */ - assert( u<=LARGEST_INT64 ); - return rc; - }else{ - /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */ - c = compare2pow63(zNum, incr); - if( c<0 ){ - /* zNum is less than 9223372036854775808 so it fits */ - assert( u<=LARGEST_INT64 ); - return rc; - }else if( c>0 ){ - /* zNum is greater than 9223372036854775808 so it overflows */ - return 2; - }else{ - /* zNum is exactly 9223372036854775808. Fits if negative. The - ** special case 2 overflow if positive */ - assert( u-1==LARGEST_INT64 ); - return neg ? rc : 3; - } - } -} - -/* -** Transform a UTF-8 integer literal, in either decimal or hexadecimal, -** into a 64-bit signed integer. This routine accepts hexadecimal literals, -** whereas sqlite3Atoi64() does not. -** -** Returns: -** -** 0 Successful transformation. Fits in a 64-bit signed integer. -** 1 Excess text after the integer value -** 2 Integer too large for a 64-bit signed integer or is malformed -** 3 Special case of 9223372036854775808 -*/ -SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){ -#ifndef SQLITE_OMIT_HEX_INTEGER - if( z[0]=='0' - && (z[1]=='x' || z[1]=='X') - ){ - u64 u = 0; - int i, k; - for(i=2; z[i]=='0'; i++){} - for(k=i; sqlite3Isxdigit(z[k]); k++){ - u = u*16 + sqlite3HexToInt(z[k]); - } - memcpy(pOut, &u, 8); - return (z[k]==0 && k-i<=16) ? 0 : 2; - }else -#endif /* SQLITE_OMIT_HEX_INTEGER */ - { - return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8); - } -} - -/* -** If zNum represents an integer that will fit in 32-bits, then set -** *pValue to that integer and return true. Otherwise return false. -** -** This routine accepts both decimal and hexadecimal notation for integers. -** -** Any non-numeric characters that following zNum are ignored. -** This is different from sqlite3Atoi64() which requires the -** input number to be zero-terminated. -*/ -SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){ - sqlite_int64 v = 0; - int i, c; - int neg = 0; - if( zNum[0]=='-' ){ - neg = 1; - zNum++; - }else if( zNum[0]=='+' ){ - zNum++; - } -#ifndef SQLITE_OMIT_HEX_INTEGER - else if( zNum[0]=='0' - && (zNum[1]=='x' || zNum[1]=='X') - && sqlite3Isxdigit(zNum[2]) - ){ - u32 u = 0; - zNum += 2; - while( zNum[0]=='0' ) zNum++; - for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){ - u = u*16 + sqlite3HexToInt(zNum[i]); - } - if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){ - memcpy(pValue, &u, 4); - return 1; - }else{ - return 0; - } - } -#endif - if( !sqlite3Isdigit(zNum[0]) ) return 0; - while( zNum[0]=='0' ) zNum++; - for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){ - v = v*10 + c; - } - - /* The longest decimal representation of a 32 bit integer is 10 digits: - ** - ** 1234567890 - ** 2^31 -> 2147483648 - */ - testcase( i==10 ); - if( i>10 ){ - return 0; - } - testcase( v-neg==2147483647 ); - if( v-neg>2147483647 ){ - return 0; - } - if( neg ){ - v = -v; - } - *pValue = (int)v; - return 1; -} - -/* -** Return a 32-bit integer value extracted from a string. If the -** string is not an integer, just return 0. -*/ -SQLITE_PRIVATE int sqlite3Atoi(const char *z){ - int x = 0; - if( z ) sqlite3GetInt32(z, &x); - return x; -} - -/* -** The variable-length integer encoding is as follows: -** -** KEY: -** A = 0xxxxxxx 7 bits of data and one flag bit -** B = 1xxxxxxx 7 bits of data and one flag bit -** C = xxxxxxxx 8 bits of data -** -** 7 bits - A -** 14 bits - BA -** 21 bits - BBA -** 28 bits - BBBA -** 35 bits - BBBBA -** 42 bits - BBBBBA -** 49 bits - BBBBBBA -** 56 bits - BBBBBBBA -** 64 bits - BBBBBBBBC -*/ - -/* -** Write a 64-bit variable-length integer to memory starting at p[0]. -** The length of data write will be between 1 and 9 bytes. The number -** of bytes written is returned. -** -** A variable-length integer consists of the lower 7 bits of each byte -** for all bytes that have the 8th bit set and one byte with the 8th -** bit clear. Except, if we get to the 9th byte, it stores the full -** 8 bits and is the last byte. -*/ -static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){ - int i, j, n; - u8 buf[10]; - if( v & (((u64)0xff000000)<<32) ){ - p[8] = (u8)v; - v >>= 8; - for(i=7; i>=0; i--){ - p[i] = (u8)((v & 0x7f) | 0x80); - v >>= 7; - } - return 9; - } - n = 0; - do{ - buf[n++] = (u8)((v & 0x7f) | 0x80); - v >>= 7; - }while( v!=0 ); - buf[0] &= 0x7f; - assert( n<=9 ); - for(i=0, j=n-1; j>=0; j--, i++){ - p[i] = buf[j]; - } - return n; -} -SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){ - if( v<=0x7f ){ - p[0] = v&0x7f; - return 1; - } - if( v<=0x3fff ){ - p[0] = ((v>>7)&0x7f)|0x80; - p[1] = v&0x7f; - return 2; - } - return putVarint64(p,v); -} - -/* -** Bitmasks used by sqlite3GetVarint(). These precomputed constants -** are defined here rather than simply putting the constant expressions -** inline in order to work around bugs in the RVT compiler. -** -** SLOT_2_0 A mask for (0x7f<<14) | 0x7f -** -** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0 -*/ -#define SLOT_2_0 0x001fc07f -#define SLOT_4_2_0 0xf01fc07f - - -/* -** Read a 64-bit variable-length integer from memory starting at p[0]. -** Return the number of bytes read. The value is stored in *v. -*/ -SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){ - u32 a,b,s; - - a = *p; - /* a: p0 (unmasked) */ - if (!(a&0x80)) - { - *v = a; - return 1; - } - - p++; - b = *p; - /* b: p1 (unmasked) */ - if (!(b&0x80)) - { - a &= 0x7f; - a = a<<7; - a |= b; - *v = a; - 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)) ); - - p++; - a = a<<14; - a |= *p; - /* a: p0<<14 | p2 (unmasked) */ - if (!(a&0x80)) - { - a &= SLOT_2_0; - b &= 0x7f; - b = b<<7; - a |= b; - *v = a; - return 3; - } - - /* CSE1 from below */ - a &= SLOT_2_0; - p++; - b = b<<14; - b |= *p; - /* b: p1<<14 | p3 (unmasked) */ - if (!(b&0x80)) - { - b &= SLOT_2_0; - /* moved CSE1 up */ - /* a &= (0x7f<<14)|(0x7f); */ - a = a<<7; - a |= b; - *v = a; - return 4; - } - - /* a: p0<<14 | p2 (masked) */ - /* b: p1<<14 | p3 (unmasked) */ - /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ - /* moved CSE1 up */ - /* a &= (0x7f<<14)|(0x7f); */ - b &= SLOT_2_0; - s = a; - /* s: p0<<14 | p2 (masked) */ - - p++; - a = a<<14; - a |= *p; - /* a: p0<<28 | p2<<14 | p4 (unmasked) */ - if (!(a&0x80)) - { - /* we can skip these cause they were (effectively) done above - ** while calculating s */ - /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */ - /* b &= (0x7f<<14)|(0x7f); */ - b = b<<7; - a |= b; - s = s>>18; - *v = ((u64)s)<<32 | a; - return 5; - } - - /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ - s = s<<7; - s |= b; - /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ - - p++; - b = b<<14; - b |= *p; - /* b: p1<<28 | p3<<14 | p5 (unmasked) */ - if (!(b&0x80)) - { - /* we can skip this cause it was (effectively) done above in calc'ing s */ - /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */ - a &= SLOT_2_0; - a = a<<7; - a |= b; - s = s>>18; - *v = ((u64)s)<<32 | a; - return 6; - } - - p++; - a = a<<14; - a |= *p; - /* a: p2<<28 | p4<<14 | p6 (unmasked) */ - if (!(a&0x80)) - { - a &= SLOT_4_2_0; - b &= SLOT_2_0; - b = b<<7; - a |= b; - s = s>>11; - *v = ((u64)s)<<32 | a; - return 7; - } - - /* CSE2 from below */ - a &= SLOT_2_0; - p++; - b = b<<14; - b |= *p; - /* b: p3<<28 | p5<<14 | p7 (unmasked) */ - if (!(b&0x80)) - { - b &= SLOT_4_2_0; - /* moved CSE2 up */ - /* a &= (0x7f<<14)|(0x7f); */ - a = a<<7; - a |= b; - s = s>>4; - *v = ((u64)s)<<32 | a; - return 8; - } - - p++; - a = a<<15; - a |= *p; - /* a: p4<<29 | p6<<15 | p8 (unmasked) */ - - /* moved CSE2 up */ - /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */ - b &= SLOT_2_0; - b = b<<8; - a |= b; - - s = s<<4; - b = p[-4]; - b &= 0x7f; - b = b>>3; - s |= b; - - *v = ((u64)s)<<32 | a; - - return 9; -} - -/* -** Read a 32-bit variable-length integer from memory starting at p[0]. -** Return the number of bytes read. The value is stored in *v. -** -** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned -** integer, then set *v to 0xffffffff. -** -** A MACRO version, getVarint32, is provided which inlines the -** single-byte case. All code should use the MACRO version as -** this function assumes the single-byte case has already been handled. -*/ -SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){ - u32 a,b; - - /* The 1-byte case. Overwhelmingly the most common. Handled inline - ** by the getVarin32() macro */ - a = *p; - /* a: p0 (unmasked) */ -#ifndef getVarint32 - if (!(a&0x80)) - { - /* Values between 0 and 127 */ - *v = a; - return 1; - } -#endif - - /* The 2-byte case */ - p++; - b = *p; - /* b: p1 (unmasked) */ - if (!(b&0x80)) - { - /* Values between 128 and 16383 */ - a &= 0x7f; - a = a<<7; - *v = a | b; - return 2; - } - - /* The 3-byte case */ - p++; - a = a<<14; - a |= *p; - /* a: p0<<14 | p2 (unmasked) */ - if (!(a&0x80)) - { - /* Values between 16384 and 2097151 */ - a &= (0x7f<<14)|(0x7f); - b &= 0x7f; - b = b<<7; - *v = a | b; - return 3; - } - - /* A 32-bit varint is used to store size information in btrees. - ** Objects are rarely larger than 2MiB limit of a 3-byte varint. - ** A 3-byte varint is sufficient, for example, to record the size - ** of a 1048569-byte BLOB or string. - ** - ** We only unroll the first 1-, 2-, and 3- byte cases. The very - ** rare larger cases can be handled by the slower 64-bit varint - ** routine. - */ -#if 1 - { - u64 v64; - u8 n; - - p -= 2; - n = sqlite3GetVarint(p, &v64); - assert( n>3 && n<=9 ); - if( (v64 & SQLITE_MAX_U32)!=v64 ){ - *v = 0xffffffff; - }else{ - *v = (u32)v64; - } - return n; - } - -#else - /* For following code (kept for historical record only) shows an - ** unrolling for the 3- and 4-byte varint cases. This code is - ** slightly faster, but it is also larger and much harder to test. - */ - p++; - b = b<<14; - b |= *p; - /* b: p1<<14 | p3 (unmasked) */ - if (!(b&0x80)) - { - /* Values between 2097152 and 268435455 */ - b &= (0x7f<<14)|(0x7f); - a &= (0x7f<<14)|(0x7f); - a = a<<7; - *v = a | b; - return 4; - } - - p++; - a = a<<14; - a |= *p; - /* a: p0<<28 | p2<<14 | p4 (unmasked) */ - if (!(a&0x80)) - { - /* Values between 268435456 and 34359738367 */ - a &= SLOT_4_2_0; - b &= SLOT_4_2_0; - b = b<<7; - *v = a | b; - return 5; - } - - /* We can only reach this point when reading a corrupt database - ** file. In that case we are not in any hurry. Use the (relatively - ** slow) general-purpose sqlite3GetVarint() routine to extract the - ** value. */ - { - u64 v64; - u8 n; - - p -= 4; - n = sqlite3GetVarint(p, &v64); - assert( n>5 && n<=9 ); - *v = (u32)v64; - return n; - } -#endif -} - -/* -** Return the number of bytes that will be needed to store the given -** 64-bit integer. -*/ -SQLITE_PRIVATE int sqlite3VarintLen(u64 v){ - int i; - for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); } - return i; -} - - -/* -** Read or write a four-byte big-endian integer value. -*/ -SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){ -#if SQLITE_BYTEORDER==4321 - u32 x; - memcpy(&x,p,4); - return x; -#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 - u32 x; - memcpy(&x,p,4); - return __builtin_bswap32(x); -#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 - u32 x; - memcpy(&x,p,4); - return _byteswap_ulong(x); -#else - testcase( p[0]&0x80 ); - return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3]; -#endif -} -SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){ -#if SQLITE_BYTEORDER==4321 - memcpy(p,&v,4); -#elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000 - u32 x = __builtin_bswap32(v); - memcpy(p,&x,4); -#elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300 - u32 x = _byteswap_ulong(v); - memcpy(p,&x,4); -#else - p[0] = (u8)(v>>24); - p[1] = (u8)(v>>16); - p[2] = (u8)(v>>8); - p[3] = (u8)v; -#endif -} - - - -/* -** Translate a single byte of Hex into an integer. -** This routine only works if h really is a valid hexadecimal -** character: 0..9a..fA..F -*/ -SQLITE_PRIVATE u8 sqlite3HexToInt(int h){ - assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') ); -#ifdef SQLITE_ASCII - h += 9*(1&(h>>6)); -#endif -#ifdef SQLITE_EBCDIC - h += 9*(1&~(h>>4)); -#endif - return (u8)(h & 0xf); -} - -#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC) -/* -** Convert a BLOB literal of the form "x'hhhhhh'" into its binary -** value. Return a pointer to its binary value. Space to hold the -** binary value has been obtained from malloc and must be freed by -** the calling routine. -*/ -SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){ - char *zBlob; - int i; - - zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1); - n--; - if( zBlob ){ - for(i=0; imagic; - if( magic!=SQLITE_MAGIC_OPEN ){ - if( sqlite3SafetyCheckSickOrOk(db) ){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - logBadConnection("unopened"); - } - return 0; - }else{ - return 1; - } -} -SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){ - u32 magic; - magic = db->magic; - if( magic!=SQLITE_MAGIC_SICK && - magic!=SQLITE_MAGIC_OPEN && - magic!=SQLITE_MAGIC_BUSY ){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - logBadConnection("invalid"); - return 0; - }else{ - return 1; - } -} - -/* -** Attempt to add, substract, or multiply the 64-bit signed value iB against -** the other 64-bit signed integer at *pA and store the result in *pA. -** Return 0 on success. Or if the operation would have resulted in an -** overflow, leave *pA unchanged and return 1. -*/ -SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){ -#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER) - return __builtin_add_overflow(*pA, iB, pA); -#else - i64 iA = *pA; - testcase( iA==0 ); testcase( iA==1 ); - testcase( iB==-1 ); testcase( iB==0 ); - if( iB>=0 ){ - testcase( iA>0 && LARGEST_INT64 - iA == iB ); - testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 ); - if( iA>0 && LARGEST_INT64 - iA < iB ) return 1; - }else{ - testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 ); - testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 ); - if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1; - } - *pA += iB; - return 0; -#endif -} -SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){ -#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER) - return __builtin_sub_overflow(*pA, iB, pA); -#else - testcase( iB==SMALLEST_INT64+1 ); - if( iB==SMALLEST_INT64 ){ - testcase( (*pA)==(-1) ); testcase( (*pA)==0 ); - if( (*pA)>=0 ) return 1; - *pA -= iB; - return 0; - }else{ - return sqlite3AddInt64(pA, -iB); - } -#endif -} -SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){ -#if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER) - return __builtin_mul_overflow(*pA, iB, pA); -#else - i64 iA = *pA; - if( iB>0 ){ - if( iA>LARGEST_INT64/iB ) return 1; - if( iA0 ){ - if( iBLARGEST_INT64/-iB ) return 1; - } - } - *pA = iA*iB; - return 0; -#endif -} - -/* -** Compute the absolute value of a 32-bit signed integer, of possible. Or -** if the integer has a value of -2147483648, return +2147483647 -*/ -SQLITE_PRIVATE int sqlite3AbsInt32(int x){ - if( x>=0 ) return x; - if( x==(int)0x80000000 ) return 0x7fffffff; - return -x; -} - -#ifdef SQLITE_ENABLE_8_3_NAMES -/* -** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database -** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and -** if filename in z[] has a suffix (a.k.a. "extension") that is longer than -** three characters, then shorten the suffix on z[] to be the last three -** characters of the original suffix. -** -** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always -** do the suffix shortening regardless of URI parameter. -** -** Examples: -** -** test.db-journal => test.nal -** test.db-wal => test.wal -** test.db-shm => test.shm -** test.db-mj7f3319fa => test.9fa -*/ -SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){ -#if SQLITE_ENABLE_8_3_NAMES<2 - if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) ) -#endif - { - int i, sz; - sz = sqlite3Strlen30(z); - for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){} - if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4); - } -} -#endif - -/* -** Find (an approximate) sum of two LogEst values. This computation is -** not a simple "+" operator because LogEst is stored as a logarithmic -** value. -** -*/ -SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){ - static const unsigned char x[] = { - 10, 10, /* 0,1 */ - 9, 9, /* 2,3 */ - 8, 8, /* 4,5 */ - 7, 7, 7, /* 6,7,8 */ - 6, 6, 6, /* 9,10,11 */ - 5, 5, 5, /* 12-14 */ - 4, 4, 4, 4, /* 15-18 */ - 3, 3, 3, 3, 3, 3, /* 19-24 */ - 2, 2, 2, 2, 2, 2, 2, /* 25-31 */ - }; - if( a>=b ){ - if( a>b+49 ) return a; - if( a>b+31 ) return a+1; - return a+x[a-b]; - }else{ - if( b>a+49 ) return b; - if( b>a+31 ) return b+1; - return b+x[b-a]; - } -} - -/* -** Convert an integer into a LogEst. In other words, compute an -** approximation for 10*log2(x). -*/ -SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){ - static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 }; - LogEst y = 40; - if( x<8 ){ - if( x<2 ) return 0; - while( x<8 ){ y -= 10; x <<= 1; } - }else{ -#if GCC_VERSION>=5004000 - int i = 60 - __builtin_clzll(x); - y += i*10; - x >>= i; -#else - while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/ - while( x>15 ){ y += 10; x >>= 1; } -#endif - } - return a[x&7] + y - 10; -} - -#ifndef SQLITE_OMIT_VIRTUALTABLE -/* -** Convert a double into a LogEst -** In other words, compute an approximation for 10*log2(x). -*/ -SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){ - u64 a; - LogEst e; - assert( sizeof(x)==8 && sizeof(a)==8 ); - if( x<=1 ) return 0; - if( x<=2000000000 ) return sqlite3LogEst((u64)x); - memcpy(&a, &x, 8); - e = (a>>52) - 1022; - return e*10; -} -#endif /* SQLITE_OMIT_VIRTUALTABLE */ - -#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \ - defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \ - defined(SQLITE_EXPLAIN_ESTIMATED_ROWS) -/* -** Convert a LogEst into an integer. -** -** Note that this routine is only used when one or more of various -** non-standard compile-time options is enabled. -*/ -SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){ - u64 n; - n = x%10; - x /= 10; - if( n>=5 ) n -= 2; - else if( n>=1 ) n -= 1; -#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \ - defined(SQLITE_EXPLAIN_ESTIMATED_ROWS) - if( x>60 ) return (u64)LARGEST_INT64; -#else - /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input - ** possible to this routine is 310, resulting in a maximum x of 31 */ - assert( x<=60 ); -#endif - return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x); -} -#endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */ - -/* -** Add a new name/number pair to a VList. This might require that the -** VList object be reallocated, so return the new VList. If an OOM -** error occurs, the original VList returned and the -** db->mallocFailed flag is set. -** -** A VList is really just an array of integers. To destroy a VList, -** simply pass it to sqlite3DbFree(). -** -** The first integer is the number of integers allocated for the whole -** VList. The second integer is the number of integers actually used. -** Each name/number pair is encoded by subsequent groups of 3 or more -** integers. -** -** Each name/number pair starts with two integers which are the numeric -** value for the pair and the size of the name/number pair, respectively. -** The text name overlays one or more following integers. The text name -** is always zero-terminated. -** -** Conceptually: -** -** struct VList { -** int nAlloc; // Number of allocated slots -** int nUsed; // Number of used slots -** struct VListEntry { -** int iValue; // Value for this entry -** int nSlot; // Slots used by this entry -** // ... variable name goes here -** } a[0]; -** } -** -** During code generation, pointers to the variable names within the -** VList are taken. When that happens, nAlloc is set to zero as an -** indication that the VList may never again be enlarged, since the -** accompanying realloc() would invalidate the pointers. -*/ -SQLITE_PRIVATE VList *sqlite3VListAdd( - sqlite3 *db, /* The database connection used for malloc() */ - VList *pIn, /* The input VList. Might be NULL */ - const char *zName, /* Name of symbol to add */ - int nName, /* Bytes of text in zName */ - int iVal /* Value to associate with zName */ -){ - int nInt; /* number of sizeof(int) objects needed for zName */ - char *z; /* Pointer to where zName will be stored */ - int i; /* Index in pIn[] where zName is stored */ - - nInt = nName/4 + 3; - assert( pIn==0 || pIn[0]>=3 ); /* Verify ok to add new elements */ - if( pIn==0 || pIn[1]+nInt > pIn[0] ){ - /* Enlarge the allocation */ - int nAlloc = (pIn ? pIn[0]*2 : 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 */ - 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; - } - pEntry->count--; - assert( pEntry->count>=0 ); - } - 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 */ "PrevIfOpen" OpHelp(""), - /* 5 */ "NextIfOpen" OpHelp(""), - /* 6 */ "Prev" OpHelp(""), - /* 7 */ "Next" OpHelp(""), - /* 8 */ "Checkpoint" OpHelp(""), - /* 9 */ "JournalMode" OpHelp(""), - /* 10 */ "Vacuum" OpHelp(""), - /* 11 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"), - /* 12 */ "VUpdate" OpHelp("data=r[P3@P2]"), - /* 13 */ "Goto" OpHelp(""), - /* 14 */ "Gosub" OpHelp(""), - /* 15 */ "InitCoroutine" OpHelp(""), - /* 16 */ "Yield" OpHelp(""), - /* 17 */ "MustBeInt" OpHelp(""), - /* 18 */ "Jump" OpHelp(""), - /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"), - /* 20 */ "Once" OpHelp(""), - /* 21 */ "If" OpHelp(""), - /* 22 */ "IfNot" OpHelp(""), - /* 23 */ "IfNullRow" OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"), - /* 24 */ "SeekLT" OpHelp("key=r[P3@P4]"), - /* 25 */ "SeekLE" OpHelp("key=r[P3@P4]"), - /* 26 */ "SeekGE" OpHelp("key=r[P3@P4]"), - /* 27 */ "SeekGT" 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 */ "Return" OpHelp(""), - /* 64 */ "EndCoroutine" OpHelp(""), - /* 65 */ "HaltIfNull" OpHelp("if r[P3]=null halt"), - /* 66 */ "Halt" OpHelp(""), - /* 67 */ "Integer" OpHelp("r[P2]=P1"), - /* 68 */ "Int64" OpHelp("r[P2]=P4"), - /* 69 */ "String" OpHelp("r[P2]='P4' (len=P1)"), - /* 70 */ "Null" OpHelp("r[P2..P3]=NULL"), - /* 71 */ "SoftNull" OpHelp("r[P1]=NULL"), - /* 72 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"), - /* 73 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"), - /* 74 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"), - /* 75 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"), - /* 76 */ "SCopy" OpHelp("r[P2]=r[P1]"), - /* 77 */ "IntCopy" OpHelp("r[P2]=r[P1]"), - /* 78 */ "ResultRow" OpHelp("output=r[P1@P2]"), - /* 79 */ "CollSeq" OpHelp(""), - /* 80 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"), - /* 81 */ "RealAffinity" OpHelp(""), - /* 82 */ "Cast" OpHelp("affinity(r[P1])"), - /* 83 */ "Permutation" OpHelp(""), - /* 84 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"), - /* 85 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"), - /* 86 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<>r[P1]"), - /* 88 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"), - /* 89 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"), - /* 90 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"), - /* 91 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"), - /* 92 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"), - /* 93 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"), - /* 94 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"), - /* 95 */ "BitNot" OpHelp("r[P1]= ~r[P1]"), - /* 96 */ "Column" OpHelp("r[P3]=PX"), - /* 97 */ "String8" OpHelp("r[P2]='P4'"), - /* 98 */ "Affinity" OpHelp("affinity(r[P1@P2])"), - /* 99 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"), - /* 100 */ "Count" OpHelp("r[P2]=count()"), - /* 101 */ "ReadCookie" OpHelp(""), - /* 102 */ "SetCookie" OpHelp(""), - /* 103 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"), - /* 104 */ "OpenRead" OpHelp("root=P2 iDb=P3"), - /* 105 */ "OpenWrite" OpHelp("root=P2 iDb=P3"), - /* 106 */ "OpenDup" OpHelp(""), - /* 107 */ "OpenAutoindex" OpHelp("nColumn=P2"), - /* 108 */ "OpenEphemeral" OpHelp("nColumn=P2"), - /* 109 */ "SorterOpen" OpHelp(""), - /* 110 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"), - /* 111 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"), - /* 112 */ "Close" OpHelp(""), - /* 113 */ "ColumnsUsed" OpHelp(""), - /* 114 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"), - /* 115 */ "NewRowid" OpHelp("r[P2]=rowid"), - /* 116 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"), - /* 117 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"), - /* 118 */ "Delete" OpHelp(""), - /* 119 */ "ResetCount" OpHelp(""), - /* 120 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"), - /* 121 */ "SorterData" OpHelp("r[P2]=data"), - /* 122 */ "RowData" OpHelp("r[P2]=data"), - /* 123 */ "Rowid" OpHelp("r[P2]=rowid"), - /* 124 */ "NullRow" OpHelp(""), - /* 125 */ "SeekEnd" OpHelp(""), - /* 126 */ "SorterInsert" OpHelp("key=r[P2]"), - /* 127 */ "IdxInsert" OpHelp("key=r[P2]"), - /* 128 */ "IdxDelete" OpHelp("key=r[P2@P3]"), - /* 129 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"), - /* 130 */ "IdxRowid" OpHelp("r[P2]=rowid"), - /* 131 */ "Destroy" OpHelp(""), - /* 132 */ "Real" OpHelp("r[P2]=P4"), - /* 133 */ "Clear" OpHelp(""), - /* 134 */ "ResetSorter" OpHelp(""), - /* 135 */ "CreateBtree" OpHelp("r[P2]=root iDb=P1 flags=P3"), - /* 136 */ "SqlExec" OpHelp(""), - /* 137 */ "ParseSchema" OpHelp(""), - /* 138 */ "LoadAnalysis" OpHelp(""), - /* 139 */ "DropTable" OpHelp(""), - /* 140 */ "DropIndex" OpHelp(""), - /* 141 */ "DropTrigger" OpHelp(""), - /* 142 */ "IntegrityCk" OpHelp(""), - /* 143 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"), - /* 144 */ "Param" OpHelp(""), - /* 145 */ "FkCounter" OpHelp("fkctr[P1]+=P2"), - /* 146 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"), - /* 147 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"), - /* 148 */ "AggStep0" OpHelp("accum=r[P3] step(r[P2@P5])"), - /* 149 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"), - /* 150 */ "AggFinal" OpHelp("accum=r[P1] N=P2"), - /* 151 */ "Expire" OpHelp(""), - /* 152 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"), - /* 153 */ "VBegin" OpHelp(""), - /* 154 */ "VCreate" OpHelp(""), - /* 155 */ "VDestroy" OpHelp(""), - /* 156 */ "VOpen" OpHelp(""), - /* 157 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"), - /* 158 */ "VRename" OpHelp(""), - /* 159 */ "Pagecount" OpHelp(""), - /* 160 */ "MaxPgcnt" OpHelp(""), - /* 161 */ "PureFunc0" OpHelp(""), - /* 162 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"), - /* 163 */ "PureFunc" OpHelp(""), - /* 164 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"), - /* 165 */ "CursorHint" OpHelp(""), - /* 166 */ "Noop" OpHelp(""), - /* 167 */ "Explain" OpHelp(""), - }; - return azName[i]; -} -#endif - -/************** End of opcodes.c *********************************************/ -/************** Begin file os_unix.c *****************************************/ -/* -** 2004 May 22 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This file contains the VFS implementation for unix-like operating systems -** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others. -** -** There are actually several different VFS implementations in this file. -** The differences are in the way that file locking is done. The default -** implementation uses Posix Advisory Locks. Alternative implementations -** use flock(), dot-files, various proprietary locking schemas, or simply -** skip locking all together. -** -** This source file is organized into divisions where the logic for various -** subfunctions is contained within the appropriate division. PLEASE -** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed -** in the correct division and should be clearly labeled. -** -** The layout of divisions is as follows: -** -** * General-purpose declarations and utility functions. -** * Unique file ID logic used by VxWorks. -** * Various locking primitive implementations (all except proxy locking): -** + for Posix Advisory Locks -** + for no-op locks -** + for dot-file locks -** + for flock() locking -** + for named semaphore locks (VxWorks only) -** + for AFP filesystem locks (MacOSX only) -** * sqlite3_file methods not associated with locking. -** * Definitions of sqlite3_io_methods objects for all locking -** methods plus "finder" functions for each locking method. -** * sqlite3_vfs method implementations. -** * Locking primitives for the proxy uber-locking-method. (MacOSX only) -** * Definitions of sqlite3_vfs objects for all locking methods -** plus implementations of sqlite3_os_init() and sqlite3_os_end(). -*/ -/* #include "sqliteInt.h" */ -#if SQLITE_OS_UNIX /* This file is used on unix only */ - -/* -** There are various methods for file locking used for concurrency -** control: -** -** 1. POSIX locking (the default), -** 2. No locking, -** 3. Dot-file locking, -** 4. flock() locking, -** 5. AFP locking (OSX only), -** 6. Named POSIX semaphores (VXWorks only), -** 7. proxy locking. (OSX only) -** -** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE -** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic -** selection of the appropriate locking style based on the filesystem -** where the database is located. -*/ -#if !defined(SQLITE_ENABLE_LOCKING_STYLE) -# if defined(__APPLE__) -# define SQLITE_ENABLE_LOCKING_STYLE 1 -# else -# define SQLITE_ENABLE_LOCKING_STYLE 0 -# endif -#endif - -/* Use pread() and pwrite() if they are available */ -#if defined(__APPLE__) -# define HAVE_PREAD 1 -# define HAVE_PWRITE 1 -#endif -#if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64) -# undef USE_PREAD -# define USE_PREAD64 1 -#elif defined(HAVE_PREAD) && defined(HAVE_PWRITE) -# undef USE_PREAD64 -# define USE_PREAD 1 -#endif - -/* -** standard include files. -*/ -#include -#include -#include -#include -#include -/* #include */ -#include -#include -#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 -# include -#endif - -#if SQLITE_ENABLE_LOCKING_STYLE -/* # include */ -# include -# include -#endif /* SQLITE_ENABLE_LOCKING_STYLE */ - -#if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \ - (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000)) -# if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \ - && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0)) -# define HAVE_GETHOSTUUID 1 -# else -# warning "gethostuuid() is disabled." -# endif -#endif - - -#if OS_VXWORKS -/* # include */ -# include -# include -#endif /* OS_VXWORKS */ - -#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE -# include -#endif - -#ifdef HAVE_UTIME -# include -#endif - -/* -** Allowed values of unixFile.fsFlags -*/ -#define SQLITE_FSFLAGS_IS_MSDOS 0x1 - -/* -** If we are to be thread-safe, include the pthreads header and define -** the SQLITE_UNIX_THREADS macro. -*/ -#if SQLITE_THREADSAFE -/* # include */ -# define SQLITE_UNIX_THREADS 1 -#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 -#if OS_VXWORKS - struct vxworksFileId *pId; /* Unique file ID */ -#endif -#ifdef SQLITE_DEBUG - /* The next group of variables are used to track whether or not the - ** transaction counter in bytes 24-27 of database files are updated - ** whenever any part of the database changes. An assertion fault will - ** occur if a file is updated without also updating the transaction - ** counter. This test is made to avoid new problems similar to the - ** one described by ticket #3584. - */ - unsigned char transCntrChng; /* True if the transaction counter changed */ - unsigned char dbUpdate; /* True if any part of database file changed */ - unsigned char inNormalWrite; /* True if in a normal write operation */ - -#endif - -#ifdef SQLITE_TEST - /* In test mode, increase the size of this structure a bit so that - ** it is larger than the struct CrashFile defined in test6.c. - */ - char aPadding[32]; -#endif -}; - -/* This variable holds the process id (pid) from when the xRandomness() -** method was called. If xOpen() is called from a different process id, -** indicating that a fork() has occurred, the PRNG will be reset. -*/ -static pid_t randomnessPid = 0; - -/* -** Allowed values for the unixFile.ctrlFlags bitmask: -*/ -#define UNIXFILE_EXCL 0x01 /* Connections from one process only */ -#define UNIXFILE_RDONLY 0x02 /* Connection is read only */ -#define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */ -#ifndef SQLITE_DISABLE_DIRSYNC -# define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */ -#else -# define UNIXFILE_DIRSYNC 0x00 -#endif -#define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */ -#define UNIXFILE_DELETE 0x20 /* Delete on close */ -#define UNIXFILE_URI 0x40 /* Filename might have query parameters */ -#define UNIXFILE_NOLOCK 0x80 /* Do no file locking */ - -/* -** Include code that is common to all os_*.c files -*/ -/************** Include os_common.h in the middle of os_unix.c ***************/ -/************** Begin file os_common.h ***************************************/ -/* -** 2004 May 22 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This file contains macros and a little bit of code that is common to -** all of the platform-specific files (os_*.c) and is #included into those -** files. -** -** This file should be #included by the os_*.c files only. It is not a -** general purpose header file. -*/ -#ifndef _OS_COMMON_H_ -#define _OS_COMMON_H_ - -/* -** At least two bugs have slipped in because we changed the MEMORY_DEBUG -** macro to SQLITE_DEBUG and some older makefiles have not yet made the -** switch. The following code should catch this problem at compile-time. -*/ -#ifdef MEMORY_DEBUG -# error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead." -#endif - -/* -** Macros for performance tracing. Normally turned off. Only works -** on i486 hardware. -*/ -#ifdef SQLITE_PERFORMANCE_TRACE - -/* -** hwtime.h contains inline assembler code for implementing -** high-performance timing routines. -*/ -/************** Include hwtime.h in the middle of os_common.h ****************/ -/************** Begin file hwtime.h ******************************************/ -/* -** 2008 May 27 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This file contains inline asm code for retrieving "high-performance" -** counters for x86 class CPUs. -*/ -#ifndef SQLITE_HWTIME_H -#define SQLITE_HWTIME_H - -/* -** The following routine only works on pentium-class (or newer) processors. -** It uses the RDTSC opcode to read the cycle count value out of the -** processor and returns that value. This can be used for high-res -** profiling. -*/ -#if (defined(__GNUC__) || defined(_MSC_VER)) && \ - (defined(i386) || defined(__i386__) || defined(_M_IX86)) - - #if defined(__GNUC__) - - __inline__ sqlite_uint64 sqlite3Hwtime(void){ - unsigned int lo, hi; - __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); - return (sqlite_uint64)hi << 32 | lo; - } - - #elif defined(_MSC_VER) - - __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){ - __asm { - rdtsc - ret ; return value at EDX:EAX - } - } - - #endif - -#elif (defined(__GNUC__) && defined(__x86_64__)) - - __inline__ sqlite_uint64 sqlite3Hwtime(void){ - unsigned long val; - __asm__ __volatile__ ("rdtsc" : "=A" (val)); - return val; - } - -#elif (defined(__GNUC__) && defined(__ppc__)) - - __inline__ sqlite_uint64 sqlite3Hwtime(void){ - unsigned long long retval; - unsigned long junk; - __asm__ __volatile__ ("\n\ - 1: mftbu %1\n\ - mftb %L0\n\ - mftbu %0\n\ - cmpw %0,%1\n\ - bne 1b" - : "=r" (retval), "=r" (junk)); - return retval; - } - -#else - - #error Need implementation of sqlite3Hwtime() for your platform. - - /* - ** To compile without implementing sqlite3Hwtime() for your platform, - ** you can remove the above #error and use the following - ** stub function. You will lose timing support for many - ** of the debugging and testing utilities, but it should at - ** least compile and run. - */ -SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } - -#endif - -#endif /* !defined(SQLITE_HWTIME_H) */ - -/************** End of hwtime.h **********************************************/ -/************** Continuing where we left off in os_common.h ******************/ - -static sqlite_uint64 g_start; -static sqlite_uint64 g_elapsed; -#define TIMER_START g_start=sqlite3Hwtime() -#define TIMER_END g_elapsed=sqlite3Hwtime()-g_start -#define TIMER_ELAPSED g_elapsed -#else -#define TIMER_START -#define TIMER_END -#define TIMER_ELAPSED ((sqlite_uint64)0) -#endif - -/* -** If we compile with the SQLITE_TEST macro set, then the following block -** of code will give us the ability to simulate a disk I/O error. This -** is used for testing the I/O recovery logic. -*/ -#if defined(SQLITE_TEST) -SQLITE_API extern int sqlite3_io_error_hit; -SQLITE_API extern int sqlite3_io_error_hardhit; -SQLITE_API extern int sqlite3_io_error_pending; -SQLITE_API extern int sqlite3_io_error_persist; -SQLITE_API extern int sqlite3_io_error_benign; -SQLITE_API extern int sqlite3_diskfull_pending; -SQLITE_API extern int sqlite3_diskfull; -#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X) -#define SimulateIOError(CODE) \ - if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \ - || sqlite3_io_error_pending-- == 1 ) \ - { local_ioerr(); CODE; } -static void local_ioerr(){ - IOTRACE(("IOERR\n")); - sqlite3_io_error_hit++; - if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++; -} -#define SimulateDiskfullError(CODE) \ - if( sqlite3_diskfull_pending ){ \ - if( sqlite3_diskfull_pending == 1 ){ \ - local_ioerr(); \ - sqlite3_diskfull = 1; \ - sqlite3_io_error_hit = 1; \ - CODE; \ - }else{ \ - sqlite3_diskfull_pending--; \ - } \ - } -#else -#define SimulateIOErrorBenign(X) -#define SimulateIOError(A) -#define SimulateDiskfullError(A) -#endif /* defined(SQLITE_TEST) */ - -/* -** When testing, keep a count of the number of open files. -*/ -#if defined(SQLITE_TEST) -SQLITE_API extern int sqlite3_open_file_count; -#define OpenCounter(X) sqlite3_open_file_count+=(X) -#else -#define OpenCounter(X) -#endif /* defined(SQLITE_TEST) */ - -#endif /* !defined(_OS_COMMON_H_) */ - -/************** End of os_common.h *******************************************/ -/************** Continuing where we left off in os_unix.c ********************/ - -/* -** Define various macros that are missing from some systems. -*/ -#ifndef O_LARGEFILE -# define O_LARGEFILE 0 -#endif -#ifdef SQLITE_DISABLE_LFS -# undef O_LARGEFILE -# define O_LARGEFILE 0 -#endif -#ifndef O_NOFOLLOW -# define O_NOFOLLOW 0 -#endif -#ifndef O_BINARY -# define O_BINARY 0 -#endif - -/* -** The threadid macro resolves to the thread-id or to 0. Used for -** testing and debugging only. -*/ -#if SQLITE_THREADSAFE -#define threadid pthread_self() -#else -#define threadid 0 -#endif - -/* -** HAVE_MREMAP defaults to true on Linux and false everywhere else. -*/ -#if !defined(HAVE_MREMAP) -# if defined(__linux__) && defined(_GNU_SOURCE) -# define HAVE_MREMAP 1 -# else -# define HAVE_MREMAP 0 -# endif -#endif - -/* -** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek() -** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined. -*/ -#ifdef __ANDROID__ -# define lseek lseek64 -#endif - -#ifdef __linux__ -/* -** Linux-specific IOCTL magic numbers used for controlling F2FS -*/ -#define F2FS_IOCTL_MAGIC 0xf5 -#define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1) -#define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2) -#define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3) -#define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5) -#define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32) -#define F2FS_FEATURE_ATOMIC_WRITE 0x0004 -#endif /* __linux__ */ - - -/* -** Different Unix systems declare open() in different ways. Same use -** open(const char*,int,mode_t). Others use open(const char*,int,...). -** The difference is important when using a pointer to the function. -** -** The safest way to deal with the problem is to always use this wrapper -** which always has the same well-defined interface. -*/ -static int posixOpen(const char *zFile, int flags, int mode){ - return open(zFile, flags, mode); -} - -/* Forward reference */ -static int openDirectory(const char*, int*); -static int unixGetpagesize(void); - -/* -** Many system calls are accessed through pointer-to-functions so that -** they may be overridden at runtime to facilitate fault injection during -** testing and sandboxing. The following array holds the names and pointers -** to all overrideable system calls. -*/ -static struct unix_syscall { - const char *zName; /* Name of the system call */ - sqlite3_syscall_ptr pCurrent; /* Current value of the system call */ - sqlite3_syscall_ptr pDefault; /* Default value */ -} aSyscall[] = { - { "open", (sqlite3_syscall_ptr)posixOpen, 0 }, -#define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent) - - { "close", (sqlite3_syscall_ptr)close, 0 }, -#define osClose ((int(*)(int))aSyscall[1].pCurrent) - - { "access", (sqlite3_syscall_ptr)access, 0 }, -#define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent) - - { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 }, -#define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent) - - { "stat", (sqlite3_syscall_ptr)stat, 0 }, -#define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent) - -/* -** The DJGPP compiler environment looks mostly like Unix, but it -** lacks the fcntl() system call. So redefine fcntl() to be something -** that always succeeds. This means that locking does not occur under -** DJGPP. But it is DOS - what did you expect? -*/ -#ifdef __DJGPP__ - { "fstat", 0, 0 }, -#define osFstat(a,b,c) 0 -#else - { "fstat", (sqlite3_syscall_ptr)fstat, 0 }, -#define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent) -#endif - - { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 }, -#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent) - - { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 }, -#define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent) - - { "read", (sqlite3_syscall_ptr)read, 0 }, -#define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent) - -#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE - { "pread", (sqlite3_syscall_ptr)pread, 0 }, -#else - { "pread", (sqlite3_syscall_ptr)0, 0 }, -#endif -#define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent) - -#if defined(USE_PREAD64) - { "pread64", (sqlite3_syscall_ptr)pread64, 0 }, -#else - { "pread64", (sqlite3_syscall_ptr)0, 0 }, -#endif -#define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent) - - { "write", (sqlite3_syscall_ptr)write, 0 }, -#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent) - -#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE - { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 }, -#else - { "pwrite", (sqlite3_syscall_ptr)0, 0 }, -#endif -#define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\ - aSyscall[12].pCurrent) - -#if defined(USE_PREAD64) - { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 }, -#else - { "pwrite64", (sqlite3_syscall_ptr)0, 0 }, -#endif -#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\ - aSyscall[13].pCurrent) - - { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 }, -#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent) - -#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE - { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 }, -#else - { "fallocate", (sqlite3_syscall_ptr)0, 0 }, -#endif -#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent) - - { "unlink", (sqlite3_syscall_ptr)unlink, 0 }, -#define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent) - - { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 }, -#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent) - - { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 }, -#define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent) - - { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 }, -#define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent) - -#if defined(HAVE_FCHOWN) - { "fchown", (sqlite3_syscall_ptr)fchown, 0 }, -#else - { "fchown", (sqlite3_syscall_ptr)0, 0 }, -#endif -#define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent) - - { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 }, -#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 ((void*(*)(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) - - { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 }, -#define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent) - -}; /* End of the overrideable system calls */ - - -/* -** On some systems, calls to fchown() will trigger a message in a security -** log if they come from non-root processes. So avoid calling fchown() if -** we are not running as root. -*/ -static int robustFchown(int fd, uid_t uid, gid_t gid){ -#if defined(HAVE_FCHOWN) - return osGeteuid() ? 0 : osFchown(fd,uid,gid); -#else - return 0; -#endif -} - -/* -** This is the xSetSystemCall() method of sqlite3_vfs for all of the -** "unix" VFSes. Return SQLITE_OK opon successfully updating the -** system call pointer, or SQLITE_NOTFOUND if there is no configurable -** system call named zName. -*/ -static int unixSetSystemCall( - sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */ - const char *zName, /* Name of system call to override */ - sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */ -){ - unsigned int i; - int rc = SQLITE_NOTFOUND; - - UNUSED_PARAMETER(pNotUsed); - if( zName==0 ){ - /* If no zName is given, restore all system calls to their default - ** settings and return NULL - */ - rc = SQLITE_OK; - for(i=0; i=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break; - osClose(fd); - sqlite3_log(SQLITE_WARNING, - "attempt to open \"%s\" as file descriptor %d", z, fd); - fd = -1; - if( osOpen("/dev/null", f, m)<0 ) break; - } - if( fd>=0 ){ - if( m!=0 ){ - struct stat statbuf; - if( osFstat(fd, &statbuf)==0 - && statbuf.st_size==0 - && (statbuf.st_mode&0777)!=m - ){ - osFchmod(fd, m); - } - } -#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0) - osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC); -#endif - } - return fd; -} - -/* -** Helper functions to obtain and relinquish the global mutex. The -** global mutex is used to protect the unixInodeInfo and -** vxworksFileId objects used by this file, all of which may be -** shared by multiple threads. -** -** Function unixMutexHeld() is used to assert() that the global mutex -** is held when required. This function is only used as part of assert() -** statements. e.g. -** -** unixEnterMutex() -** assert( unixMutexHeld() ); -** unixEnterLeave() -*/ -static void unixEnterMutex(void){ - sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); -} -static void unixLeaveMutex(void){ - sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); -} -#ifdef SQLITE_DEBUG -static int unixMutexHeld(void) { - return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); -} -#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. Or, on LinuxThreads, there is one of these structures for -** each inode opened by each thread. -** -** 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. -*/ -struct unixInodeInfo { - struct unixFileId fileId; /* The lookup key */ - int nShared; /* Number of SHARED locks held */ - unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */ - unsigned char bProcessLock; /* An exclusive process lock is held */ - int nRef; /* Number of pointers to this structure */ - unixShmNode *pShmNode; /* Shared memory associated with this inode */ - int nLock; /* Number of outstanding file locks */ - UnixUnusedFd *pUnused; /* Unused file descriptors to close */ - 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. -*/ -static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */ -static unsigned int nUnusedFd = 0; /* Total unused file descriptors */ - -/* -** -** 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; - for(p=pInode->pUnused; p; p=pNext){ - pNext = p->pNext; - robust_close(pFile, p->fd, __LINE__); - sqlite3_free(p); - nUnusedFd--; - } - pInode->pUnused = 0; -} - -/* -** Release a unixInodeInfo structure previously allocated by findInodeInfo(). -** -** The mutex entered using the unixEnterMutex() function must be held -** when this function is called. -*/ -static void releaseInodeInfo(unixFile *pFile){ - unixInodeInfo *pInode = pFile->pInode; - assert( unixMutexHeld() ); - if( ALWAYS(pInode) ){ - pInode->nRef--; - if( pInode->nRef==0 ){ - assert( pInode->pShmNode==0 ); - closePendingFds(pFile); - 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_free(pInode); - } - } - assert( inodeList!=0 || nUnusedFd==0 ); -} - -/* -** 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 mutex entered using the unixEnterMutex() function must be held -** when this function is called. -** -** 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( inodeList!=0 || nUnusedFd==0 ); - 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)); - pInode->nRef = 1; - 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 ); - unixEnterMutex(); /* Because pFile->pInode is shared across threads */ - - /* 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 - - unixLeaveMutex(); - OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved)); - - *pResOut = reserved; - return rc; -} - -/* -** 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( unixMutexHeld() ); - assert( pInode!=0 ); - 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 = osFcntl(pFile->h, F_SETLK, &lock); - if( rc<0 ) return rc; - pInode->bProcessLock = 1; - pInode->nLock++; - }else{ - rc = 0; - } - }else{ - rc = osFcntl(pFile->h, F_SETLK, pLock); - } - 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 - */ - unixEnterMutex(); - pInode = pFile->pInode; - - /* 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: - unixLeaveMutex(); - 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; - p->pNext = pInode->pUnused; - pInode->pUnused = p; - pFile->h = -1; - pFile->pPreallocatedUnused = 0; - nUnusedFd++; -} - -/* -** 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; - } - unixEnterMutex(); - pInode = pFile->pInode; - 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: - unixLeaveMutex(); - 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; - verifyDbFile(pFile); - unixUnlock(id, NO_LOCK); - 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 ); - if( ALWAYS(pFile->pInode) && pFile->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); - } - 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 ); - 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; - } - unixEnterMutex(); /* Because pFile->pInode is shared across threads */ - - /* 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; - } - } - - unixLeaveMutex(); - 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 - */ - unixEnterMutex(); - pInode = pFile->pInode; - - /* 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: - unixLeaveMutex(); - 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; - } - unixEnterMutex(); - pInode = pFile->pInode; - 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); - } - } - } - - unixLeaveMutex(); - 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); - unixEnterMutex(); - if( pFile->pInode && pFile->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); - } - releaseInodeInfo(pFile); - sqlite3_free(pFile->lockingContext); - rc = closeUnixFile(id); - unixLeaveMutex(); - return rc; -} - -#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ -/* -** The code above is the AFP lock implementation. The code is specific -** to MacOSX and does not work on other unix platforms. No alternative -** is available. If you don't compile for a mac, then the "unix-afp" -** VFS is not available. -** -********************* End of the AFP lock implementation ********************** -******************************************************************************/ - -/****************************************************************************** -*************************** Begin NFS Locking ********************************/ - -#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE -/* - ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock - ** must be either NO_LOCK or SHARED_LOCK. - ** - ** If the locking level of the file descriptor is already at or below - ** the requested locking level, this routine is a no-op. - */ -static int nfsUnlock(sqlite3_file *id, int eFileLock){ - return posixUnlock(id, eFileLock, 1); -} - -#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ -/* -** The code above is the NFS lock implementation. The code is specific -** to MacOSX and does not work on other unix platforms. No alternative -** is available. -** -********************* End of the NFS lock implementation ********************** -******************************************************************************/ - -/****************************************************************************** -**************** Non-locking sqlite3_file methods ***************************** -** -** The next division contains implementations for all methods of the -** sqlite3_file object other than the locking methods. The locking -** methods were defined in divisions above (one locking method per -** division). Those methods that are common to all locking modes -** are gather together into this division. -*/ - -/* -** Seek to the offset passed as the second argument, then read cnt -** bytes into pBuf. Return the number of bytes actually read. -** -** NB: If you define USE_PREAD or USE_PREAD64, then it might also -** be necessary to define _XOPEN_SOURCE to be 500. This varies from -** one system to another. Since SQLite does not define USE_PREAD -** in any form by default, we will not attempt to define _XOPEN_SOURCE. -** See tickets #2741 and #2681. -** -** To avoid stomping the errno value on a failed read the lastErrno value -** is set before returning. -*/ -static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){ - int got; - int prior = 0; -#if (!defined(USE_PREAD) && !defined(USE_PREAD64)) - i64 newOffset; -#endif - TIMER_START; - assert( cnt==(cnt&0x1ffff) ); - assert( id->h>2 ); - do{ -#if defined(USE_PREAD) - got = osPread(id->h, pBuf, cnt, offset); - SimulateIOError( got = -1 ); -#elif defined(USE_PREAD64) - got = osPread64(id->h, pBuf, cnt, offset); - SimulateIOError( got = -1 ); -#else - newOffset = lseek(id->h, offset, SEEK_SET); - SimulateIOError( newOffset = -1 ); - if( newOffset<0 ){ - storeLastErrno((unixFile*)id, errno); - return -1; - } - got = osRead(id->h, pBuf, cnt); -#endif - if( got==cnt ) break; - if( got<0 ){ - if( errno==EINTR ){ got = 1; continue; } - prior = 0; - storeLastErrno((unixFile*)id, errno); - break; - }else if( got>0 ){ - cnt -= got; - offset += got; - prior += got; - pBuf = (void*)(got + (char*)pBuf); - } - }while( got>0 ); - TIMER_END; - OSTRACE(("READ %-3d %5d %7lld %llu\n", - id->h, got+prior, offset-prior, TIMER_ELAPSED)); - return got+prior; -} - -/* -** Read data from a file into a buffer. Return SQLITE_OK if all -** bytes were read successfully and SQLITE_IOERR if anything goes -** wrong. -*/ -static int unixRead( - sqlite3_file *id, - void *pBuf, - int amt, - sqlite3_int64 offset -){ - unixFile *pFile = (unixFile *)id; - int got; - assert( id ); - assert( offset>=0 ); - assert( amt>0 ); - - /* If this is a database file (not a journal, master-journal or temp - ** file), the bytes in the locking range should never be read or written. */ -#if 0 - assert( pFile->pPreallocatedUnused==0 - || offset>=PENDING_BYTE+512 - || offset+amt<=PENDING_BYTE - ); -#endif - -#if SQLITE_MAX_MMAP_SIZE>0 - /* Deal with as much of this read request as possible by transfering - ** data from the memory mapping using memcpy(). */ - if( offsetmmapSize ){ - if( offset+amt <= pFile->mmapSize ){ - memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt); - return SQLITE_OK; - }else{ - int nCopy = pFile->mmapSize - offset; - memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy); - pBuf = &((u8 *)pBuf)[nCopy]; - amt -= nCopy; - offset += nCopy; - } - } -#endif - - got = seekAndRead(pFile, offset, pBuf, amt); - if( got==amt ){ - return SQLITE_OK; - }else if( got<0 ){ - /* lastErrno set by seekAndRead */ - return SQLITE_IOERR_READ; - }else{ - storeLastErrno(pFile, 0); /* not a system error */ - /* Unread parts of the buffer must be zero-filled */ - memset(&((char*)pBuf)[got], 0, amt-got); - return SQLITE_IOERR_SHORT_READ; - } -} - -/* -** Attempt to seek the file-descriptor passed as the first argument to -** absolute offset iOff, then attempt to write nBuf bytes of data from -** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise, -** return the actual number of bytes written (which may be less than -** nBuf). -*/ -static int seekAndWriteFd( - int fd, /* File descriptor to write to */ - i64 iOff, /* File offset to begin writing at */ - const void *pBuf, /* Copy data from this buffer to the file */ - int nBuf, /* Size of buffer pBuf in bytes */ - int *piErrno /* OUT: Error number if error occurs */ -){ - int rc = 0; /* Value returned by system call */ - - assert( nBuf==(nBuf&0x1ffff) ); - assert( fd>2 ); - assert( piErrno!=0 ); - nBuf &= 0x1ffff; - TIMER_START; - -#if defined(USE_PREAD) - do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR ); -#elif defined(USE_PREAD64) - do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR); -#else - do{ - i64 iSeek = lseek(fd, iOff, SEEK_SET); - SimulateIOError( iSeek = -1 ); - if( iSeek<0 ){ - rc = -1; - break; - } - rc = osWrite(fd, pBuf, nBuf); - }while( rc<0 && errno==EINTR ); -#endif - - TIMER_END; - OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED)); - - if( rc<0 ) *piErrno = errno; - return rc; -} - - -/* -** Seek to the offset in id->offset then read cnt bytes into pBuf. -** Return the number of bytes actually read. Update the offset. -** -** To avoid stomping the errno value on a failed write the lastErrno value -** is set before returning. -*/ -static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){ - return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno); -} - - -/* -** Write data from a buffer into a file. Return SQLITE_OK on success -** or some other error code on failure. -*/ -static int unixWrite( - sqlite3_file *id, - const void *pBuf, - int amt, - sqlite3_int64 offset -){ - unixFile *pFile = (unixFile*)id; - int wrote = 0; - assert( id ); - assert( amt>0 ); - - /* If this is a database file (not a journal, master-journal or temp - ** file), the bytes in the locking range should never be read or written. */ -#if 0 - assert( pFile->pPreallocatedUnused==0 - || offset>=PENDING_BYTE+512 - || offset+amt<=PENDING_BYTE - ); -#endif - -#ifdef SQLITE_DEBUG - /* If we are doing a normal write to a database file (as opposed to - ** doing a hot-journal rollback or a write to some file other than a - ** normal database file) then record the fact that the database - ** has changed. If the transaction counter is modified, record that - ** fact too. - */ - if( pFile->inNormalWrite ){ - pFile->dbUpdate = 1; /* The database has been modified */ - if( offset<=24 && offset+amt>=27 ){ - int rc; - char oldCntr[4]; - SimulateIOErrorBenign(1); - rc = seekAndRead(pFile, 24, oldCntr, 4); - SimulateIOErrorBenign(0); - if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){ - pFile->transCntrChng = 1; /* The transaction counter has changed */ - } - } - } -#endif - -#if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0 - /* Deal with as much of this write request as possible by transfering - ** data from the memory mapping using memcpy(). */ - if( offsetmmapSize ){ - if( offset+amt <= pFile->mmapSize ){ - memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt); - return SQLITE_OK; - }else{ - int nCopy = pFile->mmapSize - offset; - memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy); - pBuf = &((u8 *)pBuf)[nCopy]; - amt -= nCopy; - offset += nCopy; - } - } -#endif - - while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))0 ){ - amt -= wrote; - offset += wrote; - pBuf = &((char*)pBuf)[wrote]; - } - SimulateIOError(( wrote=(-1), amt=1 )); - SimulateDiskfullError(( wrote=0, amt=1 )); - - if( amt>wrote ){ - if( wrote<0 && pFile->lastErrno!=ENOSPC ){ - /* lastErrno set by seekAndWrite */ - return SQLITE_IOERR_WRITE; - }else{ - storeLastErrno(pFile, 0); /* not a system error */ - return SQLITE_FULL; - } - } - - return SQLITE_OK; -} - -#ifdef SQLITE_TEST -/* -** Count the number of fullsyncs and normal syncs. This is used to test -** that syncs and fullsyncs are occurring at the right times. -*/ -SQLITE_API int sqlite3_sync_count = 0; -SQLITE_API int sqlite3_fullsync_count = 0; -#endif - -/* -** We do not trust systems to provide a working fdatasync(). Some do. -** Others do no. To be safe, we will stick with the (slightly slower) -** fsync(). If you know that your system does support fdatasync() correctly, -** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC -*/ -#if !defined(fdatasync) && !HAVE_FDATASYNC -# define fdatasync fsync -#endif - -/* -** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not -** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently -** only available on Mac OS X. But that could change. -*/ -#ifdef F_FULLFSYNC -# define HAVE_FULLFSYNC 1 -#else -# define HAVE_FULLFSYNC 0 -#endif - - -/* -** The fsync() system call does not work as advertised on many -** unix systems. The following procedure is an attempt to make -** it work better. -** -** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful -** for testing when we want to run through the test suite quickly. -** You are strongly advised *not* to deploy with SQLITE_NO_SYNC -** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash -** or power failure will likely corrupt the database file. -** -** SQLite sets the dataOnly flag if the size of the file is unchanged. -** The idea behind dataOnly is that it should only write the file content -** to disk, not the inode. We only set dataOnly if the file size is -** unchanged since the file size is part of the inode. However, -** Ted Ts'o tells us that fdatasync() will also write the inode if the -** file size has changed. The only real difference between fdatasync() -** and fsync(), Ted tells us, is that fdatasync() will not flush the -** inode if the mtime or owner or other inode attributes have changed. -** We only care about the file size, not the other file attributes, so -** as far as SQLite is concerned, an fdatasync() is always adequate. -** So, we always use fdatasync() if it is available, regardless of -** the value of the dataOnly flag. -*/ -static int full_fsync(int fd, int fullSync, int dataOnly){ - int rc; - - /* The following "ifdef/elif/else/" block has the same structure as - ** the one below. It is replicated here solely to avoid cluttering - ** up the real code with the UNUSED_PARAMETER() macros. - */ -#ifdef SQLITE_NO_SYNC - UNUSED_PARAMETER(fd); - UNUSED_PARAMETER(fullSync); - UNUSED_PARAMETER(dataOnly); -#elif HAVE_FULLFSYNC - UNUSED_PARAMETER(dataOnly); -#else - UNUSED_PARAMETER(fullSync); - UNUSED_PARAMETER(dataOnly); -#endif - - /* Record the number of times that we do a normal fsync() and - ** FULLSYNC. This is used during testing to verify that this procedure - ** gets called with the correct arguments. - */ -#ifdef SQLITE_TEST - if( fullSync ) sqlite3_fullsync_count++; - sqlite3_sync_count++; -#endif - - /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a - ** no-op. But go ahead and call fstat() to validate the file - ** descriptor as we need a method to provoke a failure during - ** coverate testing. - */ -#ifdef SQLITE_NO_SYNC - { - struct stat buf; - rc = osFstat(fd, &buf); - } -#elif HAVE_FULLFSYNC - if( fullSync ){ - rc = osFcntl(fd, F_FULLFSYNC, 0); - }else{ - rc = 1; - } - /* If the FULLFSYNC failed, fall back to attempting an fsync(). - ** It shouldn't be possible for fullfsync to fail on the local - ** file system (on OSX), so failure indicates that FULLFSYNC - ** isn't supported for this file system. So, attempt an fsync - ** and (for now) ignore the overhead of a superfluous fcntl call. - ** It'd be better to detect fullfsync support once and avoid - ** the fcntl call every time sync is called. - */ - if( rc ) rc = fsync(fd); - -#elif defined(__APPLE__) - /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly - ** so currently we default to the macro that redefines fdatasync to fsync - */ - rc = fsync(fd); -#else - rc = fdatasync(fd); -#if OS_VXWORKS - if( rc==-1 && errno==ENOTSUP ){ - rc = fsync(fd); - } -#endif /* OS_VXWORKS */ -#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */ - - if( OS_VXWORKS && rc!= -1 ){ - rc = 0; - } - return rc; -} - -/* -** Open a file descriptor to the directory containing file zFilename. -** If successful, *pFd is set to the opened file descriptor and -** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM -** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined -** value. -** -** The directory file descriptor is used for only one thing - to -** fsync() a directory to make sure file creation and deletion events -** are flushed to disk. Such fsyncs are not needed on newer -** journaling filesystems, but are required on older filesystems. -** -** This routine can be overridden using the xSetSysCall interface. -** The ability to override this routine was added in support of the -** chromium sandbox. Opening a directory is a security risk (we are -** told) so making it overrideable allows the chromium sandbox to -** replace this routine with a harmless no-op. To make this routine -** a no-op, replace it with a stub that returns SQLITE_OK but leaves -** *pFd set to a negative number. -** -** If SQLITE_OK is returned, the caller is responsible for closing -** the file descriptor *pFd using close(). -*/ -static int openDirectory(const char *zFilename, int *pFd){ - int ii; - int fd = -1; - char zDirname[MAX_PATHNAME+1]; - - sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename); - for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--); - if( ii>0 ){ - zDirname[ii] = '\0'; - }else{ - if( zDirname[0]!='/' ) zDirname[0] = '.'; - zDirname[1] = 0; - } - fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0); - if( fd>=0 ){ - OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname)); - } - *pFd = fd; - if( fd>=0 ) return SQLITE_OK; - return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname); -} - -/* -** Make sure all writes to a particular file are committed to disk. -** -** If dataOnly==0 then both the file itself and its metadata (file -** size, access time, etc) are synced. If dataOnly!=0 then only the -** file data is synced. -** -** Under Unix, also make sure that the directory entry for the file -** has been created by fsync-ing the directory that contains the file. -** If we do not do this and we encounter a power failure, the directory -** entry for the journal might not exist after we reboot. The next -** SQLite to access the file will not know that the journal exists (because -** the directory entry for the journal was never created) and the transaction -** will not roll back - possibly leading to database corruption. -*/ -static int unixSync(sqlite3_file *id, int flags){ - int rc; - unixFile *pFile = (unixFile*)id; - - int isDataOnly = (flags&SQLITE_SYNC_DATAONLY); - int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL; - - /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */ - assert((flags&0x0F)==SQLITE_SYNC_NORMAL - || (flags&0x0F)==SQLITE_SYNC_FULL - ); - - /* Unix cannot, but some systems may return SQLITE_FULL from here. This - ** line is to test that doing so does not cause any problems. - */ - SimulateDiskfullError( return SQLITE_FULL ); - - assert( pFile ); - OSTRACE(("SYNC %-3d\n", pFile->h)); - rc = full_fsync(pFile->h, isFullsync, isDataOnly); - SimulateIOError( rc=1 ); - if( rc ){ - storeLastErrno(pFile, errno); - return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath); - } - - /* Also fsync the directory containing the file if the DIRSYNC flag - ** is set. This is a one-time occurrence. Many systems (examples: AIX) - ** are unable to fsync a directory, so ignore errors on the fsync. - */ - if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){ - int dirfd; - OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath, - HAVE_FULLFSYNC, isFullsync)); - rc = osOpenDirectory(pFile->zPath, &dirfd); - if( rc==SQLITE_OK ){ - full_fsync(dirfd, 0, 0); - robust_close(pFile, dirfd, __LINE__); - }else{ - assert( rc==SQLITE_CANTOPEN ); - rc = SQLITE_OK; - } - pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC; - } - return rc; -} - -/* -** Truncate an open file to a specified size -*/ -static int unixTruncate(sqlite3_file *id, i64 nByte){ - unixFile *pFile = (unixFile *)id; - int rc; - assert( pFile ); - SimulateIOError( return SQLITE_IOERR_TRUNCATE ); - - /* If the user has configured a chunk-size for this file, truncate the - ** file so that it consists of an integer number of chunks (i.e. the - ** actual file size after the operation may be larger than the requested - ** size). - */ - if( pFile->szChunk>0 ){ - nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk; - } - - rc = robust_ftruncate(pFile->h, nByte); - if( rc ){ - storeLastErrno(pFile, errno); - return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath); - }else{ -#ifdef SQLITE_DEBUG - /* If we are doing a normal write to a database file (as opposed to - ** doing a hot-journal rollback or a write to some file other than a - ** normal database file) and we truncate the file to zero length, - ** that effectively updates the change counter. This might happen - ** when restoring a database using the backup API from a zero-length - ** source. - */ - if( pFile->inNormalWrite && nByte==0 ){ - pFile->transCntrChng = 1; - } -#endif - -#if SQLITE_MAX_MMAP_SIZE>0 - /* If the file was just truncated to a size smaller than the currently - ** mapped region, reduce the effective mapping size as well. SQLite will - ** use read() and write() to access data beyond this point from now on. - */ - if( nBytemmapSize ){ - pFile->mmapSize = nByte; - } -#endif - - return SQLITE_OK; - } -} - -/* -** Determine the current size of a file in bytes -*/ -static int unixFileSize(sqlite3_file *id, i64 *pSize){ - int rc; - struct stat buf; - assert( id ); - rc = osFstat(((unixFile*)id)->h, &buf); - SimulateIOError( rc=1 ); - if( rc!=0 ){ - storeLastErrno((unixFile*)id, errno); - return SQLITE_IOERR_FSTAT; - } - *pSize = buf.st_size; - - /* When opening a zero-size database, the findInodeInfo() procedure - ** writes a single byte into that file in order to work around a bug - ** in the OS-X msdos filesystem. In order to avoid problems with upper - ** layers, we need to report this file size as zero even though it is - ** really 1. Ticket #3260. - */ - if( *pSize==1 ) *pSize = 0; - - - return SQLITE_OK; -} - -#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) -/* -** Handler for proxy-locking file-control verbs. Defined below in the -** proxying locking division. -*/ -static int proxyFileControl(sqlite3_file*,int,void*); -#endif - -/* -** This function is called to handle the SQLITE_FCNTL_SIZE_HINT -** file-control operation. Enlarge the database to nBytes in size -** (rounded up to the next chunk-size). If the database is already -** nBytes or larger, this routine is a no-op. -*/ -static int fcntlSizeHint(unixFile *pFile, i64 nByte){ - if( pFile->szChunk>0 ){ - i64 nSize; /* Required file size */ - struct stat buf; /* Used to hold return values of fstat() */ - - if( osFstat(pFile->h, &buf) ){ - return SQLITE_IOERR_FSTAT; - } - - nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk; - if( nSize>(i64)buf.st_size ){ - -#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE - /* The code below is handling the return value of osFallocate() - ** correctly. posix_fallocate() is defined to "returns zero on success, - ** or an error number on failure". See the manpage for details. */ - int err; - do{ - err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size); - }while( err==EINTR ); - if( err ) 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; - } -#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 pFile->sectorSize; - } - - 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: -** -** fid -** zFilename -** -** Either unixShmNode.mutex 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 *mutex; /* Mutex to access this object */ - char *zFilename; /* Name of the mmapped file */ - int h; /* Open file descriptor */ - int szRegion; /* Size of shared-memory regions */ - u16 nRegion; /* Size of array apRegion */ - u8 isReadonly; /* True if read-only */ - 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.pFile -** unixShm.id -** -** All other fields are read/write. The unixShm.pFile->mutex 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 mutex */ - 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( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 ); - - /* 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->h>=0 ){ - /* Initialize the locking parameters */ - memset(&f, 0, sizeof(f)); - f.l_type = lockType; - f.l_whence = SEEK_SET; - f.l_start = ofst; - f.l_len = n; - - rc = osFcntl(pShmNode->h, F_SETLK, &f); - rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY; - } - - /* Update the global lock state and do debug tracing */ -#ifdef SQLITE_DEBUG - { u16 mask; - OSTRACE(("SHM-LOCK ")); - mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<exclMask &= ~mask; - pShmNode->sharedMask &= ~mask; - }else if( lockType==F_RDLCK ){ - OSTRACE(("read-lock %d ok", ofst)); - pShmNode->exclMask &= ~mask; - pShmNode->sharedMask |= mask; - }else{ - assert( lockType==F_WRLCK ); - OSTRACE(("write-lock %d ok", ofst)); - pShmNode->exclMask |= mask; - pShmNode->sharedMask &= ~mask; - } - }else{ - if( lockType==F_UNLCK ){ - OSTRACE(("unlock %d failed", ofst)); - }else if( lockType==F_RDLCK ){ - OSTRACE(("read-lock failed")); - }else{ - assert( lockType==F_WRLCK ); - OSTRACE(("write-lock %d failed", ofst)); - } - } - OSTRACE((" - afterwards %03x,%03x\n", - pShmNode->sharedMask, pShmNode->exclMask)); - } -#endif - - return rc; -} - -/* -** Return the minimum number of 32KB shm regions that should be mapped at -** a time, assuming that each mapping must be an integer multiple of the -** current system page-size. -** -** Usually, this is 1. The exception seems to be systems that are configured -** to use 64KB pages - in this case each mapping must cover at least two -** shm regions. -*/ -static int unixShmRegionPerMap(void){ - int shmsz = 32*1024; /* SHM region size */ - int pgsz = osGetpagesize(); /* System page size */ - assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */ - if( pgszpInode->pShmNode; - assert( unixMutexHeld() ); - if( p && ALWAYS(p->nRef==0) ){ - int nShmPerMap = unixShmRegionPerMap(); - int i; - assert( p->pInode==pFd->pInode ); - sqlite3_mutex_free(p->mutex); - for(i=0; inRegion; i+=nShmPerMap){ - if( p->h>=0 ){ - osMunmap(p->apRegion[i], p->szRegion); - }else{ - sqlite3_free(p->apRegion[i]); - } - } - sqlite3_free(p->apRegion); - if( p->h>=0 ){ - robust_close(pFd, p->h, __LINE__); - p->h = -1; - } - p->pInode->pShmNode = 0; - sqlite3_free(p); - } -} - -/* -** 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; /* Result code */ - unixInodeInfo *pInode; /* The inode of fd */ - char *zShmFilename; /* 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. - */ - 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); - zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1]; -#ifdef SQLITE_SHM_DIRECTORY - sqlite3_snprintf(nShmFilename, zShmFilename, - SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x", - (u32)sStat.st_ino, (u32)sStat.st_dev); -#else - sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath); - sqlite3FileSuffix3(pDbFd->zPath, zShmFilename); -#endif - pShmNode->h = -1; - pDbFd->pInode->pShmNode = pShmNode; - pShmNode->pInode = pDbFd->pInode; - if( sqlite3GlobalConfig.bCoreMutex ){ - pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); - if( pShmNode->mutex==0 ){ - rc = SQLITE_NOMEM_BKPT; - goto shm_open_err; - } - } - - if( pInode->bProcessLock==0 ){ - int openFlags = O_RDWR | O_CREAT; - if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){ - openFlags = O_RDONLY; - pShmNode->isReadonly = 1; - } - pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777)); - if( pShmNode->h<0 ){ - rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename); - goto shm_open_err; - } - - /* 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->h, sStat.st_uid, sStat.st_gid); - - /* Check to see if another process is holding the dead-man switch. - ** If not, truncate the file to zero length. - */ - rc = SQLITE_OK; - if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){ - if( robust_ftruncate(pShmNode->h, 0) ){ - rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename); - } - } - if( rc==SQLITE_OK ){ - rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1); - } - if( rc ) 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->mutex - ** mutex. - */ - sqlite3_mutex_enter(pShmNode->mutex); - p->pNext = pShmNode->pFirst; - pShmNode->pFirst = p; - sqlite3_mutex_leave(pShmNode->mutex); - return SQLITE_OK; - - /* Jump here on any error */ -shm_open_err: - 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->mutex); - assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 ); - assert( pShmNode->pInode==pDbFd->pInode ); - assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 ); - assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 ); - - /* Minimum number of regions required to be mapped. */ - nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap; - - if( pShmNode->nRegionszRegion = szRegion; - - if( pShmNode->h>=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->h, &sStat) ){ - rc = SQLITE_IOERR_SHMSIZE; - goto shmpage_out; - } - - if( sStat.st_sizeh, 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->nRegionh>=0 ){ - pMem = osMmap(0, nMap, - pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, - MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion - ); - if( pMem==MAP_FAILED ){ - rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename); - goto shmpage_out; - } - }else{ - pMem = sqlite3_malloc64(szRegion); - if( pMem==0 ){ - rc = SQLITE_NOMEM_BKPT; - goto shmpage_out; - } - memset(pMem, 0, szRegion); - } - - 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->mutex); - 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->h>=0 || pDbFd->pInode->bProcessLock==1 ); - assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 ); - - mask = (1<<(ofst+n)) - (1<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 = 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->mutex); - 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 */ - 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->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 */ - unixEnterMutex(); - assert( pShmNode->nRef>0 ); - pShmNode->nRef--; - if( pShmNode->nRef==0 ){ - if( deleteFlag && pShmNode->h>=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 is disabled */ - nolockClose, /* xClose method */ - nolockLock, /* xLock method */ - nolockUnlock, /* xUnlock method */ - nolockCheckReservedLock, /* xCheckReservedLock method */ - 0 /* xShmMap method */ -) -IOMETHODS( - dotlockIoFinder, /* Finder function name */ - dotlockIoMethods, /* sqlite3_io_methods object name */ - 1, /* shared memory is disabled */ - dotlockClose, /* xClose method */ - dotlockLock, /* xLock method */ - dotlockUnlock, /* xUnlock method */ - dotlockCheckReservedLock, /* xCheckReservedLock method */ - 0 /* xShmMap method */ -) - -#if SQLITE_ENABLE_LOCKING_STYLE -IOMETHODS( - flockIoFinder, /* Finder function name */ - flockIoMethods, /* sqlite3_io_methods object name */ - 1, /* shared memory is disabled */ - flockClose, /* xClose method */ - flockLock, /* xLock method */ - flockUnlock, /* xUnlock method */ - flockCheckReservedLock, /* xCheckReservedLock method */ - 0 /* xShmMap method */ -) -#endif - -#if OS_VXWORKS -IOMETHODS( - semIoFinder, /* Finder function name */ - semIoMethods, /* sqlite3_io_methods object name */ - 1, /* shared memory is disabled */ - semXClose, /* xClose method */ - semXLock, /* xLock method */ - semXUnlock, /* xUnlock method */ - semXCheckReservedLock, /* xCheckReservedLock method */ - 0 /* xShmMap method */ -) -#endif - -#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE -IOMETHODS( - afpIoFinder, /* Finder function name */ - afpIoMethods, /* sqlite3_io_methods object name */ - 1, /* shared memory is disabled */ - afpClose, /* xClose method */ - afpLock, /* xLock method */ - afpUnlock, /* xUnlock method */ - afpCheckReservedLock, /* xCheckReservedLock method */ - 0 /* xShmMap method */ -) -#endif - -/* -** The proxy locking method is a "super-method" in the sense that it -** opens secondary file descriptors for the conch and lock files and -** it uses proxy, dot-file, AFP, and flock() locking methods on those -** secondary files. For this reason, the division that implements -** proxy locking is located much further down in the file. But we need -** to go ahead and define the sqlite3_io_methods and finder function -** for proxy locking here. So we forward declare the I/O methods. -*/ -#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE -static int proxyClose(sqlite3_file*); -static int proxyLock(sqlite3_file*, int); -static int proxyUnlock(sqlite3_file*, int); -static int proxyCheckReservedLock(sqlite3_file*, int*); -IOMETHODS( - proxyIoFinder, /* Finder function name */ - proxyIoMethods, /* sqlite3_io_methods object name */ - 1, /* shared memory is disabled */ - proxyClose, /* xClose method */ - proxyLock, /* xLock method */ - proxyUnlock, /* xUnlock method */ - proxyCheckReservedLock, /* xCheckReservedLock method */ - 0 /* xShmMap method */ -) -#endif - -/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */ -#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE -IOMETHODS( - nfsIoFinder, /* Finder function name */ - nfsIoMethods, /* sqlite3_io_methods object name */ - 1, /* shared memory is disabled */ - unixClose, /* xClose method */ - unixLock, /* xLock method */ - nfsUnlock, /* xUnlock method */ - unixCheckReservedLock, /* xCheckReservedLock method */ - 0 /* xShmMap method */ -) -#endif - -#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE -/* -** This "finder" function attempts to determine the best locking strategy -** for the database file "filePath". It then returns the sqlite3_io_methods -** object that implements that strategy. -** -** This is for MacOSX only. -*/ -static const sqlite3_io_methods *autolockIoFinderImpl( - const char *filePath, /* name of the database file */ - unixFile *pNew /* open file object for the database file */ -){ - static const struct Mapping { - const char *zFilesystem; /* Filesystem type name */ - const sqlite3_io_methods *pMethods; /* Appropriate locking method */ - } aMap[] = { - { "hfs", &posixIoMethods }, - { "ufs", &posixIoMethods }, - { "afpfs", &afpIoMethods }, - { "smbfs", &afpIoMethods }, - { "webdav", &nolockIoMethods }, - { 0, 0 } - }; - int i; - struct statfs fsInfo; - struct flock lockInfo; - - if( !filePath ){ - /* If filePath==NULL that means we are dealing with a transient file - ** that does not need to be locked. */ - return &nolockIoMethods; - } - if( statfs(filePath, &fsInfo) != -1 ){ - if( fsInfo.f_flags & MNT_RDONLY ){ - return &nolockIoMethods; - } - for(i=0; aMap[i].zFilesystem; i++){ - if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){ - return aMap[i].pMethods; - } - } - } - - /* Default case. Handles, amongst others, "nfs". - ** Test byte-range lock using fcntl(). If the call succeeds, - ** assume that the file-system supports POSIX style locks. - */ - lockInfo.l_len = 1; - lockInfo.l_start = 0; - lockInfo.l_whence = SEEK_SET; - lockInfo.l_type = F_RDLCK; - if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) { - if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){ - return &nfsIoMethods; - } else { - return &posixIoMethods; - } - }else{ - return &dotlockIoMethods; - } -} -static const sqlite3_io_methods - *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl; - -#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ - -#if OS_VXWORKS -/* -** This "finder" function for VxWorks checks to see if posix advisory -** locking works. If it does, then that is what is used. If it does not -** work, then fallback to named semaphore locking. -*/ -static const sqlite3_io_methods *vxworksIoFinderImpl( - const char *filePath, /* name of the database file */ - unixFile *pNew /* the open file object */ -){ - struct flock lockInfo; - - if( !filePath ){ - /* If filePath==NULL that means we are dealing with a transient file - ** that does not need to be locked. */ - return &nolockIoMethods; - } - - /* Test if fcntl() is supported and use POSIX style locks. - ** Otherwise fall back to the named semaphore method. - */ - lockInfo.l_len = 1; - lockInfo.l_start = 0; - lockInfo.l_whence = SEEK_SET; - lockInfo.l_type = F_RDLCK; - if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) { - return &posixIoMethods; - }else{ - return &semIoMethods; - } -} -static const sqlite3_io_methods - *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl; - -#endif /* OS_VXWORKS */ - -/* -** An abstract type for a pointer to an IO method finder function: -*/ -typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*); - - -/**************************************************************************** -**************************** sqlite3_vfs methods **************************** -** -** This division contains the implementation of methods on the -** sqlite3_vfs object. -*/ - -/* -** Initialize the contents of the unixFile structure pointed to by pId. -*/ -static int fillInUnixFile( - sqlite3_vfs *pVfs, /* Pointer to vfs object */ - int h, /* Open file descriptor of file being opened */ - sqlite3_file *pId, /* Write to the unixFile structure here */ - const char *zFilename, /* Name of the file being opened */ - int ctrlFlags /* Zero or more UNIXFILE_* values */ -){ - const sqlite3_io_methods *pLockingStyle; - unixFile *pNew = (unixFile *)pId; - int rc = SQLITE_OK; - - assert( pNew->pInode==NULL ); - - /* No locking occurs in temporary files */ - assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 ); - - OSTRACE(("OPEN %-3d %s\n", h, zFilename)); - pNew->h = h; - pNew->pVfs = pVfs; - pNew->zPath = zFilename; - pNew->ctrlFlags = (u8)ctrlFlags; -#if SQLITE_MAX_MMAP_SIZE>0 - pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap; -#endif - if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0), - "psow", SQLITE_POWERSAFE_OVERWRITE) ){ - pNew->ctrlFlags |= UNIXFILE_PSOW; - } - if( strcmp(pVfs->zName,"unix-excl")==0 ){ - pNew->ctrlFlags |= UNIXFILE_EXCL; - } - -#if OS_VXWORKS - pNew->pId = vxworksFindFileId(zFilename); - if( pNew->pId==0 ){ - ctrlFlags |= UNIXFILE_NOLOCK; - rc = SQLITE_NOMEM_BKPT; - } -#endif - - if( ctrlFlags & UNIXFILE_NOLOCK ){ - pLockingStyle = &nolockIoMethods; - }else{ - pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew); -#if SQLITE_ENABLE_LOCKING_STYLE - /* Cache zFilename in the locking context (AFP and dotlock override) for - ** proxyLock activation is possible (remote proxy is based on db name) - ** zFilename remains valid until file is closed, to support */ - pNew->lockingContext = (void*)zFilename; -#endif - } - - if( pLockingStyle == &posixIoMethods -#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE - || pLockingStyle == &nfsIoMethods -#endif - ){ - unixEnterMutex(); - rc = findInodeInfo(pNew, &pNew->pInode); - if( rc!=SQLITE_OK ){ - /* If an error occurred in findInodeInfo(), close the file descriptor - ** immediately, before releasing the mutex. findInodeInfo() may fail - ** in two scenarios: - ** - ** (a) A call to fstat() failed. - ** (b) A malloc failed. - ** - ** Scenario (b) may only occur if the process is holding no other - ** file descriptors open on the same file. If there were other file - ** descriptors on this file, then no malloc would be required by - ** findInodeInfo(). If this is the case, it is quite safe to close - ** handle h - as it is guaranteed that no posix locks will be released - ** by doing so. - ** - ** If scenario (a) caused the error then things are not so safe. The - ** implicit assumption here is that if fstat() fails, things are in - ** such bad shape that dropping a lock or two doesn't matter much. - */ - robust_close(pNew, h, __LINE__); - h = -1; - } - unixLeaveMutex(); - } - -#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) - else if( pLockingStyle == &afpIoMethods ){ - /* AFP locking uses the file path so it needs to be included in - ** the afpLockingContext. - */ - afpLockingContext *pCtx; - pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) ); - if( pCtx==0 ){ - rc = SQLITE_NOMEM_BKPT; - }else{ - /* NB: zFilename exists and remains valid until the file is closed - ** according to requirement F11141. So we do not need to make a - ** copy of the filename. */ - pCtx->dbPath = zFilename; - pCtx->reserved = 0; - srandomdev(); - unixEnterMutex(); - rc = findInodeInfo(pNew, &pNew->pInode); - if( rc!=SQLITE_OK ){ - sqlite3_free(pNew->lockingContext); - robust_close(pNew, h, __LINE__); - h = -1; - } - unixLeaveMutex(); - } - } -#endif - - else if( pLockingStyle == &dotlockIoMethods ){ - /* Dotfile locking uses the file path so it needs to be included in - ** the dotlockLockingContext - */ - char *zLockFile; - int nFilename; - assert( zFilename!=0 ); - nFilename = (int)strlen(zFilename) + 6; - zLockFile = (char *)sqlite3_malloc64(nFilename); - if( zLockFile==0 ){ - rc = SQLITE_NOMEM_BKPT; - }else{ - sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename); - } - pNew->lockingContext = zLockFile; - } - -#if OS_VXWORKS - else if( pLockingStyle == &semIoMethods ){ - /* Named semaphore locking uses the file path so it needs to be - ** included in the semLockingContext - */ - unixEnterMutex(); - rc = findInodeInfo(pNew, &pNew->pInode); - if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){ - char *zSemName = pNew->pInode->aSemName; - int n; - sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem", - pNew->pId->zCanonicalName); - for( n=1; zSemName[n]; n++ ) - if( zSemName[n]=='/' ) zSemName[n] = '_'; - pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1); - if( pNew->pInode->pSem == SEM_FAILED ){ - rc = SQLITE_NOMEM_BKPT; - pNew->pInode->aSemName[0] = '\0'; - } - } - unixLeaveMutex(); - } -#endif - - storeLastErrno(pNew, 0); -#if OS_VXWORKS - if( rc!=SQLITE_OK ){ - if( h>=0 ) robust_close(pNew, h, __LINE__); - h = -1; - osUnlink(zFilename); - pNew->ctrlFlags |= UNIXFILE_DELETE; - } -#endif - if( rc!=SQLITE_OK ){ - if( h>=0 ) robust_close(pNew, h, __LINE__); - }else{ - pNew->pMethod = pLockingStyle; - OpenCounter(+1); - verifyDbFile(pNew); - } - return rc; -} - -/* -** Return the name of a directory in which to put temporary files. -** If no suitable temporary file directory can be found, return NULL. -*/ -static const char *unixTempFileDir(void){ - static const char *azDirs[] = { - 0, - 0, - "/var/tmp", - "/usr/tmp", - "/tmp", - "." - }; - unsigned int i = 0; - struct stat buf; - const char *zDir = sqlite3_temp_directory; - - if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR"); - if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR"); - while(1){ - if( zDir!=0 - && osStat(zDir, &buf)==0 - && S_ISDIR(buf.st_mode) - && osAccess(zDir, 03)==0 - ){ - return zDir; - } - if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break; - zDir = azDirs[i++]; - } - return 0; -} - -/* -** Create a temporary file name in zBuf. zBuf must be allocated -** by the calling process and must be big enough to hold at least -** pVfs->mxPathname bytes. -*/ -static int unixGetTempname(int nBuf, char *zBuf){ - const char *zDir; - int iLimit = 0; - - /* It's odd to simulate an io-error here, but really this is just - ** using the io-error infrastructure to test that SQLite handles this - ** function failing. - */ - zBuf[0] = 0; - SimulateIOError( return SQLITE_IOERR ); - - zDir = unixTempFileDir(); - if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH; - do{ - u64 r; - sqlite3_randomness(sizeof(r), &r); - assert( nBuf>2 ); - zBuf[nBuf-2] = 0; - sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c", - zDir, r, 0); - if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR; - }while( osAccess(zBuf,0)==0 ); - return SQLITE_OK; -} - -#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) -/* -** Routine to transform a unixFile into a proxy-locking unixFile. -** Implementation in the proxy-lock division, but used by unixOpen() -** if SQLITE_PREFER_PROXY_LOCKING is defined. -*/ -static int proxyTransformUnixFile(unixFile*, const char*); -#endif - -/* -** Search for an unused file descriptor that was opened on the database -** file (not a journal or master-journal file) identified by pathname -** zPath with SQLITE_OPEN_XXX flags matching those passed as the second -** argument to this function. -** -** Such a file descriptor may exist if a database connection was closed -** but the associated file descriptor could not be closed because some -** other file descriptor open on the same file is holding a file-lock. -** Refer to comments in the unixClose() function and the lengthy comment -** describing "Posix Advisory Locking" at the start of this file for -** further details. Also, ticket #4018. -** -** If a suitable file descriptor is found, then it is returned. If no -** such file descriptor is located, -1 is returned. -*/ -static UnixUnusedFd *findReusableFd(const char *zPath, int flags){ - UnixUnusedFd *pUnused = 0; - - /* Do not search for an unused file descriptor on vxworks. Not because - ** vxworks would not benefit from the change (it might, we're not sure), - ** but because no way to test it is currently available. It is better - ** not to risk breaking vxworks support for the sake of such an obscure - ** feature. */ -#if !OS_VXWORKS - struct stat sStat; /* Results of stat() call */ - - unixEnterMutex(); - - /* A stat() call may fail for various reasons. If this happens, it is - ** almost certain that an open() call on the same path will also fail. - ** For this reason, if an error occurs in the stat() call here, it is - ** ignored and -1 is returned. The caller will try to open a new file - ** descriptor on the same path, fail, and return an error to SQLite. - ** - ** Even if a subsequent open() call does succeed, the consequences of - ** not searching for a reusable file descriptor are not dire. */ - if( nUnusedFd>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; - for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext)); - pUnused = *pp; - if( pUnused ){ - nUnusedFd--; - *pp = pUnused->pNext; - } - } - } - unixLeaveMutex(); -#endif /* if !OS_VXWORKS */ - return pUnused; -} - -/* -** Find the mode, uid and gid of file zFile. -*/ -static int getFileMode( - const char *zFile, /* File name */ - mode_t *pMode, /* OUT: Permissions of zFile */ - uid_t *pUid, /* OUT: uid of zFile. */ - gid_t *pGid /* OUT: gid of zFile. */ -){ - struct stat sStat; /* Output of stat() on database file */ - int rc = SQLITE_OK; - if( 0==osStat(zFile, &sStat) ){ - *pMode = sStat.st_mode & 0777; - *pUid = sStat.st_uid; - *pGid = sStat.st_gid; - }else{ - rc = SQLITE_IOERR_FSTAT; - } - return rc; -} - -/* -** This function is called by unixOpen() to determine the unix permissions -** to create new files with. If no error occurs, then SQLITE_OK is returned -** and a value suitable for passing as the third argument to open(2) is -** written to *pMode. If an IO error occurs, an SQLite error code is -** returned and the value of *pMode is not modified. -** -** In most cases, this routine sets *pMode to 0, which will become -** an indication to robust_open() to create the file using -** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask. -** But if the file being opened is a WAL or regular journal file, then -** this function queries the file-system for the permissions on the -** corresponding database file and sets *pMode to this value. Whenever -** possible, WAL and journal files are created using the same permissions -** as the associated database file. -** -** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the -** original filename is unavailable. But 8_3_NAMES is only used for -** FAT filesystems and permissions do not matter there, so just use -** the default permissions. -*/ -static int findCreateFileMode( - const char *zPath, /* Path of file (possibly) being created */ - int flags, /* Flags passed as 4th argument to xOpen() */ - mode_t *pMode, /* OUT: Permissions to open file with */ - uid_t *pUid, /* OUT: uid to set on the file */ - gid_t *pGid /* OUT: gid to set on the file */ -){ - int rc = SQLITE_OK; /* Return Code */ - *pMode = 0; - *pUid = 0; - *pGid = 0; - if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){ - char zDb[MAX_PATHNAME+1]; /* Database file path */ - int nDb; /* Number of valid bytes in zDb */ - - /* zPath is a path to a WAL or journal file. The following block derives - ** the path to the associated database file from zPath. This block handles - ** the following naming conventions: - ** - ** "-journal" - ** "-wal" - ** "-journalNN" - ** "-walNN" - ** - ** where NN is a decimal number. The NN naming schemes are - ** used by the test_multiplex.c module. - */ - nDb = sqlite3Strlen30(zPath) - 1; - while( zPath[nDb]!='-' ){ - /* In normal operation, the journal file name will always contain - ** a '-' character. However in 8+3 filename mode, or if a corrupt - ** rollback journal specifies a master journal with a goofy name, then - ** the '-' might be missing. */ - if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK; - nDb--; - } - memcpy(zDb, zPath, nDb); - zDb[nDb] = '\0'; - - rc = getFileMode(zDb, pMode, pUid, pGid); - }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){ - *pMode = 0600; - }else if( flags & SQLITE_OPEN_URI ){ - /* If this is a main database file and the file was opened using a URI - ** filename, check for the "modeof" parameter. If present, interpret - ** its value as a filename and try to copy the mode, uid and gid from - ** that file. */ - const char *z = sqlite3_uri_parameter(zPath, "modeof"); - if( z ){ - rc = getFileMode(z, pMode, pUid, pGid); - } - } - return rc; -} - -/* -** Open the file zPath. -** -** Previously, the SQLite OS layer used three functions in place of this -** one: -** -** sqlite3OsOpenReadWrite(); -** sqlite3OsOpenReadOnly(); -** sqlite3OsOpenExclusive(); -** -** These calls correspond to the following combinations of flags: -** -** ReadWrite() -> (READWRITE | CREATE) -** ReadOnly() -> (READONLY) -** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE) -** -** The old OpenExclusive() accepted a boolean argument - "delFlag". If -** true, the file was configured to be automatically deleted when the -** file handle closed. To achieve the same effect using this new -** interface, add the DELETEONCLOSE flag to those specified above for -** OpenExclusive(). -*/ -static int unixOpen( - sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */ - const char *zPath, /* Pathname of file to be opened */ - sqlite3_file *pFile, /* The file descriptor to be filled in */ - int flags, /* Input flags to control the opening */ - int *pOutFlags /* Output flags returned to SQLite core */ -){ - unixFile *p = (unixFile *)pFile; - int fd = -1; /* File descriptor returned by open() */ - int openFlags = 0; /* Flags to pass to open() */ - int eType = flags&0xFFFFFF00; /* Type of file to open */ - int noLock; /* True to omit locking primitives */ - int rc = SQLITE_OK; /* Function Return Code */ - int ctrlFlags = 0; /* UNIXFILE_* flags */ - - int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE); - int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE); - int isCreate = (flags & SQLITE_OPEN_CREATE); - int isReadonly = (flags & SQLITE_OPEN_READONLY); - int isReadWrite = (flags & SQLITE_OPEN_READWRITE); -#if SQLITE_ENABLE_LOCKING_STYLE - int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY); -#endif -#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE - struct statfs fsInfo; -#endif - - /* If creating a master or main-file journal, this function will open - ** a file-descriptor on the directory too. The first time unixSync() - ** is called the directory file descriptor will be fsync()ed and close()d. - */ - int syncDir = (isCreate && ( - eType==SQLITE_OPEN_MASTER_JOURNAL - || eType==SQLITE_OPEN_MAIN_JOURNAL - || eType==SQLITE_OPEN_WAL - )); - - /* If argument zPath is a NULL pointer, this function is required to open - ** a temporary file. Use this buffer to store the file name in. - */ - char zTmpname[MAX_PATHNAME+2]; - const char *zName = zPath; - - /* Check the following statements are true: - ** - ** (a) Exactly one of the READWRITE and READONLY flags must be set, and - ** (b) if CREATE is set, then READWRITE must also be set, and - ** (c) if EXCLUSIVE is set, then CREATE must also be set. - ** (d) if DELETEONCLOSE is set, then CREATE must also be set. - */ - assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly)); - assert(isCreate==0 || isReadWrite); - assert(isExclusive==0 || isCreate); - assert(isDelete==0 || isCreate); - - /* The main DB, main journal, WAL file and master journal are never - ** automatically deleted. Nor are they ever temporary files. */ - assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB ); - assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL ); - assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL ); - assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL ); - - /* Assert that the upper layer has set one of the "file-type" flags. */ - assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB - || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL - || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL - || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL - ); - - /* Detect a pid change and reset the PRNG. There is a race condition - ** here such that two or more threads all trying to open databases at - ** the same instant might all reset the PRNG. But multiple resets - ** are harmless. - */ - if( randomnessPid!=osGetpid(0) ){ - randomnessPid = osGetpid(0); - sqlite3_randomness(0,0); - } - - memset(p, 0, sizeof(unixFile)); - - if( eType==SQLITE_OPEN_MAIN_DB ){ - UnixUnusedFd *pUnused; - pUnused = findReusableFd(zName, flags); - if( pUnused ){ - fd = pUnused->fd; - }else{ - pUnused = sqlite3_malloc64(sizeof(*pUnused)); - if( !pUnused ){ - return SQLITE_NOMEM_BKPT; - } - } - p->pPreallocatedUnused = pUnused; - - /* Database filenames are double-zero terminated if they are not - ** URIs with parameters. Hence, they can always be passed into - ** sqlite3_uri_parameter(). */ - assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 ); - - }else if( !zName ){ - /* If zName is NULL, the upper layer is requesting a temp file. */ - assert(isDelete && !syncDir); - rc = unixGetTempname(pVfs->mxPathname, zTmpname); - if( rc!=SQLITE_OK ){ - return rc; - } - zName = zTmpname; - - /* Generated temporary filenames are always double-zero terminated - ** for use by sqlite3_uri_parameter(). */ - assert( zName[strlen(zName)+1]==0 ); - } - - /* Determine the value of the flags parameter passed to POSIX function - ** open(). These must be calculated even if open() is not called, as - ** they may be stored as part of the file handle and used by the - ** 'conch file' locking functions later on. */ - if( isReadonly ) openFlags |= O_RDONLY; - if( isReadWrite ) openFlags |= O_RDWR; - if( isCreate ) openFlags |= O_CREAT; - if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW); - openFlags |= (O_LARGEFILE|O_BINARY); - - if( fd<0 ){ - mode_t openMode; /* Permissions to create file with */ - uid_t uid; /* Userid for the file */ - gid_t gid; /* Groupid for the file */ - rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid); - if( rc!=SQLITE_OK ){ - assert( !p->pPreallocatedUnused ); - assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL ); - return rc; - } - fd = robust_open(zName, openFlags, openMode); - OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags)); - assert( !isExclusive || (openFlags & O_CREAT)!=0 ); - if( fd<0 && 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 ){ - rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName); - goto open_finished; - } - - /* If this process is running as root and if creating a new rollback - ** journal or WAL file, set the ownership of the journal or WAL to be - ** the same as the original database. - */ - if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){ - robustFchown(fd, uid, gid); - } - } - assert( fd>=0 ); - if( pOutFlags ){ - *pOutFlags = flags; - } - - if( p->pPreallocatedUnused ){ - p->pPreallocatedUnused->fd = fd; - p->pPreallocatedUnused->flags = flags; - } - - if( isDelete ){ -#if OS_VXWORKS - zPath = zName; -#elif defined(SQLITE_UNLINK_AFTER_CLOSE) - zPath = sqlite3_mprintf("%s", zName); - if( zPath==0 ){ - robust_close(p, fd, __LINE__); - return SQLITE_NOMEM_BKPT; - } -#else - osUnlink(zName); -#endif - } -#if SQLITE_ENABLE_LOCKING_STYLE - else{ - p->openFlags = openFlags; - } -#endif - -#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE - if( fstatfs(fd, &fsInfo) == -1 ){ - storeLastErrno(p, errno); - robust_close(p, fd, __LINE__); - return SQLITE_IOERR_ACCESS; - } - if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) { - ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS; - } - if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) { - ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS; - } -#endif - - /* Set up appropriate ctrlFlags */ - if( isDelete ) ctrlFlags |= UNIXFILE_DELETE; - if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY; - noLock = eType!=SQLITE_OPEN_MAIN_DB; - if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK; - if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC; - if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI; - -#if SQLITE_ENABLE_LOCKING_STYLE -#if SQLITE_PREFER_PROXY_LOCKING - isAutoProxy = 1; -#endif - if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){ - char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING"); - int useProxy = 0; - - /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means - ** never use proxy, NULL means use proxy for non-local files only. */ - if( envforce!=NULL ){ - useProxy = atoi(envforce)>0; - }else{ - useProxy = !(fsInfo.f_flags&MNT_LOCAL); - } - if( useProxy ){ - rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags); - if( rc==SQLITE_OK ){ - rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:"); - if( rc!=SQLITE_OK ){ - /* Use unixClose to clean up the resources added in fillInUnixFile - ** and clear all the structure's references. Specifically, - ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op - */ - unixClose(pFile); - return rc; - } - } - goto open_finished; - } - } -#endif - - assert( zPath==0 || zPath[0]=='/' - || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL - ); - rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags); - -open_finished: - if( rc!=SQLITE_OK ){ - sqlite3_free(p->pPreallocatedUnused); - } - return rc; -} - - -/* -** Delete the file at zPath. If the dirSync argument is true, fsync() -** the directory after deleting the file. -*/ -static int unixDelete( - sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */ - const char *zPath, /* Name of file to be deleted */ - int dirSync /* If true, fsync() directory after deleting file */ -){ - int rc = SQLITE_OK; - UNUSED_PARAMETER(NotUsed); - SimulateIOError(return SQLITE_IOERR_DELETE); - if( osUnlink(zPath)==(-1) ){ - if( errno==ENOENT -#if OS_VXWORKS - || osAccess(zPath,0)!=0 -#endif - ){ - rc = SQLITE_IOERR_DELETE_NOENT; - }else{ - rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath); - } - return rc; - } -#ifndef SQLITE_DISABLE_DIRSYNC - if( (dirSync & 1)!=0 ){ - int fd; - rc = osOpenDirectory(zPath, &fd); - if( rc==SQLITE_OK ){ - if( full_fsync(fd,0,0) ){ - rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath); - } - robust_close(0, fd, __LINE__); - }else{ - assert( rc==SQLITE_CANTOPEN ); - rc = SQLITE_OK; - } - } -#endif - return rc; -} - -/* -** Test the existence of or access permissions of file zPath. The -** test performed depends on the value of flags: -** -** SQLITE_ACCESS_EXISTS: Return 1 if the file exists -** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable. -** SQLITE_ACCESS_READONLY: Return 1 if the file is readable. -** -** Otherwise return 0. -*/ -static int unixAccess( - sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */ - const char *zPath, /* Path of the file to examine */ - int flags, /* What do we want to learn about the zPath file? */ - int *pResOut /* Write result boolean here */ -){ - UNUSED_PARAMETER(NotUsed); - SimulateIOError( return SQLITE_IOERR_ACCESS; ); - assert( pResOut!=0 ); - - /* The spec says there are three possible values for flags. But only - ** two of them are actually used */ - assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE ); - - if( flags==SQLITE_ACCESS_EXISTS ){ - struct stat buf; - *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0); - }else{ - *pResOut = osAccess(zPath, W_OK|R_OK)==0; - } - return SQLITE_OK; -} - -/* -** -*/ -static int mkFullPathname( - const char *zPath, /* Input path */ - char *zOut, /* Output buffer */ - int nOut /* Allocated size of buffer zOut */ -){ - int nPath = sqlite3Strlen30(zPath); - int iOff = 0; - if( zPath[0]!='/' ){ - if( osGetcwd(zOut, nOut-2)==0 ){ - return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath); - } - iOff = sqlite3Strlen30(zOut); - zOut[iOff++] = '/'; - } - if( (iOff+nPath+1)>nOut ){ - /* SQLite assumes that xFullPathname() nul-terminates the output buffer - ** even if it returns an error. */ - zOut[iOff] = '\0'; - return SQLITE_CANTOPEN_BKPT; - } - sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath); - return SQLITE_OK; -} - -/* -** Turn a relative pathname into a full pathname. The relative path -** is stored as a nul-terminated string in the buffer pointed to by -** zPath. -** -** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes -** (in this case, MAX_PATHNAME bytes). The full-path is written to -** this buffer before returning. -*/ -static int unixFullPathname( - sqlite3_vfs *pVfs, /* Pointer to vfs object */ - const char *zPath, /* Possibly relative input path */ - int nOut, /* Size of output buffer in bytes */ - char *zOut /* Output buffer */ -){ -#if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT) - return mkFullPathname(zPath, zOut, nOut); -#else - int rc = SQLITE_OK; - int nByte; - int nLink = 1; /* Number of symbolic links followed so far */ - const char *zIn = zPath; /* Input path for each iteration of loop */ - char *zDel = 0; - - assert( pVfs->mxPathname==MAX_PATHNAME ); - UNUSED_PARAMETER(pVfs); - - /* It's odd to simulate an io-error here, but really this is just - ** using the io-error infrastructure to test that SQLite handles this - ** function failing. This function could fail if, for example, the - ** current working directory has been unlinked. - */ - SimulateIOError( return SQLITE_ERROR ); - - do { - - /* Call stat() on path zIn. Set bLink to true if the path is a symbolic - ** link, or false otherwise. */ - int bLink = 0; - struct stat buf; - if( osLstat(zIn, &buf)!=0 ){ - if( errno!=ENOENT ){ - rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn); - } - }else{ - bLink = S_ISLNK(buf.st_mode); - } - - if( bLink ){ - if( zDel==0 ){ - zDel = sqlite3_malloc(nOut); - if( zDel==0 ) rc = SQLITE_NOMEM_BKPT; - }else if( ++nLink>SQLITE_MAX_SYMLINKS ){ - rc = SQLITE_CANTOPEN_BKPT; - } - - if( rc==SQLITE_OK ){ - nByte = osReadlink(zIn, zDel, nOut-1); - if( nByte<0 ){ - rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn); - }else{ - if( zDel[0]!='/' ){ - int n; - for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--); - if( nByte+n+1>nOut ){ - rc = SQLITE_CANTOPEN_BKPT; - }else{ - memmove(&zDel[n], zDel, nByte+1); - memcpy(zDel, zIn, n); - nByte += n; - } - } - zDel[nByte] = '\0'; - } - } - - zIn = zDel; - } - - assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' ); - if( rc==SQLITE_OK && zIn!=zOut ){ - rc = mkFullPathname(zIn, zOut, nOut); - } - if( bLink==0 ) break; - zIn = zOut; - }while( rc==SQLITE_OK ); - - sqlite3_free(zDel); - return rc; -#endif /* HAVE_READLINK && HAVE_LSTAT */ -} - - -#ifndef SQLITE_OMIT_LOAD_EXTENSION -/* -** Interfaces for opening a shared library, finding entry points -** within the shared library, and closing the shared library. -*/ -#include -static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){ - UNUSED_PARAMETER(NotUsed); - return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL); -} - -/* -** SQLite calls this function immediately after a call to unixDlSym() or -** unixDlOpen() fails (returns a null pointer). If a more detailed error -** message is available, it is written to zBufOut. If no error message -** is available, zBufOut is left unmodified and SQLite uses a default -** error message. -*/ -static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){ - const char *zErr; - UNUSED_PARAMETER(NotUsed); - unixEnterMutex(); - zErr = dlerror(); - if( zErr ){ - sqlite3_snprintf(nBuf, zBufOut, "%s", zErr); - } - unixLeaveMutex(); -} -static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){ - /* - ** GCC with -pedantic-errors says that C90 does not allow a void* to be - ** cast into a pointer to a function. And yet the library dlsym() routine - ** returns a void* which is really a pointer to a function. So how do we - ** use dlsym() with -pedantic-errors? - ** - ** Variable x below is defined to be a pointer to a function taking - ** parameters void* and const char* and returning a pointer to a function. - ** We initialize x by assigning it a pointer to the dlsym() function. - ** (That assignment requires a cast.) Then we call the function that - ** x points to. - ** - ** This work-around is unlikely to work correctly on any system where - ** you really cannot cast a function pointer into void*. But then, on the - ** other hand, dlsym() will not work on such a system either, so we have - ** not really lost anything. - */ - void (*(*x)(void*,const char*))(void); - UNUSED_PARAMETER(NotUsed); - x = (void(*(*)(void*,const char*))(void))dlsym; - return (*x)(p, zSym); -} -static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){ - UNUSED_PARAMETER(NotUsed); - dlclose(pHandle); -} -#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */ - #define unixDlOpen 0 - #define unixDlError 0 - #define unixDlSym 0 - #define unixDlClose 0 -#endif - -/* -** Write nBuf bytes of random data to the supplied buffer zBuf. -*/ -static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){ - UNUSED_PARAMETER(NotUsed); - assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int))); - - /* We have to initialize zBuf to prevent valgrind from reporting - ** errors. The reports issued by valgrind are incorrect - we would - ** prefer that the randomness be increased by making use of the - ** uninitialized space in zBuf - but valgrind errors tend to worry - ** some users. Rather than argue, it seems easier just to initialize - ** the whole array and silence valgrind, even if that means less randomness - ** in the random seed. - ** - ** When testing, initializing zBuf[] to zero is all we do. That means - ** that we always use the same random number sequence. This makes the - ** tests repeatable. - */ - memset(zBuf, 0, nBuf); - randomnessPid = osGetpid(0); -#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) - { - int fd, got; - fd = robust_open("/dev/urandom", O_RDONLY, 0); - if( fd<0 ){ - time_t t; - time(&t); - memcpy(zBuf, &t, sizeof(t)); - memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid)); - assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf ); - nBuf = sizeof(t) + sizeof(randomnessPid); - }else{ - do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR ); - robust_close(0, fd, __LINE__); - } - } -#endif - return nBuf; -} - - -/* -** Sleep for a little while. Return the amount of time slept. -** The argument is the number of microseconds we want to sleep. -** The return value is the number of microseconds of sleep actually -** requested from the underlying operating system, a number which -** might be greater than or equal to the argument, but not less -** than the argument. -*/ -static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){ -#if OS_VXWORKS - struct timespec sp; - - sp.tv_sec = microseconds / 1000000; - sp.tv_nsec = (microseconds % 1000000) * 1000; - nanosleep(&sp, NULL); - UNUSED_PARAMETER(NotUsed); - return microseconds; -#elif defined(HAVE_USLEEP) && HAVE_USLEEP - usleep(microseconds); - UNUSED_PARAMETER(NotUsed); - return microseconds; -#else - int seconds = (microseconds+999999)/1000000; - sleep(seconds); - UNUSED_PARAMETER(NotUsed); - return seconds*1000000; -#endif -} - -/* -** The following variable, if set to a non-zero value, is interpreted as -** the number of seconds since 1970 and is used to set the result of -** sqlite3OsCurrentTime() during testing. -*/ -#ifdef SQLITE_TEST -SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */ -#endif - -/* -** Find the current time (in Universal Coordinated Time). Write into *piNow -** the current time and date as a Julian Day number times 86_400_000. In -** other words, write into *piNow the number of milliseconds since the Julian -** epoch of noon in Greenwich on November 24, 4714 B.C according to the -** proleptic Gregorian calendar. -** -** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date -** cannot be found. -*/ -static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){ - static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000; - int rc = SQLITE_OK; -#if defined(NO_GETTOD) - time_t t; - time(&t); - *piNow = ((sqlite3_int64)t)*1000 + unixEpoch; -#elif OS_VXWORKS - struct timespec sNow; - clock_gettime(CLOCK_REALTIME, &sNow); - *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000; -#else - struct timeval sNow; - (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */ - *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000; -#endif - -#ifdef SQLITE_TEST - if( sqlite3_current_time ){ - *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch; - } -#endif - UNUSED_PARAMETER(NotUsed); - return rc; -} - -#ifndef SQLITE_OMIT_DEPRECATED -/* -** Find the current time (in Universal Coordinated Time). Write the -** current time and date as a Julian Day number into *prNow and -** return 0. Return 1 if the time and date cannot be found. -*/ -static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){ - sqlite3_int64 i = 0; - int rc; - UNUSED_PARAMETER(NotUsed); - rc = unixCurrentTimeInt64(0, &i); - *prNow = i/86400000.0; - return rc; -} -#else -# define unixCurrentTime 0 -#endif - -/* -** The xGetLastError() method is designed to return a better -** low-level error message when operating-system problems come up -** during SQLite operation. Only the integer return code is currently -** used. -*/ -static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){ - UNUSED_PARAMETER(NotUsed); - UNUSED_PARAMETER(NotUsed2); - UNUSED_PARAMETER(NotUsed3); - return errno; -} - - -/* -************************ End of sqlite3_vfs methods *************************** -******************************************************************************/ - -/****************************************************************************** -************************** Begin Proxy Locking ******************************** -** -** Proxy locking is a "uber-locking-method" in this sense: It uses the -** other locking methods on secondary lock files. Proxy locking is a -** meta-layer over top of the primitive locking implemented above. For -** this reason, the division that implements of proxy locking is deferred -** until late in the file (here) after all of the other I/O methods have -** been defined - so that the primitive locking methods are available -** as services to help with the implementation of proxy locking. -** -**** -** -** The default locking schemes in SQLite use byte-range locks on the -** database file to coordinate safe, concurrent access by multiple readers -** and writers [http://sqlite.org/lockingv3.html]. The five file locking -** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented -** as POSIX read & write locks over fixed set of locations (via fsctl), -** on AFP and SMB only exclusive byte-range locks are available via fsctl -** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states. -** To simulate a F_RDLCK on the shared range, on AFP a randomly selected -** address in the shared range is taken for a SHARED lock, the entire -** shared range is taken for an EXCLUSIVE lock): -** -** PENDING_BYTE 0x40000000 -** RESERVED_BYTE 0x40000001 -** SHARED_RANGE 0x40000002 -> 0x40000200 -** -** This works well on the local file system, but shows a nearly 100x -** slowdown in read performance on AFP because the AFP client disables -** the read cache when byte-range locks are present. Enabling the read -** cache exposes a cache coherency problem that is present on all OS X -** supported network file systems. NFS and AFP both observe the -** close-to-open semantics for ensuring cache coherency -** [http://nfs.sourceforge.net/#faq_a8], which does not effectively -** address the requirements for concurrent database access by multiple -** readers and writers -** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html]. -** -** To address the performance and cache coherency issues, proxy file locking -** changes the way database access is controlled by limiting access to a -** single host at a time and moving file locks off of the database file -** and onto a proxy file on the local file system. -** -** -** Using proxy locks -** ----------------- -** -** C APIs -** -** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE, -** | ":auto:"); -** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE, -** &); -** -** -** SQL pragmas -** -** PRAGMA [database.]lock_proxy_file= | :auto: -** PRAGMA [database.]lock_proxy_file -** -** Specifying ":auto:" means that if there is a conch file with a matching -** host ID in it, the proxy path in the conch file will be used, otherwise -** a proxy path based on the user's temp dir -** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the -** actual proxy file name is generated from the name and path of the -** database file. For example: -** -** For database path "/Users/me/foo.db" -** The lock path will be "/sqliteplocks/_Users_me_foo.db:auto:") -** -** Once a lock proxy is configured for a database connection, it can not -** be removed, however it may be switched to a different proxy path via -** the above APIs (assuming the conch file is not being held by another -** connection or process). -** -** -** How proxy locking works -** ----------------------- -** -** Proxy file locking relies primarily on two new supporting files: -** -** * conch file to limit access to the database file to a single host -** at a time -** -** * proxy file to act as a proxy for the advisory locks normally -** taken on the database -** -** The conch file - to use a proxy file, sqlite must first "hold the conch" -** by taking an sqlite-style shared lock on the conch file, reading the -** contents and comparing the host's unique host ID (see below) and lock -** proxy path against the values stored in the conch. The conch file is -** stored in the same directory as the database file and the file name -** is patterned after the database file name as ".-conch". -** If the conch file does not exist, or its contents do not match the -** host ID and/or proxy path, then the lock is escalated to an exclusive -** lock and the conch file contents is updated with the host ID and proxy -** path and the lock is downgraded to a shared lock again. If the conch -** is held by another process (with a shared lock), the exclusive lock -** will fail and SQLITE_BUSY is returned. -** -** The proxy file - a single-byte file used for all advisory file locks -** normally taken on the database file. This allows for safe sharing -** of the database file for multiple readers and writers on the same -** host (the conch ensures that they all use the same local lock file). -** -** Requesting the lock proxy does not immediately take the conch, it is -** only taken when the first request to lock database file is made. -** This matches the semantics of the traditional locking behavior, where -** opening a connection to a database file does not take a lock on it. -** The shared lock and an open file descriptor are maintained until -** the connection to the database is closed. -** -** The proxy file and the lock file are never deleted so they only need -** to be created the first time they are used. -** -** Configuration options -** --------------------- -** -** SQLITE_PREFER_PROXY_LOCKING -** -** Database files accessed on non-local file systems are -** automatically configured for proxy locking, lock files are -** named automatically using the same logic as -** PRAGMA lock_proxy_file=":auto:" -** -** SQLITE_PROXY_DEBUG -** -** Enables the logging of error messages during host id file -** retrieval and creation -** -** LOCKPROXYDIR -** -** Overrides the default directory used for lock proxy files that -** are named automatically via the ":auto:" setting -** -** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS -** -** Permissions to use when creating a directory for storing the -** lock proxy files, only used when LOCKPROXYDIR is not set. -** -** -** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING, -** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will -** force proxy locking to be used for every database file opened, and 0 -** will force automatic proxy locking to be disabled for all database -** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or -** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING). -*/ - -/* -** Proxy locking is only available on MacOSX -*/ -#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE - -/* -** The proxyLockingContext has the path and file structures for the remote -** and local proxy files in it -*/ -typedef struct proxyLockingContext proxyLockingContext; -struct proxyLockingContext { - unixFile *conchFile; /* Open conch file */ - char *conchFilePath; /* Name of the conch file */ - unixFile *lockProxy; /* Open proxy lock file */ - char *lockProxyPath; /* Name of the proxy lock file */ - char *dbPath; /* Name of the open file */ - int conchHeld; /* 1 if the conch is held, -1 if lockless */ - int nFails; /* Number of conch taking failures */ - void *oldLockingContext; /* Original lockingcontext to restore on close */ - sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */ -}; - -/* -** The proxy lock file path for the database at dbPath is written into lPath, -** which must point to valid, writable memory large enough for a maxLen length -** file path. -*/ -static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){ - int len; - int dbLen; - int i; - -#ifdef LOCKPROXYDIR - len = strlcpy(lPath, LOCKPROXYDIR, maxLen); -#else -# ifdef _CS_DARWIN_USER_TEMP_DIR - { - if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){ - OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n", - lPath, errno, osGetpid(0))); - return SQLITE_IOERR_LOCK; - } - len = strlcat(lPath, "sqliteplocks", maxLen); - } -# else - len = strlcpy(lPath, "/tmp/", maxLen); -# endif -#endif - - if( lPath[len-1]!='/' ){ - len = strlcat(lPath, "/", maxLen); - } - - /* transform the db path to a unique cache name */ - dbLen = (int)strlen(dbPath); - for( i=0; i 0) ){ - /* only mkdir if leaf dir != "." or "/" or ".." */ - if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') - || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){ - buf[i]='\0'; - if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){ - int err=errno; - if( err!=EEXIST ) { - OSTRACE(("CREATELOCKPATH FAILED creating %s, " - "'%s' proxy lock path=%s pid=%d\n", - buf, strerror(err), lockPath, osGetpid(0))); - return err; - } - } - } - start=i+1; - } - buf[i] = lockPath[i]; - } - OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0))); - return 0; -} - -/* -** Create a new VFS file descriptor (stored in memory obtained from -** sqlite3_malloc) and open the file named "path" in the file descriptor. -** -** The caller is responsible not only for closing the file descriptor -** but also for freeing the memory associated with the file descriptor. -*/ -static int proxyCreateUnixFile( - const char *path, /* path for the new unixFile */ - unixFile **ppFile, /* unixFile created and returned by ref */ - int islockfile /* if non zero missing dirs will be created */ -) { - int fd = -1; - unixFile *pNew; - int rc = SQLITE_OK; - int openFlags = O_RDWR | O_CREAT; - sqlite3_vfs dummyVfs; - int terrno = 0; - UnixUnusedFd *pUnused = NULL; - - /* 1. first try to open/create the file - ** 2. if that fails, and this is a lock file (not-conch), try creating - ** the parent directories and then try again. - ** 3. if that fails, try to open the file read-only - ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file - */ - pUnused = findReusableFd(path, openFlags); - if( pUnused ){ - fd = pUnused->fd; - }else{ - pUnused = sqlite3_malloc64(sizeof(*pUnused)); - if( !pUnused ){ - return SQLITE_NOMEM_BKPT; - } - } - if( fd<0 ){ - fd = robust_open(path, openFlags, 0); - terrno = errno; - if( fd<0 && errno==ENOENT && islockfile ){ - if( proxyCreateLockPath(path) == SQLITE_OK ){ - fd = robust_open(path, openFlags, 0); - } - } - } - if( fd<0 ){ - openFlags = O_RDONLY; - fd = robust_open(path, openFlags, 0); - terrno = errno; - } - if( fd<0 ){ - if( islockfile ){ - return SQLITE_BUSY; - } - switch (terrno) { - case EACCES: - return SQLITE_PERM; - case EIO: - return SQLITE_IOERR_LOCK; /* even though it is the conch */ - default: - return SQLITE_CANTOPEN_BKPT; - } - } - - pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew)); - if( pNew==NULL ){ - rc = SQLITE_NOMEM_BKPT; - goto end_create_proxy; - } - memset(pNew, 0, sizeof(unixFile)); - pNew->openFlags = openFlags; - memset(&dummyVfs, 0, sizeof(dummyVfs)); - dummyVfs.pAppData = (void*)&autolockIoFinder; - dummyVfs.zName = "dummy"; - pUnused->fd = fd; - pUnused->flags = openFlags; - pNew->pPreallocatedUnused = pUnused; - - rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0); - if( rc==SQLITE_OK ){ - *ppFile = pNew; - return SQLITE_OK; - } -end_create_proxy: - robust_close(pNew, fd, __LINE__); - sqlite3_free(pNew); - sqlite3_free(pUnused); - return rc; -} - -#ifdef SQLITE_TEST -/* simulate multiple hosts by creating unique hostid file paths */ -SQLITE_API int sqlite3_hostid_num = 0; -#endif - -#define PROXY_HOSTIDLEN 16 /* conch file host id length */ - -#ifdef HAVE_GETHOSTUUID -/* Not always defined in the headers as it ought to be */ -extern int gethostuuid(uuid_t id, const struct timespec *wait); -#endif - -/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN -** bytes of writable memory. -*/ -static int proxyGetHostID(unsigned char *pHostID, int *pError){ - assert(PROXY_HOSTIDLEN == sizeof(uuid_t)); - memset(pHostID, 0, PROXY_HOSTIDLEN); -#ifdef HAVE_GETHOSTUUID - { - struct timespec timeout = {1, 0}; /* 1 sec timeout */ - if( gethostuuid(pHostID, &timeout) ){ - int err = errno; - if( pError ){ - *pError = err; - } - return SQLITE_IOERR; - } - } -#else - UNUSED_PARAMETER(pError); -#endif -#ifdef SQLITE_TEST - /* simulate multiple hosts by creating unique hostid file paths */ - if( sqlite3_hostid_num != 0){ - pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF)); - } -#endif - - return SQLITE_OK; -} - -/* The conch file contains the header, host id and lock file path - */ -#define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */ -#define PROXY_HEADERLEN 1 /* conch file header length */ -#define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN) -#define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN) - -/* -** Takes an open conch file, copies the contents to a new path and then moves -** it back. The newly created file's file descriptor is assigned to the -** conch file structure and finally the original conch file descriptor is -** closed. Returns zero if successful. -*/ -static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){ - proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; - unixFile *conchFile = pCtx->conchFile; - char tPath[MAXPATHLEN]; - char buf[PROXY_MAXCONCHLEN]; - char *cPath = pCtx->conchFilePath; - size_t readLen = 0; - size_t pathLen = 0; - char errmsg[64] = ""; - int fd = -1; - int rc = -1; - UNUSED_PARAMETER(myHostID); - - /* create a new path by replace the trailing '-conch' with '-break' */ - pathLen = strlcpy(tPath, cPath, MAXPATHLEN); - if( pathLen>MAXPATHLEN || pathLen<6 || - (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){ - sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen); - goto end_breaklock; - } - /* read the conch content */ - readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0); - if( readLenh, __LINE__); - conchFile->h = fd; - conchFile->openFlags = O_RDWR | O_CREAT; - -end_breaklock: - if( rc ){ - if( fd>=0 ){ - osUnlink(tPath); - robust_close(pFile, fd, __LINE__); - } - fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg); - } - return rc; -} - -/* Take the requested lock on the conch file and break a stale lock if the -** host id matches. -*/ -static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){ - proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; - unixFile *conchFile = pCtx->conchFile; - int rc = SQLITE_OK; - int nTries = 0; - struct timespec conchModTime; - - memset(&conchModTime, 0, sizeof(conchModTime)); - do { - rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType); - nTries ++; - if( rc==SQLITE_BUSY ){ - /* If the lock failed (busy): - * 1st try: get the mod time of the conch, wait 0.5s and try again. - * 2nd try: fail if the mod time changed or host id is different, wait - * 10 sec and try again - * 3rd try: break the lock unless the mod time has changed. - */ - struct stat buf; - if( osFstat(conchFile->h, &buf) ){ - storeLastErrno(pFile, errno); - return SQLITE_IOERR_LOCK; - } - - if( nTries==1 ){ - conchModTime = buf.st_mtimespec; - usleep(500000); /* wait 0.5 sec and try the lock again*/ - continue; - } - - assert( nTries>1 ); - if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || - conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){ - return SQLITE_BUSY; - } - - if( nTries==2 ){ - char tBuf[PROXY_MAXCONCHLEN]; - int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0); - if( len<0 ){ - storeLastErrno(pFile, errno); - return SQLITE_IOERR_LOCK; - } - if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){ - /* don't break the lock if the host id doesn't match */ - if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){ - return SQLITE_BUSY; - } - }else{ - /* don't break the lock on short read or a version mismatch */ - return SQLITE_BUSY; - } - usleep(10000000); /* wait 10 sec and try the lock again */ - continue; - } - - assert( nTries==3 ); - if( 0==proxyBreakConchLock(pFile, myHostID) ){ - rc = SQLITE_OK; - if( lockType==EXCLUSIVE_LOCK ){ - rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK); - } - if( !rc ){ - rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType); - } - } - } - } while( rc==SQLITE_BUSY && nTries<3 ); - - return rc; -} - -/* Takes the conch by taking a shared lock and read the contents conch, if -** lockPath is non-NULL, the host ID and lock file path must match. A NULL -** lockPath means that the lockPath in the conch file will be used if the -** host IDs match, or a new lock path will be generated automatically -** and written to the conch file. -*/ -static int proxyTakeConch(unixFile *pFile){ - proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; - - if( pCtx->conchHeld!=0 ){ - return SQLITE_OK; - }else{ - unixFile *conchFile = pCtx->conchFile; - uuid_t myHostID; - int pError = 0; - char readBuf[PROXY_MAXCONCHLEN]; - char lockPath[MAXPATHLEN]; - char *tempLockPath = NULL; - int rc = SQLITE_OK; - int createConch = 0; - int hostIdMatch = 0; - int readLen = 0; - int tryOldLockPath = 0; - int forceNewLockPath = 0; - - OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h, - (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), - osGetpid(0))); - - rc = proxyGetHostID(myHostID, &pError); - if( (rc&0xff)==SQLITE_IOERR ){ - storeLastErrno(pFile, pError); - goto end_takeconch; - } - rc = proxyConchLock(pFile, myHostID, SHARED_LOCK); - if( rc!=SQLITE_OK ){ - goto end_takeconch; - } - /* read the existing conch file */ - readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN); - if( readLen<0 ){ - /* I/O error: lastErrno set by seekAndRead */ - storeLastErrno(pFile, conchFile->lastErrno); - rc = SQLITE_IOERR_READ; - goto end_takeconch; - }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || - readBuf[0]!=(char)PROXY_CONCHVERSION ){ - /* a short read or version format mismatch means we need to create a new - ** conch file. - */ - createConch = 1; - } - /* if the host id matches and the lock path already exists in the conch - ** we'll try to use the path there, if we can't open that path, we'll - ** retry with a new auto-generated path - */ - do { /* in case we need to try again for an :auto: named lock file */ - - if( !createConch && !forceNewLockPath ){ - hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, - PROXY_HOSTIDLEN); - /* if the conch has data compare the contents */ - if( !pCtx->lockProxyPath ){ - /* for auto-named local lock file, just check the host ID and we'll - ** use the local lock file path that's already in there - */ - if( hostIdMatch ){ - size_t pathLen = (readLen - PROXY_PATHINDEX); - - if( pathLen>=MAXPATHLEN ){ - pathLen=MAXPATHLEN-1; - } - memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen); - lockPath[pathLen] = 0; - tempLockPath = lockPath; - tryOldLockPath = 1; - /* create a copy of the lock path if the conch is taken */ - goto end_takeconch; - } - }else if( hostIdMatch - && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX], - readLen-PROXY_PATHINDEX) - ){ - /* conch host and lock path match */ - goto end_takeconch; - } - } - - /* if the conch isn't writable and doesn't match, we can't take it */ - if( (conchFile->openFlags&O_RDWR) == 0 ){ - rc = SQLITE_BUSY; - goto end_takeconch; - } - - /* either the conch didn't match or we need to create a new one */ - if( !pCtx->lockProxyPath ){ - proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN); - tempLockPath = lockPath; - /* create a copy of the lock path _only_ if the conch is taken */ - } - - /* update conch with host and path (this will fail if other process - ** has a shared lock already), if the host id matches, use the big - ** stick. - */ - futimes(conchFile->h, NULL); - if( hostIdMatch && !createConch ){ - if( conchFile->pInode && conchFile->pInode->nShared>1 ){ - /* We are trying for an exclusive lock but another thread in this - ** same process is still holding a shared lock. */ - rc = SQLITE_BUSY; - } else { - rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK); - } - }else{ - rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK); - } - if( rc==SQLITE_OK ){ - char writeBuffer[PROXY_MAXCONCHLEN]; - int writeSize = 0; - - writeBuffer[0] = (char)PROXY_CONCHVERSION; - memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN); - if( pCtx->lockProxyPath!=NULL ){ - strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, - MAXPATHLEN); - }else{ - strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN); - } - writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]); - robust_ftruncate(conchFile->h, writeSize); - rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0); - full_fsync(conchFile->h,0,0); - /* If we created a new conch file (not just updated the contents of a - ** valid conch file), try to match the permissions of the database - */ - if( rc==SQLITE_OK && createConch ){ - struct stat buf; - int err = osFstat(pFile->h, &buf); - if( err==0 ){ - mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP | - S_IROTH|S_IWOTH); - /* try to match the database file R/W permissions, ignore failure */ -#ifndef SQLITE_PROXY_DEBUG - osFchmod(conchFile->h, cmode); -#else - do{ - rc = osFchmod(conchFile->h, cmode); - }while( rc==(-1) && errno==EINTR ); - if( rc!=0 ){ - int code = errno; - fprintf(stderr, "fchmod %o FAILED with %d %s\n", - cmode, code, strerror(code)); - } else { - fprintf(stderr, "fchmod %o SUCCEDED\n",cmode); - } - }else{ - int code = errno; - fprintf(stderr, "STAT FAILED[%d] with %d %s\n", - err, code, strerror(code)); -#endif - } - } - } - conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK); - - end_takeconch: - OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h)); - if( rc==SQLITE_OK && pFile->openFlags ){ - int fd; - if( pFile->h>=0 ){ - robust_close(pFile, pFile->h, __LINE__); - } - pFile->h = -1; - fd = robust_open(pCtx->dbPath, pFile->openFlags, 0); - OSTRACE(("TRANSPROXY: OPEN %d\n", fd)); - if( fd>=0 ){ - pFile->h = fd; - }else{ - rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called - during locking */ - } - } - if( rc==SQLITE_OK && !pCtx->lockProxy ){ - char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath; - rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1); - if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){ - /* we couldn't create the proxy lock file with the old lock file path - ** so try again via auto-naming - */ - forceNewLockPath = 1; - tryOldLockPath = 0; - continue; /* go back to the do {} while start point, try again */ - } - } - if( rc==SQLITE_OK ){ - /* Need to make a copy of path if we extracted the value - ** from the conch file or the path was allocated on the stack - */ - if( tempLockPath ){ - pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath); - if( !pCtx->lockProxyPath ){ - rc = SQLITE_NOMEM_BKPT; - } - } - } - if( rc==SQLITE_OK ){ - pCtx->conchHeld = 1; - - if( pCtx->lockProxy->pMethod == &afpIoMethods ){ - afpLockingContext *afpCtx; - afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext; - afpCtx->dbPath = pCtx->lockProxyPath; - } - } else { - conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK); - } - OSTRACE(("TAKECONCH %d %s\n", conchFile->h, - rc==SQLITE_OK?"ok":"failed")); - return rc; - } while (1); /* in case we need to retry the :auto: lock file - - ** we should never get here except via the 'continue' call. */ - } -} - -/* -** If pFile holds a lock on a conch file, then release that lock. -*/ -static int proxyReleaseConch(unixFile *pFile){ - int rc = SQLITE_OK; /* Subroutine return code */ - proxyLockingContext *pCtx; /* The locking context for the proxy lock */ - unixFile *conchFile; /* Name of the conch file */ - - pCtx = (proxyLockingContext *)pFile->lockingContext; - conchFile = pCtx->conchFile; - OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h, - (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), - osGetpid(0))); - if( pCtx->conchHeld>0 ){ - rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK); - } - pCtx->conchHeld = 0; - OSTRACE(("RELEASECONCH %d %s\n", conchFile->h, - (rc==SQLITE_OK ? "ok" : "failed"))); - return rc; -} - -/* -** Given the name of a database file, compute the name of its conch file. -** Store the conch filename in memory obtained from sqlite3_malloc64(). -** Make *pConchPath point to the new name. Return SQLITE_OK on success -** or SQLITE_NOMEM if unable to obtain memory. -** -** The caller is responsible for ensuring that the allocated memory -** space is eventually freed. -** -** *pConchPath is set to NULL if a memory allocation error occurs. -*/ -static int proxyCreateConchPathname(char *dbPath, char **pConchPath){ - int i; /* Loop counter */ - int len = (int)strlen(dbPath); /* Length of database filename - dbPath */ - char *conchPath; /* buffer in which to construct conch name */ - - /* Allocate space for the conch filename and initialize the name to - ** the name of the original database file. */ - *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8); - if( conchPath==0 ){ - return SQLITE_NOMEM_BKPT; - } - memcpy(conchPath, dbPath, len+1); - - /* now insert a "." before the last / character */ - for( i=(len-1); i>=0; i-- ){ - if( conchPath[i]=='/' ){ - i++; - break; - } - } - conchPath[i]='.'; - while ( ilockingContext; - char *oldPath = pCtx->lockProxyPath; - int rc = SQLITE_OK; - - if( pFile->eFileLock!=NO_LOCK ){ - return SQLITE_BUSY; - } - - /* nothing to do if the path is NULL, :auto: or matches the existing path */ - if( !path || path[0]=='\0' || !strcmp(path, ":auto:") || - (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){ - return SQLITE_OK; - }else{ - unixFile *lockProxy = pCtx->lockProxy; - pCtx->lockProxy=NULL; - pCtx->conchHeld = 0; - if( lockProxy!=NULL ){ - rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy); - if( rc ) return rc; - sqlite3_free(lockProxy); - } - sqlite3_free(oldPath); - pCtx->lockProxyPath = sqlite3DbStrDup(0, path); - } - - return rc; -} - -/* -** pFile is a file that has been opened by a prior xOpen call. dbPath -** is a string buffer at least MAXPATHLEN+1 characters in size. -** -** This routine find the filename associated with pFile and writes it -** int dbPath. -*/ -static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){ -#if defined(__APPLE__) - if( pFile->pMethod == &afpIoMethods ){ - /* afp style keeps a reference to the db path in the filePath field - ** of the struct */ - assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN ); - strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, - MAXPATHLEN); - } else -#endif - if( pFile->pMethod == &dotlockIoMethods ){ - /* dot lock style uses the locking context to store the dot lock - ** file path */ - int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX); - memcpy(dbPath, (char *)pFile->lockingContext, len + 1); - }else{ - /* all other styles use the locking context to store the db file path */ - assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN ); - strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN); - } - return SQLITE_OK; -} - -/* -** Takes an already filled in unix file and alters it so all file locking -** will be performed on the local proxy lock file. The following fields -** are preserved in the locking context so that they can be restored and -** the unix structure properly cleaned up at close time: -** ->lockingContext -** ->pMethod -*/ -static int proxyTransformUnixFile(unixFile *pFile, const char *path) { - proxyLockingContext *pCtx; - char dbPath[MAXPATHLEN+1]; /* Name of the database file */ - char *lockPath=NULL; - int rc = SQLITE_OK; - - if( pFile->eFileLock!=NO_LOCK ){ - return SQLITE_BUSY; - } - proxyGetDbPathForUnixFile(pFile, dbPath); - if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){ - lockPath=NULL; - }else{ - lockPath=(char *)path; - } - - OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h, - (lockPath ? lockPath : ":auto:"), osGetpid(0))); - - pCtx = sqlite3_malloc64( sizeof(*pCtx) ); - if( pCtx==0 ){ - return SQLITE_NOMEM_BKPT; - } - memset(pCtx, 0, sizeof(*pCtx)); - - rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath); - if( rc==SQLITE_OK ){ - rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0); - if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){ - /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and - ** (c) the file system is read-only, then enable no-locking access. - ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts - ** that openFlags will have only one of O_RDONLY or O_RDWR. - */ - struct statfs fsInfo; - struct stat conchInfo; - int goLockless = 0; - - if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) { - int err = errno; - if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){ - goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY; - } - } - if( goLockless ){ - pCtx->conchHeld = -1; /* read only FS/ lockless */ - rc = SQLITE_OK; - } - } - } - if( rc==SQLITE_OK && lockPath ){ - pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath); - } - - if( rc==SQLITE_OK ){ - pCtx->dbPath = sqlite3DbStrDup(0, dbPath); - if( pCtx->dbPath==NULL ){ - rc = SQLITE_NOMEM_BKPT; - } - } - if( rc==SQLITE_OK ){ - /* all memory is allocated, proxys are created and assigned, - ** switch the locking context and pMethod then return. - */ - pCtx->oldLockingContext = pFile->lockingContext; - pFile->lockingContext = pCtx; - pCtx->pOldMethod = pFile->pMethod; - pFile->pMethod = &proxyIoMethods; - }else{ - if( pCtx->conchFile ){ - pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile); - sqlite3_free(pCtx->conchFile); - } - sqlite3DbFree(0, pCtx->lockProxyPath); - sqlite3_free(pCtx->conchFilePath); - sqlite3_free(pCtx); - } - OSTRACE(("TRANSPROXY %d %s\n", pFile->h, - (rc==SQLITE_OK ? "ok" : "failed"))); - return rc; -} - - -/* -** This routine handles sqlite3_file_control() calls that are specific -** to proxy locking. -*/ -static int proxyFileControl(sqlite3_file *id, int op, void *pArg){ - switch( op ){ - case SQLITE_FCNTL_GET_LOCKPROXYFILE: { - unixFile *pFile = (unixFile*)id; - if( pFile->pMethod == &proxyIoMethods ){ - proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext; - proxyTakeConch(pFile); - if( pCtx->lockProxyPath ){ - *(const char **)pArg = pCtx->lockProxyPath; - }else{ - *(const char **)pArg = ":auto: (not held)"; - } - } else { - *(const char **)pArg = NULL; - } - return SQLITE_OK; - } - case SQLITE_FCNTL_SET_LOCKPROXYFILE: { - unixFile *pFile = (unixFile*)id; - int rc = SQLITE_OK; - int isProxyStyle = (pFile->pMethod == &proxyIoMethods); - if( pArg==NULL || (const char *)pArg==0 ){ - if( isProxyStyle ){ - /* turn off proxy locking - not supported. If support is added for - ** switching proxy locking mode off then it will need to fail if - ** the journal mode is WAL mode. - */ - rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/; - }else{ - /* turn off proxy locking - already off - NOOP */ - rc = SQLITE_OK; - } - }else{ - const char *proxyPath = (const char *)pArg; - if( isProxyStyle ){ - proxyLockingContext *pCtx = - (proxyLockingContext*)pFile->lockingContext; - if( !strcmp(pArg, ":auto:") - || (pCtx->lockProxyPath && - !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN)) - ){ - rc = SQLITE_OK; - }else{ - rc = switchLockProxyPath(pFile, proxyPath); - } - }else{ - /* turn on proxy file locking */ - rc = proxyTransformUnixFile(pFile, proxyPath); - } - } - return rc; - } - default: { - assert( 0 ); /* The call assures that only valid opcodes are sent */ - } - } - /*NOTREACHED*/ - return SQLITE_ERROR; -} - -/* -** Within this division (the proxying locking implementation) the procedures -** above this point are all utilities. The lock-related methods of the -** proxy-locking sqlite3_io_method object follow. -*/ - - -/* -** This routine checks if there is a RESERVED lock held on the specified -** file by this or any other process. If such a lock is held, set *pResOut -** to a non-zero value otherwise *pResOut is set to zero. The return value -** is set to SQLITE_OK unless an I/O error occurs during lock checking. -*/ -static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) { - unixFile *pFile = (unixFile*)id; - int rc = proxyTakeConch(pFile); - if( rc==SQLITE_OK ){ - proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; - if( pCtx->conchHeld>0 ){ - unixFile *proxy = pCtx->lockProxy; - return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut); - }else{ /* conchHeld < 0 is lockless */ - pResOut=0; - } - } - return rc; -} - -/* -** Lock the file with the lock specified by parameter eFileLock - one -** of the following: -** -** (1) SHARED_LOCK -** (2) RESERVED_LOCK -** (3) PENDING_LOCK -** (4) EXCLUSIVE_LOCK -** -** Sometimes when requesting one lock state, additional lock states -** are inserted in between. The locking might fail on one of the later -** transitions leaving the lock state different from what it started but -** still short of its goal. The following chart shows the allowed -** transitions and the inserted intermediate states: -** -** UNLOCKED -> SHARED -** SHARED -> RESERVED -** SHARED -> (PENDING) -> EXCLUSIVE -** RESERVED -> (PENDING) -> EXCLUSIVE -** PENDING -> EXCLUSIVE -** -** This routine will only increase a lock. Use the sqlite3OsUnlock() -** routine to lower a locking level. -*/ -static int proxyLock(sqlite3_file *id, int eFileLock) { - unixFile *pFile = (unixFile*)id; - int rc = proxyTakeConch(pFile); - if( rc==SQLITE_OK ){ - proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; - if( pCtx->conchHeld>0 ){ - unixFile *proxy = pCtx->lockProxy; - rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock); - pFile->eFileLock = proxy->eFileLock; - }else{ - /* conchHeld < 0 is lockless */ - } - } - return rc; -} - - -/* -** Lower the locking level on file descriptor pFile to eFileLock. eFileLock -** must be either NO_LOCK or SHARED_LOCK. -** -** If the locking level of the file descriptor is already at or below -** the requested locking level, this routine is a no-op. -*/ -static int proxyUnlock(sqlite3_file *id, int eFileLock) { - unixFile *pFile = (unixFile*)id; - int rc = proxyTakeConch(pFile); - if( rc==SQLITE_OK ){ - proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; - if( pCtx->conchHeld>0 ){ - unixFile *proxy = pCtx->lockProxy; - rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock); - pFile->eFileLock = proxy->eFileLock; - }else{ - /* conchHeld < 0 is lockless */ - } - } - return rc; -} - -/* -** Close a file that uses proxy locks. -*/ -static int proxyClose(sqlite3_file *id) { - if( ALWAYS(id) ){ - unixFile *pFile = (unixFile*)id; - proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; - unixFile *lockProxy = pCtx->lockProxy; - unixFile *conchFile = pCtx->conchFile; - int rc = SQLITE_OK; - - if( lockProxy ){ - rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK); - if( rc ) return rc; - rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy); - if( rc ) return rc; - sqlite3_free(lockProxy); - pCtx->lockProxy = 0; - } - if( conchFile ){ - if( pCtx->conchHeld ){ - rc = proxyReleaseConch(pFile); - if( rc ) return rc; - } - rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile); - if( rc ) return rc; - sqlite3_free(conchFile); - } - sqlite3DbFree(0, pCtx->lockProxyPath); - sqlite3_free(pCtx->conchFilePath); - sqlite3DbFree(0, pCtx->dbPath); - /* restore the original locking context and pMethod then close it */ - pFile->lockingContext = pCtx->oldLockingContext; - pFile->pMethod = pCtx->pOldMethod; - sqlite3_free(pCtx); - return pFile->pMethod->xClose(id); - } - return SQLITE_OK; -} - - - -#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ -/* -** The proxy locking style is intended for use with AFP filesystems. -** And since AFP is only supported on MacOSX, the proxy locking is also -** restricted to MacOSX. -** -** -******************* End of the proxy lock implementation ********************** -******************************************************************************/ - -/* -** Initialize the operating system interface. -** -** This routine registers all VFS implementations for unix-like operating -** systems. This routine, and the sqlite3_os_end() routine that follows, -** should be the only routines in this file that are visible from other -** files. -** -** This routine is called once during SQLite initialization and by a -** single thread. The memory allocation and mutex subsystems have not -** necessarily been initialized when this routine is called, and so they -** should not be used. -*/ -SQLITE_API int sqlite3_os_init(void){ - /* - ** The following macro defines an initializer for an sqlite3_vfs object. - ** The name of the VFS is NAME. The pAppData is a pointer to a pointer - ** to the "finder" function. (pAppData is a pointer to a pointer because - ** silly C90 rules prohibit a void* from being cast to a function pointer - ** and so we have to go through the intermediate pointer to avoid problems - ** when compiling with -pedantic-errors on GCC.) - ** - ** The FINDER parameter to this macro is the name of the pointer to the - ** finder-function. The finder-function returns a pointer to the - ** sqlite_io_methods object that implements the desired locking - ** behaviors. See the division above that contains the IOMETHODS - ** macro for addition information on finder-functions. - ** - ** Most finders simply return a pointer to a fixed sqlite3_io_methods - ** object. But the "autolockIoFinder" available on MacOSX does a little - ** more than that; it looks at the filesystem type that hosts the - ** database file and tries to choose an locking method appropriate for - ** that filesystem time. - */ - #define UNIXVFS(VFSNAME, FINDER) { \ - 3, /* iVersion */ \ - sizeof(unixFile), /* szOsFile */ \ - MAX_PATHNAME, /* mxPathname */ \ - 0, /* pNext */ \ - VFSNAME, /* zName */ \ - (void*)&FINDER, /* pAppData */ \ - unixOpen, /* xOpen */ \ - unixDelete, /* xDelete */ \ - unixAccess, /* xAccess */ \ - unixFullPathname, /* xFullPathname */ \ - unixDlOpen, /* xDlOpen */ \ - unixDlError, /* xDlError */ \ - unixDlSym, /* xDlSym */ \ - unixDlClose, /* xDlClose */ \ - unixRandomness, /* xRandomness */ \ - unixSleep, /* xSleep */ \ - unixCurrentTime, /* xCurrentTime */ \ - unixGetLastError, /* xGetLastError */ \ - unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \ - unixSetSystemCall, /* xSetSystemCall */ \ - unixGetSystemCall, /* xGetSystemCall */ \ - unixNextSystemCall, /* xNextSystemCall */ \ - } - - /* - ** All default VFSes for unix are contained in the following array. - ** - ** Note that the sqlite3_vfs.pNext field of the VFS object is modified - ** by the SQLite core when the VFS is registered. So the following - ** array cannot be const. - */ - static sqlite3_vfs aVfs[] = { -#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) - UNIXVFS("unix", autolockIoFinder ), -#elif OS_VXWORKS - UNIXVFS("unix", vxworksIoFinder ), -#else - UNIXVFS("unix", posixIoFinder ), -#endif - UNIXVFS("unix-none", nolockIoFinder ), - UNIXVFS("unix-dotfile", dotlockIoFinder ), - UNIXVFS("unix-excl", posixIoFinder ), -#if OS_VXWORKS - UNIXVFS("unix-namedsem", semIoFinder ), -#endif -#if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS - UNIXVFS("unix-posix", posixIoFinder ), -#endif -#if SQLITE_ENABLE_LOCKING_STYLE - UNIXVFS("unix-flock", flockIoFinder ), -#endif -#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) - UNIXVFS("unix-afp", afpIoFinder ), - UNIXVFS("unix-nfs", nfsIoFinder ), - UNIXVFS("unix-proxy", proxyIoFinder ), -#endif - }; - unsigned int i; /* Loop counter */ - - /* Double-check that the aSyscall[] array has been constructed - ** correctly. See ticket [bb3a86e890c8e96ab] */ - assert( ArraySize(aSyscall)==29 ); - - /* Register all VFSes defined in the aVfs[] array */ - for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){ - sqlite3_vfs_register(&aVfs[i], i==0); - } - 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){ - return SQLITE_OK; -} - -#endif /* SQLITE_OS_UNIX */ - -/************** End of os_unix.c *********************************************/ -/************** Begin file os_win.c ******************************************/ -/* -** 2004 May 22 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This file contains code that is specific to Windows. -*/ -/* #include "sqliteInt.h" */ -#if SQLITE_OS_WIN /* This file is used for Windows only */ - -/* -** Include code that is common to all os_*.c files -*/ -/************** Include os_common.h in the middle of os_win.c ****************/ -/************** Begin file os_common.h ***************************************/ -/* -** 2004 May 22 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This file contains macros and a little bit of code that is common to -** all of the platform-specific files (os_*.c) and is #included into those -** files. -** -** This file should be #included by the os_*.c files only. It is not a -** general purpose header file. -*/ -#ifndef _OS_COMMON_H_ -#define _OS_COMMON_H_ - -/* -** At least two bugs have slipped in because we changed the MEMORY_DEBUG -** macro to SQLITE_DEBUG and some older makefiles have not yet made the -** switch. The following code should catch this problem at compile-time. -*/ -#ifdef MEMORY_DEBUG -# error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead." -#endif - -/* -** Macros for performance tracing. Normally turned off. Only works -** on i486 hardware. -*/ -#ifdef SQLITE_PERFORMANCE_TRACE - -/* -** hwtime.h contains inline assembler code for implementing -** high-performance timing routines. -*/ -/************** Include hwtime.h in the middle of os_common.h ****************/ -/************** Begin file hwtime.h ******************************************/ -/* -** 2008 May 27 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This file contains inline asm code for retrieving "high-performance" -** counters for x86 class CPUs. -*/ -#ifndef SQLITE_HWTIME_H -#define SQLITE_HWTIME_H - -/* -** The following routine only works on pentium-class (or newer) processors. -** It uses the RDTSC opcode to read the cycle count value out of the -** processor and returns that value. This can be used for high-res -** profiling. -*/ -#if (defined(__GNUC__) || defined(_MSC_VER)) && \ - (defined(i386) || defined(__i386__) || defined(_M_IX86)) - - #if defined(__GNUC__) - - __inline__ sqlite_uint64 sqlite3Hwtime(void){ - unsigned int lo, hi; - __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); - return (sqlite_uint64)hi << 32 | lo; - } - - #elif defined(_MSC_VER) - - __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){ - __asm { - rdtsc - ret ; return value at EDX:EAX - } - } - - #endif - -#elif (defined(__GNUC__) && defined(__x86_64__)) - - __inline__ sqlite_uint64 sqlite3Hwtime(void){ - unsigned long val; - __asm__ __volatile__ ("rdtsc" : "=A" (val)); - return val; - } - -#elif (defined(__GNUC__) && defined(__ppc__)) - - __inline__ sqlite_uint64 sqlite3Hwtime(void){ - unsigned long long retval; - unsigned long junk; - __asm__ __volatile__ ("\n\ - 1: mftbu %1\n\ - mftb %L0\n\ - mftbu %0\n\ - cmpw %0,%1\n\ - bne 1b" - : "=r" (retval), "=r" (junk)); - return retval; - } - -#else - - #error Need implementation of sqlite3Hwtime() for your platform. - - /* - ** To compile without implementing sqlite3Hwtime() for your platform, - ** you can remove the above #error and use the following - ** stub function. You will lose timing support for many - ** of the debugging and testing utilities, but it should at - ** least compile and run. - */ -SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } - -#endif - -#endif /* !defined(SQLITE_HWTIME_H) */ - -/************** End of hwtime.h **********************************************/ -/************** Continuing where we left off in os_common.h ******************/ - -static sqlite_uint64 g_start; -static sqlite_uint64 g_elapsed; -#define TIMER_START g_start=sqlite3Hwtime() -#define TIMER_END g_elapsed=sqlite3Hwtime()-g_start -#define TIMER_ELAPSED g_elapsed -#else -#define TIMER_START -#define TIMER_END -#define TIMER_ELAPSED ((sqlite_uint64)0) -#endif - -/* -** If we compile with the SQLITE_TEST macro set, then the following block -** of code will give us the ability to simulate a disk I/O error. This -** is used for testing the I/O recovery logic. -*/ -#if defined(SQLITE_TEST) -SQLITE_API extern int sqlite3_io_error_hit; -SQLITE_API extern int sqlite3_io_error_hardhit; -SQLITE_API extern int sqlite3_io_error_pending; -SQLITE_API extern int sqlite3_io_error_persist; -SQLITE_API extern int sqlite3_io_error_benign; -SQLITE_API extern int sqlite3_diskfull_pending; -SQLITE_API extern int sqlite3_diskfull; -#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X) -#define SimulateIOError(CODE) \ - if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \ - || sqlite3_io_error_pending-- == 1 ) \ - { local_ioerr(); CODE; } -static void local_ioerr(){ - IOTRACE(("IOERR\n")); - sqlite3_io_error_hit++; - if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++; -} -#define SimulateDiskfullError(CODE) \ - if( sqlite3_diskfull_pending ){ \ - if( sqlite3_diskfull_pending == 1 ){ \ - local_ioerr(); \ - sqlite3_diskfull = 1; \ - sqlite3_io_error_hit = 1; \ - CODE; \ - }else{ \ - sqlite3_diskfull_pending--; \ - } \ - } -#else -#define SimulateIOErrorBenign(X) -#define SimulateIOError(A) -#define SimulateDiskfullError(A) -#endif /* defined(SQLITE_TEST) */ - -/* -** When testing, keep a count of the number of open files. -*/ -#if defined(SQLITE_TEST) -SQLITE_API extern int sqlite3_open_file_count; -#define OpenCounter(X) sqlite3_open_file_count+=(X) -#else -#define OpenCounter(X) -#endif /* defined(SQLITE_TEST) */ - -#endif /* !defined(_OS_COMMON_H_) */ - -/************** End of os_common.h *******************************************/ -/************** Continuing where we left off in os_win.c *********************/ - -/* -** Include the header file for the Windows VFS. -*/ -/* #include "os_win.h" */ - -/* -** Compiling and using WAL mode requires several APIs that are only -** available in Windows platforms based on the NT kernel. -*/ -#if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL) -# error "WAL mode requires support from the Windows NT kernel, compile\ - with SQLITE_OMIT_WAL." -#endif - -#if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0 -# error "Memory mapped files require support from the Windows NT kernel,\ - compile with SQLITE_MAX_MMAP_SIZE=0." -#endif - -/* -** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions -** based on the sub-platform)? -*/ -#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI) -# define SQLITE_WIN32_HAS_ANSI -#endif - -/* -** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions -** based on the sub-platform)? -*/ -#if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \ - !defined(SQLITE_WIN32_NO_WIDE) -# define SQLITE_WIN32_HAS_WIDE -#endif - -/* -** Make sure at least one set of Win32 APIs is available. -*/ -#if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE) -# error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\ - must be defined." -#endif - -/* -** Define the required Windows SDK version constants if they are not -** already available. -*/ -#ifndef NTDDI_WIN8 -# define NTDDI_WIN8 0x06020000 -#endif - -#ifndef NTDDI_WINBLUE -# define NTDDI_WINBLUE 0x06030000 -#endif - -#ifndef NTDDI_WINTHRESHOLD -# define NTDDI_WINTHRESHOLD 0x06040000 -#endif - -/* -** Check to see if the GetVersionEx[AW] functions are deprecated on the -** target system. GetVersionEx was first deprecated in Win8.1. -*/ -#ifndef SQLITE_WIN32_GETVERSIONEX -# if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE -# define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */ -# else -# define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */ -# endif -#endif - -/* -** Check to see if the CreateFileMappingA function is supported on the -** target system. It is unavailable when using "mincore.lib" on Win10. -** When compiling for Windows 10, always assume "mincore.lib" is in use. -*/ -#ifndef SQLITE_WIN32_CREATEFILEMAPPINGA -# if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD -# define SQLITE_WIN32_CREATEFILEMAPPINGA 0 -# else -# define SQLITE_WIN32_CREATEFILEMAPPINGA 1 -# endif -#endif - -/* -** This constant should already be defined (in the "WinDef.h" SDK file). -*/ -#ifndef MAX_PATH -# define MAX_PATH (260) -#endif - -/* -** Maximum pathname length (in chars) for Win32. This should normally be -** MAX_PATH. -*/ -#ifndef SQLITE_WIN32_MAX_PATH_CHARS -# define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH) -#endif - -/* -** This constant should already be defined (in the "WinNT.h" SDK file). -*/ -#ifndef UNICODE_STRING_MAX_CHARS -# define UNICODE_STRING_MAX_CHARS (32767) -#endif - -/* -** Maximum pathname length (in chars) for WinNT. This should normally be -** UNICODE_STRING_MAX_CHARS. -*/ -#ifndef SQLITE_WINNT_MAX_PATH_CHARS -# define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS) -#endif - -/* -** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in -** characters, so we allocate 4 bytes per character assuming worst-case of -** 4-bytes-per-character for UTF8. -*/ -#ifndef SQLITE_WIN32_MAX_PATH_BYTES -# define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4) -#endif - -/* -** Maximum pathname length (in bytes) for WinNT. This should normally be -** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR). -*/ -#ifndef SQLITE_WINNT_MAX_PATH_BYTES -# define SQLITE_WINNT_MAX_PATH_BYTES \ - (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS) -#endif - -/* -** Maximum error message length (in chars) for WinRT. -*/ -#ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS -# define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024) -#endif - -/* -** Returns non-zero if the character should be treated as a directory -** separator. -*/ -#ifndef winIsDirSep -# define winIsDirSep(a) (((a) == '/') || ((a) == '\\')) -#endif - -/* -** This macro is used when a local variable is set to a value that is -** [sometimes] not used by the code (e.g. via conditional compilation). -*/ -#ifndef UNUSED_VARIABLE_VALUE -# define UNUSED_VARIABLE_VALUE(x) (void)(x) -#endif - -/* -** Returns the character that should be used as the directory separator. -*/ -#ifndef winGetDirSep -# define winGetDirSep() '\\' -#endif - -/* -** Do we need to manually define the Win32 file mapping APIs for use with WAL -** mode or memory mapped files (e.g. these APIs are available in the Windows -** CE SDK; however, they are not present in the header file)? -*/ -#if SQLITE_WIN32_FILEMAPPING_API && \ - (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) -/* -** Two of the file mapping APIs are different under WinRT. Figure out which -** set we need. -*/ -#if SQLITE_OS_WINRT -WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \ - LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR); - -WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T); -#else -#if defined(SQLITE_WIN32_HAS_ANSI) -WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \ - DWORD, DWORD, DWORD, LPCSTR); -#endif /* defined(SQLITE_WIN32_HAS_ANSI) */ - -#if defined(SQLITE_WIN32_HAS_WIDE) -WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \ - DWORD, DWORD, DWORD, LPCWSTR); -#endif /* defined(SQLITE_WIN32_HAS_WIDE) */ - -WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T); -#endif /* SQLITE_OS_WINRT */ - -/* -** These file mapping APIs are common to both Win32 and WinRT. -*/ - -WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T); -WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID); -#endif /* SQLITE_WIN32_FILEMAPPING_API */ - -/* -** Some Microsoft compilers lack this definition. -*/ -#ifndef INVALID_FILE_ATTRIBUTES -# define INVALID_FILE_ATTRIBUTES ((DWORD)-1) -#endif - -#ifndef FILE_FLAG_MASK -# define FILE_FLAG_MASK (0xFF3C0000) -#endif - -#ifndef FILE_ATTRIBUTE_MASK -# define FILE_ATTRIBUTE_MASK (0x0003FFF7) -#endif - -#ifndef SQLITE_OMIT_WAL -/* Forward references to structures used for WAL */ -typedef struct winShm winShm; /* A connection to shared-memory */ -typedef struct winShmNode winShmNode; /* A region of shared-memory */ -#endif - -/* -** WinCE lacks native support for file locking so we have to fake it -** with some code of our own. -*/ -#if SQLITE_OS_WINCE -typedef struct winceLock { - int nReaders; /* Number of reader locks obtained */ - BOOL bPending; /* Indicates a pending lock has been obtained */ - BOOL bReserved; /* Indicates a reserved lock has been obtained */ - BOOL bExclusive; /* Indicates an exclusive lock has been obtained */ -} winceLock; -#endif - -/* -** The winFile structure is a subclass of sqlite3_file* specific to the win32 -** portability layer. -*/ -typedef struct winFile winFile; -struct winFile { - const sqlite3_io_methods *pMethod; /*** Must be first ***/ - sqlite3_vfs *pVfs; /* The VFS used to open this file */ - HANDLE h; /* Handle for accessing the file */ - u8 locktype; /* Type of lock currently held on this file */ - short sharedLockByte; /* Randomly chosen byte used as a shared lock */ - u8 ctrlFlags; /* Flags. See WINFILE_* below */ - DWORD lastErrno; /* The Windows errno from the last I/O error */ -#ifndef SQLITE_OMIT_WAL - winShm *pShm; /* Instance of shared memory on this file */ -#endif - const char *zPath; /* Full pathname of this file */ - int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */ -#if SQLITE_OS_WINCE - LPWSTR zDeleteOnClose; /* Name of file to delete when closing */ - HANDLE hMutex; /* Mutex used to control access to shared lock */ - HANDLE hShared; /* Shared memory segment used for locking */ - winceLock local; /* Locks obtained by this instance of winFile */ - winceLock *shared; /* Global shared lock memory for the file */ -#endif -#if SQLITE_MAX_MMAP_SIZE>0 - int nFetchOut; /* Number of outstanding xFetch references */ - HANDLE hMap; /* Handle for accessing memory mapping */ - void *pMapRegion; /* Area memory mapped */ - sqlite3_int64 mmapSize; /* Usable size of mapped region */ - sqlite3_int64 mmapSizeActual; /* Actual 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 - -/* - * The value used with sqlite3_win32_set_directory() to specify that - * the data directory should be changed. - */ -#ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE -# define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1) -#endif - -/* - * The value used with sqlite3_win32_set_directory() to specify that - * the temporary directory should be changed. - */ -#ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE -# define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2) -#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 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(DWORD type, LPCWSTR zValue){ - 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 *zValueUtf8 = 0; - if( zValue && zValue[0] ){ - zValueUtf8 = winUnicodeToUtf8(zValue); - if ( zValueUtf8==0 ){ - return SQLITE_NOMEM_BKPT; - } - } - sqlite3_free(*ppDirectory); - *ppDirectory = zValueUtf8; - return SQLITE_OK; - } - return SQLITE_ERROR; -} - -/* -** 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; - - 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; - } - - /* 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 the file was 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( pFile->pMapRegion && nBytemmapSize ){ - pFile->mmapSize = nByte; - } -#endif - - OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n", - osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc))); - return rc; -} - -#ifdef SQLITE_TEST -/* -** Count the number of fullsyncs and normal syncs. This is used to test -** that syncs and fullsyncs are occuring at the right times. -*/ -SQLITE_API int sqlite3_sync_count = 0; -SQLITE_API int sqlite3_fullsync_count = 0; -#endif - -/* -** Make sure all writes to a particular file are committed to disk. -*/ -static int winSync(sqlite3_file *id, int flags){ -#ifndef SQLITE_NO_SYNC - /* - ** Used only when SQLITE_NO_SYNC is not defined. - */ - BOOL rc; -#endif -#if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \ - defined(SQLITE_HAVE_OS_TRACE) - /* - ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or - ** OSTRACE() macros. - */ - winFile *pFile = (winFile*)id; -#else - UNUSED_PARAMETER(id); -#endif - - assert( pFile ); - /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */ - assert((flags&0x0F)==SQLITE_SYNC_NORMAL - || (flags&0x0F)==SQLITE_SYNC_FULL - ); - - /* Unix cannot, but some systems may return SQLITE_FULL from here. This - ** line is to test that doing so does not cause any problems. - */ - SimulateDiskfullError( return SQLITE_FULL ); - - OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n", - osGetCurrentProcessId(), pFile, pFile->h, flags, - pFile->locktype)); - -#ifndef SQLITE_TEST - UNUSED_PARAMETER(flags); -#else - if( (flags&0x0F)==SQLITE_SYNC_FULL ){ - sqlite3_fullsync_count++; - } - sqlite3_sync_count++; -#endif - - /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a - ** no-op - */ -#ifdef SQLITE_NO_SYNC - OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", - osGetCurrentProcessId(), pFile, pFile->h)); - return SQLITE_OK; -#else -#if SQLITE_MAX_MMAP_SIZE>0 - if( pFile->pMapRegion ){ - if( osFlushViewOfFile(pFile->pMapRegion, 0) ){ - OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, " - "rc=SQLITE_OK\n", osGetCurrentProcessId(), - pFile, pFile->pMapRegion)); - }else{ - pFile->lastErrno = osGetLastError(); - OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, " - "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), - pFile, pFile->pMapRegion)); - return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno, - "winSync1", pFile->zPath); - } - } -#endif - rc = osFlushFileBuffers(pFile->h); - SimulateIOError( rc=FALSE ); - if( rc ){ - OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n", - osGetCurrentProcessId(), pFile, pFile->h)); - return SQLITE_OK; - }else{ - pFile->lastErrno = osGetLastError(); - OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n", - osGetCurrentProcessId(), pFile, pFile->h)); - return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno, - "winSync2", pFile->zPath); - } -#endif -} - -/* -** Determine the current size of a file in bytes -*/ -static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){ - winFile *pFile = (winFile*)id; - int rc = SQLITE_OK; - - assert( id!=0 ); - assert( pSize!=0 ); - SimulateIOError(return SQLITE_IOERR_FSTAT); - OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize)); - -#if SQLITE_OS_WINRT - { - FILE_STANDARD_INFO info; - if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo, - &info, sizeof(info)) ){ - *pSize = info.EndOfFile.QuadPart; - }else{ - pFile->lastErrno = osGetLastError(); - rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno, - "winFileSize", pFile->zPath); - } - } -#else - { - DWORD upperBits; - DWORD lowerBits; - DWORD lastErrno; - - lowerBits = osGetFileSize(pFile->h, &upperBits); - *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits; - if( (lowerBits == INVALID_FILE_SIZE) - && ((lastErrno = osGetLastError())!=NO_ERROR) ){ - pFile->lastErrno = lastErrno; - rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno, - "winFileSize", pFile->zPath); - } - } -#endif - OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n", - pFile->h, pSize, *pSize, sqlite3ErrName(rc))); - return rc; -} - -/* -** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems. -*/ -#ifndef LOCKFILE_FAIL_IMMEDIATELY -# define LOCKFILE_FAIL_IMMEDIATELY 1 -#endif - -#ifndef LOCKFILE_EXCLUSIVE_LOCK -# define LOCKFILE_EXCLUSIVE_LOCK 2 -#endif - -/* -** Historically, SQLite has used both the LockFile and LockFileEx functions. -** When the LockFile function was used, it was always expected to fail -** immediately if the lock could not be obtained. Also, it always expected to -** obtain an exclusive lock. These flags are used with the LockFileEx function -** and reflect those expectations; therefore, they should not be changed. -*/ -#ifndef SQLITE_LOCKFILE_FLAGS -# define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \ - LOCKFILE_EXCLUSIVE_LOCK) -#endif - -/* -** Currently, SQLite never calls the LockFileEx function without wanting the -** call to fail immediately if the lock cannot be obtained. -*/ -#ifndef SQLITE_LOCKFILEEX_FLAGS -# define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY) -#endif - -/* -** Acquire a reader lock. -** Different API routines are called depending on whether or not this -** is Win9x or WinNT. -*/ -static int winGetReadLock(winFile *pFile){ - int res; - OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype)); - if( osIsNT() ){ -#if SQLITE_OS_WINCE - /* - ** NOTE: Windows CE is handled differently here due its lack of the Win32 - ** API LockFileEx. - */ - res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0); -#else - res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0, - SHARED_SIZE, 0); -#endif - } -#ifdef SQLITE_WIN32_HAS_ANSI - else{ - int lk; - sqlite3_randomness(sizeof(lk), &lk); - pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1)); - res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, - SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0); - } -#endif - if( res == 0 ){ - pFile->lastErrno = osGetLastError(); - /* No need to log a failure to lock */ - } - OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res)); - return res; -} - -/* -** Undo a readlock -*/ -static int winUnlockReadLock(winFile *pFile){ - int res; - DWORD lastErrno; - OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype)); - if( osIsNT() ){ - res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0); - } -#ifdef SQLITE_WIN32_HAS_ANSI - else{ - res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0); - } -#endif - if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){ - pFile->lastErrno = lastErrno; - winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno, - "winUnlockReadLock", pFile->zPath); - } - OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res)); - return res; -} - -/* -** Lock the file with the lock specified by parameter locktype - one -** of the following: -** -** (1) SHARED_LOCK -** (2) RESERVED_LOCK -** (3) PENDING_LOCK -** (4) EXCLUSIVE_LOCK -** -** Sometimes when requesting one lock state, additional lock states -** are inserted in between. The locking might fail on one of the later -** transitions leaving the lock state different from what it started but -** still short of its goal. The following chart shows the allowed -** transitions and the inserted intermediate states: -** -** UNLOCKED -> SHARED -** SHARED -> RESERVED -** SHARED -> (PENDING) -> EXCLUSIVE -** RESERVED -> (PENDING) -> EXCLUSIVE -** PENDING -> EXCLUSIVE -** -** This routine will only increase a lock. The winUnlock() routine -** erases all locks at once and returns us immediately to locking level 0. -** It is not possible to lower the locking level one step at a time. You -** must go straight to locking level 0. -*/ -static int winLock(sqlite3_file *id, int locktype){ - int rc = SQLITE_OK; /* Return code from subroutines */ - int res = 1; /* Result of a Windows lock call */ - int newLocktype; /* Set pFile->locktype to this value before exiting */ - int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */ - winFile *pFile = (winFile*)id; - DWORD lastErrno = NO_ERROR; - - assert( id!=0 ); - OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n", - pFile->h, pFile->locktype, pFile->sharedLockByte, locktype)); - - /* If there is already a lock of this type or more restrictive on the - ** OsFile, do nothing. Don't use the end_lock: exit path, as - ** sqlite3OsEnterMutex() hasn't been called yet. - */ - if( pFile->locktype>=locktype ){ - OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h)); - return SQLITE_OK; - } - - /* Do not allow any kind of write-lock on a read-only database - */ - if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){ - return SQLITE_IOERR_LOCK; - } - - /* Make sure the locking sequence is correct - */ - assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK ); - assert( locktype!=PENDING_LOCK ); - assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK ); - - /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or - ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of - ** the PENDING_LOCK byte is temporary. - */ - newLocktype = pFile->locktype; - if( pFile->locktype==NO_LOCK - || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK) - ){ - int cnt = 3; - while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, - PENDING_BYTE, 0, 1, 0))==0 ){ - /* Try 3 times to get the pending lock. This is needed to work - ** around problems caused by indexing and/or anti-virus software on - ** Windows systems. - ** If you are using this code as a model for alternative VFSes, do not - ** copy this retry logic. It is a hack intended for Windows only. - */ - lastErrno = osGetLastError(); - OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n", - pFile->h, cnt, res)); - if( lastErrno==ERROR_INVALID_HANDLE ){ - pFile->lastErrno = lastErrno; - rc = SQLITE_IOERR_LOCK; - OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n", - pFile->h, cnt, sqlite3ErrName(rc))); - return rc; - } - if( cnt ) sqlite3_win32_sleep(1); - } - gotPendingLock = res; - if( !res ){ - lastErrno = osGetLastError(); - } - } - - /* Acquire a shared lock - */ - if( locktype==SHARED_LOCK && res ){ - assert( pFile->locktype==NO_LOCK ); - res = winGetReadLock(pFile); - if( res ){ - newLocktype = SHARED_LOCK; - }else{ - lastErrno = osGetLastError(); - } - } - - /* Acquire a RESERVED lock - */ - if( locktype==RESERVED_LOCK && res ){ - assert( pFile->locktype==SHARED_LOCK ); - res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0); - if( res ){ - newLocktype = RESERVED_LOCK; - }else{ - lastErrno = osGetLastError(); - } - } - - /* Acquire a PENDING lock - */ - if( locktype==EXCLUSIVE_LOCK && res ){ - newLocktype = PENDING_LOCK; - gotPendingLock = 0; - } - - /* Acquire an EXCLUSIVE lock - */ - if( locktype==EXCLUSIVE_LOCK && res ){ - assert( pFile->locktype>=SHARED_LOCK ); - res = winUnlockReadLock(pFile); - res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0, - SHARED_SIZE, 0); - if( res ){ - newLocktype = EXCLUSIVE_LOCK; - }else{ - lastErrno = osGetLastError(); - winGetReadLock(pFile); - } - } - - /* If we are holding a PENDING lock that ought to be released, then - ** release it now. - */ - if( gotPendingLock && locktype==SHARED_LOCK ){ - winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0); - } - - /* Update the state of the lock has held in the file descriptor then - ** return the appropriate result code. - */ - if( res ){ - rc = SQLITE_OK; - }else{ - pFile->lastErrno = lastErrno; - rc = SQLITE_BUSY; - OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n", - pFile->h, locktype, newLocktype)); - } - pFile->locktype = (u8)newLocktype; - OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n", - pFile->h, pFile->locktype, sqlite3ErrName(rc))); - return rc; -} - -/* -** This routine checks if there is a RESERVED lock held on the specified -** file by this or any other process. If such a lock is held, return -** non-zero, otherwise zero. -*/ -static int winCheckReservedLock(sqlite3_file *id, int *pResOut){ - int res; - winFile *pFile = (winFile*)id; - - SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); - OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut)); - - assert( id!=0 ); - if( pFile->locktype>=RESERVED_LOCK ){ - res = 1; - OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res)); - }else{ - res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0); - if( res ){ - winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0); - } - res = !res; - OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res)); - } - *pResOut = res; - OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n", - pFile->h, pResOut, *pResOut)); - return SQLITE_OK; -} - -/* -** Lower the locking level on file descriptor id to locktype. locktype -** must be either NO_LOCK or SHARED_LOCK. -** -** If the locking level of the file descriptor is already at or below -** the requested locking level, this routine is a no-op. -** -** It is not possible for this routine to fail if the second argument -** is NO_LOCK. If the second argument is SHARED_LOCK then this routine -** might return SQLITE_IOERR; -*/ -static int winUnlock(sqlite3_file *id, int locktype){ - int type; - winFile *pFile = (winFile*)id; - int rc = SQLITE_OK; - assert( pFile!=0 ); - assert( locktype<=SHARED_LOCK ); - OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n", - pFile->h, pFile->locktype, pFile->sharedLockByte, locktype)); - type = pFile->locktype; - if( type>=EXCLUSIVE_LOCK ){ - winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0); - if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){ - /* This should never happen. We should always be able to - ** reacquire the read lock */ - rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(), - "winUnlock", pFile->zPath); - } - } - if( type>=RESERVED_LOCK ){ - winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0); - } - if( locktype==NO_LOCK && type>=SHARED_LOCK ){ - winUnlockReadLock(pFile); - } - if( type>=PENDING_LOCK ){ - winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0); - } - pFile->locktype = (u8)locktype; - OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n", - pFile->h, pFile->locktype, sqlite3ErrName(rc))); - return rc; -} - -/****************************************************************************** -****************************** No-op Locking ********************************** -** -** Of the various locking implementations available, this is by far the -** simplest: locking is ignored. No attempt is made to lock the database -** file for reading or writing. -** -** This locking mode is appropriate for use on read-only databases -** (ex: databases that are burned into CD-ROM, for example.) It can -** also be used if the application employs some external mechanism to -** prevent simultaneous access of the same database by two or more -** database connections. But there is a serious risk of database -** corruption if this locking mode is used in situations where multiple -** database connections are accessing the same database file at the same -** time and one or more of those connections are writing. -*/ - -static int winNolockLock(sqlite3_file *id, int locktype){ - UNUSED_PARAMETER(id); - UNUSED_PARAMETER(locktype); - return SQLITE_OK; -} - -static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){ - UNUSED_PARAMETER(id); - UNUSED_PARAMETER(pResOut); - return SQLITE_OK; -} - -static int winNolockUnlock(sqlite3_file *id, int locktype){ - UNUSED_PARAMETER(id); - UNUSED_PARAMETER(locktype); - return SQLITE_OK; -} - -/******************* End of the no-op lock implementation ********************* -******************************************************************************/ - -/* -** If *pArg is initially negative then this is a query. Set *pArg to -** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set. -** -** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags. -*/ -static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){ - if( *pArg<0 ){ - *pArg = (pFile->ctrlFlags & mask)!=0; - }else if( (*pArg)==0 ){ - pFile->ctrlFlags &= ~mask; - }else{ - pFile->ctrlFlags |= mask; - } -} - -/* Forward references to VFS helper methods used for temporary files */ -static int winGetTempname(sqlite3_vfs *, char **); -static int winIsDir(const void *); -static BOOL winIsDriveLetterAndColon(const char *); - -/* -** Control and query of the open file handle. -*/ -static int winFileControl(sqlite3_file *id, int op, void *pArg){ - winFile *pFile = (winFile*)id; - OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg)); - switch( op ){ - case SQLITE_FCNTL_LOCKSTATE: { - *(int*)pArg = pFile->locktype; - OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); - return SQLITE_OK; - } - case SQLITE_FCNTL_LAST_ERRNO: { - *(int*)pArg = (int)pFile->lastErrno; - OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); - return SQLITE_OK; - } - case SQLITE_FCNTL_CHUNK_SIZE: { - pFile->szChunk = *(int *)pArg; - OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); - return SQLITE_OK; - } - case SQLITE_FCNTL_SIZE_HINT: { - if( pFile->szChunk>0 ){ - sqlite3_int64 oldSz; - int rc = winFileSize(id, &oldSz); - if( rc==SQLITE_OK ){ - sqlite3_int64 newSz = *(sqlite3_int64*)pArg; - if( newSz>oldSz ){ - SimulateIOErrorBenign(1); - rc = winTruncate(id, newSz); - SimulateIOErrorBenign(0); - } - } - OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc))); - return rc; - } - OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); - return SQLITE_OK; - } - case SQLITE_FCNTL_PERSIST_WAL: { - winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg); - OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); - return SQLITE_OK; - } - case SQLITE_FCNTL_POWERSAFE_OVERWRITE: { - winModeBit(pFile, WINFILE_PSOW, (int*)pArg); - OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); - return SQLITE_OK; - } - case SQLITE_FCNTL_VFSNAME: { - *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName); - OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); - return SQLITE_OK; - } - case SQLITE_FCNTL_WIN32_AV_RETRY: { - int *a = (int*)pArg; - if( a[0]>0 ){ - winIoerrRetry = a[0]; - }else{ - a[0] = winIoerrRetry; - } - if( a[1]>0 ){ - winIoerrRetryDelay = a[1]; - }else{ - a[1] = winIoerrRetryDelay; - } - OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); - return SQLITE_OK; - } - case SQLITE_FCNTL_WIN32_GET_HANDLE: { - LPHANDLE phFile = (LPHANDLE)pArg; - *phFile = pFile->h; - OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h)); - return SQLITE_OK; - } -#ifdef SQLITE_TEST - case SQLITE_FCNTL_WIN32_SET_HANDLE: { - LPHANDLE phFile = (LPHANDLE)pArg; - HANDLE hOldFile = pFile->h; - pFile->h = *phFile; - *phFile = hOldFile; - OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n", - hOldFile, pFile->h)); - return SQLITE_OK; - } -#endif - case SQLITE_FCNTL_TEMPFILENAME: { - char *zTFile = 0; - int rc = winGetTempname(pFile->pVfs, &zTFile); - if( rc==SQLITE_OK ){ - *(char**)pArg = zTFile; - } - OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc))); - return rc; - } -#if SQLITE_MAX_MMAP_SIZE>0 - case SQLITE_FCNTL_MMAP_SIZE: { - i64 newLimit = *(i64*)pArg; - int rc = SQLITE_OK; - if( newLimit>sqlite3GlobalConfig.mxMmap ){ - newLimit = sqlite3GlobalConfig.mxMmap; - } - - /* The value of newLimit may be eventually cast to (SIZE_T) and passed - ** to MapViewOfFile(). Restrict its value to 2GB if (SIZE_T) is not at - ** least a 64-bit type. */ - if( newLimit>0 && sizeof(SIZE_T)<8 ){ - newLimit = (newLimit & 0x7FFFFFFF); - } - - *(i64*)pArg = pFile->mmapSizeMax; - if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){ - pFile->mmapSizeMax = newLimit; - if( pFile->mmapSize>0 ){ - winUnmapfile(pFile); - rc = winMapfile(pFile, -1); - } - } - OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc))); - return rc; - } -#endif - } - OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h)); - return SQLITE_NOTFOUND; -} - -/* -** Return the sector size in bytes of the underlying block device for -** the specified file. This is almost always 512 bytes, but may be -** larger for some devices. -** -** SQLite code assumes this function cannot fail. It also assumes that -** if two files are created in the same file-system directory (i.e. -** a database and its journal file) that the sector size will be the -** same for both. -*/ -static int winSectorSize(sqlite3_file *id){ - (void)id; - return SQLITE_DEFAULT_SECTOR_SIZE; -} - -/* -** Return a vector of device characteristics. -*/ -static int winDeviceCharacteristics(sqlite3_file *id){ - winFile *p = (winFile*)id; - return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN | - ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0); -} - -/* -** Windows will only let you create file view mappings -** on allocation size granularity boundaries. -** During sqlite3_os_init() we do a GetSystemInfo() -** to get the granularity size. -*/ -static SYSTEM_INFO winSysInfo; - -#ifndef SQLITE_OMIT_WAL - -/* -** Helper functions to obtain and relinquish the global mutex. The -** global mutex is used to protect the winLockInfo objects used by -** this file, all of which may be shared by multiple threads. -** -** Function winShmMutexHeld() is used to assert() that the global mutex -** is held when required. This function is only used as part of assert() -** statements. e.g. -** -** winShmEnterMutex() -** assert( winShmMutexHeld() ); -** winShmLeaveMutex() -*/ -static void winShmEnterMutex(void){ - sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); -} -static void winShmLeaveMutex(void){ - sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); -} -#ifndef NDEBUG -static int winShmMutexHeld(void) { - return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1)); -} -#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 */ - 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( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 ); - - 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; - } - } -} - -/* -** Open the shared-memory area associated with database file pDbFd. -** -** When opening a new shared-memory file, if no other instances of that -** file are currently open, in this process or in other processes, then -** the file must be truncated to zero length or have its header cleared. -*/ -static int winOpenSharedMemory(winFile *pDbFd){ - struct winShm *p; /* The connection to be opened */ - struct winShmNode *pShmNode = 0; /* The underlying mmapped file */ - int rc; /* Result code */ - struct winShmNode *pNew; /* Newly allocated winShmNode */ - int nName; /* Size of zName in bytes */ - - 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{ - 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; - } - } - - rc = winOpen(pDbFd->pVfs, - pShmNode->zFilename, /* Name of the file (UTF-8) */ - (sqlite3_file*)&pShmNode->hFile, /* File handle here */ - SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, - 0); - if( SQLITE_OK!=rc ){ - goto shm_open_err; - } - - /* Check to see if another process is holding the dead-man switch. - ** If not, truncate the file to zero length. - */ - if( winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){ - rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0); - if( rc!=SQLITE_OK ){ - rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(), - "winOpenShm", pDbFd->zPath); - } - } - if( rc==SQLITE_OK ){ - winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1); - rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1); - } - if( rc ) 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 SQLITE_OK; - - /* 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; - int rc = SQLITE_OK; - - if( !pShm ){ - rc = winOpenSharedMemory(pDbFd); - if( rc!=SQLITE_OK ) return rc; - pShm = pDbFd->pShm; - } - pShmNode = pShm->pShmNode; - - sqlite3_mutex_enter(pShmNode->mutex); - 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; - - 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, PAGE_READWRITE, nByte, NULL - ); -#elif defined(SQLITE_WIN32_HAS_WIDE) - hMap = osCreateFileMappingW(pShmNode->hFile.h, - NULL, PAGE_READWRITE, 0, nByte, NULL - ); -#elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA - hMap = osCreateFileMappingA(pShmNode->hFile.h, - NULL, PAGE_READWRITE, 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, FILE_MAP_WRITE | FILE_MAP_READ, - iOffset - iOffsetShift, szRegion + iOffsetShift - ); -#else - pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ, - 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; - } - 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, mmapSizeActual=%lld, mmapSizeMax=%lld\n", - osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion, - pFile->mmapSize, pFile->mmapSizeActual, 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; - pFile->mmapSizeActual = 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; - pFd->mmapSizeActual = nMap; - } - - OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n", - osGetCurrentProcessId(), pFd)); - return SQLITE_OK; -} -#endif /* SQLITE_MAX_MMAP_SIZE>0 */ - -/* -** If possible, return a pointer to a mapping of file fd starting at offset -** iOff. The mapping must be valid for at least nAmt bytes. -** -** If such a pointer can be obtained, store it in *pp and return SQLITE_OK. -** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK. -** Finally, if an error does occur, return an SQLite error code. The final -** value of *pp is undefined in this case. -** -** If this function does return a pointer, the caller must eventually -** release the reference by calling winUnfetch(). -*/ -static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){ -#if SQLITE_MAX_MMAP_SIZE>0 - winFile *pFd = (winFile*)fd; /* The underlying database file */ -#endif - *pp = 0; - - OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n", - osGetCurrentProcessId(), fd, iOff, nAmt, pp)); - -#if SQLITE_MAX_MMAP_SIZE>0 - if( pFd->mmapSizeMax>0 ){ - if( pFd->pMapRegion==0 ){ - int rc = winMapfile(pFd, -1); - if( rc!=SQLITE_OK ){ - OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n", - osGetCurrentProcessId(), pFd, sqlite3ErrName(rc))); - return rc; - } - } - if( pFd->mmapSize >= iOff+nAmt ){ - *pp = &((u8 *)pFd->pMapRegion)[iOff]; - pFd->nFetchOut++; - } - } -#endif - - OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n", - osGetCurrentProcessId(), fd, pp, *pp)); - return SQLITE_OK; -} - -/* -** If the third argument is non-NULL, then this function releases a -** reference obtained by an earlier call to winFetch(). The second -** argument passed to this function must be the same as the corresponding -** argument that was passed to the winFetch() invocation. -** -** Or, if the third argument is NULL, then this function is being called -** to inform the VFS layer that, according to POSIX, any existing mapping -** may now be invalid and should be unmapped. -*/ -static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){ -#if SQLITE_MAX_MMAP_SIZE>0 - winFile *pFd = (winFile*)fd; /* The underlying database file */ - - /* If p==0 (unmap the entire file) then there must be no outstanding - ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference), - ** then there must be at least one outstanding. */ - assert( (p==0)==(pFd->nFetchOut==0) ); - - /* If p!=0, it must match the iOff value. */ - assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] ); - - OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n", - osGetCurrentProcessId(), pFd, iOff, p)); - - if( p ){ - pFd->nFetchOut--; - }else{ - /* FIXME: If Windows truly always prevents truncating or deleting a - ** file while a mapping is held, then the following winUnmapfile() call - ** is unnecessary can be omitted - potentially improving - ** performance. */ - winUnmapfile(pFd); - } - - assert( pFd->nFetchOut>=0 ); -#endif - - OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n", - osGetCurrentProcessId(), fd)); - return SQLITE_OK; -} - -/* -** Here ends the implementation of all sqlite3_file methods. -** -********************** End sqlite3_file Methods ******************************* -******************************************************************************/ - -/* -** This vector defines all the methods that can operate on an -** sqlite3_file for win32. -*/ -static const sqlite3_io_methods winIoMethod = { - 3, /* iVersion */ - winClose, /* xClose */ - winRead, /* xRead */ - winWrite, /* xWrite */ - winTruncate, /* xTruncate */ - winSync, /* xSync */ - winFileSize, /* xFileSize */ - winLock, /* xLock */ - winUnlock, /* xUnlock */ - winCheckReservedLock, /* xCheckReservedLock */ - winFileControl, /* xFileControl */ - winSectorSize, /* xSectorSize */ - winDeviceCharacteristics, /* xDeviceCharacteristics */ - winShmMap, /* xShmMap */ - winShmLock, /* xShmLock */ - winShmBarrier, /* xShmBarrier */ - winShmUnmap, /* xShmUnmap */ - winFetch, /* xFetch */ - winUnfetch /* xUnfetch */ -}; - -/* -** This vector defines all the methods that can operate on an -** sqlite3_file for win32 without performing any locking. -*/ -static const sqlite3_io_methods winIoNolockMethod = { - 3, /* iVersion */ - winClose, /* xClose */ - winRead, /* xRead */ - winWrite, /* xWrite */ - winTruncate, /* xTruncate */ - winSync, /* xSync */ - winFileSize, /* xFileSize */ - winNolockLock, /* xLock */ - winNolockUnlock, /* xUnlock */ - winNolockCheckReservedLock, /* xCheckReservedLock */ - winFileControl, /* xFileControl */ - winSectorSize, /* xSectorSize */ - winDeviceCharacteristics, /* xDeviceCharacteristics */ - winShmMap, /* xShmMap */ - winShmLock, /* xShmLock */ - winShmBarrier, /* xShmBarrier */ - winShmUnmap, /* xShmUnmap */ - winFetch, /* xFetch */ - winUnfetch /* xUnfetch */ -}; - -static winVfsAppData winAppData = { - &winIoMethod, /* pMethod */ - 0, /* pAppData */ - 0 /* bNoLock */ -}; - -static winVfsAppData winNolockAppData = { - &winIoNolockMethod, /* pMethod */ - 0, /* pAppData */ - 1 /* bNoLock */ -}; - -/**************************************************************************** -**************************** sqlite3_vfs methods **************************** -** -** This division contains the implementation of methods on the -** sqlite3_vfs object. -*/ - -#if defined(__CYGWIN__) -/* -** Convert a filename from whatever the underlying operating system -** supports for filenames into UTF-8. Space to hold the result is -** obtained from malloc and must be freed by the calling function. -*/ -static char *winConvertToUtf8Filename(const void *zFilename){ - char *zConverted = 0; - if( osIsNT() ){ - zConverted = winUnicodeToUtf8(zFilename); - } -#ifdef SQLITE_WIN32_HAS_ANSI - else{ - zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI()); - } -#endif - /* caller will handle out of memory */ - return zConverted; -} -#endif - -/* -** Convert a UTF-8 filename into whatever form the underlying -** operating system wants filenames in. Space to hold the result -** is obtained from malloc and must be freed by the calling -** function. -*/ -static void *winConvertFromUtf8Filename(const char *zFilename){ - void *zConverted = 0; - if( osIsNT() ){ - zConverted = winUtf8ToUnicode(zFilename); - } -#ifdef SQLITE_WIN32_HAS_ANSI - else{ - zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI()); - } -#endif - /* caller will handle out of memory */ - return zConverted; -} - -/* -** This function returns non-zero if the specified UTF-8 string buffer -** ends with a directory separator character or one was successfully -** added to it. -*/ -static int winMakeEndInDirSep(int nBuf, char *zBuf){ - if( zBuf ){ - int nLen = sqlite3Strlen30(zBuf); - if( nLen>0 ){ - if( winIsDirSep(zBuf[nLen-1]) ){ - return 1; - }else if( nLen+1mxPathname; nBuf = nMax + 2; - zBuf = sqlite3MallocZero( nBuf ); - if( !zBuf ){ - OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n")); - return SQLITE_IOERR_NOMEM_BKPT; - } - - /* Figure out the effective temporary directory. First, check if one - ** has been explicitly set by the application; otherwise, use the one - ** configured by the operating system. - */ - nDir = nMax - (nPre + 15); - assert( nDir>0 ); - if( sqlite3_temp_directory ){ - int nDirLen = sqlite3Strlen30(sqlite3_temp_directory); - if( nDirLen>0 ){ - if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){ - nDirLen++; - } - if( nDirLen>nDir ){ - sqlite3_free(zBuf); - OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n")); - return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0); - } - sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory); - } - } -#if defined(__CYGWIN__) - else{ - static const char *azDirs[] = { - 0, /* getenv("SQLITE_TMPDIR") */ - 0, /* getenv("TMPDIR") */ - 0, /* getenv("TMP") */ - 0, /* getenv("TEMP") */ - 0, /* getenv("USERPROFILE") */ - "/var/tmp", - "/usr/tmp", - "/tmp", - ".", - 0 /* List terminator */ - }; - unsigned int i; - const char *zDir = 0; - - if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR"); - if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR"); - if( !azDirs[2] ) azDirs[2] = getenv("TMP"); - if( !azDirs[3] ) azDirs[3] = getenv("TEMP"); - if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE"); - for(i=0; i/etilqs_XXXXXXXXXXXXXXX\0\0" - ** - ** If not, return SQLITE_ERROR. The number 17 is used here in order to - ** account for the space used by the 15 character random suffix and the - ** two trailing NUL characters. The final directory separator character - ** has already added if it was not already present. - */ - nLen = sqlite3Strlen30(zBuf); - if( (nLen + nPre + 17) > nBuf ){ - sqlite3_free(zBuf); - OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n")); - return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0); - } - - sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX); - - j = sqlite3Strlen30(zBuf); - sqlite3_randomness(15, &zBuf[j]); - for(i=0; i<15; i++, j++){ - zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ]; - } - zBuf[j] = 0; - zBuf[j+1] = 0; - *pzBuf = zBuf; - - OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf)); - return SQLITE_OK; -} - -/* -** Return TRUE if the named file is really a directory. Return false if -** it is something other than a directory, or if there is any kind of memory -** allocation failure. -*/ -static int winIsDir(const void *zConverted){ - DWORD attr; - int rc = 0; - DWORD lastErrno; - - if( osIsNT() ){ - int cnt = 0; - WIN32_FILE_ATTRIBUTE_DATA sAttrData; - memset(&sAttrData, 0, sizeof(sAttrData)); - while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted, - GetFileExInfoStandard, - &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){} - if( !rc ){ - return 0; /* Invalid name? */ - } - attr = sAttrData.dwFileAttributes; -#if SQLITE_OS_WINCE==0 - }else{ - attr = osGetFileAttributesA((char*)zConverted); -#endif - } - return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY); -} - -/* forward reference */ -static int winAccess( - sqlite3_vfs *pVfs, /* Not used on win32 */ - const char *zFilename, /* Name of file to check */ - int flags, /* Type of test to make on this file */ - int *pResOut /* OUT: Result */ -); - -/* -** Open a file. -*/ -static int winOpen( - sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */ - const char *zName, /* Name of the file (UTF-8) */ - sqlite3_file *id, /* Write the SQLite file handle here */ - int flags, /* Open mode flags */ - int *pOutFlags /* Status return flags */ -){ - HANDLE h; - DWORD lastErrno = 0; - DWORD dwDesiredAccess; - DWORD dwShareMode; - DWORD dwCreationDisposition; - DWORD dwFlagsAndAttributes = 0; -#if SQLITE_OS_WINCE - int isTemp = 0; -#endif - winVfsAppData *pAppData; - winFile *pFile = (winFile*)id; - void *zConverted; /* Filename in OS encoding */ - const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */ - int cnt = 0; - - /* If argument zPath is a NULL pointer, this function is required to open - ** a temporary file. Use this buffer to store the file name in. - */ - char *zTmpname = 0; /* For temporary filename, if necessary. */ - - int rc = SQLITE_OK; /* Function Return Code */ -#if !defined(NDEBUG) || SQLITE_OS_WINCE - int eType = flags&0xFFFFFF00; /* Type of file to open */ -#endif - - int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE); - int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE); - int isCreate = (flags & SQLITE_OPEN_CREATE); - int isReadonly = (flags & SQLITE_OPEN_READONLY); - int isReadWrite = (flags & SQLITE_OPEN_READWRITE); - -#ifndef NDEBUG - int isOpenJournal = (isCreate && ( - eType==SQLITE_OPEN_MASTER_JOURNAL - || eType==SQLITE_OPEN_MAIN_JOURNAL - || eType==SQLITE_OPEN_WAL - )); -#endif - - OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n", - zUtf8Name, id, flags, pOutFlags)); - - /* Check the following statements are true: - ** - ** (a) Exactly one of the READWRITE and READONLY flags must be set, and - ** (b) if CREATE is set, then READWRITE must also be set, and - ** (c) if EXCLUSIVE is set, then CREATE must also be set. - ** (d) if DELETEONCLOSE is set, then CREATE must also be set. - */ - assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly)); - assert(isCreate==0 || isReadWrite); - assert(isExclusive==0 || isCreate); - assert(isDelete==0 || isCreate); - - /* The main DB, main journal, WAL file and master journal are never - ** automatically deleted. Nor are they ever temporary files. */ - assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB ); - assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL ); - assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL ); - assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL ); - - /* Assert that the upper layer has set one of the "file-type" flags. */ - assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB - || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL - || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL - || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL - ); - - assert( pFile!=0 ); - memset(pFile, 0, sizeof(winFile)); - pFile->h = INVALID_HANDLE_VALUE; - -#if SQLITE_OS_WINRT - if( !zUtf8Name && !sqlite3_temp_directory ){ - sqlite3_log(SQLITE_ERROR, - "sqlite3_temp_directory variable should be set for WinRT"); - } -#endif - - /* If the second argument to this function is NULL, generate a - ** temporary file name to use - */ - if( !zUtf8Name ){ - assert( isDelete && !isOpenJournal ); - rc = winGetTempname(pVfs, &zTmpname); - if( rc!=SQLITE_OK ){ - OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc))); - return rc; - } - zUtf8Name = zTmpname; - } - - /* Database filenames are double-zero terminated if they are not - ** URIs with parameters. Hence, they can always be passed into - ** sqlite3_uri_parameter(). - */ - assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) || - zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 ); - - /* Convert the filename to the system encoding. */ - zConverted = winConvertFromUtf8Filename(zUtf8Name); - if( zConverted==0 ){ - sqlite3_free(zTmpname); - OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name)); - return SQLITE_IOERR_NOMEM_BKPT; - } - - if( winIsDir(zConverted) ){ - sqlite3_free(zConverted); - sqlite3_free(zTmpname); - OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name)); - return SQLITE_CANTOPEN_ISDIR; - } - - if( isReadWrite ){ - dwDesiredAccess = GENERIC_READ | GENERIC_WRITE; - }else{ - dwDesiredAccess = GENERIC_READ; - } - - /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is - ** created. SQLite doesn't use it to indicate "exclusive access" - ** as it is usually understood. - */ - if( isExclusive ){ - /* Creates a new file, only if it does not already exist. */ - /* If the file exists, it fails. */ - dwCreationDisposition = CREATE_NEW; - }else if( isCreate ){ - /* Open existing file, or create if it doesn't exist */ - dwCreationDisposition = OPEN_ALWAYS; - }else{ - /* Opens a file, only if it exists. */ - dwCreationDisposition = OPEN_EXISTING; - } - - dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; - - if( isDelete ){ -#if SQLITE_OS_WINCE - dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN; - isTemp = 1; -#else - dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY - | FILE_ATTRIBUTE_HIDDEN - | FILE_FLAG_DELETE_ON_CLOSE; -#endif - }else{ - dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL; - } - /* Reports from the internet are that performance is always - ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */ -#if SQLITE_OS_WINCE - dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS; -#endif - - if( osIsNT() ){ -#if SQLITE_OS_WINRT - CREATEFILE2_EXTENDED_PARAMETERS extendedParameters; - extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS); - extendedParameters.dwFileAttributes = - dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK; - extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK; - extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS; - extendedParameters.lpSecurityAttributes = NULL; - extendedParameters.hTemplateFile = NULL; - do{ - h = osCreateFile2((LPCWSTR)zConverted, - dwDesiredAccess, - dwShareMode, - dwCreationDisposition, - &extendedParameters); - if( h!=INVALID_HANDLE_VALUE ) break; - if( isReadWrite ){ - int isRO = 0; - int rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO); - 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 isRO = 0; - int rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO); - 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 isRO = 0; - int rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO); - if( rc2==SQLITE_OK && isRO ) break; - } - }while( winRetryIoerr(&cnt, &lastErrno) ); - } -#endif - winLogIoerr(cnt, __LINE__); - - OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name, - dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok")); - - if( h==INVALID_HANDLE_VALUE ){ - sqlite3_free(zConverted); - sqlite3_free(zTmpname); - if( isReadWrite && !isExclusive ){ - return winOpen(pVfs, zName, id, - ((flags|SQLITE_OPEN_READONLY) & - ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), - pOutFlags); - }else{ - pFile->lastErrno = lastErrno; - winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name); - return SQLITE_CANTOPEN_BKPT; - } - } - - if( pOutFlags ){ - if( isReadWrite ){ - *pOutFlags = SQLITE_OPEN_READWRITE; - }else{ - *pOutFlags = SQLITE_OPEN_READONLY; - } - } - - OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, " - "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ? - *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok")); - - pAppData = (winVfsAppData*)pVfs->pAppData; - -#if SQLITE_OS_WINCE - { - if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB - && ((pAppData==NULL) || !pAppData->bNoLock) - && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK - ){ - osCloseHandle(h); - sqlite3_free(zConverted); - sqlite3_free(zTmpname); - OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc))); - return rc; - } - } - if( isTemp ){ - pFile->zDeleteOnClose = zConverted; - }else -#endif - { - sqlite3_free(zConverted); - } - - sqlite3_free(zTmpname); - pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod; - pFile->pVfs = pVfs; - pFile->h = h; - if( isReadonly ){ - pFile->ctrlFlags |= WINFILE_RDONLY; - } - if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){ - pFile->ctrlFlags |= WINFILE_PSOW; - } - pFile->lastErrno = NO_ERROR; - pFile->zPath = zName; -#if SQLITE_MAX_MMAP_SIZE>0 - pFile->hMap = NULL; - pFile->pMapRegion = 0; - pFile->mmapSize = 0; - pFile->mmapSizeActual = 0; - pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap; -#endif - - OpenCounter(+1); - return rc; -} - -/* -** Delete the named file. -** -** Note that Windows does not allow a file to be deleted if some other -** process has it open. Sometimes a virus scanner or indexing program -** will open a journal file shortly after it is created in order to do -** whatever it does. While this other process is holding the -** file open, we will be unable to delete it. To work around this -** problem, we delay 100 milliseconds and try to delete again. Up -** to MX_DELETION_ATTEMPTs deletion attempts are run before giving -** up and returning an error. -*/ -static int winDelete( - sqlite3_vfs *pVfs, /* Not used on win32 */ - const char *zFilename, /* Name of file to delete */ - int syncDir /* Not used on win32 */ -){ - int cnt = 0; - int rc; - DWORD attr; - DWORD lastErrno = 0; - void *zConverted; - UNUSED_PARAMETER(pVfs); - UNUSED_PARAMETER(syncDir); - - SimulateIOError(return SQLITE_IOERR_DELETE); - OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir)); - - zConverted = winConvertFromUtf8Filename(zFilename); - if( zConverted==0 ){ - OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename)); - return SQLITE_IOERR_NOMEM_BKPT; - } - if( osIsNT() ){ - do { -#if SQLITE_OS_WINRT - WIN32_FILE_ATTRIBUTE_DATA sAttrData; - memset(&sAttrData, 0, sizeof(sAttrData)); - if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard, - &sAttrData) ){ - attr = sAttrData.dwFileAttributes; - }else{ - lastErrno = osGetLastError(); - if( lastErrno==ERROR_FILE_NOT_FOUND - || lastErrno==ERROR_PATH_NOT_FOUND ){ - rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */ - }else{ - rc = SQLITE_ERROR; - } - break; - } -#else - attr = osGetFileAttributesW(zConverted); -#endif - if ( attr==INVALID_FILE_ATTRIBUTES ){ - lastErrno = osGetLastError(); - if( lastErrno==ERROR_FILE_NOT_FOUND - || lastErrno==ERROR_PATH_NOT_FOUND ){ - rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */ - }else{ - rc = SQLITE_ERROR; - } - break; - } - if ( attr&FILE_ATTRIBUTE_DIRECTORY ){ - rc = SQLITE_ERROR; /* Files only. */ - break; - } - if ( osDeleteFileW(zConverted) ){ - rc = SQLITE_OK; /* Deleted OK. */ - break; - } - if ( !winRetryIoerr(&cnt, &lastErrno) ){ - rc = SQLITE_ERROR; /* No more retries. */ - break; - } - } while(1); - } -#ifdef SQLITE_WIN32_HAS_ANSI - else{ - do { - attr = osGetFileAttributesA(zConverted); - if ( attr==INVALID_FILE_ATTRIBUTES ){ - lastErrno = osGetLastError(); - if( lastErrno==ERROR_FILE_NOT_FOUND - || lastErrno==ERROR_PATH_NOT_FOUND ){ - rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */ - }else{ - rc = SQLITE_ERROR; - } - break; - } - if ( attr&FILE_ATTRIBUTE_DIRECTORY ){ - rc = SQLITE_ERROR; /* Files only. */ - break; - } - if ( osDeleteFileA(zConverted) ){ - rc = SQLITE_OK; /* Deleted OK. */ - break; - } - if ( !winRetryIoerr(&cnt, &lastErrno) ){ - rc = SQLITE_ERROR; /* No more retries. */ - break; - } - } while(1); - } -#endif - if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){ - rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename); - }else{ - winLogIoerr(cnt, __LINE__); - } - sqlite3_free(zConverted); - OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc))); - return rc; -} - -/* -** Check the existence and status of a file. -*/ -static int winAccess( - sqlite3_vfs *pVfs, /* Not used on win32 */ - const char *zFilename, /* Name of file to check */ - int flags, /* Type of test to make on this file */ - int *pResOut /* OUT: Result */ -){ - DWORD attr; - int rc = 0; - DWORD lastErrno = 0; - void *zConverted; - UNUSED_PARAMETER(pVfs); - - SimulateIOError( return SQLITE_IOERR_ACCESS; ); - OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n", - zFilename, flags, pResOut)); - - zConverted = winConvertFromUtf8Filename(zFilename); - if( zConverted==0 ){ - OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename)); - return SQLITE_IOERR_NOMEM_BKPT; - } - if( osIsNT() ){ - int cnt = 0; - WIN32_FILE_ATTRIBUTE_DATA sAttrData; - memset(&sAttrData, 0, sizeof(sAttrData)); - while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted, - GetFileExInfoStandard, - &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){} - if( rc ){ - /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file - ** as if it does not exist. - */ - if( flags==SQLITE_ACCESS_EXISTS - && sAttrData.nFileSizeHigh==0 - && sAttrData.nFileSizeLow==0 ){ - attr = INVALID_FILE_ATTRIBUTES; - }else{ - attr = sAttrData.dwFileAttributes; - } - }else{ - winLogIoerr(cnt, __LINE__); - if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){ - sqlite3_free(zConverted); - return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", - zFilename); - }else{ - attr = INVALID_FILE_ATTRIBUTES; - } - } - } -#ifdef SQLITE_WIN32_HAS_ANSI - else{ - attr = osGetFileAttributesA((char*)zConverted); - } -#endif - sqlite3_free(zConverted); - switch( flags ){ - case SQLITE_ACCESS_READ: - case SQLITE_ACCESS_EXISTS: - rc = attr!=INVALID_FILE_ATTRIBUTES; - break; - case SQLITE_ACCESS_READWRITE: - rc = attr!=INVALID_FILE_ATTRIBUTES && - (attr & FILE_ATTRIBUTE_READONLY)==0; - break; - default: - assert(!"Invalid flags argument"); - } - *pResOut = rc; - OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n", - zFilename, pResOut, *pResOut)); - return SQLITE_OK; -} - -/* -** Returns non-zero if the specified path name starts with a drive letter -** followed by a colon character. -*/ -static BOOL winIsDriveLetterAndColon( - const char *zPathname -){ - return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' ); -} - -/* -** Returns non-zero if the specified path name should be used verbatim. If -** non-zero is returned from this function, the calling function must simply -** use the provided path name verbatim -OR- resolve it into a full path name -** using the GetFullPathName Win32 API function (if available). -*/ -static BOOL winIsVerbatimPathname( - const char *zPathname -){ - /* - ** If the path name starts with a forward slash or a backslash, it is either - ** a legal UNC name, a volume relative path, or an absolute path name in the - ** "Unix" format on Windows. There is no easy way to differentiate between - ** the final two cases; therefore, we return the safer return value of TRUE - ** so that callers of this function will simply use it verbatim. - */ - if ( winIsDirSep(zPathname[0]) ){ - return TRUE; - } - - /* - ** If the path name starts with a letter and a colon it is either a volume - ** relative path or an absolute path. Callers of this function must not - ** attempt to treat it as a relative path name (i.e. they should simply use - ** it verbatim). - */ - if ( winIsDriveLetterAndColon(zPathname) ){ - return TRUE; - } - - /* - ** If we get to this point, the path name should almost certainly be a purely - ** relative one (i.e. not a UNC name, not absolute, and not volume relative). - */ - return FALSE; -} - -/* -** Turn a relative pathname into a full pathname. Write the full -** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname -** bytes in size. -*/ -static int winFullPathname( - sqlite3_vfs *pVfs, /* Pointer to vfs object */ - const char *zRelative, /* Possibly relative input path */ - int nFull, /* Size of output buffer in bytes */ - char *zFull /* Output buffer */ -){ -#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__) - DWORD nByte; - void *zConverted; - char *zOut; -#endif - - /* If this path name begins with "/X:", where "X" is any alphabetic - ** character, discard the initial "/" from the pathname. - */ - if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){ - zRelative++; - } - -#if defined(__CYGWIN__) - SimulateIOError( return SQLITE_ERROR ); - UNUSED_PARAMETER(nFull); - assert( nFull>=pVfs->mxPathname ); - if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ - /* - ** NOTE: We are dealing with a relative path name and the data - ** directory has been set. Therefore, use it as the basis - ** for converting the relative path name to an absolute - ** one by prepending the data directory and a slash. - */ - char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 ); - if( !zOut ){ - return SQLITE_IOERR_NOMEM_BKPT; - } - if( cygwin_conv_path( - (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) | - CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){ - sqlite3_free(zOut); - return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno, - "winFullPathname1", zRelative); - }else{ - char *zUtf8 = winConvertToUtf8Filename(zOut); - if( !zUtf8 ){ - sqlite3_free(zOut); - return SQLITE_IOERR_NOMEM_BKPT; - } - sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s", - sqlite3_data_directory, winGetDirSep(), zUtf8); - sqlite3_free(zUtf8); - sqlite3_free(zOut); - } - }else{ - char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 ); - if( !zOut ){ - return SQLITE_IOERR_NOMEM_BKPT; - } - if( cygwin_conv_path( - (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A), - zRelative, zOut, pVfs->mxPathname+1)<0 ){ - sqlite3_free(zOut); - return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno, - "winFullPathname2", zRelative); - }else{ - char *zUtf8 = winConvertToUtf8Filename(zOut); - if( !zUtf8 ){ - sqlite3_free(zOut); - return SQLITE_IOERR_NOMEM_BKPT; - } - sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8); - sqlite3_free(zUtf8); - sqlite3_free(zOut); - } - } - return SQLITE_OK; -#endif - -#if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__) - SimulateIOError( return SQLITE_ERROR ); - /* WinCE has no concept of a relative pathname, or so I am told. */ - /* WinRT has no way to convert a relative path to an absolute one. */ - if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ - /* - ** NOTE: We are dealing with a relative path name and the data - ** directory has been set. Therefore, use it as the basis - ** for converting the relative path name to an absolute - ** one by prepending the data directory and a backslash. - */ - sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s", - sqlite3_data_directory, winGetDirSep(), zRelative); - }else{ - sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative); - } - return SQLITE_OK; -#endif - -#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__) - /* It's odd to simulate an io-error here, but really this is just - ** using the io-error infrastructure to test that SQLite handles this - ** function failing. This function could fail if, for example, the - ** current working directory has been unlinked. - */ - SimulateIOError( return SQLITE_ERROR ); - if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){ - /* - ** NOTE: We are dealing with a relative path name and the data - ** directory has been set. Therefore, use it as the basis - ** for converting the relative path name to an absolute - ** one by prepending the data directory and a backslash. - */ - sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s", - sqlite3_data_directory, winGetDirSep(), zRelative); - return SQLITE_OK; - } - zConverted = winConvertFromUtf8Filename(zRelative); - if( zConverted==0 ){ - return SQLITE_IOERR_NOMEM_BKPT; - } - if( osIsNT() ){ - LPWSTR zTemp; - nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0); - if( nByte==0 ){ - sqlite3_free(zConverted); - return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), - "winFullPathname1", zRelative); - } - nByte += 3; - zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) ); - if( zTemp==0 ){ - sqlite3_free(zConverted); - return SQLITE_IOERR_NOMEM_BKPT; - } - nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0); - if( nByte==0 ){ - sqlite3_free(zConverted); - sqlite3_free(zTemp); - return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), - "winFullPathname2", zRelative); - } - sqlite3_free(zConverted); - zOut = winUnicodeToUtf8(zTemp); - sqlite3_free(zTemp); - } -#ifdef SQLITE_WIN32_HAS_ANSI - else{ - char *zTemp; - nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0); - if( nByte==0 ){ - sqlite3_free(zConverted); - return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), - "winFullPathname3", zRelative); - } - nByte += 3; - zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) ); - if( zTemp==0 ){ - sqlite3_free(zConverted); - return SQLITE_IOERR_NOMEM_BKPT; - } - nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0); - if( nByte==0 ){ - sqlite3_free(zConverted); - sqlite3_free(zTemp); - return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(), - "winFullPathname4", zRelative); - } - sqlite3_free(zConverted); - zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI()); - sqlite3_free(zTemp); - } -#endif - if( zOut ){ - sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut); - sqlite3_free(zOut); - return SQLITE_OK; - }else{ - return SQLITE_IOERR_NOMEM_BKPT; - } -#endif -} - -#ifndef SQLITE_OMIT_LOAD_EXTENSION -/* -** Interfaces for opening a shared library, finding entry points -** within the shared library, and closing the shared library. -*/ -static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){ - HANDLE h; -#if defined(__CYGWIN__) - int nFull = pVfs->mxPathname+1; - char *zFull = sqlite3MallocZero( nFull ); - void *zConverted = 0; - if( zFull==0 ){ - OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0)); - return 0; - } - if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){ - sqlite3_free(zFull); - OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0)); - return 0; - } - zConverted = winConvertFromUtf8Filename(zFull); - sqlite3_free(zFull); -#else - void *zConverted = winConvertFromUtf8Filename(zFilename); - UNUSED_PARAMETER(pVfs); -#endif - if( zConverted==0 ){ - OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0)); - return 0; - } - if( osIsNT() ){ -#if SQLITE_OS_WINRT - h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0); -#else - h = osLoadLibraryW((LPCWSTR)zConverted); -#endif - } -#ifdef SQLITE_WIN32_HAS_ANSI - else{ - h = osLoadLibraryA((char*)zConverted); - } -#endif - OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h)); - sqlite3_free(zConverted); - return (void*)h; -} -static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){ - UNUSED_PARAMETER(pVfs); - winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut); -} -static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){ - FARPROC proc; - UNUSED_PARAMETER(pVfs); - proc = osGetProcAddressA((HANDLE)pH, zSym); - OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n", - (void*)pH, zSym, (void*)proc)); - return (void(*)(void))proc; -} -static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){ - UNUSED_PARAMETER(pVfs); - osFreeLibrary((HANDLE)pHandle); - OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle)); -} -#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */ - #define winDlOpen 0 - #define winDlError 0 - #define winDlSym 0 - #define winDlClose 0 -#endif - -/* State information for the randomness gatherer. */ -typedef struct EntropyGatherer EntropyGatherer; -struct EntropyGatherer { - unsigned char *a; /* Gather entropy into this buffer */ - int na; /* Size of a[] in bytes */ - int i; /* XOR next input into a[i] */ - int nXor; /* Number of XOR operations done */ -}; - -#if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) -/* Mix sz bytes of entropy into p. */ -static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){ - int j, k; - for(j=0, k=p->i; ja[k++] ^= x[j]; - if( k>=p->na ) k = 0; - } - p->i = k; - p->nXor += sz; -} -#endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */ - -/* -** Write up to nBuf bytes of randomness into zBuf. -*/ -static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ -#if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) - UNUSED_PARAMETER(pVfs); - memset(zBuf, 0, nBuf); - return nBuf; -#else - EntropyGatherer e; - UNUSED_PARAMETER(pVfs); - memset(zBuf, 0, nBuf); - e.a = (unsigned char*)zBuf; - e.na = nBuf; - e.nXor = 0; - e.i = 0; - { - SYSTEMTIME x; - osGetSystemTime(&x); - xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME)); - } - { - DWORD pid = osGetCurrentProcessId(); - xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD)); - } -#if SQLITE_OS_WINRT - { - ULONGLONG cnt = osGetTickCount64(); - xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG)); - } -#else - { - DWORD cnt = osGetTickCount(); - xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD)); - } -#endif /* SQLITE_OS_WINRT */ - { - LARGE_INTEGER i; - osQueryPerformanceCounter(&i); - xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER)); - } -#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID - { - UUID id; - memset(&id, 0, sizeof(UUID)); - osUuidCreate(&id); - xorMemory(&e, (unsigned char*)&id, sizeof(UUID)); - memset(&id, 0, sizeof(UUID)); - osUuidCreateSequential(&id); - xorMemory(&e, (unsigned char*)&id, sizeof(UUID)); - } -#endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */ - return e.nXor>nBuf ? nBuf : e.nXor; -#endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */ -} - - -/* -** Sleep for a little while. Return the amount of time slept. -*/ -static int winSleep(sqlite3_vfs *pVfs, int microsec){ - sqlite3_win32_sleep((microsec+999)/1000); - UNUSED_PARAMETER(pVfs); - return ((microsec+999)/1000)*1000; -} - -/* -** The following variable, if set to a non-zero value, is interpreted as -** the number of seconds since 1970 and is used to set the result of -** sqlite3OsCurrentTime() during testing. -*/ -#ifdef SQLITE_TEST -SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */ -#endif - -/* -** Find the current time (in Universal Coordinated Time). Write into *piNow -** the current time and date as a Julian Day number times 86_400_000. In -** other words, write into *piNow the number of milliseconds since the Julian -** epoch of noon in Greenwich on November 24, 4714 B.C according to the -** proleptic Gregorian calendar. -** -** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date -** cannot be found. -*/ -static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){ - /* FILETIME structure is a 64-bit value representing the number of - 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). - */ - FILETIME ft; - static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000; -#ifdef SQLITE_TEST - static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000; -#endif - /* 2^32 - to avoid use of LL and warnings in gcc */ - static const sqlite3_int64 max32BitValue = - (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + - (sqlite3_int64)294967296; - -#if SQLITE_OS_WINCE - SYSTEMTIME time; - osGetSystemTime(&time); - /* if SystemTimeToFileTime() fails, it returns zero. */ - if (!osSystemTimeToFileTime(&time,&ft)){ - return SQLITE_ERROR; - } -#else - osGetSystemTimeAsFileTime( &ft ); -#endif - - *piNow = winFiletimeEpoch + - ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + - (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000; - -#ifdef SQLITE_TEST - if( sqlite3_current_time ){ - *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch; - } -#endif - UNUSED_PARAMETER(pVfs); - return SQLITE_OK; -} - -/* -** Find the current time (in Universal Coordinated Time). Write the -** current time and date as a Julian Day number into *prNow and -** return 0. Return 1 if the time and date cannot be found. -*/ -static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){ - int rc; - sqlite3_int64 i; - rc = winCurrentTimeInt64(pVfs, &i); - if( !rc ){ - *prNow = i/86400000.0; - } - return rc; -} - -/* -** The idea is that this function works like a combination of -** GetLastError() and FormatMessage() on Windows (or errno and -** strerror_r() on Unix). After an error is returned by an OS -** function, SQLite calls this function with zBuf pointing to -** a buffer of nBuf bytes. The OS layer should populate the -** buffer with a nul-terminated UTF-8 encoded error message -** describing the last IO error to have occurred within the calling -** thread. -** -** If the error message is too large for the supplied buffer, -** it should be truncated. The return value of xGetLastError -** is zero if the error message fits in the buffer, or non-zero -** otherwise (if the message was truncated). If non-zero is returned, -** then it is not necessary to include the nul-terminator character -** in the output buffer. -** -** Not supplying an error message will have no adverse effect -** on SQLite. It is fine to have an implementation that never -** returns an error message: -** -** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ -** assert(zBuf[0]=='\0'); -** return 0; -** } -** -** However if an error message is supplied, it will be incorporated -** by sqlite into the error message available to the user using -** sqlite3_errmsg(), possibly making IO errors easier to debug. -*/ -static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){ - DWORD e = osGetLastError(); - UNUSED_PARAMETER(pVfs); - if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf); - return e; -} - -/* -** Initialize and deinitialize the operating system interface. -*/ -SQLITE_API int sqlite3_os_init(void){ - static sqlite3_vfs winVfs = { - 3, /* iVersion */ - sizeof(winFile), /* szOsFile */ - SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */ - 0, /* pNext */ - "win32", /* zName */ - &winAppData, /* pAppData */ - winOpen, /* xOpen */ - winDelete, /* xDelete */ - winAccess, /* xAccess */ - winFullPathname, /* xFullPathname */ - winDlOpen, /* xDlOpen */ - winDlError, /* xDlError */ - winDlSym, /* xDlSym */ - winDlClose, /* xDlClose */ - winRandomness, /* xRandomness */ - winSleep, /* xSleep */ - winCurrentTime, /* xCurrentTime */ - winGetLastError, /* xGetLastError */ - winCurrentTimeInt64, /* xCurrentTimeInt64 */ - winSetSystemCall, /* xSetSystemCall */ - winGetSystemCall, /* xGetSystemCall */ - winNextSystemCall, /* xNextSystemCall */ - }; -#if defined(SQLITE_WIN32_HAS_WIDE) - static sqlite3_vfs winLongPathVfs = { - 3, /* iVersion */ - sizeof(winFile), /* szOsFile */ - SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */ - 0, /* pNext */ - "win32-longpath", /* zName */ - &winAppData, /* pAppData */ - winOpen, /* xOpen */ - winDelete, /* xDelete */ - winAccess, /* xAccess */ - winFullPathname, /* xFullPathname */ - winDlOpen, /* xDlOpen */ - winDlError, /* xDlError */ - winDlSym, /* xDlSym */ - winDlClose, /* xDlClose */ - winRandomness, /* xRandomness */ - winSleep, /* xSleep */ - winCurrentTime, /* xCurrentTime */ - winGetLastError, /* xGetLastError */ - winCurrentTimeInt64, /* xCurrentTimeInt64 */ - winSetSystemCall, /* xSetSystemCall */ - winGetSystemCall, /* xGetSystemCall */ - winNextSystemCall, /* xNextSystemCall */ - }; -#endif - static sqlite3_vfs winNolockVfs = { - 3, /* iVersion */ - sizeof(winFile), /* szOsFile */ - SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */ - 0, /* pNext */ - "win32-none", /* zName */ - &winNolockAppData, /* pAppData */ - winOpen, /* xOpen */ - winDelete, /* xDelete */ - winAccess, /* xAccess */ - winFullPathname, /* xFullPathname */ - winDlOpen, /* xDlOpen */ - winDlError, /* xDlError */ - winDlSym, /* xDlSym */ - winDlClose, /* xDlClose */ - winRandomness, /* xRandomness */ - winSleep, /* xSleep */ - winCurrentTime, /* xCurrentTime */ - winGetLastError, /* xGetLastError */ - winCurrentTimeInt64, /* xCurrentTimeInt64 */ - winSetSystemCall, /* xSetSystemCall */ - winGetSystemCall, /* xGetSystemCall */ - winNextSystemCall, /* xNextSystemCall */ - }; -#if defined(SQLITE_WIN32_HAS_WIDE) - static sqlite3_vfs winLongPathNolockVfs = { - 3, /* iVersion */ - sizeof(winFile), /* szOsFile */ - SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */ - 0, /* pNext */ - "win32-longpath-none", /* zName */ - &winNolockAppData, /* pAppData */ - winOpen, /* xOpen */ - winDelete, /* xDelete */ - winAccess, /* xAccess */ - winFullPathname, /* xFullPathname */ - winDlOpen, /* xDlOpen */ - winDlError, /* xDlError */ - winDlSym, /* xDlSym */ - winDlClose, /* xDlClose */ - winRandomness, /* xRandomness */ - winSleep, /* xSleep */ - winCurrentTime, /* xCurrentTime */ - winGetLastError, /* xGetLastError */ - winCurrentTimeInt64, /* xCurrentTimeInt64 */ - winSetSystemCall, /* xSetSystemCall */ - winGetSystemCall, /* xGetSystemCall */ - winNextSystemCall, /* xNextSystemCall */ - }; -#endif - - /* Double-check that the aSyscall[] array has been constructed - ** correctly. See ticket [bb3a86e890c8e96ab] */ - assert( ArraySize(aSyscall)==80 ); - - /* get memory map allocation granularity */ - memset(&winSysInfo, 0, sizeof(SYSTEM_INFO)); -#if SQLITE_OS_WINRT - osGetNativeSystemInfo(&winSysInfo); -#else - osGetSystemInfo(&winSysInfo); -#endif - assert( winSysInfo.dwAllocationGranularity>0 ); - assert( winSysInfo.dwPageSize>0 ); - - sqlite3_vfs_register(&winVfs, 1); - -#if defined(SQLITE_WIN32_HAS_WIDE) - sqlite3_vfs_register(&winLongPathVfs, 0); -#endif - - sqlite3_vfs_register(&winNolockVfs, 0); - -#if defined(SQLITE_WIN32_HAS_WIDE) - sqlite3_vfs_register(&winLongPathNolockVfs, 0); -#endif - - return SQLITE_OK; -} - -SQLITE_API int sqlite3_os_end(void){ -#if SQLITE_OS_WINRT - if( sleepObj!=NULL ){ - osCloseHandle(sleepObj); - sleepObj = NULL; - } -#endif - return SQLITE_OK; -} - -#endif /* SQLITE_OS_WIN */ - -/************** End of os_win.c **********************************************/ -/************** Begin file bitvec.c ******************************************/ -/* -** 2008 February 16 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -************************************************************************* -** This file implements an object that represents a fixed-length -** bitmap. Bits are numbered starting with 1. -** -** A bitmap is used to record which pages of a database file have been -** journalled during a transaction, or which pages have the "dont-write" -** property. Usually only a few pages are meet either condition. -** So the bitmap is usually sparse and has low cardinality. -** But sometimes (for example when during a DROP of a large table) most -** or all of the pages in a database can get journalled. In those cases, -** the bitmap becomes dense with high cardinality. The algorithm needs -** to handle both cases well. -** -** The size of the bitmap is fixed when the object is created. -** -** All bits are clear when the bitmap is created. Individual bits -** may be set or cleared one at a time. -** -** Test operations are about 100 times more common that set operations. -** Clear operations are exceedingly rare. There are usually between -** 5 and 500 set operations per Bitvec object, though the number of sets can -** sometimes grow into tens of thousands or larger. The size of the -** Bitvec object is the number of pages in the database file at the -** start of a transaction, and is thus usually less than a few thousand, -** but can be as large as 2 billion for a really big database. -*/ -/* #include "sqliteInt.h" */ - -/* Size of the Bitvec structure in bytes. */ -#define BITVEC_SZ 512 - -/* Round the union size down to the nearest pointer boundary, since that's how -** it will be aligned within the Bitvec struct. */ -#define BITVEC_USIZE \ - (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*)) - -/* Type of the array "element" for the bitmap representation. -** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. -** Setting this to the "natural word" size of your CPU may improve -** performance. */ -#define BITVEC_TELEM u8 -/* Size, in bits, of the bitmap element. */ -#define BITVEC_SZELEM 8 -/* Number of elements in a bitmap array. */ -#define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM)) -/* Number of bits in the bitmap array. */ -#define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM) - -/* Number of u32 values in hash table. */ -#define BITVEC_NINT (BITVEC_USIZE/sizeof(u32)) -/* Maximum number of entries in hash table before -** sub-dividing and re-hashing. */ -#define BITVEC_MXHASH (BITVEC_NINT/2) -/* Hashing function for the aHash representation. -** Empirical testing showed that the *37 multiplier -** (an arbitrary prime)in the hash function provided -** no fewer collisions than the no-op *1. */ -#define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT) - -#define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *)) - - -/* -** A bitmap is an instance of the following structure. -** -** This bitmap records the existence of zero or more bits -** with values between 1 and iSize, inclusive. -** -** There are three possible representations of the bitmap. -** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight -** bitmap. The least significant bit is bit 1. -** -** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is -** a hash table that will hold up to BITVEC_MXHASH distinct values. -** -** Otherwise, the value i is redirected into one of BITVEC_NPTR -** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap -** handles up to iDivisor separate values of i. apSub[0] holds -** values between 1 and iDivisor. apSub[1] holds values between -** iDivisor+1 and 2*iDivisor. apSub[N] holds values between -** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized -** to hold deal with values between 1 and iDivisor. -*/ -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 to 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{ - /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then - ** the number of cache pages is adjusted to use approximately abs(N*1024) - ** bytes of memory. */ - return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra)); - } -} - -/*************************************************** General Interfaces ****** -** -** Initialize and shutdown the page cache subsystem. Neither of these -** functions are threadsafe. -*/ -SQLITE_PRIVATE int sqlite3PcacheInitialize(void){ - if( sqlite3GlobalConfig.pcache2.xInit==0 ){ - /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the - ** built-in default page cache is used instead of the application defined - ** page cache. */ - sqlite3PCacheSetDefault(); - } - return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg); -} -SQLITE_PRIVATE void sqlite3PcacheShutdown(void){ - if( sqlite3GlobalConfig.pcache2.xShutdown ){ - /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */ - sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg); - } -} - -/* -** Return the size in bytes of a PCache object. -*/ -SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); } - -/* -** Create a new PCache object. Storage space to hold the object -** has already been allocated and is passed in as the p pointer. -** The caller discovers how much space needs to be allocated by -** calling sqlite3PcacheSize(). -** -** szExtra is some extra space allocated for each page. The first -** 8 bytes of the extra space will be zeroed as the page is allocated, -** but remaining content will be uninitialized. Though it is opaque -** to this module, the extra space really ends up being the MemPage -** structure in the pager. -*/ -SQLITE_PRIVATE int sqlite3PcacheOpen( - int szPage, /* Size of every page */ - int szExtra, /* Extra space associated with each page */ - int bPurgeable, /* True if pages are on backing store */ - int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */ - void *pStress, /* Argument to xStress */ - PCache *p /* Preallocated space for the PCache */ -){ - memset(p, 0, sizeof(PCache)); - p->szPage = 1; - p->szExtra = szExtra; - assert( szExtra>=8 ); /* First 8 bytes will be zeroed */ - p->bPurgeable = bPurgeable; - p->eCreate = 2; - p->xStress = xStress; - p->pStress = pStress; - p->szCache = 100; - p->szSpill = 1; - pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable)); - return sqlite3PcacheSetPageSize(p, szPage); -} - -/* -** Change the page size for PCache object. The caller must ensure that there -** are no outstanding page references when this function is called. -*/ -SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){ - assert( pCache->nRefSum==0 && pCache->pDirty==0 ); - if( pCache->szPage ){ - sqlite3_pcache *pNew; - pNew = sqlite3GlobalConfig.pcache2.xCreate( - szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)), - pCache->bPurgeable - ); - if( pNew==0 ) return SQLITE_NOMEM_BKPT; - sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache)); - if( pCache->pCache ){ - sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache); - } - pCache->pCache = pNew; - pCache->szPage = szPage; - pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage)); - } - return SQLITE_OK; -} - -/* -** Try to obtain a page from the cache. -** -** This routine returns a pointer to an sqlite3_pcache_page object if -** such an object is already in cache, or if a new one is created. -** This routine returns a NULL pointer if the object was not in cache -** and could not be created. -** -** The createFlags should be 0 to check for existing pages and should -** be 3 (not 1, but 3) to try to create a new page. -** -** If the createFlag is 0, then NULL is always returned if the page -** is not already in the cache. If createFlag is 1, then a new page -** is created only if that can be done without spilling dirty pages -** and without exceeding the cache size limit. -** -** The caller needs to invoke sqlite3PcacheFetchFinish() to properly -** initialize the sqlite3_pcache_page object and convert it into a -** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish() -** routines are split this way for performance reasons. When separated -** they can both (usually) operate without having to push values to -** the stack on entry and pop them back off on exit, which saves a -** lot of pushing and popping. -*/ -SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch( - PCache *pCache, /* Obtain the page from this cache */ - Pgno pgno, /* Page number to obtain */ - int createFlag /* If true, create page if it does not exist already */ -){ - int eCreate; - sqlite3_pcache_page *pRes; - - assert( pCache!=0 ); - assert( pCache->pCache!=0 ); - assert( createFlag==3 || createFlag==0 ); - assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) ); - - /* eCreate defines what to do if the page does not exist. - ** 0 Do not allocate a new page. (createFlag==0) - ** 1 Allocate a new page if doing so is inexpensive. - ** (createFlag==1 AND bPurgeable AND pDirty) - ** 2 Allocate a new page even it doing so is difficult. - ** (createFlag==1 AND !(bPurgeable AND pDirty) - */ - eCreate = createFlag & pCache->eCreate; - assert( eCreate==0 || eCreate==1 || eCreate==2 ); - assert( createFlag==0 || pCache->eCreate==eCreate ); - assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) ); - pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate); - pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno, - createFlag?" create":"",pRes)); - return pRes; -} - -/* -** If the sqlite3PcacheFetch() routine is unable to allocate a new -** page because no clean pages are available for reuse and the cache -** size limit has been reached, then this routine can be invoked to -** try harder to allocate a page. This routine might invoke the stress -** callback to spill dirty pages to the journal. It will then try to -** allocate the new page and will only fail to allocate a new page on -** an OOM error. -** -** This routine should be invoked only after sqlite3PcacheFetch() fails. -*/ -SQLITE_PRIVATE int sqlite3PcacheFetchStress( - PCache *pCache, /* Obtain the page from this cache */ - Pgno pgno, /* Page number to obtain */ - sqlite3_pcache_page **ppPage /* Write result here */ -){ - PgHdr *pPg; - if( pCache->eCreate==2 ) return 0; - - if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){ - /* Find a dirty page to write-out and recycle. First try to find a - ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC - ** cleared), but if that is not possible settle for any other - ** unreferenced dirty page. - ** - ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC - ** flag is currently referenced, then the following may leave pSynced - ** set incorrectly (pointing to other than the LRU page with NEED_SYNC - ** cleared). This is Ok, as pSynced is just an optimization. */ - for(pPg=pCache->pSynced; - pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); - pPg=pPg->pDirtyPrev - ); - pCache->pSynced = pPg; - if( !pPg ){ - for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev); - } - if( pPg ){ - int rc; -#ifdef SQLITE_LOG_CACHE_SPILL - sqlite3_log(SQLITE_FULL, - "spill page %d making room for %d - cache used: %d/%d", - pPg->pgno, pgno, - sqlite3GlobalConfig.pcache.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) ); - if( ALWAYS((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; -} - -#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. -*/ -struct PgHdr1 { - sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */ - unsigned int iKey; /* Key value (page number) */ - u8 isBulkLocal; /* This page from bulk local storage */ - u8 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 */ -}; - -/* -** A page is pinned if it is no on the LRU list -*/ -#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() */ - - /* 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; - pCache->pFree = pX; - zBulk += pCache->szAlloc; - }while( --nBulk ); - } - return pCache->pFree!=0; -} - -/* -** Malloc function used within this file to allocate space from the buffer -** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no -** such buffer exists or there is no space left in it, this function falls -** back to sqlite3Malloc(). -** -** Multiple threads can run this routine at the same time. Global variables -** in pcache1 need to be protected via mutex. -*/ -static void *pcache1Alloc(int nByte){ - void *p = 0; - assert( sqlite3_mutex_notheld(pcache1.grp.mutex) ); - if( nByte<=pcache1.szSlot ){ - sqlite3_mutex_enter(pcache1.mutex); - p = (PgHdr1 *)pcache1.pFree; - if( p ){ - pcache1.pFree = pcache1.pFree->pNext; - pcache1.nFreeSlot--; - pcache1.bUnderPressure = pcache1.nFreeSlot=0 ); - sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte); - sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1); - } - sqlite3_mutex_leave(pcache1.mutex); - } - if( p==0 ){ - /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get - ** it from sqlite3Malloc instead. - */ - p = sqlite3Malloc(nByte); -#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS - if( p ){ - int sz = sqlite3MallocSize(p); - sqlite3_mutex_enter(pcache1.mutex); - sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte); - sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz); - sqlite3_mutex_leave(pcache1.mutex); - } -#endif - sqlite3MemdebugSetType(p, MEMTYPE_PCACHE); - } - return p; -} - -/* -** Free an allocated buffer obtained from pcache1Alloc(). -*/ -static void pcache1Free(void *p){ - if( p==0 ) return; - if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){ - PgFreeslot *pSlot; - sqlite3_mutex_enter(pcache1.mutex); - sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1); - pSlot = (PgFreeslot*)p; - pSlot->pNext = pcache1.pFree; - pcache1.pFree = pSlot; - pcache1.nFreeSlot++; - pcache1.bUnderPressure = pcache1.nFreeSlot=pcache1.pStart && ppGroup->mutex) ); - if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){ - p = pCache->pFree; - pCache->pFree = p->pNext; - p->pNext = 0; - }else{ -#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT - /* The group mutex must be released before pcache1Alloc() is called. This - ** is because it might call sqlite3_release_memory(), which assumes that - ** this mutex is not held. */ - assert( pcache1.separateCache==0 ); - assert( pCache->pGroup==&pcache1.grp ); - pcache1LeaveMutex(pCache->pGroup); -#endif - if( benignMalloc ){ sqlite3BeginBenignMalloc(); } -#ifdef SQLITE_PCACHE_SEPARATE_HEADER - pPg = pcache1Alloc(pCache->szPage); - p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra); - if( !pPg || !p ){ - pcache1Free(pPg); - sqlite3_free(p); - pPg = 0; - } -#else - pPg = pcache1Alloc(pCache->szAlloc); - p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage]; -#endif - if( benignMalloc ){ sqlite3EndBenignMalloc(); } -#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT - pcache1EnterMutex(pCache->pGroup); -#endif - if( pPg==0 ) return 0; - p->page.pBuf = pPg; - p->page.pExtra = &p[1]; - p->isBulkLocal = 0; - p->isAnchor = 0; - } - (*pCache->pnPurgeable)++; - return p; -} - -/* -** Free a page object allocated by pcache1AllocPage(). -*/ -static void pcache1FreePage(PgHdr1 *p){ - PCache1 *pCache; - assert( p!=0 ); - pCache = p->pCache; - assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) ); - if( p->isBulkLocal ){ - p->pNext = pCache->pFree; - pCache->pFree = p; - }else{ - pcache1Free(p->page.pBuf); -#ifdef SQLITE_PCACHE_SEPARATE_HEADER - sqlite3_free(p); -#endif - } - (*pCache->pnPurgeable)--; -} - -/* -** Malloc function used by SQLite to obtain space from the buffer configured -** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer -** exists, this function falls back to sqlite3Malloc(). -*/ -SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){ - 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; - 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; - } - 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); - pcache1EnterMutex(pGroup); - pcache1ResizeHash(pCache); - if( bPurgeable ){ - pCache->nMin = 10; - pGroup->nMinPage += pCache->nMin; - pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage; - pCache->pnPurgeable = &pGroup->nPurgeable; - }else{ - static unsigned int dummyCurrentPage; - pCache->pnPurgeable = &dummyCurrentPage; - } - 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->pLruPrev = 0; - pPage->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->pLruPrev==0 && 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 */ - -/* -** Turn bulk memory into a RowSet object. N bytes of memory -** are available at pSpace. The db pointer is used as a memory context -** for any subsequent allocations that need to occur. -** Return a pointer to the new RowSet object. -** -** It must be the case that N is sufficient to make a Rowset. If not -** an assertion fault occurs. -** -** If N is larger than the minimum, use the surplus as an initial -** allocation of entries available to be filled. -*/ -SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){ - RowSet *p; - assert( N >= ROUND8(sizeof(*p)) ); - p = pSpace; - 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(RowSet *p){ - 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; -} - -/* -** Allocate a new RowSetEntry object that is associated with the -** given RowSet. Return a pointer to the new and completely uninitialized -** objected. -** -** In an OOM situation, the RowSet.db->mallocFailed flag is set and this -** routine returns NULL. -*/ -static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){ - assert( p!=0 ); - if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/ - /* We could allocate a fresh RowSetEntry each time one is needed, but it - ** is more efficient to pull a preallocated entry from the pool */ - struct RowSetChunk *pNew; - pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew)); - if( pNew==0 ){ - return 0; - } - pNew->pNextChunk = p->pChunk; - p->pChunk = pNew; - p->pFresh = pNew->aEntry; - p->nFresh = ROWSET_ENTRY_PER_CHUNK; - } - p->nFresh--; - return p->pFresh++; -} - -/* -** Insert a new value into a RowSet. -** -** The mallocFailed flag of the database connection is set if a -** memory allocation fails. -*/ -SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){ - struct RowSetEntry *pEntry; /* The new entry */ - struct RowSetEntry *pLast; /* The last prior entry */ - - /* This routine is never called after sqlite3RowSetNext() */ - assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 ); - - pEntry = rowSetEntryAlloc(p); - if( pEntry==0 ) return; - pEntry->v = rowid; - pEntry->pRight = 0; - pLast = p->pLast; - if( pLast ){ - if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/ - /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags - ** where possible */ - p->rsFlags &= ~ROWSET_SORTED; - } - pLast->pRight = pEntry; - }else{ - p->pEntry = pEntry; - } - p->pLast = pEntry; -} - -/* -** Merge two lists of RowSetEntry objects. Remove duplicates. -** -** The input lists are connected via pRight pointers and are -** assumed to each already be in sorted order. -*/ -static struct RowSetEntry *rowSetEntryMerge( - struct RowSetEntry *pA, /* First sorted list to be merged */ - struct RowSetEntry *pB /* Second sorted list to be merged */ -){ - struct RowSetEntry head; - struct RowSetEntry *pTail; - - pTail = &head; - assert( pA!=0 && pB!=0 ); - for(;;){ - assert( pA->pRight==0 || pA->v<=pA->pRight->v ); - assert( pB->pRight==0 || pB->v<=pB->pRight->v ); - if( pA->v<=pB->v ){ - if( pA->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 entiries 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); -#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); - -#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 master journal file is used, then all writes to the database file -** are synced prior to the master journal being deleted. -** -** Definition: Two databases (or the same database at two points it time) -** are said to be "logically equivalent" if they give the same answer to -** all queries. Note in particular the 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) - -/* -** A macro used for invoking the codec if there is one -*/ -#ifdef SQLITE_HAS_CODEC -# define CODEC1(P,D,N,X,E) \ - if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; } -# define CODEC2(P,D,N,X,E,O) \ - if( P->xCodec==0 ){ O=(char*)D; }else \ - if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; } -#else -# define CODEC1(P,D,N,X,E) /* NO-OP */ -# define CODEC2(P,D,N,X,E,O) O=(char*)D -#endif - -/* -** The maximum allowed sector size. 64KiB. If the xSectorsize() method -** returns a value larger than this, then MAX_SECTOR_SIZE is used instead. -** This could conceivably cause corruption following a power failure on -** such a system. This is currently an undocumented limit. -*/ -#define MAX_SECTOR_SIZE 0x10000 - - -/* -** 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. -** -** setMaster -** -** When PagerCommitPhaseOne() is called to commit a transaction, it may -** (or may not) specify a master-journal name to be written into the -** journal file before it is synced to disk. -** -** Whether or not a journal file contains a master-journal pointer affects -** the way in which the journal file is finalized after the transaction is -** committed or rolled back when running in "journal_mode=PERSIST" mode. -** If a journal file does not contain a master-journal pointer, it is -** finalized by overwriting the first journal header with zeroes. If -** it does contain a master-journal pointer the journal file is finalized -** by truncating it to zero bytes, just as if the connection were -** running in "journal_mode=truncate" mode. -** -** Journal files that contain master journal pointers cannot be finalized -** simply by overwriting the first journal-header with zeroes, as the -** master journal pointer could interfere with hot-journal rollback of any -** subsequently interrupted transaction that reuses the journal file. -** -** The flag is cleared as soon as the journal file is finalized (either -** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the -** journal file from being successfully finalized, the setMaster flag -** is cleared anyway (and the pager will move to ERROR state). -** -** doNotSpill -** -** 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 setMaster; /* True if a m-j name has been written to 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[3]; /* Total cache hits, misses and writes */ -#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 */ -#ifdef SQLITE_HAS_CODEC - void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */ - void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */ - void (*xCodecFree)(void*); /* Destructor for the codec */ - void *pCodec; /* First argument to xCodec... methods */ -#endif - 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 - -/* -** 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 maximum legal page number is (2^31 - 1). -*/ -#define PAGER_MAX_PGNO 2147483647 - -/* -** The argument to this macro is a file descriptor (type sqlite3_file*). -** Return 0 if it is not open, or non-zero (but not 1) if it is. -** -** This is so that expressions can be written as: -** -** if( isOpen(pPager->jfd) ){ ... -** -** instead of -** -** if( pPager->jfd->pMethods ){ ... -*/ -#define isOpen(pFd) ((pFd)->pMethods!=0) - -/* -** Return true if this pager uses a write-ahead log to read page pgno. -** Return false if the pager reads pgno directly from the database. -*/ -#if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_DIRECT_OVERFLOW_READ) -SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager, Pgno pgno){ - u32 iRead = 0; - int rc; - if( pPager->pWal==0 ) return 0; - rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead); - return rc || iRead; -} -#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->setMaster==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) -*/ -static 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) -#ifdef SQLITE_HAS_CODEC - && pPager->xCodec==0 -#endif - ){ - 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)) - } - 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( 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 master journal file name from the -** end of the file and, if successful, copies it into memory supplied -** by the caller. See comments above writeMasterJournal() for the format -** used to store a master journal file name at the end of a journal file. -** -** zMaster must point to a buffer of at least nMaster bytes allocated by -** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is -** enough space to write the master journal name). If the master journal -** name in the journal is longer than nMaster bytes (including a -** nul-terminator), then this is handled as if no master journal name -** were present in the journal. -** -** If a master journal file name is present at the end of the journal -** file, then it is copied into the buffer pointed to by zMaster. A -** nul-terminator byte is appended to the buffer following the master -** journal file name. -** -** If it is determined that no master journal file name is present -** zMaster[0] is set to 0 and SQLITE_OK returned. -** -** If an error occurs while reading from the journal file, an SQLite -** error code is returned. -*/ -static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){ - int rc; /* Return code */ - u32 len; /* Length in bytes of master 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 */ - zMaster[0] = '\0'; - - if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ)) - || szJ<16 - || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len)) - || len>=nMaster - || 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, zMaster, len, szJ-16-len)) - ){ - return rc; - } - - /* See if the checksum matches the master 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 master journal name into the journal file for pager -** pPager at the current location. The master journal name must be the last -** thing written to a journal file. If the pager is in full-sync mode, the -** journal file descriptor is advanced to the next sector boundary before -** anything is written. The format is: -** -** + 4 bytes: PAGER_MJ_PGNO. -** + N bytes: Master journal filename in utf-8. -** + 4 bytes: N (length of master journal name in bytes, no nul-terminator). -** + 4 bytes: Master journal name checksum. -** + 8 bytes: aJournalMagic[]. -** -** The master journal page checksum is the sum of the bytes in the master -** journal name, where each byte is interpreted as a signed 8-bit integer. -** -** If zMaster is a NULL pointer (occurs for a single database transaction), -** this call is a no-op. -*/ -static int writeMasterJournal(Pager *pPager, const char *zMaster){ - int rc; /* Return code */ - int nMaster; /* Length of string zMaster */ - i64 iHdrOff; /* Offset of header in journal file */ - i64 jrnlSize; /* Size of journal file on disk */ - u32 cksum = 0; /* Checksum of string zMaster */ - - assert( pPager->setMaster==0 ); - assert( !pagerUseWal(pPager) ); - - if( !zMaster - || pPager->journalMode==PAGER_JOURNALMODE_MEMORY - || !isOpen(pPager->jfd) - ){ - return SQLITE_OK; - } - pPager->setMaster = 1; - assert( pPager->journalHdr <= pPager->journalOff ); - - /* Calculate the length in bytes and the checksum of zMaster */ - for(nMaster=0; zMaster[nMaster]; nMaster++){ - cksum += zMaster[nMaster]; - } - - /* If in full-sync mode, advance to the next disk sector before writing - ** the master journal name. This is in case the previous page written to - ** the journal has already been synced. - */ - if( pPager->fullSync ){ - pPager->journalOff = journalHdrOffset(pPager); - } - iHdrOff = pPager->journalOff; - - /* Write the master journal data to the end of the journal file. If - ** an error occurs, return the error code to the caller. - */ - if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager)))) - || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4))) - || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster))) - || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum))) - || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, - iHdrOff+4+nMaster+8))) - ){ - return rc; - } - pPager->journalOff += (nMaster+20); - - /* If the pager is in peristent-journal mode, then the physical - ** journal-file may extend past the end of the master-journal name - ** and 8 bytes of magic data just written to the file. This is - ** dangerous because the code to rollback a hot-journal file - ** will not be able to find the master-journal name to determine - ** whether or not the journal is hot. - ** - ** Easiest thing to do in this scenario is to truncate the journal - ** file to the required size. - */ - if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &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){ - assert( pPager->eState>PAGER_OPEN ); - 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->changeCountDone = 0; - 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->setMaster = 0; -} - -/* -** This function is called whenever an IOERR or FULL error that requires -** the pager to transition into the ERROR state may ahve occurred. -** The first argument is a pointer to the pager structure, the second -** the error-code about to be returned by a pager API function. The -** value returned is a copy of the second argument to this function. -** -** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the -** IOERR sub-codes, the pager enters the ERROR state and the error code -** is stored in Pager.errCode. While the pager remains in the ERROR state, -** all major API calls on the Pager will immediately return Pager.errCode. -** -** The ERROR state indicates that the contents of the pager-cache -** cannot be trusted. This state can be cleared by completely discarding -** the contents of the pager-cache. If a transaction was active when -** the persistent error occurred, then the rollback journal may need -** to be replayed to restore the contents of the database file (as if -** it were a hot-journal). -*/ -static int pager_error(Pager *pPager, int rc){ - int rc2 = rc & 0xff; - 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 hasMaster, 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, hasMaster||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 && isOpen(pPager->fd) ){ - 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->changeCountDone = 0; - } - pPager->eState = PAGER_READER; - pPager->setMaster = 0; - - return (rc==SQLITE_OK?rc2:rc); -} - -/* -** Execute a rollback if a transaction is active and unlock the -** database file. -** -** If the pager has already entered the ERROR state, do not attempt -** the rollback at this time. Instead, pager_unlock() is called. The -** call to pager_unlock() will discard all in-memory pages, unlock -** the database file and move the pager back to OPEN state. If this -** means that there is a hot-journal left in the file-system, the next -** connection to obtain a shared lock on the pager (which may be this one) -** will roll it back. -** -** If the pager has not already entered the ERROR state, but an IO or -** malloc error occurs during a rollback, then this will itself cause -** the pager to enter the ERROR state. Which will be cleared by the -** call to pager_unlock(), as described above. -*/ -static void pagerUnlockAndRollback(Pager *pPager){ - if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){ - 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; -} - -/* -** Report the current page size and number of reserved bytes back -** to the codec. -*/ -#ifdef SQLITE_HAS_CODEC -static void pagerReportSize(Pager *pPager){ - if( pPager->xCodecSizeChng ){ - pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize, - (int)pPager->nReserve); - } -} -#else -# define pagerReportSize(X) /* No-op if we do not support a codec */ -#endif - -#ifdef SQLITE_HAS_CODEC -/* -** Make sure the number of reserved bits is the same in the destination -** pager as it is in the source. This comes up when a VACUUM changes the -** number of reserved bits to the "optimal" amount. -*/ -SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){ - if( pDest->nReserve!=pSrc->nReserve ){ - pDest->nReserve = pSrc->nReserve; - pagerReportSize(pDest); - } -} -#endif - -/* -** Read a single page from either the journal file (if isMainJrnl==1) or -** from the sub-journal (if isMainJrnl==0) and playback that page. -** The page begins at offset *pOffset into the file. The *pOffset -** value is increased to the start of the next page in the journal. -** -** The main rollback journal uses checksums - the statement journal does -** not. -** -** If the page number of the page record read from the (sub-)journal file -** is greater than the current value of Pager.dbSize, then playback is -** skipped and SQLITE_OK is returned. -** -** If pDone is not NULL, then it is a record of pages that have already -** been played back. If the page at *pOffset has already been played back -** (if the corresponding pDone bit is set) then skip the playback. -** Make sure the pDone bit corresponding to the *pOffset page is set -** prior to returning. -** -** If the page record is successfully read from the (sub-)journal file -** and played back, then SQLITE_OK is returned. If an IO error occurs -** while reading the record from the (sub-)journal file or while writing -** to the database file, then the IO error code is returned. If data -** is successfully read from the (sub-)journal file but appears to be -** corrupted, SQLITE_DONE is returned. Data is considered corrupted in -** two circumstances: -** -** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or -** * If the record is being rolled back from the main journal file -** and the checksum field does not match the record content. -** -** Neither of these two scenarios are possible during a savepoint rollback. -** -** If this is a savepoint rollback, then memory may have to be dynamically -** allocated by this function. If this is the case and an allocation fails, -** SQLITE_NOMEM is returned. -*/ -static int pager_playback_one_page( - Pager *pPager, /* The pager being played back */ - 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 */ -#ifdef SQLITE_HAS_CODEC - /* The jrnlEnc flag is true if Journal pages should be passed through - ** the codec. It is false for pure in-memory journals. */ - const int jrnlEnc = (isMainJrnl || pPager->subjInMemory==0); -#endif - - 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]; - pagerReportSize(pPager); - } - - /* If the pager is in CACHEMOD state, then there must be a copy of this - ** page in the pager cache. In this case just update the pager cache, - ** not the database file. The page is left marked dirty in this case. - ** - ** An exception to the above rule: If the database is in no-sync mode - ** and a page is moved during an incremental vacuum then the page may - ** not be in the pager cache. Later: if a malloc() or IO error occurs - ** during a Movepage() call, then the page may not be in the cache - ** either. So the condition described in the above paragraph is not - ** assert()able. - ** - ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the - ** pager cache if it exists and the main file. The page is then marked - ** not dirty. Since this code is only executed in PAGER_OPEN state for - ** a hot-journal rollback, it is guaranteed that the page-cache is empty - ** if the pager is in OPEN state. - ** - ** Ticket #1171: The statement journal might contain page content that is - ** different from the page content at the start of the transaction. - ** This occurs when a page is changed prior to the start of a statement - ** then changed again within the statement. When rolling back such a - ** statement we must not write to the original database unless we know - ** for certain that original page contents are synced into the main rollback - ** journal. Otherwise, a power loss might leave modified data in the - ** database file without an entry in the rollback journal that can - ** restore the database to its original form. Two conditions must be - ** met before writing to the database files. (1) the database must be - ** locked. (2) we know that the original page content is fully synced - ** in the main journal either because the page is not in cache or else - ** the page is marked as needSync==0. - ** - ** 2008-04-14: When attempting to vacuum a corrupt database file, it - ** is possible to fail a statement on a database that does not yet exist. - ** Do not attempt to write if database file has never been opened. - */ - if( pagerUseWal(pPager) ){ - pPg = 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. */ -#ifdef SQLITE_HAS_CODEC - if( !jrnlEnc ){ - CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData); - rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst); - CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT); - }else -#endif - rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst); - - if( pgno>pPager->dbFileSize ){ - pPager->dbFileSize = pgno; - } - if( pPager->pBackup ){ -#ifdef SQLITE_HAS_CODEC - if( jrnlEnc ){ - CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT); - sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData); - CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT,aData); - }else -#endif - 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)); - } - - /* Decode the page just read from disk */ -#if SQLITE_HAS_CODEC - if( jrnlEnc ){ CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT); } -#endif - sqlite3PcacheRelease(pPg); - } - return rc; -} - -/* -** Parameter zMaster is the name of a master journal file. A single journal -** file that referred to the master journal file has just been rolled back. -** This routine checks if it is possible to delete the master journal file, -** and does so if it is. -** -** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not -** available for use within this function. -** -** When a master journal file is created, it is populated with the names -** of all of its child journals, one after another, formatted as utf-8 -** encoded text. The end of each child journal file is marked with a -** nul-terminator byte (0x00). i.e. the entire contents of a master journal -** file for a transaction involving two databases might be: -** -** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00" -** -** A master journal file may only be deleted once all of its child -** journals have been rolled back. -** -** This function reads the contents of the master-journal file into -** memory and loops through each of the child journal names. For -** each child journal, it checks if: -** -** * if the child journal exists, and if so -** * if the child journal contains a reference to master journal -** file zMaster -** -** If a child journal can be found that matches both of the criteria -** above, this function returns without doing anything. Otherwise, if -** no such child journal can be found, file zMaster is deleted from -** the file-system using sqlite3OsDelete(). -** -** If an IO error within this function, an error code is returned. This -** function allocates memory by calling sqlite3Malloc(). If an allocation -** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors -** occur, SQLITE_OK is returned. -** -** TODO: This function allocates a single block of memory to load -** the entire contents of the master journal file. This could be -** a couple of kilobytes or so - potentially larger than the page -** size. -*/ -static int pager_delmaster(Pager *pPager, const char *zMaster){ - sqlite3_vfs *pVfs = pPager->pVfs; - int rc; /* Return code */ - sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */ - sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */ - char *zMasterJournal = 0; /* Contents of master journal file */ - i64 nMasterJournal; /* Size of master journal file */ - char *zJournal; /* Pointer to one journal within MJ file */ - char *zMasterPtr; /* Space to hold MJ filename from a journal file */ - int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */ - - /* Allocate space for both the pJournal and pMaster file descriptors. - ** If successful, open the master journal file for reading. - */ - pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2); - pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile); - if( !pMaster ){ - rc = SQLITE_NOMEM_BKPT; - }else{ - const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL); - rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0); - } - if( rc!=SQLITE_OK ) goto delmaster_out; - - /* Load the entire master journal file into space obtained from - ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain - ** sufficient space (in zMasterPtr) to hold the names of master - ** journal files extracted from regular rollback-journals. - */ - rc = sqlite3OsFileSize(pMaster, &nMasterJournal); - if( rc!=SQLITE_OK ) goto delmaster_out; - nMasterPtr = pVfs->mxPathname+1; - zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1); - if( !zMasterJournal ){ - rc = SQLITE_NOMEM_BKPT; - goto delmaster_out; - } - zMasterPtr = &zMasterJournal[nMasterJournal+1]; - rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0); - if( rc!=SQLITE_OK ) goto delmaster_out; - zMasterJournal[nMasterJournal] = 0; - - zJournal = zMasterJournal; - while( (zJournal-zMasterJournal)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 -** master journal pointers within created journal files. -** -** For temporary files the effective sector size is always 512 bytes. -** -** Otherwise, for non-temporary files, the effective sector size is -** the value returned by the xSectorSize() method rounded up to 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 *zMaster = 0; /* Name of master 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 master journal name from the journal, if it is present. - ** If a master journal file name is specified, but the file is not - ** present on disk, then the journal is not hot and does not need to be - ** played back. - ** - ** TODO: Technically the following is an error because it assumes that - ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that - ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c, - ** mxPathname is 512, which is the same as the minimum allowable value - ** for pageSize. - */ - zMaster = pPager->pTmpSpace; - rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1); - if( rc==SQLITE_OK && zMaster[0] ){ - rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res); - } - zMaster = 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 - if( pPager->fd->pMethods ){ - 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 ){ - zMaster = pPager->pTmpSpace; - rc = readMasterJournal(pPager->jfd, zMaster, 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, zMaster[0]!='\0', 0); - testcase( rc!=SQLITE_OK ); - } - if( rc==SQLITE_OK && zMaster[0] && res ){ - /* If there was a master journal and this routine will return success, - ** see if it is possible to delete the master journal. - */ - rc = pager_delmaster(pPager, zMaster); - 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)); - } - } - CODEC1(pPager, pPg->pData, pPg->pgno, 3, rc = SQLITE_NOMEM_BKPT); - - 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 master journal file. The case pSavepoint==NULL occurs when -** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction -** savepoint. -** -** When pSavepoint is not NULL (meaning a non-transaction savepoint is -** being rolled back), then the rollback consists of up to three stages, -** performed in the order specified: -** -** * Pages are played back from the main journal starting at byte -** offset PagerSavepoint.iOffset and continuing to -** PagerSavepoint.iHdrOffset, or to the end of the main journal -** file if PagerSavepoint.iHdrOffset is zero. -** -** * If PagerSavepoint.iHdrOffset is not zero, then pages are played -** back starting from the journal header immediately following -** PagerSavepoint.iHdrOffset to the end of the main journal file. -** -** * Pages are then played back from the sub-journal file, starting -** with the PagerSavepoint.iSubRec and continuing to the end of -** the journal file. -** -** Throughout the rollback process, each time a page is rolled back, the -** corresponding bit is set in a bitvec structure (variable pDone in the -** implementation below). This is used to ensure that a page is only -** rolled back the first time it is encountered in either journal. -** -** If pSavepoint is NULL, then pages are only played back from the main -** journal file. There is no need for a bitvec in this case. -** -** In either case, before playback commences the Pager.dbSize variable -** is reset to the value that it held at the start of the savepoint -** (or transaction). No page with a page-number greater than this value -** is played back. If one is encountered it is simply skipped. -*/ -static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){ - i64 szJ; /* Effective size of the main journal */ - i64 iHdrOff; /* End of first segment of main-journal records */ - int rc = SQLITE_OK; /* Return code */ - Bitvec *pDone = 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 */ -){ - pPager->xBusyHandler = xBusyHandler; - pPager->pBusyHandlerArg = pBusyHandlerArg; - - if( isOpen(pPager->fd) ){ - void **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 ){ - pNew = (char *)sqlite3PageMalloc(pageSize); - if( !pNew ) rc = SQLITE_NOMEM_BKPT; - } - - 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; - pagerReportSize(pPager); - 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 int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){ - if( mxPage>0 ){ - pPager->mxPgno = mxPage; - } - assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */ - assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */ - return pPager->mxPgno; -} - -/* -** The following set of routines are used to disable the simulated -** I/O error mechanism. These routines are used to avoid simulated -** errors in places where we do not care about errors. -** -** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops -** and generate no code. -*/ -#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); - } -} - - -/* -** 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 - assert( db || pPager->pWal==0 ); - sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize, - (db && (db->flags & SQLITE_NoCkptOnClose) ? 0 : pTmp) - ); - 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); - -#ifdef SQLITE_HAS_CODEC - if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec); -#endif - - 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); - - /* Encode the database */ - CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, 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; - -#if SQLITE_HAS_CODEC - if( !pPager->subjInMemory ){ - CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2); - }else -#endif - 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; - } - - 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 */ - 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 nUri = 0; /* Number of bytes of URI args at *zUri */ - - /* Figure out how much space is required for each journal file-handle - ** (there are two of them, the main journal and the sub-journal). */ - 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); - nPathname = sqlite3Strlen30(zPathname); - z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1]; - while( *z ){ - z += sqlite3Strlen30(z)+1; - z += sqlite3Strlen30(z)+1; - } - nUri = (int)(&z[1] - zUri); - assert( nUri>=0 ); - 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) - ** Database file name (nPathname+1 bytes) - ** Journal file name (nPathname+8+1 bytes) - */ - pPtr = (u8 *)sqlite3MallocZero( - ROUND8(sizeof(*pPager)) + /* Pager structure */ - ROUND8(pcacheSize) + /* PCache object */ - ROUND8(pVfs->szOsFile) + /* The main db file */ - journalFileSize * 2 + /* The two journal files */ - nPathname + 1 + nUri + /* zFilename */ - nPathname + 8 + 2 /* zJournal */ -#ifndef SQLITE_OMIT_WAL - + nPathname + 4 + 2 /* zWal */ -#endif - ); - assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) ); - if( !pPtr ){ - sqlite3DbFree(0, zPathname); - return SQLITE_NOMEM_BKPT; - } - pPager = (Pager*)(pPtr); - pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager))); - pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize)); - pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile)); - pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize); - pPager->zFilename = (char*)(pPtr += journalFileSize); - assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) ); - - /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */ - if( zPathname ){ - assert( nPathname>0 ); - pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri); - memcpy(pPager->zFilename, zPathname, nPathname); - if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri); - memcpy(pPager->zJournal, zPathname, nPathname); - memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2); - sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal); -#ifndef SQLITE_OMIT_WAL - pPager->zWal = &pPager->zJournal[nPathname+8+1]; - memcpy(pPager->zWal, zPathname, nPathname); - memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1); - sqlite3FileSuffix3(pPager->zFilename, pPager->zWal); -#endif - 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 ); - readOnly = (fout&SQLITE_OPEN_READONLY); - - /* 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(zFilename, "nolock", 0); - if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0 - || sqlite3_uri_boolean(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 ){ - 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; -} - - -/* Verify that the database file has not be deleted or renamed out from -** under the pager. Return SQLITE_OK if the database is still were 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; -} - - -/* -** This function is called after transitioning from PAGER_UNLOCK to -** PAGER_SHARED state. It tests if there is a hot journal present in -** the file-system for the given pager. A hot journal is one that -** needs to be played back. According to this function, a hot-journal -** file exists if the following criteria are met: -** -** * The journal file exists in the file system, and -** * No process holds a RESERVED or greater lock on the database file, and -** * The database file itself is greater than 0 bytes in size, and -** * The first byte of the journal file exists and is not 0x00. -** -** If the current size of the database file is 0 but a journal file -** exists, that is probably an old journal left over from a prior -** database with the same name. In this case the journal file is -** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK -** is returned. -** -** This routine does not check if there is a master journal filename -** at the end of the file. If there is, and that master journal file -** does not exist, then the journal file is not really hot. In this -** case this routine will return a false-positive. The pager_playback() -** routine will discover that the journal file is not really hot and -** will not roll it back. -** -** If a hot-journal file is found to exist, *pExists is set to 1 and -** SQLITE_OK returned. If no hot-journal file is present, *pExists is -** set to 0 and SQLITE_OK returned. If an IO error occurs while trying -** to determine whether or not a hot-journal file exists, the IO error -** code is returned and the value of *pExists is undefined. -*/ -static int hasHotJournal(Pager *pPager, 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_MAX_PGNO && 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: - ** - ** (1) The maximum page number is 2^31 - ** (2) Never try to fetch the locking page - */ - if( pgno>PAGER_MAX_PGNO || 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) ); -#ifdef SQLITE_HAS_CODEC - assert( pPager->xCodec==0 ); -#endif - - /* 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->setMaster = 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 ); - CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2); - 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 ); - CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf); - 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 *zMaster){ - int rc = SQLITE_OK; - - if( isOpen(pPager->fd) ){ - void *pArg = (void*)zMaster; - 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. zMaster points to the name -** of a master journal file that should be written into the individual -** journal file. zMaster may be NULL, which is interpreted as no master -** journal (a single database transaction). -** -** This routine ensures that: -** -** * The database file change-counter is updated, -** * the journal is synced (unless the atomic-write optimization is used), -** * all dirty pages are written to the database file, -** * the database file is truncated (if required), and -** * the database file synced. -** -** The only thing that remains to commit the transaction is to finalize -** (delete, truncate or zero the first part of) the journal file (or -** delete the master journal file if specified). -** -** Note that if zMaster==NULL, this does not overwrite a previous value -** passed to an sqlite3PagerCommitPhaseOne() call. -** -** If the final parameter - noSync - is true, then the database file itself -** is not synced. The caller must call sqlite3PagerSync() directly to -** sync the database file before calling CommitPhaseTwo() to delete the -** journal file in this case. -*/ -SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne( - Pager *pPager, /* Pager object */ - const char *zMaster, /* If not NULL, the master 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 zMaster=%s nSize=%d\n", - pPager->zFilename, zMaster, 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{ - if( pagerUseWal(pPager) ){ - PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache); - PgHdr *pPageOne = 0; - 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. - */ - sqlite3_file *fd = pPager->fd; -#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE - const int bBatch = zMaster==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( !zMaster && 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 -#ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE - if( zMaster ){ - rc = sqlite3JournalCreate(pPager->jfd); - if( rc!=SQLITE_OK ) goto commit_phase_one_exit; - } -#endif - rc = pager_incr_changecounter(pPager, 0); -#endif - if( rc!=SQLITE_OK ) goto commit_phase_one_exit; - - /* Write the master journal name into the journal file. If a master - ** journal file name has already been written to the journal file, - ** or if zMaster is NULL (no master journal), then this call is a no-op. - */ - rc = writeMasterJournal(pPager, zMaster); - if( rc!=SQLITE_OK ) goto commit_phase_one_exit; - - /* Sync the journal file and write all dirty pages to the database. - ** If the atomic-update optimization is being used, this sync will not - ** create the journal file or perform any real IO. - ** - ** Because the change-counter page was just modified, unless the - ** atomic-update optimization is used it is almost certain that the - ** journal requires a sync here. However, in locking_mode=exclusive - ** on a system under memory pressure it is just possible that this is - ** not the case. In this case it is likely enough that the redundant - ** xSync() call will be changed to a no-op by the OS anyhow. - */ - rc = syncJournal(pPager, 0); - if( rc!=SQLITE_OK ) goto commit_phase_one_exit; - - if( bBatch ){ - /* The pager is now in DBMOD state. But regardless of what happens - ** next, attempting to play the journal back into the database would - ** be unsafe. Close it now to make sure that does not happen. */ - sqlite3OsClose(pPager->jfd); - rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_BEGIN_ATOMIC_WRITE, 0); - if( rc!=SQLITE_OK ) goto commit_phase_one_exit; - } - rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache)); - if( bBatch ){ - if( rc==SQLITE_OK ){ - rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_COMMIT_ATOMIC_WRITE, 0); - }else{ - sqlite3OsFileControl(fd, SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE, 0); - } - } - - 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, zMaster); - } - 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; - - 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))); - pPager->iDataVersion++; - rc = pager_end_transaction(pPager, pPager->setMaster, 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->setMaster, 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 either SQLITE_DBSTATUS_CACHE_HIT or -** SQLITE_DBSTATUS_CACHE_MISS. 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 - ); - - 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 ); - - *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT]; - if( reset ){ - pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 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. -*/ -SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){ - return (nullIfMemDb && pPager->memDb) ? "" : 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; -} - -#ifdef SQLITE_HAS_CODEC -/* -** Set or retrieve the codec for this pager -*/ -SQLITE_PRIVATE void sqlite3PagerSetCodec( - Pager *pPager, - void *(*xCodec)(void*,void*,Pgno,int), - void (*xCodecSizeChng)(void*,int,int), - void (*xCodecFree)(void*), - void *pCodec -){ - if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec); - pPager->xCodec = pPager->memDb ? 0 : xCodec; - pPager->xCodecSizeChng = xCodecSizeChng; - pPager->xCodecFree = xCodecFree; - pPager->pCodec = pCodec; - setGetterMethod(pPager); - pagerReportSize(pPager); -} -SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){ - return pPager->pCodec; -} - -/* -** This function is called by the wal module when writing page content -** into the log file. -** -** This function returns a pointer to a buffer containing the encrypted -** page content. If a malloc fails, this function may return NULL. -*/ -SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){ - void *aData = 0; - CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData); - return aData; -} - -/* -** Return the current pager state -*/ -SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){ - return pPager->eState; -} -#endif /* SQLITE_HAS_CODEC */ - -#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 ); - if( pPgOld ){ - 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 */ - -#ifdef SQLITE_DEBUG - /* The print_pager_state() routine is intended to be used by the debugger - ** only. We invoke it once here to suppress a compiler warning. */ - print_pager_state(pPager); -#endif - - - /* The eMode parameter is always valid */ - 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_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; -} -#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. -** -** 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 - -/* -** Indices of 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. -*/ -#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 24 */ -#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 */ - 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 -}; - -/* -** 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 { - int 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 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 int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){ - int rc = SQLITE_OK; - - /* Enlarge the pWal->apWiData[] array if required */ - if( pWal->nWiData<=iPage ){ - int nByte = sizeof(u32*)*(iPage+1); - volatile u32 **apNew; - apNew = (volatile u32 **)sqlite3_realloc64((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 */ - if( 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] - ); - if( rc==SQLITE_READONLY ){ - pWal->readOnly |= WAL_SHM_RDONLY; - rc = SQLITE_OK; - } - } - } - - *ppPage = pWal->apWiData[iPage]; - assert( iPage==0 || *ppPage || rc!=SQLITE_OK ); - return rc; -} - -/* -** 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 ); - - if( nativeCksum ){ - do { - s1 += *aData++ + s2; - s2 += *aData++ + s1; - }while( aDataexclusiveMode!=WAL_HEAPMEMORY_MODE ){ - sqlite3OsShmBarrier(pWal->pDbFd); - } -} - -/* -** Write the header information in pWal->hdr into the wal-index. -** -** The checksum on pWal->hdr is updated before it is written. -*/ -static 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); - 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!=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!=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); -} - -/* -** 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 *paHash to point to the start of the hash table -** in the wal-index file. Set *piZero 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 -** (*piZero+N) in the log. -** -** Finally, set *paPgno so that *paPgno[1] is the page number of the -** first frame indexed by the hash table, frame (*piZero+1). -*/ -static int walHashGet( - Wal *pWal, /* WAL handle */ - int iHash, /* Find the iHash'th table */ - volatile ht_slot **paHash, /* OUT: Pointer to hash index */ - volatile u32 **paPgno, /* OUT: Pointer to page number array */ - u32 *piZero /* OUT: Frame associated with *paPgno[0] */ -){ - int rc; /* Return code */ - volatile u32 *aPgno; - - rc = walIndexPage(pWal, iHash, &aPgno); - assert( rc==SQLITE_OK || iHash>0 ); - - if( rc==SQLITE_OK ){ - u32 iZero; - volatile ht_slot *aHash; - - aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE]; - if( iHash==0 ){ - aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)]; - iZero = 0; - }else{ - iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE; - } - - *paPgno = &aPgno[-1]; - *paHash = aHash; - *piZero = iZero; - } - 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)) - ); - 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){ - volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */ - volatile u32 *aPgno = 0; /* Page number array for hash table */ - u32 iZero = 0; /* frame == (aHash[x]+iZero) */ - int iLimit = 0; /* Zero values greater than this */ - int nByte; /* Number of bytes to zero in aPgno[] */ - int i; /* Used to iterate through aHash[] */ - - 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. - */ - assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) ); - assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] ); - walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero); - - /* Zero all hash-table entries that correspond to frame numbers greater - ** than pWal->hdr.mxFrame. - */ - iLimit = pWal->hdr.mxFrame - iZero; - assert( iLimit>0 ); - for(i=0; iiLimit ){ - 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 *)aHash - (char *)&aPgno[iLimit+1]); - memset((void *)&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(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){ - if( aHash[iKey]==j ) break; - } - assert( 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 */ - u32 iZero = 0; /* One less than frame number of aPgno[1] */ - volatile u32 *aPgno = 0; /* Page number array */ - volatile ht_slot *aHash = 0; /* Hash table */ - - rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero); - - /* 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 - 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 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]); - memset((void*)&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( aPgno[idx] ){ - walCleanupHash(pWal); - assert( !aPgno[idx] ); - } - - /* Write the aPgno[] array entry and the hash-table slot. */ - nCollide = idx; - for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){ - if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT; - } - aPgno[idx] = iPage; - 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; - nLock = SQLITE_SHM_NLOCK - iLock; - rc = walLockExclusive(pWal, iLock, nLock); - 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 */ - 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 iFrame; /* Index of last frame read */ - i64 iOffset; /* Next offset to read from log file */ - 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 */ - - /* 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); - if( !aFrame ){ - rc = SQLITE_NOMEM_BKPT; - goto recovery_error; - } - aData = &aFrame[WAL_FRAME_HDRSIZE]; - - /* Read all frames from the log file. */ - iFrame = 0; - for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){ - u32 pgno; /* Database page number for frame */ - u32 nTruncate; /* dbsize field from frame header */ - - /* Read and decode the next log frame. */ - iFrame++; - 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( 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]; - } - } - - sqlite3_free(aFrame); - } - -finished: - if( rc==SQLITE_OK ){ - volatile WalCkptInfo *pInfo; - int i; - pWal->hdr.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 readers, writers and - ** checkpointers. - */ - pInfo = walCkptInfo(pWal); - pInfo->nBackfill = 0; - pInfo->nBackfillAttempted = pWal->hdr.mxFrame; - pInfo->aReadMark[0] = 0; - for(i=1; iaReadMark[i] = READMARK_NOT_USED; - if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame; - - /* 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, nLock); - return rc; -} - -/* -** Close an open wal-index. -*/ -static void walIndexClose(Wal *pWal, int isDelete){ - if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){ - int i; - for(i=0; inWiData; i++){ - sqlite3_free((void *)pWal->apWiData[i]); - pWal->apWiData[i] = 0; - } - }else{ - 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 in ascending order. 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, WalIterator **pp){ - WalIterator *p; /* Return value */ - int nSegment; /* Number of segments to merge */ - u32 iLast; /* Last frame in log */ - int 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=0; rc==SQLITE_OK && iaSegment[p->nSegment])[iZero]; - iZero++; - - for(j=0; jaSegment[i].iZero = iZero; - p->aSegment[i].nEntry = nEntry; - p->aSegment[i].aIndex = aIndex; - p->aSegment[i].aPgno = (u32 *)aPgno; - } - } - sqlite3_free(aTmp); - - if( rc!=SQLITE_OK ){ - walIteratorFree(p); - } - *pp = p; - return rc; -} - -/* -** 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) ); - 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); - 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 ){ - - /* Allocate the iterator */ - rc = walIteratorInit(pWal, &pIter); - if( rc!=SQLITE_OK ){ - return rc; - } - assert( pIter ); - - /* 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 ){ - pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED); - walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1); - }else if( rc==SQLITE_BUSY ){ - mxSafeFrame = y; - xBusy = 0; - }else{ - goto walcheckpoint_out; - } - } - } - - if( pInfo->nBackfillnBackfill; - - 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); - rc = sqlite3OsFileSize(pWal->pDbFd, &nSize); - if( rc==SQLITE_OK && nSizepDbFd, 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( 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; - } - - /* 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 ){ - 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 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. - ** - ** 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. - */ - aHdr = walIndexHdr(pWal); - memcpy(&h1, (void *)&aHdr[0], sizeof(h1)); - 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; -} - -/* -** 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 ){ - return rc; - }; - assert( page0 || 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. - */ - assert( badHdr==0 || pWal->writeLock==0 ); - if( badHdr ){ - if( pWal->readOnly & WAL_SHM_RDONLY ){ - if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){ - walUnlockShared(pWal, WAL_WRITE_LOCK); - rc = SQLITE_READONLY_RECOVERY; - } - }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){ - 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; - } - } - 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; - } - - return rc; -} - -/* -** This is the value that walTryBeginRead returns when it needs to -** be retried. -*/ -#define WAL_RETRY (-1) - -/* -** 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 paget 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 */ - - /* 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 ){ - 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; - } - } - - pInfo = walCkptInfo(pWal); - if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame -#ifdef SQLITE_ENABLE_SNAPSHOT - && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0 - || 0==memcmp(&pWal->hdr, pWal->pSnapshot, sizeof(WalIndexHdr))) -#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; - 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_CANTLOCK; - } - - 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 = pInfo->nBackfill+1; - walShmBarrier(pWal); - if( 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>pInfo->nBackfill; i--){ - volatile ht_slot *dummy; - volatile u32 *aPgno; /* Array of page numbers */ - u32 iZero; /* Frame corresponding to aPgno[0] */ - 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), &dummy, &aPgno, &iZero); - if( rc!=SQLITE_OK ) break; - pgno = aPgno[i-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 is 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; - if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){ - bChanged = 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 ); - - /* 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. - ** - ** TODO: Does the aReadMark[] lock prevent a checkpointer from doing - ** this already? - */ - rc = walLockShared(pWal, WAL_CKPT_LOCK); - - if( rc==SQLITE_OK ){ - /* 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_BUSY_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_BUSY_SNAPSHOT; - } - - /* Release the shared CKPT lock obtained above. */ - walUnlockShared(pWal, WAL_CKPT_LOCK); - } - - - if( rc!=SQLITE_OK ){ - sqlite3WalEndReadTransaction(pWal); - } - } - } -#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 ){ - *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 && iRead==0; iHash--){ - volatile ht_slot *aHash; /* Pointer to hash table */ - volatile u32 *aPgno; /* Pointer to array of page numbers */ - u32 iZero; /* Frame number corresponding to aPgno[0] */ - int iKey; /* Hash slot index */ - int nCollide; /* Number of hash collisions remaining */ - int rc; /* Error code */ - - rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero); - if( rc!=SQLITE_OK ){ - return rc; - } - nCollide = HASHTABLE_NSLOT; - for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){ - u32 iFrame = aHash[iKey] + iZero; - if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){ - assert( iFrame>iRead || CORRUPT_DB ); - iRead = iFrame; - } - if( (nCollide--)==0 ){ - return SQLITE_CORRUPT_BKPT; - } - } - } - -#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->minFrame>0 ); - for(iTest=iLast; iTest>=pWal->minFrame; 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; - - /* 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 */ -#if defined(SQLITE_HAS_CODEC) - if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT; -#else - pData = pPage->pData; -#endif - 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; - } -#if defined(SQLITE_HAS_CODEC) - if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM; -#else - pData = p->pData; -#endif - 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); - } - 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)); - - /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive - ** "checkpoint" lock on the database file. */ - rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1); - if( rc ){ - /* 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. - */ - testcase( rc==SQLITE_BUSY ); - testcase( xBusy!=0 ); - return rc; - } - 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, xBusy, 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 ){ - rc = walIndexReadHdr(pWal, &isChanged); - 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)); - } - - /* Release the locks. */ - sqlite3WalEndWriteTransaction(pWal); - walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1); - pWal->ckptLock = 0; - WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok")); - 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 ){ - pWal->exclusiveMode = 0; - if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){ - pWal->exclusiveMode = 1; - } - rc = pWal->exclusiveMode==0; - }else{ - /* Already in locking_mode=NORMAL */ - rc = 0; - } - }else if( op>0 ){ - assert( pWal->exclusiveMode==0 ); - assert( pWal->readLock>=0 ); - walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock)); - pWal->exclusiveMode = 1; - rc = 1; - }else{ - rc = pWal->exclusiveMode==0; - } - 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; -} -#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 */ - u16 nFree; /* Number of free bytes on the page */ - 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_MASTER mutex. The pPager field -** may not be modified once it is initially set as long as nRef>0. -** The pSchema field may be set once under BtShared.mutex and -** thereafter is unchanged as long as nRef>0. -** -** isPending: -** -** If a BtShared client fails to obtain a write-lock on a database -** table (because there exists one or more read-locks on the table), -** the shared-cache enters 'pending-lock' state and isPending is -** set to true. -** -** The shared-cache leaves the 'pending lock' state when either of -** the following occur: -** -** 1) The current writer (BtShared.pWriter) concludes its transaction, OR -** 2) The number of locks held by other connections drops to zero. -** -** while in the 'pending-lock' state, no connection may start a new -** transaction. -** -** This feature is included to help prevent writer-starvation. -*/ -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 */ -#ifdef SQLITE_HAS_CODEC - u8 optimalReserve; /* Desired amount of reserved space per page */ -#endif - 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: -** eState==SKIPNEXT && skipNext>0: Next sqlite3BtreeNext() is no-op. -** eState==SKIPNEXT && skipNext<0: Next sqlite3BtreePrevious() is no-op. -** eState==FAULT: Cursor fault with skipNext as 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 nOvflAlloc; /* Allocated size of aOverflow[] array */ - Btree *pBtree; /* The Btree to which this cursor belongs */ - BtShared *pBt; /* The BtShared this cursor points to */ - BtCursor *pNext; /* Forms a linked list of all cursors */ - Pgno *aOverflow; /* Cache of overflow page locations */ - CellInfo info; /* A parse of the cell we are pointing at */ - i64 nKey; /* Size of pKey, or last integer key */ - void *pKey; /* Saved key that was cursor last known position */ - Pgno pgnoRoot; /* The root page of this tree */ - int skipNext; /* Prev() is noop if negative. Next() is noop if positive. - ** Error code if eState==CURSOR_FAULT */ - /* All fields above are zeroed when the cursor is allocated. See - ** sqlite3BtreeCursorZero(). Fields that follow must be manually - ** initialized. */ - 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 */ - -/* -** 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_INVALID 0 -#define CURSOR_VALID 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 mallocFailed; /* A memory allocation error has occurred */ - const char *zPfx; /* Error message prefix */ - int v1, v2; /* Values for up to two %d fields in zPfx */ - StrAccum errMsg; /* Accumulate the error message text here */ - u32 *heap; /* Min-heap used for analyzing cell coverage */ -}; - -/* -** 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->skipBtreeMutex = skipOk; -} -SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){ - if( db->skipBtreeMutex==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->skipBtreeMutex==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_MASTER. -*/ -#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 - -#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; - for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){ - Index *pIdx = (Index *)sqliteHashData(p); - if( pIdx->tnum==(int)iRoot ){ - if( iTab ){ - /* 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; - } - } - }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_master - ** 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) || sqlite3BitvecTest(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 */ - void *pKey; - pCur->nKey = sqlite3BtreePayloadSize(pCur); - pKey = sqlite3Malloc( pCur->nKey ); - if( pKey ){ - rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey); - if( rc==SQLITE_OK ){ - 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->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 ){ - assert( nKey==(i64)(int)nKey ); - pIdxKey = sqlite3VdbeAllocUnpackedRecord(pCur->pKeyInfo); - if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT; - sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey); - if( pIdxKey->nField==0 ){ - 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; - assert( cursorOwnsBtShared(pCur) ); - assert( pCur->eState>=CURSOR_REQUIRESEEK ); - if( pCur->eState==CURSOR_FAULT ){ - return pCur->skipNext; - } - pCur->eState = CURSOR_INVALID; - rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext); - if( rc==SQLITE_OK ){ - sqlite3_free(pCur->pKey); - pCur->pKey = 0; - assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID ); - 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){ - return pCur->eState!=CURSOR_VALID; -} - -/* -** 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{ - assert( pCur->skipNext==0 ); - *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 master-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; - } - 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, 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 -/* -** If the cell pCell, part of page pPage contains a pointer -** to an overflow page, insert an entry into the pointer-map -** for the overflow page. -*/ -static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){ - CellInfo info; - if( *pRC ) return; - assert( pCell!=0 ); - pPage->xParseCell(pPage, pCell, &info); - if( info.nLocalpBt, 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]) ); - 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 ){ - int iFree2 = get2byte(&data[iFree]); - - /* pageFindSlot() has already verified that free blocks are sorted - ** in order of offset within the page, and that no block extends - ** past the end of the page. Provided the two free slots do not - ** overlap, this guarantees that the memmove() calls below will not - ** overwrite the usableSize byte buffer, even if the database page - ** is corrupt. */ - assert( iFree2==0 || iFree2>iFree ); - assert( iFree+get2byte(&data[iFree+2]) <= usableSize ); - assert( iFree2==0 || iFree2+get2byte(&data[iFree2+2]) <= usableSize ); - - 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_PGNO(pPage->pgno); - } - if( iFree2 ){ - assert( iFree+sz<=iFree2 ); /* Verified by pageFindSlot() */ - sz2 = get2byte(&data[iFree2+2]); - assert( iFree+sz+sz2+iFree2-(iFree+sz) <= usableSize ); - memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz)); - sz += sz2; - } - cbrk = top+sz; - assert( cbrk+(iFree-top) <= usableSize ); - memmove(&data[cbrk], &data[top], iFree-top); - for(pAddr=&data[cellOffset]; pAddriCellLast ){ - return SQLITE_CORRUPT_PGNO(pPage->pgno); - } - assert( pc>=iCellFirst && pc<=iCellLast ); - size = pPage->xCellSize(pPage, &src[pc]); - cbrk -= size; - if( cbrkusableSize ){ - return SQLITE_CORRUPT_PGNO(pPage->pgno); - } - 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: - if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){ - return SQLITE_CORRUPT_PGNO(pPage->pgno); - } - 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; - u8 * const aData = pPg->aData; - int iAddr = hdr + 1; - int pc = get2byte(&aData[iAddr]); - int x; - int usableSize = pPg->pBt->usableSize; - int size; /* Size of the free slot */ - - assert( pc>0 ); - while( pc<=usableSize-4 ){ - /* 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( size+pc > usableSize ){ - *pRc = SQLITE_CORRUPT_PGNO(pPg->pgno); - return 0; - }else 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{ - /* 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( pcpgno); - } - - 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 ); /* Prevent by getAndInitPage() */ - if( gap>top ){ - if( top==0 && pPage->pBt->usableSize==65536 ){ - top = 65536; - }else{ - return SQLITE_CORRUPT_PGNO(pPage->pgno); - } - } - - /* If there is enough space between gap and top for one more cell pointer - ** array entry offset, and if the freelist is not empty, then search the - ** freelist looking for a free 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 ){ - assert( pSpace>=data && (pSpace - data)<65536 ); - *pIdx = (int)(pSpace - data); - 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 ); - 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 btreeInitPage() call has already - ** validated the freelist. Given that the freelist is valid, there - ** is no way that the allocation can extend off the end of the page. - ** The 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. -** -** Note that even though the freeblock list was checked by btreeInitPage(), -** 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]))pgno); - } - iPtr = iFreeBlk; - } - if( iFreeBlk>pPage->pBt->usableSize-4 ){ - return SQLITE_CORRUPT_PGNO(pPage->pgno); - } - 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_PGNO(pPage->pgno); - iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]); - if( iEnd > pPage->pBt->usableSize ){ - return SQLITE_CORRUPT_PGNO(pPage->pgno); - } - 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_PGNO(pPage->pgno); - nFrag += iStart - iPtrEnd; - iSize = iEnd - iPtr; - iStart = iPtr; - } - } - if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PGNO(pPage->pgno); - 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( iStartpgno); - put2byte(&data[hdr+1], iFreeBlk); - put2byte(&data[hdr+5], iEnd); - }else{ - /* Insert the new freeblock into the freelist */ - put2byte(&data[iPtr], iStart); - } - if( pPage->pBt->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_PGNO(pPage->pgno); - } - pPage->max1bytePayload = pBt->max1bytePayload; - 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){ - int pc; /* Address of a freeblock within pPage->aData[] */ - u8 hdr; /* Offset to beginning of page header */ - u8 *data; /* Equal to pPage->aData */ - BtShared *pBt; /* The main btree structure */ - int usableSize; /* Amount of usable space on each page */ - u16 cellOffset; /* Offset from start of page to first cell pointer */ - int nFree; /* Number of unused bytes on the page */ - int top; /* First byte of the cell content area */ - int iCellFirst; /* First allowable cell or freeblock offset */ - int iCellLast; /* Last possible cell or freeblock offset */ - - 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; - hdr = pPage->hdrOffset; - data = pPage->aData; - /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating - ** the b-tree page type. */ - if( decodeFlags(pPage, data[hdr]) ){ - return SQLITE_CORRUPT_PGNO(pPage->pgno); - } - assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); - pPage->maskPage = (u16)(pBt->pageSize - 1); - pPage->nOverflow = 0; - usableSize = pBt->usableSize; - pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize; - pPage->aDataEnd = &data[usableSize]; - pPage->aCellIdx = &data[cellOffset]; - pPage->aDataOfst = &data[pPage->childPtrSize]; - /* 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]); - /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the - ** number of cells on the page. */ - pPage->nCell = get2byte(&data[hdr+3]); - if( pPage->nCell>MX_CELL(pBt) ){ - /* To many cells for a single page. The page must be corrupt */ - return SQLITE_CORRUPT_PGNO(pPage->pgno); - } - 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 || top==usableSize || CORRUPT_DB ); - - /* A malformed database page might cause us to read past the end - ** of page when parsing a cell. - ** - ** The following block of code checks early to see if a cell extends - ** past the end of a page boundary and causes SQLITE_CORRUPT to be - ** returned if it does. - */ - iCellFirst = cellOffset + 2*pPage->nCell; - iCellLast = usableSize - 4; - if( pBt->db->flags & SQLITE_CellSizeCk ){ - int i; /* Index into the cell pointer array */ - int sz; /* Size of a cell */ - - 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_PGNO(pPage->pgno); - } - sz = pPage->xCellSize(pPage, &data[pc]); - testcase( pc+sz==usableSize ); - if( pc+sz>usableSize ){ - return SQLITE_CORRUPT_PGNO(pPage->pgno); - } - } - if( !pPage->leaf ) iCellLast++; - } - - /* 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( pcpgno); - } - while( 1 ){ - if( pc>iCellLast ){ - /* Freeblock off the end of the page */ - return SQLITE_CORRUPT_PGNO(pPage->pgno); - } - 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_PGNO(pPage->pgno); - } - if( pc+size>(unsigned int)usableSize ){ - /* Last freeblock extends past page end */ - return SQLITE_CORRUPT_PGNO(pPage->pgno); - } - } - - /* At this point, nFree contains the sum of the offset to the start - ** of the cell-content area plus the number of free bytes within - ** the cell-content area. If this is greater than the usable-size - ** of the page, then the page must be corrupted. This check also - ** serves to verify that the offset to the start of the cell-content - ** area, according to the page header, lies within the page. - */ - if( nFree>usableSize ){ - return SQLITE_CORRUPT_PGNO(pPage->pgno); - } - pPage->nFree = (u16)(nFree - iCellFirst); - pPage->isInit = 1; - return SQLITE_OK; -} - -/* -** Set up a raw page so that it looks like a database page holding -** no entries. -*/ -static void zeroPage(MemPage *pPage, int flags){ - 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 u32 sqlite3BtreeLastPage(Btree *p){ - assert( sqlite3BtreeHoldsMutex(p) ); - assert( ((p->pBt->nPage)&0x80000000)==0 ); - 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_error; - } - rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly); - if( rc ){ - goto getAndInitPage_error; - } - *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage); - if( (*ppPage)->isInit==0 ){ - btreePageFromDbPage(pDbPage, pgno, pBt); - rc = btreeInitPage(*ppPage); - if( rc!=SQLITE_OK ){ - releasePage(*ppPage); - goto getAndInitPage_error; - } - } - 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); - releasePage(*ppPage); - goto getAndInitPage_error; - } - return SQLITE_OK; - -getAndInitPage_error: - 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 ){ - 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_MASTER); - 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_MASTER);) - 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 *pMaster; ) - BtShared *pList; - int removed = 0; - - assert( sqlite3_mutex_notheld(pBt->mutex) ); - MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) - sqlite3_mutex_enter(pMaster); - 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(pMaster); - 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; - BtShared *pBt = p->pBt; - assert( nReserve>=-1 && nReserve<=255 ); - sqlite3BtreeEnter(p); -#if SQLITE_HAS_CODEC - if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve; -#endif - if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){ - sqlite3BtreeLeave(p); - return SQLITE_READONLY; - } - if( nReserve<0 ){ - nReserve = pBt->pageSize - pBt->usableSize; - } - 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. -** -** If SQLITE_HAS_MUTEX is defined then the number returned is the -** greater of the current reserved space and the maximum requested -** reserve space. -*/ -SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){ - int n; - sqlite3BtreeEnter(p); - n = sqlite3BtreeGetReserveNoMutex(p); -#ifdef SQLITE_HAS_CODEC - if( npBt->optimalReserve ) n = p->pBt->optimalReserve; -#endif - sqlite3BtreeLeave(p); - return n; -} - - -/* -** Set the maximum page count for a database if mxPage is positive. -** No changes are made if mxPage is 0 or negative. -** Regardless of the value of mxPage, return the maximum page count. -*/ -SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){ - int 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 - -/* -** 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 */ - int nPage; /* Number of pages in the database */ - int nPageFile = 0; /* Number of pages in the database file */ - int 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, &nPageFile); - if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){ - nPage = nPageFile; - } - if( nPage>0 ){ - u32 pageSize; - u32 usableSize; - u8 *page1 = pPage1->aData; - rc = SQLITE_NOTADB; - /* 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; - } - 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( (pBt->db->flags & SQLITE_WriteSchema)==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){ - BtShared *pBt = p->pBt; - int rc = SQLITE_OK; - - sqlite3BtreeEnter(p); - btreeIntegrity(p); - - /* If the btree is already in a write-transaction, or it - ** is already in a read-transaction and a read-transaction - ** is requested, this is a no-op. - */ - if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){ - goto trans_begun; - } - assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 ); - - /* 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, MASTER_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 { - /* 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(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db)); - if( rc==SQLITE_OK ){ - rc = newDatabase(pBt); - } - } - } - - if( rc!=SQLITE_OK ){ - unlockBtreeIfUnused(pBt); - } - }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE && - btreeInvokeBusyHandler(pBt) ); - - 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 && 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(pBt->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_PGNO(pPage->pgno); - } - 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_PGNO(pPage->pgno); - } - 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_PGNO(pPage->pgno); - } - 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 ); - - /* 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( nOrig0 ){ - 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. zMaster points to -** the name of a master journal file that should be written into the -** individual journal file, or is NULL, indicating no master journal file -** (single database transaction). -** -** When this is called, the master journal should already have been -** created, populated with this journal pointer and synced to disk. -** -** Once this is routine has returned, the only thing required to commit -** the write-transaction for this database file is to delete the journal. -*/ -SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){ - 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, zMaster, 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 master journal file) and the caller will ignore this -** functions return code. So, even if an error occurs in the pager layer, -** reset the b-tree objects internal state to indicate that the write -** transaction has been closed. This is quite safe, as the pager will have -** transitioned to the error state. -** -** This will release the write lock on the database file. If there -** are no active cursors, it also releases the read lock. -*/ -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; -} - -/* -** 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 ){ - int nPage = get4byte(28+(u8*)pPage1->aData); - testcase( nPage==0 ); - if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage); - testcase( pBt->nPage!=nPage ); - pBt->nPage = nPage; - 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); - pBt->nPage = get4byte(28 + pBt->pPage1->aData); - - /* The database size was written into the offset 28 of the header - ** when the transaction started, so we know that the value at offset - ** 28 is nonzero. */ - assert( pBt->nPage>0 ); - } - sqlite3BtreeLeave(p); - } - return rc; -} - -/* -** Create a new cursor for the BTree whose root is on the page -** iTable. If a read-only cursor is requested, it is assumed that -** the caller already has at least a read-only transaction open -** on the database already. If a write-cursor is requested, then -** the caller is assumed to have an open write transaction. -** -** If 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 */ - int 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. */ - assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2: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 && 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 = (Pgno)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==(Pgno)iTable ){ - pX->curFlags |= BTCF_Multiple; - pCur->curFlags |= BTCF_Multiple; - } - } - pCur->pNext = pBt->pCursor; - pBt->pCursor = pCur; - pCur->eState = CURSOR_INVALID; - return SQLITE_OK; -} -SQLITE_PRIVATE int sqlite3BtreeCursor( - Btree *p, /* The btree */ - int 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 */ -){ - int rc; - if( iTable<1 ){ - rc = SQLITE_CORRUPT_BKPT; - }else{ - sqlite3BtreeEnter(p); - rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur); - sqlite3BtreeLeave(p); - } - return rc; -} - -/* -** Return the size of a BtCursor object in bytes. -** -** This interfaces is needed so that users of cursors can preallocate -** sufficient storage to hold a cursor. The BtCursor object is opaque -** to users so they cannot do the sizeof() themselves - they must call -** this routine. -*/ -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, iPage)); -} - -/* -** 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); - } - 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 void assertCellInfo(BtCursor *pCur){ - CellInfo info; - memset(&info, 0, sizeof(info)); - btreeParseCell(pCur->pPage, pCur->ix, &info); - assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 ); - } -#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; -} - -/* -** 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; -} - -/* -** 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_PGNO(pPage->pgno); - } - - /* 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( nOvfl>pCur->nOvflAlloc ){ - Pgno *aNew = (Pgno*)sqlite3Realloc( - pCur->aOverflow, nOvfl*2*sizeof(Pgno) - ); - if( aNew==0 ){ - return SQLITE_NOMEM_BKPT; - }else{ - pCur->nOvflAlloc = nOvfl*2; - 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. */ - 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). - */ -#ifdef SQLITE_DIRECT_OVERFLOW_READ - sqlite3_file *fd; /* File from which to do direct overflow read */ -#endif - 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 is no open write-transaction, and - ** 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) */ - && pBt->inTransaction==TRANS_READ /* (3) */ - && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (4) */ - && 0==sqlite3PagerUseWal(pBt->pPager, nextPage) /* (5) */ - && &pBuf[-4]>=pBufStart /* (6) */ - ){ - 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)); - 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_PGNO(pPage->pgno); - } - 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_PGNO(pCur->pPage->pgno); - } - -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 - 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 && !pCur->skipNext ){ - *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_PGNO(pPage->pgno); - } - } - } - 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; - 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 ){ - rc = SQLITE_CORRUPT_PGNO(pPage->pgno); - goto moveto_finish; - } - pCellKey = sqlite3Malloc( nCell+18 ); - if( pCellKey==0 ){ - rc = SQLITE_NOMEM_BKPT; - goto moveto_finish; - } - pCur->ix = (u16)idx; - rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0); - pCur->curFlags &= ~BTCF_ValidOvfl; - if( rc ){ - sqlite3_free(pCellKey); - goto moveto_finish; - } - c = xRecordCompare(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) ); - assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); - 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->skipNext ){ - assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT ); - pCur->eState = CURSOR_VALID; - if( pCur->skipNext>0 ){ - pCur->skipNext = 0; - return SQLITE_OK; - } - pCur->skipNext = 0; - } - } - - pPage = pCur->pPage; - idx = ++pCur->ix; - assert( pPage->isInit ); - - /* 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. */ - testcase( 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 ); - assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); - 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->skipNext==0 || pCur->eState!=CURSOR_VALID ); - 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( pCur->skipNext ){ - assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT ); - pCur->eState = CURSOR_VALID; - if( pCur->skipNext<0 ){ - pCur->skipNext = 0; - return SQLITE_OK; - } - pCur->skipNext = 0; - } - } - - 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 ); - assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); - 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( *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 */ - int 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 ) 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]); - 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. Write the -** local Cell size (the number of bytes on the original page, omitting -** overflow) into *pnSize. -*/ -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 */ - } - if( pCell+pInfo->nSize-1 > pPage->aData+pPage->maskPage ){ - /* Cell extends past end of page */ - return SQLITE_CORRUPT_PGNO(pPage->pgno); - } - 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) ); - 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) ); - /* The cell should normally be sized correctly. However, when moving a - ** malformed cell from a leaf page to an interior page, if the cell size - ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size - ** might be less than 8 (leaf-size + pointer) on the interior node. Hence - ** the term after the || in the following assert(). */ - assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>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); - memcpy(&data[idx], pCell, sz); - if( iChild ){ - put4byte(&data[idx], iChild); - } - 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 ); -#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, pCell, pRC); - } -#endif - } -} - -/* -** A CellArray object contains a cache of pointers and sizes for a -** consecutive sequence of cells that might be held on multiple pages. -*/ -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[] */ -}; - -/* -** 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( - MemPage *pPg, /* Edit this page */ - int nCell, /* Final number of cells on page */ - u8 **apCell, /* Array of cells */ - u16 *szCell /* Array of cell sizes */ -){ - 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; - u8 *pCellptr = pPg->aCellIdx; - u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager); - u8 *pData; - - i = get2byte(&aData[hdr+5]); - memcpy(&pTmp[i], &aData[i], usableSize - i); - - pData = pEnd; - for(i=0; ixCellSize(pPg, pCell) || CORRUPT_DB ); - testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) ); - } - - /* 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; -} - -/* -** Array apCell[] contains nCell pointers to b-tree cells. Array szCell -** contains the size in bytes of each such cell. 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; - u8 *aData = pPg->aData; - u8 *pData = *ppData; - int iEnd = iFirst + nCell; - assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */ - for(i=iFirst; iapCell[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 ); - memmove(pSlot, pCArray->apCell[i], sz); - put2byte(pCellptr, (pSlot - aData)); - pCellptr += 2; - } - *ppData = pData; - return 0; -} - -/* -** Array apCell[] contains nCell pointers to b-tree cells. Array szCell -** contains the size in bytes of each such cell. 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; -} - -/* -** apCell[] and szCell[] contains pointers to and sizes of all cells in the -** pages being balanced. The current page, pPg, has pPg->nCell cells starting -** with 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 */ - if( iOldaCellIdx, &pPg->aCellIdx[nShift*2], nCell*2); - nCell -= nShift; - } - if( iNewEnd < iOldEnd ){ - nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray); - } - - pData = &aData[get2byteNotZero(&aData[hdr+5])]; - if( pDataaCellIdx; - 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]; - memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2); - nCell++; - if( pageInsertArray( - pPg, pBegin, &pData, pCellptr, - iCell+iNew, 1, pCArray - ) ) goto editpage_fail; - } - } - - /* Append cells to the end of the page */ - 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(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]); -} - -/* -** 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. -*/ -#define NN 1 /* Number of neighbors on either side of pPage */ -#define NB (NN*2+1) /* Total pages involved in the balance */ - - -#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 ); - - /* This error condition is now caught prior to reaching this function */ - if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT; - - /* Allocate a new page. This page will become the right-sibling of - ** pPage. Make the parent page writable, so that the new divider cell - ** may be inserted. If both these operations are successful, proceed. - */ - rc = allocateBtreePage(pBt, &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; - - assert( sqlite3PagerIswriteable(pNew->pDbPage) ); - assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) ); - zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF); - rc = rebuildPage(pNew, 1, &pCell, &szCell); - if( NEVER(rc) ) 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, 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 ){ - *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) ); - -#if 0 - TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno)); -#endif - - /* At this point pParent may have at most one overflow cell. And if - ** this overflow cell is present, it must be the cell with - ** index iParentIdx. This scenario comes about when this function - ** is called (indirectly) from sqlite3BtreeDelete(). - */ - assert( pParent->nOverflow==0 || pParent->nOverflow==1 ); - assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx ); - - if( !aOvflSpace ){ - return SQLITE_NOMEM_BKPT; - } - - /* 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; - } - nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow; - 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 = (nMaxCells + 3)&~3; - - /* - ** Allocate space for memory structures - */ - szScratch = - nMaxCells*sizeof(u8*) /* b.apCell */ - + nMaxCells*sizeof(u16) /* b.szCell */ - + pBt->pageSize; /* aSpace1 */ - - assert( szScratch<=6*(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; - - /* 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 - ** constains 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 ){ - 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( piCellmaxLocal+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=0; inFree; - 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) ); - 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 *pNew = apNew[0]; - u8 *aOld = pNew->aData; - int cntOldNext = pNew->nCell + pNew->nOverflow; - int usableSize = pBt->usableSize; - int iNew = 0; - int iOld = 0; - - for(i=0; inCell + pOld->nOverflow + !leafData; - aOld = pOld->aData; - } - 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,aOld,&aOld[usableSize]) - ){ - if( !leafCorrection ){ - ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc); - } - if( cachedCellSize(&b,i)>pNew->minLocal ){ - ptrmapPutOvflPtr(pNew, 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 == - (get2byte(&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 ); - - 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; -} - -/* -** 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 = pCur->iPage; - MemPage *pPage = pCur->pPage; - - if( iPage==0 ){ - if( pPage->nOverflow ){ - /* 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 if( pPage->nOverflow==0 && pPage->nFree<=nMin ){ - break; - }else{ - MemPage * const pParent = pCur->apPage[iPage-1]; - int const iIdx = pCur->aiIdx[iPage-1]; - - rc = sqlite3PagerWrite(pParent->pDbPage); - 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; -} - - -/* -** Insert a new record into the BTree. The content of the new record -** is described by the pX object. The pCur cursor is used only to -** define what table the record should be inserted into, and is left -** pointing at a random location. -** -** For a table btree (used for rowid tables), only the pX.nKey value of -** the key is used. The pX.pKey value must be NULL. The pX.nKey is the -** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields -** hold the content of the row. -** -** For an index btree (used for indexes and WITHOUT ROWID tables), the -** key is an arbitrary byte sequence stored in pX.pKey,nKey. The -** pX.pData,nData,nZero fields must be zero. -** -** If the seekResult parameter is non-zero, then a successful call to -** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already -** been performed. In other words, if seekResult!=0 then the cursor -** is currently pointing to a cell that will be adjacent to the cell -** to be inserted. If seekResult<0 then pCur points to a cell that is -** smaller then (pKey,nKey). If seekResult>0 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. */ - assert( (flags & BTREE_SAVEPOSITION)==0 || - ((pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey) ); - - /* If the cursor is currently on the last row and we are appending a - ** new row onto the end, set the "loc" to avoid an unnecessary - ** btreeMoveto() call */ - if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){ - loc = 0; - }else if( loc==0 ){ - rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc); - if( rc ) return rc; - } - }else 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; - } - assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) ); - - pPage = pCur->pPage; - assert( pPage->intKey || pX->nKey>=0 ); - assert( pPage->leaf || !pPage->intKey ); - - 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); - 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+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( pCur->ixpPage->nCell ); - assert( pCur->eState==CURSOR_VALID ); - assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 ); - - iCellDepth = pCur->iPage; - iCellIdx = pCur->ix; - pPage = pCur->pPage; - pCell = findCell(pPage, iCellIdx); - - /* 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) - ){ - /* 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( 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, int *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); - 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 || CORRUPT_DB ); - testcase( 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 = (int)pgnoRoot; - return SQLITE_OK; -} -SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *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 ); - - 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, MASTER_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; -} - -#ifndef SQLITE_OMIT_BTREECOUNT -/* -** The first argument, pCur, is a cursor opened on some b-tree. Count the -** number of entries in the b-tree and write the result to *pnEntry. -** -** SQLITE_OK is returned if the operation is successfully executed. -** Otherwise, if an error is encountered (i.e. an IO error or database -** corruption) an SQLite error code is returned. -*/ -SQLITE_PRIVATE int sqlite3BtreeCount(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 ){ - 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; -} -#endif - -/* -** 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 ){ - sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1); - } - if( pCheck->zPfx ){ - sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2); - } - sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap); - va_end(ap); - if( pCheck->errMsg.accError==STRACCUM_NOMEM ){ - pCheck->mallocFailed = 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==0 ) return 1; - if( iPage>pCheck->nPage ){ - checkAppendMsg(pCheck, "invalid page number %d", iPage); - return 1; - } - if( getPageReferenced(pCheck, iPage) ){ - checkAppendMsg(pCheck, "2nd reference to page %d", iPage); - 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->mallocFailed = 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 */ - int iPage, /* Page number for first page in the list */ - int N /* Expected number of pages in the list */ -){ - int i; - int expected = N; - int iFirst = iPage; - while( N-- > 0 && pCheck->mxErr ){ - DbPage *pOvflPage; - unsigned char *pOvflData; - if( iPage<1 ){ - checkAppendMsg(pCheck, - "%d of %d pages missing from overflow list starting at %d", - N+1, expected, iFirst); - break; - } - if( checkRef(pCheck, iPage) ) break; - if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){ - checkAppendMsg(pCheck, "failed to get page %d", iPage); - break; - } - pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage); - if( isFreeList ){ - int n = get4byte(&pOvflData[4]); -#ifndef SQLITE_OMIT_AUTOVACUUM - if( pCheck->pBt->autoVacuum ){ - checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0); - } -#endif - if( n>(int)pCheck->pBt->usableSize/4-2 ){ - checkAppendMsg(pCheck, - "freelist leaf count too big on page %d", iPage); - N--; - }else{ - for(i=0; ipBt->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( isFreeList && N<(iPage!=0) ){ - checkAppendMsg(pCheck, "free-page count in header is too small"); - } - } -} -#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 %d: "; - pCheck->v1 = iPage; - if( (rc = btreeGetPage(pBt, (Pgno)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; - } - data = pPage->aData; - hdr = pPage->hdrOffset; - - /* Set up for cell analysis */ - pCheck->zPfx = "On tree page %d 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 %d 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 ){ - int 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 btreeInitPage() */ - size = get2byte(&data[i+2]); - assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */ - 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 btreeInitPage() */ - assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */ - 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 %d", 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 %d", - 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. -*/ -SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck( - Btree *p, /* The btree to be checked */ - int *aRoot, /* An array of root pages numbers for individual trees */ - int nRoot, /* Number of entries in aRoot[] */ - int mxErr, /* Stop reporting errors after this many */ - int *pnErr /* Write number of errors seen to this variable */ -){ - Pgno i; - IntegrityCk sCheck; - BtShared *pBt = p->pBt; - int savedDbFlags = pBt->db->flags; - char zErr[100]; - VVA_ONLY( int nRef ); - - sqlite3BtreeEnter(p); - assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE ); - VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) ); - assert( nRef>=0 ); - sCheck.pBt = pBt; - sCheck.pPager = pBt->pPager; - sCheck.nPage = btreePagecount(sCheck.pBt); - sCheck.mxErr = mxErr; - sCheck.nErr = 0; - sCheck.mallocFailed = 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.mallocFailed = 1; - goto integrity_ck_cleanup; - } - sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize ); - if( sCheck.heap==0 ){ - sCheck.mallocFailed = 1; - goto integrity_ck_cleanup; - } - - i = PENDING_BYTE_PAGE(pBt); - if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i); - - /* Check the integrity of the freelist - */ - sCheck.zPfx = "Main freelist: "; - checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]), - get4byte(&pBt->pPage1->aData[36])); - sCheck.zPfx = 0; - - /* Check all the tables. - */ - testcase( pBt->db->flags & SQLITE_CellSizeCk ); - pBt->db->flags &= ~SQLITE_CellSizeCk; - for(i=0; (int)iautoVacuum && aRoot[i]>1 ){ - 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 - */ - 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.mallocFailed ){ - sqlite3StrAccumReset(&sCheck.errMsg); - sCheck.nErr++; - } - *pnErr = sCheck.nErr; - if( sCheck.nErr==0 ) sqlite3StrAccumReset(&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_master table. Otherwise SQLITE_OK. -*/ -SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){ - int rc; - assert( sqlite3_mutex_held(p->db->mutex) ); - sqlite3BtreeEnter(p); - rc = querySharedCacheTableLock(p, MASTER_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); - if( rc==SQLITE_OK ){ - u8 *aData = pBt->pPage1->aData; - if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){ - rc = sqlite3BtreeBeginTrans(pBtree, 2); - if( rc==SQLITE_OK ){ - rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); - if( rc==SQLITE_OK ){ - aData[18] = (u8)iVersion; - aData[19] = (u8)iVersion; - } - } - } - } - - pBt->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),-1,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; -#ifdef SQLITE_HAS_CODEC - /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is - ** guaranteed that the shared-mutex is held by this thread, handle - ** p->pSrc may not actually be the owner. */ - int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc); - int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest); -#endif - 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; - } - -#ifdef SQLITE_HAS_CODEC - /* Backup is not possible if the page size of the destination is changing - ** and a codec is in use. - */ - if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){ - rc = SQLITE_READONLY; - } - - /* Backup is not possible if the number of bytes of reserve space differ - ** between source and destination. If there is a difference, try to - ** fix the destination to agree with the source. If that is not possible, - ** then the backup cannot proceed. - */ - if( nSrcReserve!=nDestReserve ){ - u32 newPgsz = nSrcPgsz; - rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve); - if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY; - } -#endif - - /* This loop runs once for each destination page spanned by the source - ** page. For each iteration, variable iOff is set to the byte offset - ** of the destination page. - */ - for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && 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); - 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)) - ){ - p->bDestLocked = 1; - sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema); - } - - /* 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)); - while( *pp!=p ){ - pp = &(*pp)->pNext; - } - *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; - -#ifdef SQLITE_HAS_CODEC - sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom)); -#endif - - /* 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" */ - -#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 be both MEM_Int and MEM_Real at the same time */ - assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) ); - - 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_RowSet|MEM_Frame|MEM_Agg|MEM_Zero))==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_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 - - -/* -** 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( (pMem->flags&MEM_RowSet)==0 ); - 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 -** min(n,32) 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( (pMem->flags&MEM_RowSet)==0 ); - 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( n<32 ) n = 32; - if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){ - pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n); - 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, 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( 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); - return SQLITE_OK; -} - -/* -** It is already known that pMem contains an unterminated string. -** Add the zero terminator. -*/ -static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){ - if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){ - return SQLITE_NOMEM_BKPT; - } - pMem->z[pMem->n] = 0; - pMem->z[pMem->n+1] = 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( (pMem->flags&MEM_RowSet)==0 ); - 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 ); - assert( (pMem->flags&MEM_RowSet)==0 ); - 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 ){ - 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. Numbers -** are converted using sqlite3_snprintf(). Converting a BLOB to a string -** is a no-op. -** -** Existing representations MEM_Int and MEM_Real 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){ - int fg = pMem->flags; - const int nByte = 32; - - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - assert( !(fg&MEM_Zero) ); - assert( !(fg&(MEM_Str|MEM_Blob)) ); - assert( fg&(MEM_Int|MEM_Real) ); - assert( (pMem->flags&MEM_RowSet)==0 ); - assert( EIGHT_BYTE_ALIGNMENT(pMem) ); - - - if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){ - pMem->enc = 0; - return SQLITE_NOMEM_BKPT; - } - - /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8 - ** string representation of the value. Then, if the required encoding - ** is UTF-16le or UTF-16be do a translation. - ** - ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16. - */ - if( fg & MEM_Int ){ - sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i); - }else{ - assert( fg & MEM_Real ); - sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r); - } - pMem->n = sqlite3Strlen30(pMem->z); - pMem->enc = SQLITE_UTF8; - pMem->flags |= MEM_Str|MEM_Term; - if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real); - 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){ - int rc = SQLITE_OK; - if( ALWAYS(pFunc && pFunc->xFinalize) ){ - sqlite3_context ctx; - Mem t; - 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)); - rc = ctx.isError; - } - return rc; -} - -/* -** 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->flags&MEM_RowSet)==0 ); - assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 ); - p->xDel((void *)p->z); - }else if( p->flags&MEM_RowSet ){ - sqlite3RowSetClear(p->u.pRowSet); - }else if( p->flags&MEM_Frame ){ - VdbeFrame *pFrame = p->u.pFrame; - pFrame->pParent = pFrame->v->pDelFrame; - pFrame->v->pDelFrame = pFrame; - } - 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 ){ - return pMem->u.i; - }else if( flags & MEM_Real ){ - return doubleToInt64(pMem->u.r); - }else if( flags & (MEM_Str|MEM_Blob) ){ - assert( pMem->z || pMem->n==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 ){ - 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; - } -} - -/* -** 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( (pMem->flags & MEM_RowSet)==0 ); - 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( (pMem->flags & MEM_RowSet)==0 ); - 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; -} - -/* -** Convert pMem so that it has types MEM_Real or MEM_Int or both. -** 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){ - if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){ - int rc; - assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 ); - assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - rc = sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc); - if( rc==0 ){ - MemSetTypeFlag(pMem, MEM_Int); - }else{ - i64 i = pMem->u.i; - sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc); - if( rc==1 && pMem->u.r==(double)i ){ - pMem->u.i = i; - MemSetTypeFlag(pMem, MEM_Int); - }else{ - MemSetTypeFlag(pMem, MEM_Real); - } - } - } - assert( (pMem->flags & (MEM_Int|MEM_Real|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 void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){ - if( pMem->flags & MEM_Null ) return; - 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_Blob|MEM_Zero); - break; - } - } -} - -/* -** 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 */ -static 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 - -/* -** Delete any previous value and set the value of pMem to be an -** empty boolean index. -*/ -SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){ - sqlite3 *db = pMem->db; - assert( db!=0 ); - assert( (pMem->flags & MEM_RowSet)==0 ); - sqlite3VdbeMemRelease(pMem); - pMem->zMalloc = sqlite3DbMallocRawNN(db, 64); - if( db->mallocFailed ){ - pMem->flags = MEM_Null; - pMem->szMalloc = 0; - }else{ - assert( pMem->zMalloc ); - pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc); - pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc); - assert( pMem->u.pRowSet!=0 ); - pMem->flags = MEM_RowSet; - } -} - -/* -** 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 make sure shallow -** copies are not misused. -*/ -SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){ - int i; - Mem *pX; - for(i=0, pX=pVdbe->aMem; inMem; i++, pX++){ - if( pX->pScopyFrom==pMem ){ - 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( (pFrom->flags & MEM_RowSet)==0 ); - 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( (pFrom->flags & MEM_RowSet)==0 ); - 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( (pMem->flags & MEM_RowSet)==0 ); - - /* 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); - if( nByte>iLimit ) nByte = iLimit+1; - }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 ){ - int nAlloc = nByte; - if( flags&MEM_Term ){ - nAlloc += (enc==SQLITE_UTF8?1:2); - } - if( nByte>iLimit ){ - return SQLITE_TOOBIG; - } - testcase( nAlloc==0 ); - testcase( nAlloc==31 ); - testcase( nAlloc==32 ); - if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){ - return SQLITE_NOMEM_BKPT; - } - memcpy(pMem->z, z, nAlloc); - }else if( xDel==SQLITE_DYNAMIC ){ - sqlite3VdbeMemRelease(pMem); - pMem->zMalloc = pMem->z = (char *)z; - pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc); - }else{ - sqlite3VdbeMemRelease(pMem); - pMem->z = (char *)z; - pMem->xDel = xDel; - flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn); - } - - pMem->n = nByte; - pMem->flags = flags; - pMem->enc = (enc==0 ? SQLITE_UTF8 : enc); - -#ifndef SQLITE_OMIT_UTF16 - if( pMem->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. -*/ -static SQLITE_NOINLINE int vdbeMemFromBtreeResize( - 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( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+1)) ){ - rc = sqlite3BtreePayload(pCur, offset, amt, pMem->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 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. */ -){ - char *zData; /* Data from the btree layer */ - 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( (pMem->flags & MEM_RowSet)==0 ); - zData = (char *)sqlite3BtreePayloadFetch(pCur, &available); - assert( zData!=0 ); - - if( offset+amt<=available ){ - pMem->z = &zData[offset]; - pMem->flags = MEM_Blob|MEM_Ephem; - pMem->n = (int)amt; - }else{ - rc = vdbeMemFromBtreeResize(pCur, offset, 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( (pVal->flags & MEM_RowSet)==0 ); - 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) ){ - 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( (pVal->flags & MEM_RowSet)==0 ); - if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){ - 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_STAT3_OR_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_STAT3_OR_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_STAT3_OR_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( NEVER(op==TK_REGISTER) ) op = pExpr->op2; - - /* 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); - } - if( pVal->flags & (MEM_Int|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 ){ - pVal->u.r = -(double)SMALLEST_INT64; - 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; - sqlite3VdbeMemNumerify(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_STAT3_OR_STAT4 - else if( op==TK_FUNCTION && pCtx!=0 ){ - rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx); - } -#endif - - *ppVal = pVal; - return rc; - -no_mem: - sqlite3OomFault(db); - sqlite3DbFree(db, zVal); - assert( *ppVal==0 ); -#ifdef SQLITE_ENABLE_STAT3_OR_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_STAT3_OR_STAT4 -/* -** The implementation of the sqlite_record() function. This function accepts -** a single argument of any type. The return value is a formatted database -** record (a blob) containing the argument value. -** -** This is used to convert the value stored in the 'sample' column of the -** sqlite_stat3 table to the record format SQLite uses internally. -*/ -static void recordFunc( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - const int file_format = 1; - u32 iSerial; /* Serial type */ - int nSerial; /* Bytes of space for iSerial as varint */ - u32 nVal; /* Bytes of space required for argv[0] */ - int nRet; - sqlite3 *db; - u8 *aRet; - - UNUSED_PARAMETER( argc ); - iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal); - nSerial = sqlite3VarintLen(iSerial); - db = sqlite3_context_db_handle(context); - - nRet = 1 + nSerial + nVal; - aRet = sqlite3DbMallocRawNN(db, nRet); - if( aRet==0 ){ - sqlite3_result_error_nomem(context); - }else{ - aRet[0] = nSerial+1; - putVarint32(&aRet[1], iSerial); - sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial); - sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT); - sqlite3DbFreeNN(db, aRet); - } -} - -/* -** Register built-in functions used to help read ANALYZE data. -*/ -SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){ - static FuncDef aAnalyzeTableFuncs[] = { - FUNCTION(sqlite_record, 1, 0, 0, recordFunc), - }; - sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs)); -} - -/* -** 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; /* 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; /* 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" */ - -/* -** 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( pParse->nOpAlloc==0 ); - assert( pParse->szOpAlloc==0 ); - sqlite3VdbeAddOp2(p, OP_Init, 0, 1); - return p; -} - -/* -** 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); -} - -/* -** 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; - 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 Parse.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 - int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp); -#else - int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(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>=(p->nOpAlloc+nOp) ); - pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op)); - if( pNew ){ - p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew); - p->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". -*/ -static void test_addop_breakpoint(void){ - 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->pParse->nOpAlloc<=p->nOp ); - if( growOpArray(p, 1) ) return 1; - assert( p->pParse->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->pParse->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 ){ - int jj, kk; - Parse *pParse = p->pParse; - for(jj=kk=0; jjnColCache; jj++){ - struct yColCache *x = pParse->aColCache + jj; - printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn); - kk++; - } - if( kk ) printf("\n"); - sqlite3VdbePrintOp(0, i, &p->aOp[i]); - test_addop_breakpoint(); - } -#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 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); -} - -/* -** 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. -** -** Zero is returned if a malloc() fails. -*/ -SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){ - Parse *p = v->pParse; - int i = p->nLabel++; - assert( v->magic==VDBE_MAGIC_INIT ); - if( (i & (i-1))==0 ){ - p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel, - (i*2+1)*sizeof(p->aLabel[0])); - } - if( p->aLabel ){ - p->aLabel[i] = -1; - } - return ADDR(i); -} - -/* -** 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(). -*/ -SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){ - Parse *p = v->pParse; - int j = ADDR(x); - assert( v->magic==VDBE_MAGIC_INIT ); - assert( jnLabel ); - assert( j>=0 ); - if( p->aLabel ){ - 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_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 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_Halt || opcode==OP_HaltIfNull) - && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort)) - ){ - hasAbort = 1; - break; - } - if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 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) ); -} -#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */ - -/* -** 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; - /* fall thru */ - } - 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_NextIfOpen: - 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: - case OP_PrevIfOpen: { - 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 */ - } -#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)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->pParse->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 - -/* -** 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->pParse->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 */ -){ - int 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, u32 addr, u8 iNewOpcode){ - sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode; -} -SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){ - sqlite3VdbeGetOp(p,addr)->p1 = val; -} -SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){ - sqlite3VdbeGetOp(p,addr)->p2 = val; -} -SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 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); -} - - -/* -** 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); - } -} - -static void vdbeFreeOpArray(sqlite3 *, Op *, int); - -/* -** 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_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; -} - -/* -** 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; - } -} - -/* -** 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 ); - 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 -*/ -static int displayComment( - const Op *pOp, /* The opcode to be commented */ - const char *zP4, /* Previously obtained value for P4 */ - char *zTemp, /* Write result here */ - int nTemp /* Space available in zTemp[] */ -){ - const char *zOpName; - const char *zSynopsis; - int nOpName; - int ii, jj; - char zAlt[50]; - 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=jj=0; jjzComment); - seenCom = 1; - }else{ - int v1 = translateP(c, pOp); - int v2; - sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1); - if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){ - ii += 3; - jj += sqlite3Strlen30(zTemp+jj); - v2 = translateP(zSynopsis[ii], pOp); - if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){ - ii += 2; - v2++; - } - if( v2>1 ){ - sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1); - } - }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){ - ii += 4; - } - } - jj += sqlite3Strlen30(zTemp+jj); - }else{ - zTemp[jj++] = c; - } - } - if( !seenCom && jjzComment ){ - sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment); - jj += sqlite3Strlen30(zTemp+jj); - } - if( jjzComment ){ - sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment); - jj = sqlite3Strlen30(zTemp); - }else{ - zTemp[0] = 0; - jj = 0; - } - return jj; -} -#endif /* SQLITE_DEBUG */ - -#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: - sqlite3XPrintf(p, "%Q", pExpr->u.zToken); - break; - case TK_INTEGER: - sqlite3XPrintf(p, "%d", pExpr->u.iValue); - break; - case TK_NULL: - sqlite3XPrintf(p, "NULL"); - break; - case TK_REGISTER: { - sqlite3XPrintf(p, "r[%d]", pExpr->iTable); - break; - } - case TK_COLUMN: { - if( pExpr->iColumn<0 ){ - sqlite3XPrintf(p, "rowid"); - }else{ - sqlite3XPrintf(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: - sqlite3XPrintf(p, "%s", "expr"); - break; - } - - if( zOp ){ - sqlite3XPrintf(p, "%s(", zOp); - displayP4Expr(p, pExpr->pLeft); - if( pExpr->pRight ){ - sqlite3StrAccumAppend(p, ",", 1); - displayP4Expr(p, pExpr->pRight); - } - sqlite3StrAccumAppend(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. -*/ -static char *displayP4(Op *pOp, char *zTemp, int nTemp){ - char *zP4 = zTemp; - StrAccum x; - assert( nTemp>=20 ); - sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0); - switch( pOp->p4type ){ - case P4_KEYINFO: { - int j; - KeyInfo *pKeyInfo = pOp->p4.pKeyInfo; - assert( pKeyInfo->aSortOrder!=0 ); - sqlite3XPrintf(&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"; - sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl); - } - sqlite3StrAccumAppend(&x, ")", 1); - break; - } -#ifdef SQLITE_ENABLE_CURSOR_HINTS - case P4_EXPR: { - displayP4Expr(&x, pOp->p4.pExpr); - break; - } -#endif - case P4_COLLSEQ: { - CollSeq *pColl = pOp->p4.pColl; - sqlite3XPrintf(&x, "(%.20s)", pColl->zName); - break; - } - case P4_FUNCDEF: { - FuncDef *pDef = pOp->p4.pFunc; - sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg); - break; - } -#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE) - case P4_FUNCCTX: { - FuncDef *pDef = pOp->p4.pCtx->pFunc; - sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg); - break; - } -#endif - case P4_INT64: { - sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64); - break; - } - case P4_INT32: { - sqlite3XPrintf(&x, "%d", pOp->p4.i); - break; - } - case P4_REAL: { - sqlite3XPrintf(&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 ){ - sqlite3XPrintf(&x, "%lld", pMem->u.i); - }else if( pMem->flags & MEM_Real ){ - sqlite3XPrintf(&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; - sqlite3XPrintf(&x, "vtab:%p", pVtab); - break; - } -#endif - case P4_INTARRAY: { - int i; - int *ai = pOp->p4.ai; - int 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++){ - sqlite3XPrintf(&x, ",%d", ai[i]); - } - zTemp[0] = '['; - sqlite3StrAccumAppend(&x, "]", 1); - break; - } - case P4_SUBPROGRAM: { - sqlite3XPrintf(&x, "program"); - break; - } - case P4_ADVANCE: { - zTemp[0] = 0; - break; - } - case P4_TABLE: { - sqlite3XPrintf(&x, "%s", pOp->p4.pTab->zName); - break; - } - default: { - zP4 = pOp->p4.z; - if( zP4==0 ){ - zP4 = zTemp; - zTemp[0] = 0; - } - } - } - sqlite3StrAccumFinish(&x); - assert( zP4!=0 ); - return zP4; -} -#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, Op *pOp){ - char *zP4; - char zPtr[50]; - char zCom[100]; - static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n"; - if( pOut==0 ) pOut = stdout; - zP4 = displayP4(pOp, zPtr, sizeof(zPtr)); -#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS - displayComment(pOp, zP4, zCom, sizeof(zCom)); -#else - zCom[0] = 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, pOp->p5, - zCom - ); - fflush(pOut); -} -#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->flags & MEM_Frame ); - testcase( p->flags & MEM_RowSet ); - if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){ - sqlite3VdbeMemRelease(p); - }else if( p->szMalloc ){ - sqlite3DbFreeNN(db, p->zMalloc); - p->szMalloc = 0; - } - - p->flags = MEM_Undefined; - }while( (++p)nChildMem]; - 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. -** -** 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 */ -){ - 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 */ - 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 */ - - 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_BKPT ){ - /* This happens if a malloc() inside a call to sqlite3_column_text() or - ** sqlite3_column_text16() failed. */ - sqlite3OomFault(db); - return SQLITE_ERROR; - } - - /* 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( p->explain==1 ){ - /* 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]; - if( pSub->flags&MEM_Blob ){ - /* On the first call to sqlite3_step(), pSub will hold a 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; - } - } - - do{ - i = p->pc++; - }while( iexplain==2 && p->aOp[i].opcode!=OP_Explain ); - if( i>=nRow ){ - p->rc = SQLITE_OK; - rc = SQLITE_DONE; - }else if( db->u1.isInterrupted ){ - p->rc = SQLITE_INTERRUPT; - rc = SQLITE_ERROR; - sqlite3VdbeError(p, sqlite3ErrStr(p->rc)); - }else{ - char *zP4; - Op *pOp; - if( inOp ){ - /* The output line number is small enough that we are still in the - ** main program. */ - pOp = &p->aOp[i]; - }else{ - /* We are currently listing subprograms. Figure out which one and - ** pick up the appropriate opcode. */ - int j; - i -= p->nOp; - for(j=0; i>=apSub[j]->nOp; j++){ - i -= apSub[j]->nOp; - } - pOp = &apSub[j]->aOp[i]; - } - if( p->explain==1 ){ - pMem->flags = MEM_Int; - pMem->u.i = i; /* Program counter */ - pMem++; - - pMem->flags = MEM_Static|MEM_Str|MEM_Term; - pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */ - assert( pMem->z!=0 ); - pMem->n = sqlite3Strlen30(pMem->z); - pMem->enc = SQLITE_UTF8; - pMem++; - - /* 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( pOp->p4type==P4_SUBPROGRAM ){ - int nByte = (nSub+1)*sizeof(SubProgram*); - int j; - for(j=0; jp4.pProgram ) break; - } - if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){ - apSub = (SubProgram **)pSub->z; - apSub[nSub++] = pOp->p4.pProgram; - pSub->flags |= MEM_Blob; - pSub->n = nSub*sizeof(SubProgram*); - } - } - } - - pMem->flags = MEM_Int; - pMem->u.i = pOp->p1; /* P1 */ - pMem++; - - pMem->flags = MEM_Int; - pMem->u.i = pOp->p2; /* P2 */ - pMem++; - - pMem->flags = MEM_Int; - pMem->u.i = pOp->p3; /* P3 */ - pMem++; - - if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */ - assert( p->db->mallocFailed ); - return SQLITE_ERROR; - } - pMem->flags = MEM_Str|MEM_Term; - zP4 = displayP4(pOp, pMem->z, pMem->szMalloc); - if( zP4!=pMem->z ){ - pMem->n = 0; - sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0); - }else{ - assert( pMem->z!=0 ); - pMem->n = sqlite3Strlen30(pMem->z); - pMem->enc = SQLITE_UTF8; - } - pMem++; - - if( p->explain==1 ){ - if( sqlite3VdbeMemClearAndResize(pMem, 4) ){ - assert( p->db->mallocFailed ); - return SQLITE_ERROR; - } - pMem->flags = MEM_Str|MEM_Term; - pMem->n = 2; - sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */ - pMem->enc = SQLITE_UTF8; - pMem++; - -#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS - if( sqlite3VdbeMemClearAndResize(pMem, 500) ){ - assert( p->db->mallocFailed ); - return SQLITE_ERROR; - } - pMem->flags = MEM_Str|MEM_Term; - pMem->n = displayComment(pOp, zP4, pMem->z, 500); - pMem->enc = SQLITE_UTF8; -#else - pMem->flags = MEM_Null; /* Comment */ -#endif - } - - p->nResColumn = 8 - 4*(p->explain-1); - p->pResultSet = &p->aMem[1]; - 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 */ - int nFree; /* Bytes of available memory */ - int 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 */ - int 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 && nMem<10 ){ - nMem = 10; - } - p->expired = 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. - */ - do { - x.nNeeded = 0; - 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 - if( x.nNeeded==0 ) break; - x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded); - x.nFree = x.nNeeded; - }while( !db->mallocFailed ); - - p->pVList = pParse->pVList; - pParse->pVList = 0; - p->explain = pParse->explain; - 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 master 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 - ** master-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 master 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 master 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 master journal depends upon - ** its journal mode (among other things). This matrix determines which - ** journal modes use a master 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)] - ){ - 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 - ** master-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 master journal file to ensure the transaction is - ** committed atomically. - */ -#ifndef SQLITE_OMIT_DISKIO - else{ - sqlite3_vfs *pVfs = db->pVfs; - char *zMaster = 0; /* File-name for the master journal */ - char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt); - sqlite3_file *pMaster = 0; - i64 offset = 0; - int res; - int retryCount = 0; - int nMainFile; - - /* Select a master journal file name */ - nMainFile = sqlite3Strlen30(zMainFile); - zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile); - if( zMaster==0 ) return SQLITE_NOMEM_BKPT; - do { - u32 iRandom; - if( retryCount ){ - if( retryCount>100 ){ - sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster); - sqlite3OsDelete(pVfs, zMaster, 0); - break; - }else if( retryCount==1 ){ - sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster); - } - } - retryCount++; - sqlite3_randomness(sizeof(iRandom), &iRandom); - sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X", - (iRandom>>8)&0xffffff, iRandom&0xff); - /* The antipenultimate character of the master journal name must - ** be "9" to avoid name collisions when using 8+3 filenames. */ - assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' ); - sqlite3FileSuffix3(zMainFile, zMaster); - rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res); - }while( rc==SQLITE_OK && res ); - if( rc==SQLITE_OK ){ - /* Open the master journal. */ - rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, - SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE| - SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0 - ); - } - if( rc!=SQLITE_OK ){ - sqlite3DbFree(db, zMaster); - return rc; - } - - /* Write the name of each database file in the transaction into the new - ** master journal file. If an error occurs at this point close - ** and delete the master journal file. All the individual journal files - ** still have 'null' as the master 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(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset); - offset += sqlite3Strlen30(zFile)+1; - if( rc!=SQLITE_OK ){ - sqlite3OsCloseFree(pMaster); - sqlite3OsDelete(pVfs, zMaster, 0); - sqlite3DbFree(db, zMaster); - return rc; - } - } - } - - /* Sync the master journal file. If the IOCAP_SEQUENTIAL device - ** flag is set this is not required. - */ - if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL) - && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL)) - ){ - sqlite3OsCloseFree(pMaster); - sqlite3OsDelete(pVfs, zMaster, 0); - sqlite3DbFree(db, zMaster); - return rc; - } - - /* Sync all the db files involved in the transaction. The same call - ** sets the master journal pointer in each individual journal. If - ** an error occurs here, do not delete the master journal file. - ** - ** If the error occurs during the first call to - ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the - ** master journal file will be orphaned. But we cannot delete it, - ** in case the master 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, zMaster); - } - } - sqlite3OsCloseFree(pMaster); - assert( rc!=SQLITE_BUSY ); - if( rc!=SQLITE_OK ){ - sqlite3DbFree(db, zMaster); - return rc; - } - - /* Delete the master journal file. This commits the transaction. After - ** doing this the directory is synced again before any individual - ** transaction files are deleted. - */ - rc = sqlite3OsDelete(pVfs, zMaster, 1); - sqlite3DbFree(db, zMaster); - zMaster = 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 ){ - 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 &= ~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 be 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); - sqlite3VdbeTransferError(p); - 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 - sqlite3DbFree(db, p->zErrMsg); - p->zErrMsg = 0; - p->pResultSet = 0; - - /* 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_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; - - if( NEVER(p==0) ) return; - 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. -*/ -static int SQLITE_NOINLINE handleDeferredMoveto(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, int *piCol){ - VdbeCursor *p = *pp; - assert( p->eCurType==CURTYPE_BTREE || p->eCurType==CURTYPE_PSEUDO ); - if( p->deferredMoveto ){ - int iMap; - if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){ - *pp = p->pAltCursor; - *piCol = iMap - 1; - return SQLITE_OK; - } - return handleDeferredMoveto(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. -*/ - -/* -** Return the serial-type for the value stored in pMem. -*/ -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 ){ - /* 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; - 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; - 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)); -} - -/* -** 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 SQLITE_NOINLINE 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 = sqlite3IsNaN(pMem->u.r) ? 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: /* Reserved for future use */ - 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->aSortOrder!=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; - int 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; - } - 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->aSortOrder!=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+serial_type1+2>(u32)nKey1 - && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)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->aColl[i]); - if( rc!=0 ){ - assert( mem1.szMalloc==0 ); /* See comment below */ - if( pKeyInfo->aSortOrder[i] ){ - 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>9223372036854775807.0 ) return -1; - y = (i64)r; - if( iy ){ - if( y==SMALLEST_INT64 && r>0.0 ) return -1; - 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( (combined_flags & MEM_RowSet)==0 ); - - /* 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) ){ - if( (f1 & f2 & MEM_Int)!=0 ){ - 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)!=0 ){ - if( (f2&MEM_Real)!=0 ){ - return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r); - }else{ - return -1; - } - } - if( (f1&MEM_Real)!=0 ){ - if( (f2&MEM_Int)!=0 ){ - 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 = pPKey2->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; - if( d1>(unsigned)nKey1 ){ - pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT; - return 0; /* Corruption */ - } - i = 0; - } - - VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */ - assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField - || CORRUPT_DB ); - assert( pPKey2->pKeyInfo->aSortOrder!=0 ); - assert( pPKey2->pKeyInfo->nKeyField>0 ); - assert( idx1<=szHdr1 || CORRUPT_DB ); - do{ - u32 serial_type; - - /* RHS is an integer */ - if( pRhs->flags & MEM_Int ){ - 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 ){ - getVarint32(&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 ){ - 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 ); - getVarint32(&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 ){ - if( pKeyInfo->aSortOrder[i] ){ - rc = -rc; - } - assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) ); - assert( mem1.szMalloc==0 ); /* See comment below */ - return rc; - } - - i++; - pRhs++; - d1 += sqlite3VdbeSerialTypeLen(serial_type); - idx1 += sqlite3VarintLen(serial_type); - }while( idx1<(unsigned)szHdr1 && inField && 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) - || 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); - getVarint32(&aKey1[1], 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 = 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; - } - }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->aSortOrder[0] ){ - 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_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 = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m); - if( rc ){ - return rc; - } - - /* The index entry must begin with a header size */ - (void)getVarint32((u8*)m.z, szHdr); - testcase( szHdr==3 ); - testcase( szHdr==m.n ); - if( unlikely(szHdr<3 || (int)szHdr>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. */ - (void)getVarint32((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 = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m); - if( rc ){ - return rc; - } - *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked); - 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. -*/ -SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){ - Vdbe *p; - for(p = db->pVdbe; p; p=p->pNext){ - p->expired = 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){ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - if( pCtx->pVdbe==0 ) return 1; -#endif - if( pCtx->pVdbe->aOp[pCtx->iOp].opcode==OP_PureFunc ){ - sqlite3_result_error(pCtx, - "non-deterministic function in index expression or CHECK constraint", - -1); - 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.aSortOrder = (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->xProfile!=0 || (db->mTrace & SQLITE_TRACE_PROFILE)!=0 ); - assert( db->init.busy==0 ); - assert( p->zSql!=0 ); - sqlite3OsCurrentTimeInt64(db->pVfs, &iNow); - iElapse = (iNow - p->startTime)*1000000; - if( db->xProfile ){ - db->xProfile(db->pProfileArg, p->zSql, iElapse); - } - if( db->mTrace & SQLITE_TRACE_PROFILE ){ - db->xTrace(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 */ - SQLITE_NULL, /* 0x01 */ - SQLITE_TEXT, /* 0x02 */ - SQLITE_NULL, /* 0x03 */ - SQLITE_INTEGER, /* 0x04 */ - SQLITE_NULL, /* 0x05 */ - SQLITE_INTEGER, /* 0x06 */ - SQLITE_NULL, /* 0x07 */ - SQLITE_FLOAT, /* 0x08 */ - SQLITE_NULL, /* 0x09 */ - SQLITE_FLOAT, /* 0x0a */ - SQLITE_NULL, /* 0x0b */ - SQLITE_INTEGER, /* 0x0c */ - SQLITE_NULL, /* 0x0d */ - SQLITE_INTEGER, /* 0x0e */ - SQLITE_NULL, /* 0x0f */ - SQLITE_BLOB, /* 0x10 */ - SQLITE_NULL, /* 0x11 */ - SQLITE_TEXT, /* 0x12 */ - SQLITE_NULL, /* 0x13 */ - SQLITE_INTEGER, /* 0x14 */ - SQLITE_NULL, /* 0x15 */ - SQLITE_INTEGER, /* 0x16 */ - SQLITE_NULL, /* 0x17 */ - SQLITE_FLOAT, /* 0x18 */ - SQLITE_NULL, /* 0x19 */ - SQLITE_FLOAT, /* 0x1a */ - SQLITE_NULL, /* 0x1b */ - SQLITE_INTEGER, /* 0x1c */ - SQLITE_NULL, /* 0x1d */ - SQLITE_INTEGER, /* 0x1e */ - SQLITE_NULL, /* 0x1f */ - }; - return aType[pVal->flags&MEM_AffMask]; -} - -/* 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; - pCtx->fErrorOrAux = 1; - 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; - pCtx->fErrorOrAux = 1; - 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; - pCtx->fErrorOrAux = 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; - pCtx->fErrorOrAux = 1; - 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; - pCtx->fErrorOrAux = 1; - sqlite3OomFault(pCtx->pOut->db); -} - -/* -** 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; - 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 ){ - db->u1.isInterrupted = 0; - } - - assert( db->nVdbeWrite>0 || db->autoCommit==0 - || (db->nDeferredCons==0 && db->nDeferredImmCons==0) - ); - -#ifndef SQLITE_OMIT_TRACE - if( (db->xProfile || (db->mTrace & SQLITE_TRACE_PROFILE)!=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--; - } - -#ifndef SQLITE_OMIT_TRACE - /* If the statement completed successfully, invoke the profile callback */ - if( rc!=SQLITE_ROW ) 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; - } - } - - db->errCode = rc; - if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){ - p->rc = SQLITE_NOMEM_BKPT; - } -end_of_step: - /* At this point local variable rc holds the value that should be - ** returned if this statement was compiled using the legacy - ** sqlite3_prepare() interface. According to the docs, this can only - ** be one of the values in the first assert() below. Variable p->rc - ** contains the value that would be returned if sqlite3_finalize() - ** were called on statement p. - */ - assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR - || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE - ); - assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp ); - if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 - && rc!=SQLITE_ROW - && rc!=SQLITE_DONE - ){ - /* 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); - } - 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; -} - -/* -** 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_STAT3_OR_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; -} - -/* -** 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. -*/ -SQLITE_PRIVATE 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 = context->pFunc->zName; - 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); -} - -/* -** 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_STAT3_OR_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_STAT3_OR_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->fErrorOrAux==0 ){ - pCtx->isError = 0; - pCtx->fErrorOrAux = 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, - /* .pFiller = */ (void*)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, - int N, - const void *(*xFunc)(Mem*), - int useType -){ - 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 ); - ret = xFunc(&p->aColName[N]); - /* A malloc may have failed inside of the xFunc() 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, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME); -} -#ifndef SQLITE_OMIT_UTF16 -SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){ - return columnName( - pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, 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, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE); -} -#ifndef SQLITE_OMIT_UTF16 -SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){ - return columnName( - pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, 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, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE); -} -#ifndef SQLITE_OMIT_UTF16 -SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){ - return columnName( - pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, 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, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE); -} -#ifndef SQLITE_OMIT_UTF16 -SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){ - return columnName( - pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, 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, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN); -} -#ifndef SQLITE_OMIT_UTF16 -SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){ - return columnName( - pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, 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; - sqlite3Error(p->db, 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-48440-37595 If the specific value bound to 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 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 ){ - (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_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 = sqlite3ColumnOfIndex(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 ){ - 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 = sqlite3ColumnOfIndex(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 ); - sqlite3StrAccumAppend(&out, "-- ", 3); - assert( (zRawSql - zStart) > 0 ); - sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart)); - } - }else if( p->nVar==0 ){ - sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql)); - }else{ - while( zRawSql[0] ){ - n = findNextHostParameter(zRawSql, &nToken); - assert( n>0 ); - sqlite3StrAccumAppend(&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 ){ - sqlite3StrAccumAppend(&out, "NULL", 4); - }else if( pVar->flags & MEM_Int ){ - sqlite3XPrintf(&out, "%lld", pVar->u.i); - }else if( pVar->flags & MEM_Real ){ - sqlite3XPrintf(&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 = STRACCUM_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 - sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z); -#ifdef SQLITE_TRACE_SIZE_LIMIT - if( nOutn ){ - sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut); - } -#endif -#ifndef SQLITE_OMIT_UTF16 - if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8); -#endif - }else if( pVar->flags & MEM_Zero ){ - sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero); - }else{ - int nOut; /* Number of bytes of the blob to include in output */ - assert( pVar->flags & MEM_Blob ); - sqlite3StrAccumAppend(&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); - } - sqlite3StrAccumAppend(&out, "'", 1); -#ifdef SQLITE_TRACE_SIZE_LIMIT - if( nOutn ){ - sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut); - } -#endif - } - } - } - if( out.accError ) sqlite3StrAccumReset(&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 - -/* -** 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 an integer, 2 or 3, that indices how many different ways the -** branch can go. It is usually 2. "I" is the direction the branch -** goes. 0 means falls through. 1 means branch is taken. 2 means the -** second alternative branch is taken. -** -** iSrcLine is the source code line (from the __LINE__ macro) that -** generated the VDBE instruction. This instrumentation assumes that all -** source code is in a single file (the amalgamation). Special values 1 -** and 2 for the iSrcLine parameter mean that this particular branch is -** always taken or never taken, respectively. -*/ -#if !defined(SQLITE_VDBE_COVERAGE) -# define VdbeBranchTaken(I,M) -#else -# define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M) - static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){ - if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){ - M = iSrcLine; - /* Assert the truth of VdbeCoverageAlwaysTaken() and - ** VdbeCoverageNeverTaken() */ - assert( (M & I)==I ); - }else{ - if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/ - sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg, - iSrcLine,I,M); - } - } -#endif - -/* -** Convert the given register into a string if it isn't one -** already. Return non-zero if a malloc() fails. -*/ -#define Stringify(P, enc) \ - if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \ - { goto no_mem; } - -/* -** 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*/ - 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; -} - -/* -** 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; - i64 iValue; - u8 enc = pRec->enc; - assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str ); - if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return; - if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){ - pRec->u.i = iValue; - pRec->flags |= MEM_Int; - }else{ - pRec->u.r = rValue; - pRec->flags |= MEM_Real; - if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec); - } -} - -/* -** 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: -** 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)) ){ - sqlite3VdbeMemStringify(pRec, enc, 1); - } - } - pRec->flags &= ~(MEM_Real|MEM_Int); - } -} - -/* -** 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){ - assert( (pMem->flags & (MEM_Int|MEM_Real))==0 ); - assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ); - if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){ - return 0; - } - if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==0 ){ - 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) ){ - return pMem->flags & (MEM_Int|MEM_Real); - } - if( pMem->flags & (MEM_Str|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, char *zBuf){ - char *zCsr = zBuf; - 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'; - } - *(zCsr++) = c; - sqlite3_snprintf(100, zCsr, "%d[", pMem->n); - zCsr += sqlite3Strlen30(zCsr); - for(i=0; i<16 && in; i++){ - sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF)); - zCsr += sqlite3Strlen30(zCsr); - } - for(i=0; i<16 && in; i++){ - char z = pMem->z[i]; - if( z<32 || z>126 ) *zCsr++ = '.'; - else *zCsr++ = z; - } - *(zCsr++) = ']'; - if( f & MEM_Zero ){ - sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero); - zCsr += sqlite3Strlen30(zCsr); - } - *zCsr = '\0'; - }else if( f & MEM_Str ){ - int j, k; - zBuf[0] = ' '; - if( f & MEM_Dyn ){ - zBuf[1] = 'z'; - assert( (f & (MEM_Static|MEM_Ephem))==0 ); - }else if( f & MEM_Static ){ - zBuf[1] = 't'; - assert( (f & (MEM_Dyn|MEM_Ephem))==0 ); - }else if( f & MEM_Ephem ){ - zBuf[1] = 'e'; - assert( (f & (MEM_Static|MEM_Dyn))==0 ); - }else{ - zBuf[1] = 's'; - } - k = 2; - sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n); - k += sqlite3Strlen30(&zBuf[k]); - zBuf[k++] = '['; - for(j=0; j<15 && jn; j++){ - u8 c = pMem->z[j]; - if( c>=0x20 && c<0x7f ){ - zBuf[k++] = c; - }else{ - zBuf[k++] = '.'; - } - } - zBuf[k++] = ']'; - sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]); - k += sqlite3Strlen30(&zBuf[k]); - zBuf[k++] = 0; - } -} -#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(" NULL"); - }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){ - printf(" si:%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:%g", p->u.r); -#endif - }else if( p->flags & MEM_RowSet ){ - printf(" (rowset)"); - }else{ - char zBuf[200]; - sqlite3VdbeMemPrettyPrint(p, zBuf); - printf(" %s", zBuf); - } - if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype); -} -static void registerTrace(int iReg, Mem *p){ - printf("REG[%d] = ", iReg); - memTracePrint(p); - printf("\n"); - sqlite3VdbeCheckMemInvariants(p); -} -#endif - -#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 class CPUs. -*/ -#ifndef SQLITE_HWTIME_H -#define SQLITE_HWTIME_H - -/* -** The following routine only works on pentium-class (or newer) processors. -** It uses the RDTSC opcode to read the cycle count value out of the -** processor and returns that value. This can be used for high-res -** profiling. -*/ -#if (defined(__GNUC__) || defined(_MSC_VER)) && \ - (defined(i386) || defined(__i386__) || defined(_M_IX86)) - - #if defined(__GNUC__) - - __inline__ sqlite_uint64 sqlite3Hwtime(void){ - unsigned int lo, hi; - __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi)); - return (sqlite_uint64)hi << 32 | lo; - } - - #elif defined(_MSC_VER) - - __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){ - __asm { - rdtsc - ret ; return value at EDX:EAX - } - } - - #endif - -#elif (defined(__GNUC__) && defined(__x86_64__)) - - __inline__ sqlite_uint64 sqlite3Hwtime(void){ - unsigned long val; - __asm__ __volatile__ ("rdtsc" : "=A" (val)); - return val; - } - -#elif (defined(__GNUC__) && defined(__ppc__)) - - __inline__ sqlite_uint64 sqlite3Hwtime(void){ - unsigned long long retval; - unsigned long junk; - __asm__ __volatile__ ("\n\ - 1: mftbu %1\n\ - mftb %L0\n\ - mftbu %0\n\ - cmpw %0,%1\n\ - bne 1b" - : "=r" (retval), "=r" (junk)); - return retval; - } - -#else - - #error Need implementation of sqlite3Hwtime() for your platform. - - /* - ** To compile without implementing sqlite3Hwtime() for your platform, - ** you can remove the above #error and use the following - ** stub function. You will lose timing support for many - ** of the debugging and testing utilities, but it should at - ** least compile and run. - */ -SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); } - -#endif - -#endif /* !defined(SQLITE_HWTIME_H) */ - -/************** End of hwtime.h **********************************************/ -/************** Continuing where we left off in 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 */ - unsigned nVmStep = 0; /* Number of virtual machine steps */ -#ifndef SQLITE_OMIT_PROGRESS_CALLBACK - unsigned 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); - 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 ); - assert( p->bIsReader || p->readOnly!=0 ); - p->iCurrentTime = 0; - assert( p->explain==0 ); - p->pResultSet = 0; - db->busyHandler.nBusy = 0; - if( db->u1.isInterrupted ) goto abort_due_to_interrupt; - sqlite3VdbeIOTraceSql(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 = 0xffffffff; - } -#endif -#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 = 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); - } -#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 */ -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( 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. - */ - if( nVmStep>=nProgressLimit && db->xProgress!=0 ){ - assert( db->nProgressOps!=0 ); - nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps); - if( db->xProgress(db->pProgressArg) ){ - 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]; - if( (pIn3->flags & MEM_Null)==0 ) break; - /* Fall through into OP_Halt */ -} - -/* 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); - 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->opcode = OP_String; - 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( 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; - } - testcase( rc==SQLITE_TOOBIG ); -#endif - if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ - goto too_big; - } - assert( rc==SQLITE_OK ); - /* Fall through to the next case, OP_String */ -} - -/* 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; - 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]; - sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static); - 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 - if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrompScopyFrom += pOp->p2 - p1; - } -#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 ){ - 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 - if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1; -#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 ); - -#ifndef SQLITE_OMIT_PROGRESS_CALLBACK - /* Run the progress counter just before returning. - */ - if( db->xProgress!=0 - && nVmStep>=nProgressLimit - && db->xProgress(db->pProgressArg)!=0 - ){ - rc = SQLITE_INTERRUPT; - goto abort_due_to_error; - } -#endif - - /* 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]); - } - if( db->mallocFailed ) goto no_mem; - - if( db->mTrace & SQLITE_TRACE_ROW ){ - db->xTrace(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; - - pIn1 = &aMem[pOp->p1]; - pIn2 = &aMem[pOp->p2]; - pOut = &aMem[pOp->p3]; - assert( pIn1!=pOut ); - if( (pIn1->flags | pIn2->flags) & MEM_Null ){ - sqlite3VdbeMemSetNull(pOut); - break; - } - if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem; - Stringify(pIn1, encoding); - Stringify(pIn2, encoding); - nByte = pIn1->n + pIn2->n; - if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){ - goto too_big; - } - if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){ - goto no_mem; - } - MemSetTypeFlag(pOut, MEM_Str); - if( pOut!=pIn2 ){ - memcpy(pOut->z, pIn2->z, pIn2->n); - } - memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n); - pOut->z[nByte]=0; - pOut->z[nByte+1] = 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 */ - char bIntint; /* Started out as two integer operands */ - 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; - bIntint = 1; - 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{ - bIntint = 0; -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 = (i64)rA; - iB = (i64)rB; - 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); - if( ((type1|type2)&MEM_Real)==0 && !bIntint ){ - sqlite3VdbeIntegerAffinity(pOut); - } -#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); - VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2); - if( (pIn1->flags & MEM_Int)==0 ){ - if( pOp->p2==0 ){ - rc = SQLITE_MISMATCH; - goto abort_due_to_error; - }else{ - goto jump_to_p2; - } - } - } - 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 ){ - sqlite3VdbeMemRealify(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); - sqlite3VdbeMemCast(pIn1, pOp->p2, encoding); - UPDATE_MAX_BLOBSIZE(pIn1); - if( rc ) goto abort_due_to_error; - 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( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne ); - assert( (flags1 & MEM_Cleared)==0 ); - assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 ); - if( (flags1&flags3&MEM_Null)!=0 - && (flags3&MEM_Cleared)==0 - ){ - res = 0; /* Operands are equal */ - }else{ - res = 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_Real|MEM_Str))==MEM_Str ){ - applyNumericAffinity(pIn1,0); - testcase( flags3!=pIn3->flags ); /* Possible if pIn1==pIn3 */ - flags3 = pIn3->flags; - } - if( (flags3 & (MEM_Int|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))!=0 ){ - testcase( pIn1->flags & MEM_Int ); - testcase( pIn1->flags & MEM_Real ); - sqlite3VdbeMemStringify(pIn1, encoding, 1); - testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) ); - flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask); - assert( pIn1!=pIn3 ); - } - if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){ - testcase( pIn3->flags & MEM_Int ); - testcase( pIn3->flags & MEM_Real ); - 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( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) ); - pIn1->flags = flags1; - assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) ); - pIn3->flags = flags3; - - 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(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3); - if( res2 ){ - goto jump_to_p2; - } - } - break; -} - -/* Opcode: ElseNotEq * P2 * * * -** -** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator. -** If result of an OP_Eq comparison on the same two operands -** would have be 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 */ - assert( pOp>aOp ); - assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt ); - assert( pOp[-1].p5 & SQLITE_STOREP2 ); - 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; - int idx; - CollSeq *pColl; /* Collating sequence to use on this term */ - int bRev; /* True for DESCENDING sort order */ - int *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; kmx ) 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->aSortOrder[i]; - iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl); - if( 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,3); pOp = &aOp[pOp->p1 - 1]; - }else if( iCompare==0 ){ - VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1]; - }else{ - VdbeBranchTaken(2,3); 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 */ - - pIn1 = &aMem[pOp->p1]; - if( pIn1->flags & MEM_Null ){ - v1 = 2; - }else{ - v1 = sqlite3VdbeIntValue(pIn1)!=0; - } - pIn2 = &aMem[pOp->p2]; - if( pIn2->flags & MEM_Null ){ - v2 = 2; - }else{ - v2 = sqlite3VdbeIntValue(pIn2)!=0; - } - 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: 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]; - sqlite3VdbeMemSetNull(pOut); - if( (pIn1->flags & MEM_Null)==0 ){ - pOut->flags = MEM_Int; - pOut->u.i = !sqlite3VdbeIntValue(pIn1); - } - break; -} - -/* Opcode: BitNot P1 P2 * * * -** Synopsis: r[P1]= ~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. -*/ -/* 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_If: /* jump, in1 */ -case OP_IfNot: { /* jump, in1 */ - int c; - pIn1 = &aMem[pOp->p1]; - if( pIn1->flags & MEM_Null ){ - c = pOp->p3; - }else{ -#ifdef SQLITE_OMIT_FLOATING_POINT - c = sqlite3VdbeIntValue(pIn1)!=0; -#else - c = sqlite3VdbeRealValue(pIn1)!=0.0; -#endif - if( pOp->opcode==OP_IfNot ) c = !c; - } - 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; -} - -/* 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_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor, -** then the cache of the cursor is reset prior to extracting the column. -** The first OP_Column against a pseudo-table after the value of the content -** register has changed should have this bit set. -** -** 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: { - int 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 */ - - pC = p->apCsr[pOp->p1]; - p2 = 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( pOp->p1>=0 && pOp->p1nCursor ); - assert( pC!=0 ); - assert( p2nField ); - 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 = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, 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( (t = zHdr[0])<0x80 ){ - zHdr++; - offset64 += sqlite3VdbeOneByteSerialTypeLen(t); - }else{ - zHdr += sqlite3GetVarint32(zHdr, &t); - offset64 += sqlite3VdbeSerialTypeLen(t); - } - pC->aType[i++] = t; - aOffset[i] = (u32)(offset64 & 0xffffffff); - }while( 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 up to 16. So 16 bytes of bogus content is supplied. - */ - static u8 aZero[16]; /* This is the bogus content */ - sqlite3VdbeSerialGet(aZero, 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]; - do{ - assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] ); - assert( memIsValid(pIn1) ); - applyAffinity(pIn1, *(zAffinity++), encoding); - pIn1++; - }while( zAffinity[0] ); - 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. -*/ -case OP_MakeRecord: { - u8 *zNewRecord; /* A buffer to hold the data for the new record */ - 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 */ - int i; /* Space used in zNewRecord[] header */ - int j; /* Space used in zNewRecord[] content */ - u32 len; /* Length of a field */ - - /* 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++), encoding); - 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. - */ - pRec = pLast; - do{ - assert( memIsValid(pRec) ); - pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format, &len); - if( pRec->flags & MEM_Zero ){ - if( nData ){ - if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem; - }else{ - nZero += pRec->u.nZero; - len -= pRec->u.nZero; - } - } - nData += len; - testcase( serial_type==127 ); - testcase( serial_type==128 ); - nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(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( nVarintdb->aLimit[SQLITE_LIMIT_LENGTH] ){ - goto too_big; - } - - /* Make sure the output register has a buffer large enough to store - ** the new record. The output register (pOp->p3) 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( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){ - goto no_mem; - } - zNewRecord = (u8 *)pOut->z; - - /* Write the record */ - i = putVarint32(zNewRecord, nHdr); - j = 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. */ - i += putVarint32(&zNewRecord[i], serial_type); /* serial type */ - /* EVIDENCE-OF: R-64536-51728 The values for each column in the record - ** immediately follow the header. */ - j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */ - }while( (++pRec)<=pLast ); - assert( i==nHdr ); - assert( j==nByte ); - - assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) ); - pOut->n = (int)nByte; - pOut->flags = MEM_Blob; - if( nZero ){ - pOut->u.nZero = nZero; - pOut->flags |= MEM_Zero; - } - REGISTER_TRACE(pOp->p3, pOut); - UPDATE_MAX_BLOBSIZE(pOut); - break; -} - -/* Opcode: Count P1 P2 * * * -** Synopsis: r[P2]=count() -** -** Store the number of entries (an integer value) in the table or index -** opened by cursor P1 in register P2 -*/ -#ifndef SQLITE_OMIT_BTREECOUNT -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 ); - nEntry = 0; /* Not needed. Only used to silence a warning. */ - rc = sqlite3BtreeCount(pCrsr, &nEntry); - if( rc ) goto abort_due_to_error; - pOut = out2Prerelease(p, pOp); - pOut->u.i = nEntry; - break; -} -#endif - -/* 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, P1==0. To release (commit) an -** existing savepoint, P1==1, or to rollback an existing savepoint P1==2. -*/ -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{ - 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; - } - db->isTransactionSavepoint = 0; - rc = p->rc; - }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{ - 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); - sqlite3ResetAllSchemasOfConnection(db); - db->mDbFlags |= DBFLAG_SchemaChange; - } - } - - /* 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{ - 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; - } - assert( db->nStatement==0 ); - 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; - } - break; -} - -/* 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; - int iGen; - - 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); - 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( pOp->p2 && p->usesStmtJournal - && (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; - } - - /* Gather the schema version number for checking: - ** 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. - */ - sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta); - iGen = db->aDb[pOp->p1].pSchema->iGeneration; - }else{ - iGen = iMeta = 0; - } - assert( pOp->p5==0 || pOp->p4type==P4_INT32 ); - if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){ - 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 * * -** -** 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. -*/ -case OP_SetCookie: { - Db *pDb; - 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; - 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); - 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. -** -** If P5!=0 then use the content of register P2 as the root page, not -** the value of P2 itself. -** -** There will be a read lock on the database whenever there is an -** open cursor. If the database was unlocked prior to this instruction -** then a read lock is acquired as part of this instruction. A read -** lock allows other processes to read the database but prohibits -** any other process from modifying the database. The read lock is -** released when all cursors are closed. If this instruction attempts -** to get a read lock but fails, the script terminates with an -** SQLITE_BUSY error code. -** -** 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 -** structure, then said structure defines the content and collating -** sequence of the index being opened. Otherwise, if P4 is an integer -** value, it is set to the number of columns in the table. -** -** See also: OpenWrite, ReopenIdx -*/ -/* Opcode: ReopenIdx P1 P2 P3 P4 P5 -** Synopsis: root=P2 iDb=P3 -** -** The ReopenIdx opcode works exactly like ReadOpen except that it first -** checks to see if the cursor on P1 is already open with a root page -** number of P2 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 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. -** -** See the OpenRead opcode documentation for additional information. -*/ -/* 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 if P5!=0 use the content of register P2 to find the -** root page. -** -** 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 -** structure, then said structure defines the content and collating -** sequence of the index being opened. Otherwise, if P4 is an integer -** value, it is set to the number of columns in the table, or to the -** largest index of any column of the table that is actually used. -** -** This instruction works just like OpenRead except that it opens the cursor -** in read/write mode. For a given table, there can be one or more read-only -** cursors or a single read/write cursor but not both. -** -** See also OpenRead. -*/ -case OP_ReopenIdx: { - int nField; - KeyInfo *pKeyInfo; - int 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 ){ - rc = SQLITE_ABORT_ROLLBACK; - goto abort_due_to_error; - } - - nField = 0; - pKeyInfo = 0; - p2 = 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<=(p->nMem+1 - p->nCursor) ); - 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 ); -#ifdef SQLITE_ENABLE_CURSOR_HINTS - testcase( pOp->p2 & OPFLAG_SEEKEQ ); -#endif - 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->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; - rc = sqlite3BtreeCursor(pOrig->pBtx, MASTER_ROOT, 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. -** -** 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 = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE); - if( pCx==0 ) goto no_mem; - pCx->nullRow = 1; - 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); - } - 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 ){ - int pgno; - assert( pOp->p4type==P4_KEYINFO ); - rc = sqlite3BtreeCreateTable(pCx->pBtx, &pgno, BTREE_BLOBKEY | pOp->p5); - if( rc==SQLITE_OK ){ - assert( pgno==MASTER_ROOT+1 ); - assert( pKeyInfo->db==db ); - assert( pKeyInfo->enc==ENC(db) ); - rc = sqlite3BtreeCursor(pCx->pBtx, pgno, BTREE_WRCSR, - pKeyInfo, pCx->uc.pCursor); - } - pCx->isTable = 0; - }else{ - rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR, - 0, pCx->uc.pCursor); - pCx->isTable = 1; - } - } - if( rc ) goto abort_due_to_error; - pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED); - 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 always land on a record that equally equals the key, or -** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this -** opcode must be followed by an IdxLE opcode with the same arguments. -** The IdxLE opcode will be skipped if this opcode succeeds, but the -** IdxLE opcode will be used on subsequent loop iterations. -** -** 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 always land on a record that equally equals the key, or -** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this -** opcode must be followed by an IdxGE 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. -** -** See also: Found, NotFound, SeekGt, SeekGe, SeekLt -*/ -case OP_SeekLT: /* jump, in3 */ -case OP_SeekLE: /* jump, in3 */ -case OP_SeekGE: /* jump, in3 */ -case OP_SeekGT: { /* jump, in3 */ - 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 - - if( pC->isTable ){ - /* The 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]; - if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){ - applyNumericAffinity(pIn3, 0); - } - iKey = sqlite3VdbeIntValue(pIn3); - - /* If the P3 value could not be converted into an integer without - ** loss of information, then special processing is required... */ - if( (pIn3->flags & MEM_Int)==0 ){ - if( (pIn3->flags & MEM_Real)==0 ){ - /* If the P3 value cannot be converted into any kind of a number, - ** then the seek is not possible, so jump to P2 */ - VdbeBranchTaken(1,2); goto jump_to_p2; - break; - } - - /* 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 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[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; - } - } - pC->deferredMoveto = 0; - pC->cacheStatus = CACHE_STALE; -#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: 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 -*/ -/* 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_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]; - if( (pIn3->flags & MEM_Int)==0 ){ - applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding); - if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2; - } - /* Fall through into OP_NotExists */ -case OP_NotExists: /* jump, in3 */ - pIn3 = &aMem[pOp->p3]; - assert( pIn3->flags & MEM_Int ); - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); -#ifdef SQLITE_DEBUG - pC->seekOp = 0; -#endif - assert( pC->isTable ); - assert( pC->eCurType==CURTYPE_BTREE ); - pCrsr = pC->uc.pCursor; - assert( pCrsr!=0 ); - res = 0; - iKey = pIn3->u.i; - 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->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. -*/ -/* Opcode: InsertInt P1 P2 P3 P4 P5 -** Synopsis: intkey=P3 data=r[P2] -** -** This works exactly like OP_Insert except that the key is the -** integer value P3, not the value of the integer stored in register P3. -*/ -case OP_Insert: -case OP_InsertInt: { - 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 */ - int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */ - BtreePayload x; /* Payload to be inserted */ - - op = 0; - 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->uc.pCursor!=0 ); - assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable ); - assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC ); - REGISTER_TRACE(pOp->p2, pData); - - if( pOp->opcode==OP_Insert ){ - pKey = &aMem[pOp->p3]; - assert( pKey->flags & MEM_Int ); - assert( memIsValid(pKey) ); - REGISTER_TRACE(pOp->p3, pKey); - x.nKey = pKey->u.i; - }else{ - assert( pOp->opcode==OP_InsertInt ); - x.nKey = pOp->p3; - } - - 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) ); - op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT); - }else{ - pTab = 0; /* Not needed. Silence a compiler warning. */ - zDb = 0; /* Not needed. Silence a compiler warning. */ - } - -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK - /* Invoke the pre-update hook, if any */ - if( db->xPreUpdateCallback - && pOp->p4type==P4_TABLE - && !(pOp->p5 & OPFLAG_ISUPDATE) - ){ - sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey, pOp->p2); - } - 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( db->xUpdateCallback && op ){ - db->xUpdateCallback(db->pUpdateArg, op, 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 ); - -#ifdef SQLITE_DEBUG - if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){ - /* 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( 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 ephermeral 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 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) ); -#if 0 /* Not required due to the previous to assert() statements */ - rc = sqlite3VdbeCursorMoveto(pC); - if( rc!=SQLITE_OK ) goto abort_due_to_error; -#endif - - n = sqlite3BtreePayloadSize(pCrsr); - if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){ - goto too_big; - } - testcase( n==0 ); - rc = sqlite3VdbeMemFromBtree(pCrsr, 0, 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); - } - 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 */ -} -/* 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 ); - 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, NextIfOpen -*/ -/* Opcode: NextIfOpen P1 P2 P3 P4 P5 -** -** This opcode works just like Next except that if cursor P1 is not -** open it behaves a no-op. -*/ -/* 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: PrevIfOpen P1 P2 P3 P4 P5 -** -** This opcode works just like Prev except that if cursor P1 is not -** open it behaves a no-op. -*/ -/* 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_PrevIfOpen: /* jump */ -case OP_NextIfOpen: /* jump */ - if( p->apCsr[pOp->p1]==0 ) break; - /* Fall through */ -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 ); - assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext ); - assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious); - - /* The Next opcode is only used after SeekGT, SeekGE, and Rewind. - ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */ - assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen - || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE - || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found); - assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen - || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE - || pC->seekOp==OP_Last ); - - 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. -*/ -/* 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 */ -case OP_IdxInsert: { /* in2 */ - VdbeCursor *pC; - BtreePayload x; - - assert( pOp->p1>=0 && pOp->p1nCursor ); - pC = p->apCsr[pOp->p1]; - assert( pC!=0 ); - assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) ); - pIn2 = &aMem[pOp->p2]; - assert( pIn2->flags & MEM_Blob ); - if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++; - assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert ); - assert( pC->isTable==0 ); - rc = ExpandBlob(pIn2); - if( rc ) goto abort_due_to_error; - if( pOp->opcode==OP_SorterInsert ){ - rc = sqlite3VdbeSorterWrite(pC, pIn2); - }else{ - 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: IdxDelete P1 P2 P3 * * -** 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. -*/ -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 ); - pCrsr = pC->uc.pCursor; - assert( pCrsr!=0 ); - assert( pOp->p5==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; - } - 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: 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; iopcode&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; - - 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; - - nChange = 0; - assert( p->readOnly==0 ); - assert( DbMaskTest(p->btreeMask, pOp->p2) ); - rc = sqlite3BtreeClearTable( - db->aDb[pOp->p2].pBt, 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 a index or WITHOUT ROWID table. -** The root page number of the new b-tree is stored in register P2. -*/ -case OP_CreateBtree: { /* out2 */ - int pgno; - Db *pDb; - - 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: { - 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 SQLITE_MASTER table of database P1 -** that match the WHERE clause P4. -** -** 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 *zMaster; - 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) ); - /* Used to be a conditional */ { - zMaster = MASTER_NAME; - initData.db = db; - initData.iDb = pOp->p1; - initData.pzErrMsg = &p->zErrMsg; - zSql = sqlite3MPrintf(db, - "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid", - db->aDb[iDb].zDbSName, zMaster, pOp->p4.z); - if( zSql==0 ){ - rc = SQLITE_NOMEM_BKPT; - }else{ - assert( db->init.busy==0 ); - db->init.busy = 1; - initData.rc = SQLITE_OK; - assert( !db->mallocFailed ); - rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0); - if( rc==SQLITE_OK ) rc = initData.rc; - 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: { - 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: { - 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: { - 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.) */ - int *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]==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->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); - break; -} -#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_RowSet)==0 ){ - sqlite3VdbeMemSetRowSet(pIn1); - if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem; - } - sqlite3RowSetInsert(pIn1->u.pRowSet, 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]; - if( (pIn1->flags & MEM_RowSet)==0 - || sqlite3RowSetNext(pIn1->u.pRowSet, &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_RowSet)==0 ){ - sqlite3VdbeMemSetRowSet(pIn1); - if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem; - } - - assert( pOp->p4type==P4_INT32 ); - assert( iSet==-1 || iSet>=0 ); - if( iSet ){ - exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i); - VdbeBranchTaken(exists!=0,2); - if( exists ) goto jump_to_p2; - } - if( iSet>=0 ){ - sqlite3RowSetInsert(pIn1->u.pRowSet, 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_Frame)==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_Frame; - pRt->u.pFrame = pFrame; - - 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 - - pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem]; - for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){ - pMem->flags = MEM_Undefined; - pMem->db = db; - } - }else{ - pFrame = pRt->u.pFrame; - 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 - pOp = &aOp[-1]; - - break; -} - -/* 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: AggStep0 * P2 P3 P4 P5 -** Synopsis: accum=r[P3] step(r[P2@P5]) -** -** Execute the step 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: AggStep * P2 P3 P4 P5 -** Synopsis: accum=r[P3] step(r[P2@P5]) -** -** Execute the step function for an aggregate. The -** function has P5 arguments. P4 is a pointer to an sqlite3_context -** object that is used to run the function. Register P3 is -** as 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_AggStep0: { - 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, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*)); - if( pCtx==0 ) goto no_mem; - pCtx->pMem = 0; - pCtx->pFunc = pOp->p4.pFunc; - pCtx->iOp = (int)(pOp - aOp); - pCtx->pVdbe = p; - pCtx->argc = n; - pOp->p4type = P4_FUNCCTX; - pOp->p4.pCtx = pCtx; - pOp->opcode = OP_AggStep; - /* Fall through into OP_AggStep */ -} -case OP_AggStep: { - int i; - sqlite3_context *pCtx; - Mem *pMem; - Mem t; - - assert( pOp->p4type==P4_FUNCCTX ); - pCtx = pOp->p4.pCtx; - pMem = &aMem[pOp->p3]; - - /* 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++; - sqlite3VdbeMemInit(&t, db, MEM_Null); - pCtx->pOut = &t; - pCtx->fErrorOrAux = 0; - pCtx->skipFlag = 0; - (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */ - if( pCtx->fErrorOrAux ){ - if( pCtx->isError ){ - sqlite3VdbeError(p, "%s", sqlite3_value_text(&t)); - rc = pCtx->isError; - } - sqlite3VdbeMemRelease(&t); - if( rc ) goto abort_due_to_error; - }else{ - assert( t.flags==MEM_Null ); - } - if( pCtx->skipFlag ){ - assert( pOp[-1].opcode==OP_CollSeq ); - i = pOp[-1].p1; - if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1); - } - break; -} - -/* Opcode: AggFinal P1 P2 * P4 * -** Synopsis: accum=r[P1] N=P2 -** -** Execute the finalizer function for an aggregate. P1 is -** the memory location that is the accumulator for the aggregate. -** -** 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 degenerate case where -** the step function was not previously called. -*/ -case OP_AggFinal: { - Mem *pMem; - assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) ); - pMem = &aMem[pOp->p1]; - assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 ); - 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 * * * * -** -** 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. -*/ -case OP_Vacuum: { - assert( p->readOnly==0 ); - rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1); - 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 * * * * -** -** 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. -*/ -case OP_Expire: { - if( !pOp->p1 ){ - sqlite3ExpirePreparedStatements(db); - }else{ - p->expired = 1; - } - 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--; - 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 * * -** Synopsis: r[P3]=vcolumn(P2) -** -** Store the value of the P2-th column of -** the row of the virtual-table that the -** P1 cursor is pointing to into register P3. -*/ -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; - MemSetTypeFlag(pDest, MEM_Null); - rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2); - sqlite3VtabImportErrmsg(p, pVtab); - if( sContext.isError ){ - 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; - - 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); - 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 ); - 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: Function0 P1 P2 P3 P4 P5 -** Synopsis: r[P3]=func(r[P2@P5]) -** -** Invoke a user function (P4 is a pointer to a FuncDef object that -** defines the function) with P5 arguments taken from register P2 and -** successors. 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: Function, AggStep, AggFinal -*/ -/* Opcode: Function P1 P2 P3 P4 P5 -** Synopsis: r[P3]=func(r[P2@P5]) -** -** Invoke a user function (P4 is a pointer to an sqlite3_context object that -** contains a pointer to the function to be run) with P5 arguments taken -** from register P2 and successors. 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. -** -** SQL functions are initially coded as OP_Function0 with P4 pointing -** to a FuncDef object. But on first evaluation, the P4 operand is -** automatically converted into an sqlite3_context object and the operation -** changed to this OP_Function opcode. In this way, the initialization of -** the sqlite3_context object occurs only once, rather than once for each -** evaluation of the function. -** -** See also: Function0, AggStep, AggFinal -*/ -case OP_PureFunc0: -case OP_Function0: { - 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, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*)); - if( pCtx==0 ) goto no_mem; - pCtx->pOut = 0; - pCtx->pFunc = pOp->p4.pFunc; - pCtx->iOp = (int)(pOp - aOp); - pCtx->pVdbe = p; - pCtx->argc = n; - pOp->p4type = P4_FUNCCTX; - pOp->p4.pCtx = pCtx; - assert( OP_PureFunc == OP_PureFunc0+2 ); - assert( OP_Function == OP_Function0+2 ); - pOp->opcode += 2; - /* Fall through into OP_Function */ -} -case OP_PureFunc: -case OP_Function: { - 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->pOut = pOut; - for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i]; - } - - 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); - pCtx->fErrorOrAux = 0; - (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */ - - /* If the function returned an error, throw an exception */ - if( pCtx->fErrorOrAux ){ - if( pCtx->isError ){ - sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut)); - rc = pCtx->isError; - } - sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1); - 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: 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_Init: { /* jump */ - char *zTrace; - int i; - - /* 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 ); - assert( pOp==p->aOp ); /* Always instruction 0 */ - -#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 ){ - void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace; - char *z = sqlite3VdbeExpandSql(p, zTrace); - x(db->pTraceArg, z); - sqlite3_free(z); - }else -#endif - if( db->nVdbeExec>1 ){ - char *z = sqlite3MPrintf(db, "-- %s", zTrace); - (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z); - sqlite3DbFree(db, z); - }else{ - (void)db->xTrace(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 ){ - 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 */ - -/* 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 and 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 = 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]); - } - } -#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: - testcase( nVmStep>0 ); - 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( db->u1.isInterrupted ); - rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT; - p->rc = rc; - sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc)); - 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 ){ - db = p->db; - sqlite3_mutex_enter(db->mutex); - rc = sqlite3_finalize(p->pStmt); - sqlite3DbFree(db, p); - sqlite3_mutex_leave(db->mutex); - }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*2); - 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; - - getVarint32(&p1[1], n1); - getVarint32(&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{ - if( pTask->pSorter->pKeyInfo->aSortOrder[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->aSortOrder[0] ){ - 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) - ){ - 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 **aSlot; - SorterRecord *p; - int rc; - - rc = vdbeSortAllocUnpacked(pTask); - if( rc!=SQLITE_OK ) return rc; - - p = pList->pList; - pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter); - - aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *)); - if( !aSlot ){ - return SQLITE_NOMEM_BKPT; - } - - 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; i<64; i++){ - if( aSlot[i]==0 ) continue; - p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i]; - } - pList->pList = p; - - sqlite3_free(aSlot); - 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 = pTask->list.aMemory; - void *pCtx = (void*)pTask; - - assert( pTask->pThread==0 && pTask->bDone==0 ); - assert( pTask->list.pList==0 ); - assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 ); - - 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; - getVarint32((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; - int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory; - int nNew = pSorter->nMemory * 2; - 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; - 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 = pMerger->nTree; - - /* 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; - - 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 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 defined(SQLITE_ENABLE_ATOMIC_WRITE) \ - || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE) - if( (iAmt+iOfst)>p->endpoint.iOffset ){ - return SQLITE_IOERR_SHORT_READ; - } -#endif - - assert( (iAmt+iOfst)<=p->endpoint.iOffset ); - 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) ); - } - - p->pMethod = (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( p->pMethod==&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 */ - - -/* -** 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)) ){ - if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort; - assert( pExpr->x.pList==0 || pExpr->pRight==0 ); - if( pExpr->pRight ){ - pExpr = pExpr->pRight; - continue; - }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){ - if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort; - }else if( pExpr->x.pList ){ - if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort; - } - } - 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( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort; - 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( ALWAYS(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; -} - -/************** 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" */ - -/* -** 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. -*/ -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 ) return; - if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery); - if( pExpr->op==TK_COLLATE ){ - pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken); - } - ExprSetProperty(pDup, EP_Alias); - - /* 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; - } - sqlite3DbFree(db, pDup); -} - - -/* -** 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 sqlite3MatchSpanName( - const char *zSpan, - const char *zCol, - const char *zTab, - const char *zDb -){ - int n; - 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; -} - -/* -** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up -** that name in the set of source tables in pSrcList and make the pExpr -** expression node refer back to that source column. The following changes -** are made to pExpr: -** -** pExpr->iDb Set the index in db->aDb[] of the database X -** (even if X is implied). -** pExpr->iTable Set to the cursor number for the table obtained -** from pSrcList. -** pExpr->pTab Points to the Table structure of X.Y (even if -** X and/or Y are implied.) -** pExpr->iColumn Set to the column number within the table. -** pExpr->op Set to TK_COLUMN. -** pExpr->pLeft Any expression this points to is deleted -** pExpr->pRight Any expression this points to is deleted. -** -** The zDb variable is the name of the database (the "X"). This value may be -** NULL meaning that name is of the form Y.Z or Z. Any available database -** can be used. The zTable variable is the name of the table (the "Y"). This -** value can be NULL if zDb is also NULL. If zTable is NULL it -** means that the form of the name is Z and that columns from any table -** can be used. -** -** If the name cannot be resolved unambiguously, leave an error message -** in pParse and return WRC_Abort. Return WRC_Prune on success. -*/ -static int lookupName( - Parse *pParse, /* The parsing context */ - 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 isTrigger = 0; /* True if resolved to a trigger column */ - 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; - pExpr->pTab = 0; - 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; - } - } - } - } - - /* 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++){ - 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( sqlite3MatchSpanName(pEList->a[j].zSpan, 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( 0==(cntTab++) ){ - pMatch = pItem; - } - for(j=0, pCol=pTab->aCol; jnCol; j++, pCol++){ - if( 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->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->pTab->pSchema; - } - } /* if( pSrcList ) */ - -#ifndef SQLITE_OMIT_TRIGGER - /* If we have not already resolved the name, then maybe - ** it is a new.* or old.* trigger argument reference - */ - if( zDb==0 && zTab!=0 && cntTab==0 && 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; - }else{ - pTab = 0; - } - - if( pTab ){ - int iCol; - pSchema = pTab->pSchema; - cntTab++; - for(iCol=0, pCol=pTab->aCol; iColnCol; iCol++, pCol++){ - if( 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++; - if( iCol<0 ){ - pExpr->affinity = SQLITE_AFF_INTEGER; - }else if( pExpr->iTable==0 ){ - testcase( iCol==31 ); - testcase( iCol==32 ); - pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<iColumn = (i16)iCol; - pExpr->pTab = pTab; - isTrigger = 1; - } - } - } -#endif /* !defined(SQLITE_OMIT_TRIGGER) */ - - /* - ** Perhaps the name is a reference to the ROWID - */ - if( cnt==0 - && cntTab==1 - && pMatch - && (pNC->ncFlags & NC_IdxExpr)==0 - && sqlite3IsRowid(zCol) - && VisibleRowid(pMatch->pTab) - ){ - cnt = 1; - pExpr->iColumn = -1; - pExpr->affinity = SQLITE_AFF_INTEGER; - } - - /* - ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z - ** might refer to an result-set alias. This happens, for example, when - ** we are resolving names in the WHERE clause of the following command: - ** - ** SELECT a+b AS x FROM table WHERE x<10; - ** - ** In cases like this, replace pExpr with a copy of the expression that - ** forms the result set entry ("a+b" in the example) and return immediately. - ** Note that the expression in the result set should have already been - ** resolved by the time the WHERE clause is resolved. - ** - ** 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( (pEList = pNC->pEList)!=0 - && zTab==0 - && cnt==0 - ){ - for(j=0; jnExpr; j++){ - char *zAs = pEList->a[j].zName; - if( zAs!=0 && sqlite3StrICmp(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( 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 ); - 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 && ExprHasProperty(pExpr,EP_DblQuoted) ){ - pExpr->op = TK_STRING; - pExpr->pTab = 0; - 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. If the - ** column number is greater than the number of bits in the bitmask - ** then set the high-order bit of the bitmask. - */ - if( pExpr->iColumn>=0 && pMatch!=0 ){ - int n = pExpr->iColumn; - testcase( n==BMS-1 ); - if( n>=BMS ){ - n = BMS-1; - } - assert( pMatch->iCursor==pExpr->iTable ); - pMatch->colUsed |= ((Bitmask)1)<pLeft); - pExpr->pLeft = 0; - sqlite3ExprDelete(db, pExpr->pRight); - pExpr->pRight = 0; - pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN); - 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]; - p->pTab = pItem->pTab; - p->iTable = pItem->iCursor; - if( p->pTab->iPKey==iCol ){ - p->iColumn = -1; - }else{ - p->iColumn = (ynVar)iCol; - testcase( iCol==BMS ); - testcase( iCol==BMS-1 ); - pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol); - } - } - 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 */ -){ - assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 ); - if( (pNC->ncFlags & validMask)!=0 ){ - 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 - sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn); - } -} - -/* -** 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 ){ - -#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) - /* The special operator TK_ROW means use the rowid for the first - ** column in the FROM clause. This is used by the LIMIT and ORDER BY - ** clause processing on UPDATE and DELETE statements. - */ - case TK_ROW: { - SrcList *pSrcList = pNC->pSrcList; - struct SrcList_item *pItem; - assert( pSrcList && pSrcList->nSrc==1 ); - pItem = pSrcList->a; - pExpr->op = TK_COLUMN; - pExpr->pTab = pItem->pTab; - pExpr->iTable = pItem->iCursor; - pExpr->iColumn = -1; - pExpr->affinity = SQLITE_AFF_INTEGER; - break; - } -#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) - && !defined(SQLITE_OMIT_SUBQUERY) */ - - /* A 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{ - notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr); - pRight = pExpr->pRight; - if( pRight->op==TK_ID ){ - zDb = 0; - zTable = pExpr->pLeft->u.zToken; - zColumn = pRight->u.zToken; - }else{ - assert( pRight->op==TK_DOT ); - zDb = pExpr->pLeft->u.zToken; - zTable = pRight->pLeft->u.zToken; - zColumn = pRight->pRight->u.zToken; - } - } - return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr); - } - - /* Resolve function names - */ - case TK_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 */ - - 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|EP_Skip); - 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 */ - ExprSetProperty(pExpr,EP_ConstFunc); - } - if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){ - /* Date/time functions that use 'now', and other functions like - ** sqlite_version() that might change over time cannot be used - ** in an index. */ - notValid(pParse, pNC, "non-deterministic functions", - NC_IdxExpr|NC_PartIdx); - } - } - if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){ - sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId); - pNC->nErr++; - is_agg = 0; - }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++; - } - if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg; - sqlite3WalkExprList(pWalker, pList); - if( is_agg ){ - NameContext *pNC2 = pNC; - pExpr->op = TK_AGG_FUNCTION; - pExpr->op2 = 0; - while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){ - pExpr->op2++; - pNC2 = pNC2->pNext; - } - assert( pDef!=0 ); - if( pNC2 ){ - assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg ); - testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 ); - pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX); - - } - pNC->ncFlags |= NC_AllowAgg; - } - /* 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; - notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr); - 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: { - notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr); - break; - } - case TK_BETWEEN: - case TK_EQ: - case TK_NE: - case TK_LT: - case TK_LE: - case TK_GT: - case TK_GE: - case TK_IS: - case TK_ISNOT: { - 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++){ - char *zAs = pEList->a[i].zName; - if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ - return i+1; - } - } - } - return 0; -} - -/* -** pE is a pointer to an expression which is a single term in the -** ORDER BY of a compound SELECT. The expression has not been -** name resolved. -** -** At the point this routine is called, we already know that the -** ORDER BY term is not an integer index into the result set. That -** case is handled by the calling routine. -** -** Attempt to match pE against result set columns in the left-most -** SELECT statement. Return the index i of the matching column, -** as an indication to the caller that it should sort by the i-th column. -** The left-most column is 1. In other words, the value returned is the -** same integer value that would be used in the SQL statement to indicate -** the column. -** -** If there is no match, return 0. Return -1 if an error occurs. -*/ -static int resolveOrderByTermToExprList( - Parse *pParse, /* Parsing context for error messages */ - Select *pSelect, /* The SELECT statement with the ORDER BY clause */ - Expr *pE /* The specific ORDER BY term */ -){ - int i; /* 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.pEList = pEList; - nc.ncFlags = NC_AllowAgg; - nc.nErr = 0; - db = pParse->db; - savedSuppErr = db->suppressErr; - 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 = sqlite3ExprSkipCollate(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 ){ - pDup = sqlite3ExprDup(db, pE, 0); - if( !db->mallocFailed ){ - assert(pDup); - iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup); - } - 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 */ - 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 ) 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; -} - -/* -** 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 = sqlite3ExprSkipCollate(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 ){ - 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; - if( sqlite3ResolveExprNames(&sNC, p->pLimit) || - sqlite3ResolveExprNames(&sNC, p->pOffset) ){ - 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 ){ - 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; - sNC.pSrcList = p->pSrc; - sNC.pNext = pOuterNC; - - /* Resolve names in the result set. */ - if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort; - - /* If there are no aggregate functions in the result-set, and no GROUP BY - ** expression, do not allow aggregates in any of the other expressions. - */ - 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. - */ - sNC.pEList = p->pEList; - 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; - - /* 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; - } - - /* 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; - } - } - } - - /* 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. */ -){ - u16 savedHasAgg; - Walker w; - - if( pExpr==0 ) return SQLITE_OK; - savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg); - pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg); - 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 - if( pNC->ncFlags & NC_HasAgg ){ - ExprSetProperty(pExpr, EP_Agg); - } - 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; - if( pList ){ - for(i=0; inExpr; i++){ - if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort; - } - } - 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: -** -** * CHECK constraints -** * WHERE clauses on partial indices -** -** 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. -** -** Any errors cause an error message to be set in pParse. -*/ -SQLITE_PRIVATE void sqlite3ResolveSelfReference( - Parse *pParse, /* Parsing context */ - Table *pTab, /* The table being referenced */ - int type, /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */ - Expr *pExpr, /* Expression to resolve. May be NULL. */ - ExprList *pList /* Expression list to resolve. May be NUL. */ -){ - SrcList sSrc; /* Fake SrcList for pParse->pNewTable */ - NameContext sNC; /* Name context for pParse->pNewTable */ - - assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr ); - memset(&sNC, 0, sizeof(sNC)); - memset(&sSrc, 0, sizeof(sSrc)); - sSrc.nSrc = 1; - sSrc.a[0].zName = pTab->zName; - sSrc.a[0].pTab = pTab; - sSrc.a[0].iCursor = -1; - sNC.pParse = pParse; - sNC.pSrcList = &sSrc; - sNC.ncFlags = type; - if( sqlite3ResolveExprNames(&sNC, pExpr) ) return; - if( pList ) sqlite3ResolveExprListNames(&sNC, pList); -} - -/************** 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(Expr *pExpr){ - int op; - pExpr = sqlite3ExprSkipCollate(pExpr); - if( pExpr->flags & EP_Generic ) return 0; - op = pExpr->op; - if( op==TK_SELECT ){ - assert( pExpr->flags&EP_xIsSelect ); - 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->pTab ){ - return sqlite3TableColumnAffinity(pExpr->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 - ); - } - return pExpr->affinity; -} - -/* -** 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 and any unlikely() -** or likelihood() function at the root of an expression. -*/ -SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){ - while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){ - 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 = 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, Expr *pExpr){ - sqlite3 *db = pParse->db; - CollSeq *pColl = 0; - Expr *p = pExpr; - while( p ){ - int op = p->op; - if( p->flags & EP_Generic ) break; - if( op==TK_CAST || op==TK_UPLUS ){ - p = p->pLeft; - continue; - } - if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){ - pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken); - break; - } - if( (op==TK_AGG_COLUMN || op==TK_COLUMN - || op==TK_REGISTER || op==TK_TRIGGER) - && p->pTab!=0 - ){ - /* op==TK_REGISTER && p->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->pTab->aCol[j].zColl; - pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); - } - 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 ); - /* p->flags holds EP_Collate and p->pLeft->flags does not. And - ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at - ** least one EP_Collate. Thus the following two ALWAYS. */ - if( p->x.pList!=0 && 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, 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, Expr *pE1, 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(Expr *pExpr, char aff2){ - char aff1 = sqlite3ExprAffinity(pExpr); - if( aff1 && aff2 ){ - /* 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 if( !aff1 && !aff2 ){ - /* Neither side of the comparison is a column. Compare the - ** results directly. - */ - return SQLITE_AFF_BLOB; - }else{ - /* One side is a column, the other is not. Use the columns affinity. */ - assert( aff1==0 || aff2==0 ); - return (aff1 + aff2); - } -} - -/* -** pExpr is a comparison operator. Return the type affinity that should -** be applied to both operands prior to doing the comparison. -*/ -static char comparisonAffinity(Expr *pExpr){ - char aff; - 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(Expr *pExpr, char idx_affinity){ - char aff = comparisonAffinity(pExpr); - switch( aff ){ - case SQLITE_AFF_BLOB: - return 1; - case SQLITE_AFF_TEXT: - return idx_affinity==SQLITE_AFF_TEXT; - default: - return sqlite3IsNumericAffinity(idx_affinity); - } -} - -/* -** Return the P5 value that should be used for a binary comparison -** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2. -*/ -static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){ - u8 aff = (char)sqlite3ExprAffinity(pExpr2); - aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull; - return aff; -} - -/* -** Return a pointer to the collation sequence that should be used by -** a binary comparison operator comparing pLeft and pRight. -** -** If the left hand expression has a collating sequence type, then it is -** used. Otherwise the collation sequence for the right hand expression -** is used, or the default (BINARY) if neither expression has a collating -** type. -** -** Argument pRight (but not pLeft) may be a null pointer. In this case, -** it is not considered. -*/ -SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq( - Parse *pParse, - Expr *pLeft, - Expr *pRight -){ - CollSeq *pColl; - assert( pLeft ); - if( pLeft->flags & 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; -} - -/* -** Generate code for a comparison operator. -*/ -static int codeCompare( - Parse *pParse, /* The parsing (and code generating) context */ - Expr *pLeft, /* The left operand */ - Expr *pRight, /* The right operand */ - int opcode, /* The comparison opcode */ - int in1, int in2, /* Register holding operands */ - int dest, /* Jump here if true. */ - int jumpIfNull /* If true, jump if either operand is NULL */ -){ - int p5; - int addr; - CollSeq *p4; - - p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight); - p5 = binaryCompareP5(pLeft, pRight, jumpIfNull); - addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1, - (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); - } - 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, 0, 0); - } -#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(v); - - 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 ) sqlite3ExprCachePush(pParse); - r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, ®Free1); - r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, ®Free2); - codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5); - 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); - testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); - testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq); - testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne); - sqlite3ReleaseTempReg(pParse, regFree1); - sqlite3ReleaseTempReg(pParse, regFree2); - if( i>0 ) sqlite3ExprCachePop(pParse); - if( i==nLeft-1 ){ - break; - } - if( opx==TK_EQ ){ - sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v); - p5 |= SQLITE_KEEPNULL; - }else if( opx==TK_NE ){ - sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v); - p5 |= SQLITE_KEEPNULL; - }else{ - assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE ); - sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone); - VdbeCoverageIf(v, op==TK_LT); - VdbeCoverageIf(v, op==TK_GT); - VdbeCoverageIf(v, op==TK_LE); - VdbeCoverageIf(v, op==TK_GE); - if( i==nLeft-2 ) opx = op; - } - } - sqlite3VdbeResolveLabel(v, addrDone); -} - -#if SQLITE_MAX_EXPR_DEPTH>0 -/* -** Check that argument nHeight is less than or equal to the maximum -** expression depth allowed. If it is not, leave an error message in -** pParse. -*/ -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 *p, int *pnHeight){ - if( p ){ - heightOfExpr(p->pWhere, pnHeight); - heightOfExpr(p->pHaving, pnHeight); - heightOfExpr(p->pLimit, pnHeight); - heightOfExpr(p->pOffset, pnHeight); - heightOfExprList(p->pEList, pnHeight); - heightOfExprList(p->pGroupBy, pnHeight); - heightOfExprList(p->pOrderBy, pnHeight); - heightOfSelect(p->pPrior, 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; - 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]) ){ - if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted; - sqlite3Dequote(pNew->u.zToken); - } - } - } -#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; - if( op==TK_AND && pParse->nErr==0 ){ - /* Take advantage of short-circuit false optimization for AND */ - p = sqlite3ExprAnd(pParse->db, pLeft, pRight); - }else{ - p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)); - if( p ){ - memset(p, 0, sizeof(Expr)); - p->op = op & TKFLG_MASK; - p->iAgg = -1; - } - sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight); - } - if( p ) { - sqlite3ExprCheckHeight(pParse, p->nHeight); - } - 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); - } -} - - -/* -** If the expression is always either TRUE or FALSE (respectively), -** then return 1. If one cannot determine the truth value of the -** expression at compile-time return 0. -** -** This is an optimization. If is OK to return 0 here even if -** the expression really is always false or false (a false negative). -** But it is a bug to return 1 if the expression might have different -** boolean values in different circumstances (a false positive.) -** -** Note that if the expression is part of conditional for a -** LEFT JOIN, then we cannot determine at compile-time whether or not -** is it true or false, so always return 0. -*/ -static int exprAlwaysTrue(Expr *p){ - int v = 0; - if( ExprHasProperty(p, EP_FromJoin) ) return 0; - if( !sqlite3ExprIsInteger(p, &v) ) return 0; - return v!=0; -} -static int exprAlwaysFalse(Expr *p){ - int v = 0; - if( ExprHasProperty(p, EP_FromJoin) ) return 0; - if( !sqlite3ExprIsInteger(p, &v) ) return 0; - return v==0; -} - -/* -** 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(sqlite3 *db, Expr *pLeft, Expr *pRight){ - if( pLeft==0 ){ - return pRight; - }else if( pRight==0 ){ - return pLeft; - }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){ - sqlite3ExprDelete(db, pLeft); - sqlite3ExprDelete(db, pRight); - return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0); - }else{ - Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0); - sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight); - return pNew; - } -} - -/* -** Construct a new expression node for a function with multiple -** arguments. -*/ -SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){ - 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; - } - pNew->x.pList = pList; - assert( !ExprHasProperty(pNew, EP_xIsSelect) ); - sqlite3ExprSetHeightAndFlags(pParse, pNew); - return pNew; -} - -/* -** Assign a variable number to an expression that encodes a wildcard -** in the original SQL statement. -** -** Wildcards consisting of a single "?" are assigned the next sequential -** variable number. -** -** Wildcards of the form "?nnn" are assigned the number "nnn". We make -** sure "nnn" is not too 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 ); -#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 ){ - sqlite3ExprDeleteNN(db, p->pRight); - }else if( ExprHasProperty(p, EP_xIsSelect) ){ - sqlite3SelectDelete(db, p->x.pSelect); - }else{ - sqlite3ExprListDelete(db, p->x.pList); - } - } - 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); -} - -/* -** Return the number of bytes allocated for the expression structure -** passed as the first argument. This is always one of EXPR_FULLSIZE, -** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE. -*/ -static int exprStructSize(Expr *p){ - if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE; - if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE; - return EXPR_FULLSIZE; -} - -/* -** The dupedExpr*Size() routines each return the number of bytes required -** to store a copy of an expression or expression tree. They differ in -** how much of the tree is measured. -** -** dupedExprStructSize() Size of only the Expr structure -** dupedExprNodeSize() Size of Expr + space for token -** dupedExprSize() Expr + token + subtree components -** -*************************************************************************** -** -** The dupedExprStructSize() function returns two values OR-ed together: -** (1) the space required for a copy of the Expr structure only and -** (2) the EP_xxx flags that indicate what the structure size should be. -** The return values is always one of: -** -** EXPR_FULLSIZE -** EXPR_REDUCEDSIZE | EP_Reduced -** EXPR_TOKENONLYSIZE | EP_TokenOnly -** -** The size of the structure can be found by masking the return value -** of this routine with 0xfff. The flags can be found by masking the -** return value with EP_Reduced|EP_TokenOnly. -** -** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size -** (unreduced) Expr objects as they or originally constructed by the parser. -** During expression analysis, extra information is computed and moved into -** later parts of teh Expr object and that extra information might get chopped -** off if the expression is reduced. Note also that it does not work to -** make 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 ){ - nSize = EXPR_FULLSIZE; - }else{ - assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); - assert( !ExprHasProperty(p, EP_FromJoin) ); - assert( !ExprHasProperty(p, EP_MemToken) ); - assert( !ExprHasProperty(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 += sqlite3Strlen30(p->u.zToken)+1; - } - return ROUND8(nByte); -} - -/* -** Return the number of bytes required to create a duplicate of the -** expression passed as the first argument. The second argument is a -** mask containing EXPRDUP_XXX flags. -** -** The value returned includes space to create a copy of the Expr struct -** itself and the buffer referred to by Expr.u.zToken, if any. -** -** If the EXPRDUP_REDUCE flag is set, then the return value includes -** space to duplicate all Expr nodes in the tree formed by Expr.pLeft -** and Expr.pRight variables (but not for any structures pointed to or -** descended from the Expr.x.pList or Expr.x.pSelect variables). -*/ -static int dupedExprSize(Expr *p, int flags){ - int nByte = 0; - if( p ){ - 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; - - /* 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) ){ - 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; - } - 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 ){ - int 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 - -/* -** 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->zName = sqlite3DbStrDup(db, pOldItem->zName); - pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan); - pItem->sortOrder = pOldItem->sortOrder; - pItem->done = 0; - pItem->bSpanIsTab = pOldItem->bSpanIsTab; - 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->pOffset = sqlite3ExprDup(db, p->pOffset, 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); - sqlite3SelectSetName(pNew, p->zSelName); - *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*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,zName)==sizeof(pItem->pExpr) ); - assert( offsetof(struct ExprList_item,pExpr)==0 ); - memset(&pItem->zName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zName)); - 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); - pList = sqlite3ExprListAppend(pParse, pList, pSubExpr); - if( pList ){ - assert( pList->nExpr==iFirst+i+1 ); - pList->a[pList->nExpr-1].zName = 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: - sqlite3ExprDelete(db, 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){ - if( p==0 ) return; - assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 ); - assert( p->nExpr>0 ); - if( iSortOrder<0 ){ - assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC ); - return; - } - p->a[p->nExpr-1].sortOrder = (u8)iSortOrder; -} - -/* -** Set the ExprList.a[].zName element of the most recently added item -** on the expression list. -** -** pList might be NULL following an OOM error. But pName should never be -** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag -** is set. -*/ -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 ); - if( pList ){ - struct ExprList_item *pItem; - assert( pList->nExpr>0 ); - pItem = &pList->a[pList->nExpr-1]; - assert( pItem->zName==0 ); - pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n); - if( dequote ) sqlite3Dequote(pItem->zName); - } -} - -/* -** Set the ExprList.a[].zSpan element of the most recently added item -** on the expression list. -** -** pList might be NULL following an OOM error. But pSpan should never be -** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag -** is set. -*/ -SQLITE_PRIVATE void sqlite3ExprListSetSpan( - Parse *pParse, /* Parsing context */ - ExprList *pList, /* List to which to add the span. */ - ExprSpan *pSpan /* The span to be added */ -){ - sqlite3 *db = pParse->db; - assert( pList!=0 || db->mallocFailed!=0 ); - if( pList ){ - struct ExprList_item *pItem = &pList->a[pList->nExpr-1]; - assert( pList->nExpr>0 ); - assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr ); - sqlite3DbFree(db, pItem->zSpan); - pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart, - (int)(pSpan->zEnd - pSpan->zStart)); - } -} - -/* -** 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->zName); - sqlite3DbFree(db, pItem->zSpan); - 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; -} - -/* -** 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 expressions -** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing -** an existing schema and 4 when processing a new statement. A bound -** parameter raises an error for new statements, but is silently converted -** to NULL for existing schemas. This allows sqlite_master 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) ){ - return WRC_Continue; - }else{ - pWalker->eCode = 0; - return WRC_Abort; - } - case TK_ID: - case TK_COLUMN: - case TK_AGG_FUNCTION: - case TK_AGG_COLUMN: - testcase( pExpr->op==TK_ID ); - testcase( pExpr->op==TK_COLUMN ); - testcase( pExpr->op==TK_AGG_FUNCTION ); - testcase( pExpr->op==TK_AGG_COLUMN ); - if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){ - return WRC_Continue; - } - /* Fall through */ - case TK_IF_NULL_ROW: - testcase( pExpr->op==TK_IF_NULL_ROW ); - 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_master 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; - } - /* Fall through */ - default: - testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail will disallow */ - testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail will disallow */ - 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 the expression is constant -** that does no originate from the ON or USING clauses of a join. -** Return 0 if it involves variables or function calls or terms from -** an ON or USING clause. -*/ -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( sqlite3_stricmp("BINARY", pColl->zName)==0 ){ - 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. Return non-zero if the expression is constant -** or a function call with constant arguments. Return and 0 if there -** are any variables. -** -** For the purposes of this function, a double-quoted string (ex: "abc") -** is considered a variable but a single-quoted string (ex: 'abc') is -** a constant. -*/ -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( p==0 ) return 0; /* Can 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->pTab==0 || /* Reference to column of index on expression */ - (p->iColumn>=0 && p->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; - if( aff==SQLITE_AFF_BLOB ) return 1; - while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; } - op = p->op; - if( op==TK_REGISTER ) op = p->op2; - switch( op ){ - case TK_INTEGER: { - return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC; - } - case TK_FLOAT: { - return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC; - } - case TK_STRING: { - return aff==SQLITE_AFF_TEXT; - } - case TK_BLOB: { - return 1; - } - case TK_COLUMN: { - assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */ - return p->iColumn<0 - && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC); - } - 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 */ - assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */ - 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 exactly one of the bits -** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. 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 must be used 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 right-hand side (RHS) of the IN operator */ - 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 */ -){ - 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
    . */ - i16 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); - sqlite3CodeVerifySchema(pParse, iDb); - sqlite3TableLock(pParse, iDb, pTab->tnum, 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; - - 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->nColumnnColumn==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); -#ifndef SQLITE_OMIT_EXPLAIN - sqlite3VdbeAddOp4(v, OP_Explain, 0, 0, 0, - sqlite3MPrintf(db, "USING INDEX %s FOR IN-OPERATOR",pIdx->zName), - P4_DYNAMIC); -#endif - 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; - if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){ - eType = IN_INDEX_ROWID; - } - }else if( prRhsHasNull ){ - *prRhsHasNull = rMayHaveNull = ++pParse->nMem; - } - sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID); - pParse->nQueryLoop = savedNQueryLoop; - }else{ - pX->iTable = iTab; - } - - 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){ - 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"); - } -} - -/* -** Generate code for scalar subqueries used as a subquery expression, EXISTS, -** or IN operators. Examples: -** -** (SELECT a FROM b) -- subquery -** EXISTS (SELECT a FROM b) -- EXISTS subquery -** x IN (4,5,11) -- IN operator with list on right-hand side -** x IN (SELECT a FROM b) -- IN operator with subquery on the right -** -** The pExpr parameter describes the expression that contains the IN -** operator or subquery. -** -** If parameter isRowid is non-zero, then expression pExpr is guaranteed -** to be of the form " IN (?, ?, ?)", where is a reference -** to some integer key column of a table B-Tree. In this case, use an -** intkey B-Tree to store the set of IN(...) values instead of the usual -** (slower) variable length keys B-Tree. -** -** If rMayHaveNull is non-zero, that means that the operation is an IN -** (not a SELECT or EXISTS) and that the RHS might contains NULLs. -** All this routine does is initialize the register given by rMayHaveNull -** to NULL. Calling routines will take care of changing this register -** value to non-NULL if the RHS is NULL-free. -** -** For a SELECT or EXISTS operator, 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 for IN operators or if an error occurs. -*/ -#ifndef SQLITE_OMIT_SUBQUERY -SQLITE_PRIVATE int sqlite3CodeSubselect( - Parse *pParse, /* Parsing context */ - Expr *pExpr, /* The IN, SELECT, or EXISTS operator */ - int rHasNullFlag, /* Register that records whether NULLs exist in RHS */ - int isRowid /* If true, LHS of IN operator is a rowid */ -){ - int jmpIfDynamic = -1; /* One-time test address */ - int rReg = 0; /* Register storing resulting */ - Vdbe *v = sqlite3GetVdbe(pParse); - if( NEVER(v==0) ) return 0; - sqlite3ExprCachePush(pParse); - - /* The evaluation of the IN/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) ){ - jmpIfDynamic = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); - } - -#ifndef SQLITE_OMIT_EXPLAIN - if( pParse->explain==2 ){ - char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d", - jmpIfDynamic>=0?"":"CORRELATED ", - pExpr->op==TK_IN?"LIST":"SCALAR", - pParse->iNextSelectId - ); - sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); - } -#endif - - switch( pExpr->op ){ - case TK_IN: { - int addr; /* Address of OP_OpenEphemeral instruction */ - Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */ - KeyInfo *pKeyInfo = 0; /* Key information */ - int nVal; /* Size of vector pLeft */ - - nVal = sqlite3ExprVectorSize(pLeft); - assert( !isRowid || nVal==1 ); - - /* Whether this is an 'x IN(SELECT...)' or an 'x IN()' - ** expression it is handled the same way. An ephemeral table is - ** filled with index keys representing the results from the - ** SELECT or the . - ** - ** If the 'x' expression is a column value, or the SELECT... - ** statement returns a column value, then the affinity of that - ** column is used to build the index keys. If both 'x' and the - ** SELECT... statement are columns, then numeric affinity is used - ** if either column has NUMERIC or INTEGER affinity. If neither - ** 'x' nor the SELECT... statement are columns, then numeric affinity - ** is used. - */ - pExpr->iTable = pParse->nTab++; - addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, - pExpr->iTable, (isRowid?0:nVal)); - pKeyInfo = isRowid ? 0 : 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; - - assert( !isRowid ); - /* 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, pExpr->iTable); - 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 0; - } - 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, r3; - - affinity = sqlite3ExprAffinity(pLeft); - if( !affinity ){ - affinity = SQLITE_AFF_BLOB; - } - if( pKeyInfo ){ - assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); - pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft); - } - - /* Loop through each expression in . */ - r1 = sqlite3GetTempReg(pParse); - r2 = sqlite3GetTempReg(pParse); - if( isRowid ) sqlite3VdbeAddOp4(v, OP_Blob, 0, r2, 0, "", P4_STATIC); - for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){ - Expr *pE2 = pItem->pExpr; - int iValToIns; - - /* 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( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){ - sqlite3VdbeChangeToNoop(v, jmpIfDynamic); - jmpIfDynamic = -1; - } - - /* Evaluate the expression and insert it into the temp table */ - if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){ - sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns); - }else{ - r3 = sqlite3ExprCodeTarget(pParse, pE2, r1); - if( isRowid ){ - sqlite3VdbeAddOp2(v, OP_MustBeInt, r3, - sqlite3VdbeCurrentAddr(v)+2); - VdbeCoverage(v); - sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3); - }else{ - sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1); - sqlite3ExprCacheAffinityChange(pParse, r3, 1); - sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pExpr->iTable, r2, r3, 1); - } - } - } - sqlite3ReleaseTempReg(pParse, r1); - sqlite3ReleaseTempReg(pParse, r2); - } - if( pKeyInfo ){ - sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO); - } - break; - } - - case TK_EXISTS: - case TK_SELECT: - default: { - /* Case 3: (SELECT ... FROM ...) - ** or: EXISTS(SELECT ... FROM ...) - ** - ** 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. - */ - Select *pSel; /* SELECT statement to encode */ - SelectDest dest; /* How to deal with SELECT result */ - int nReg; /* Registers to allocate */ - - 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; - 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")); - } - sqlite3ExprDelete(pParse->db, pSel->pLimit); - pSel->pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER, - &sqlite3IntTokens[1], 0); - pSel->iLimit = 0; - pSel->selFlags &= ~SF_MultiValue; - if( sqlite3Select(pParse, pSel, &dest) ){ - return 0; - } - rReg = dest.iSDParm; - ExprSetVVAProperty(pExpr, EP_NoReduce); - break; - } - } - - if( rHasNullFlag ){ - sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag); - } - - if( jmpIfDynamic>=0 ){ - sqlite3VdbeJumpHere(v, jmpIfDynamic); - } - sqlite3ExprCachePop(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 */ - - 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 ith cursor pExpr->iTable - ** 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); - - 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. - */ - sqlite3ExprCachePush(pParse); - rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy); - for(i=0; ix.pList; - CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft); - int labelOk = sqlite3VdbeMakeLabel(v); - 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); - } - if( iinExpr-1 || destIfNull!=destIfFalse ){ - sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2, - (void*)pColl, P4_COLLSEQ); - VdbeCoverageIf(v, iinExpr-1); - VdbeCoverageIf(v, ii==pList->nExpr-1); - sqlite3VdbeChangeP5(v, zAff[0]); - }else{ - assert( destIfNull==destIfFalse ); - sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2, - (void*)pColl, P4_COLLSEQ); VdbeCoverage(v); - sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL); - } - sqlite3ReleaseTempReg(pParse, regToFree); - } - 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(v); - } - 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, pExpr->iTable, 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, pExpr->iTable, 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, pExpr->iTable, 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, pExpr->iTable, destIfFalse); - VdbeCoverage(v); - if( nVector>1 ){ - destNotNull = sqlite3VdbeMakeLabel(v); - }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; iiTable, i, r3); - sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3, - (void*)pColl, P4_COLLSEQ); - VdbeCoverage(v); - sqlite3ReleaseTempReg(pParse, r3); - } - sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull); - if( nVector>1 ){ - sqlite3VdbeResolveLabel(v, destNotNull); - sqlite3VdbeAddOp2(v, OP_Next, pExpr->iTable, 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); - sqlite3ExprCachePop(pParse); - 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); - } - } -} - -/* -** Erase column-cache entry number i -*/ -static void cacheEntryClear(Parse *pParse, int i){ - if( pParse->aColCache[i].tempReg ){ - if( pParse->nTempRegaTempReg) ){ - pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg; - } - } - pParse->nColCache--; - if( inColCache ){ - pParse->aColCache[i] = pParse->aColCache[pParse->nColCache]; - } -} - - -/* -** Record in the column cache that a particular column from a -** particular table is stored in a particular register. -*/ -SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){ - int i; - int minLru; - int idxLru; - struct yColCache *p; - - /* Unless an error has occurred, register numbers are always positive. */ - assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed ); - assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */ - - /* The SQLITE_ColumnCache flag disables the column cache. This is used - ** for testing only - to verify that SQLite always gets the same answer - ** with and without the column cache. - */ - if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return; - - /* First replace any existing entry. - ** - ** Actually, the way the column cache is currently used, we are guaranteed - ** that the object will never already be in cache. Verify this guarantee. - */ -#ifndef NDEBUG - for(i=0, p=pParse->aColCache; inColCache; i++, p++){ - assert( p->iTable!=iTab || p->iColumn!=iCol ); - } -#endif - - /* If the cache is already full, delete the least recently used entry */ - if( pParse->nColCache>=SQLITE_N_COLCACHE ){ - minLru = 0x7fffffff; - idxLru = -1; - for(i=0, p=pParse->aColCache; ilrulru; - } - } - p = &pParse->aColCache[idxLru]; - }else{ - p = &pParse->aColCache[pParse->nColCache++]; - } - - /* Add the new entry to the end of the cache */ - p->iLevel = pParse->iCacheLevel; - p->iTable = iTab; - p->iColumn = iCol; - p->iReg = iReg; - p->tempReg = 0; - p->lru = pParse->iCacheCnt++; -} - -/* -** Indicate that registers between iReg..iReg+nReg-1 are being overwritten. -** Purge the range of registers from the column cache. -*/ -SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){ - int i = 0; - while( inColCache ){ - struct yColCache *p = &pParse->aColCache[i]; - if( p->iReg >= iReg && p->iReg < iReg+nReg ){ - cacheEntryClear(pParse, i); - }else{ - i++; - } - } -} - -/* -** Remember the current column cache context. Any new entries added -** added to the column cache after this call are removed when the -** corresponding pop occurs. -*/ -SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){ - pParse->iCacheLevel++; -#ifdef SQLITE_DEBUG - if( pParse->db->flags & SQLITE_VdbeAddopTrace ){ - printf("PUSH to %d\n", pParse->iCacheLevel); - } -#endif -} - -/* -** Remove from the column cache any entries that were added since the -** the previous sqlite3ExprCachePush operation. In other words, restore -** the cache to the state it was in prior the most recent Push. -*/ -SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){ - int i = 0; - assert( pParse->iCacheLevel>=1 ); - pParse->iCacheLevel--; -#ifdef SQLITE_DEBUG - if( pParse->db->flags & SQLITE_VdbeAddopTrace ){ - printf("POP to %d\n", pParse->iCacheLevel); - } -#endif - while( inColCache ){ - if( pParse->aColCache[i].iLevel>pParse->iCacheLevel ){ - cacheEntryClear(pParse, i); - }else{ - i++; - } - } -} - -/* -** When a cached column is reused, make sure that its register is -** no longer available as a temp register. ticket #3879: that same -** register might be in the cache in multiple places, so be sure to -** get them all. -*/ -static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){ - int i; - struct yColCache *p; - for(i=0, p=pParse->aColCache; inColCache; i++, p++){ - if( p->iReg==iReg ){ - p->tempReg = 0; - } - } -} - -/* 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); - } -} - -/* -** Generate code to extract the value of the iCol-th column of a table. -*/ -SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable( - Vdbe *v, /* The VDBE under construction */ - 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 */ -){ - 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 = IsVirtual(pTab) ? OP_VColumn : OP_Column; - int x = iCol; - if( !HasRowid(pTab) && !IsVirtual(pTab) ){ - x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol); - } - sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut); - } - if( iCol>=0 ){ - sqlite3ColumnDefault(v, pTab, iCol, regOut); - } -} - -/* -** Generate code that will extract the iColumn-th column from -** table pTab and store the column value in a register. -** -** An effort is made to store the column value in register iReg. This -** is not garanteeed for GetColumn() - the result can be stored in -** any register. But the result is guaranteed to land in register iReg -** for GetColumnToReg(). -** -** 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 */ -){ - Vdbe *v = pParse->pVdbe; - int i; - struct yColCache *p; - - for(i=0, p=pParse->aColCache; inColCache; i++, p++){ - if( p->iTable==iTable && p->iColumn==iColumn ){ - p->lru = pParse->iCacheCnt++; - sqlite3ExprCachePinRegister(pParse, p->iReg); - return p->iReg; - } - } - assert( v!=0 ); - sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg); - if( p5 ){ - sqlite3VdbeChangeP5(v, p5); - }else{ - sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg); - } - return iReg; -} -SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg( - 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 */ -){ - int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0); - if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg); -} - - -/* -** Clear all column cache entries. -*/ -SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){ - int i; - -#ifdef SQLITE_DEBUG - if( pParse->db->flags & SQLITE_VdbeAddopTrace ){ - printf("CLEAR\n"); - } -#endif - for(i=0; inColCache; i++){ - if( pParse->aColCache[i].tempReg - && pParse->nTempRegaTempReg) - ){ - pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg; - } - } - pParse->nColCache = 0; -} - -/* -** Record the fact that an affinity change has occurred on iCount -** registers starting with iStart. -*/ -SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){ - sqlite3ExprCacheRemove(pParse, iStart, iCount); -} - -/* -** Generate code to move content from registers iFrom...iFrom+nReg-1 -** over to iTo..iTo+nReg-1. Keep the column cache up-to-date. -*/ -SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){ - assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo ); - sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg); - sqlite3ExprCacheRemove(pParse, iFrom, nReg); -} - -#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST) -/* -** Return true if any register in the range iFrom..iTo (inclusive) -** is used as part of the column cache. -** -** This routine is used within assert() and testcase() macros only -** and does not appear in a normal build. -*/ -static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){ - int i; - struct yColCache *p; - for(i=0, p=pParse->aColCache; inColCache; i++, p++){ - int r = p->iReg; - if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/ - } - return 0; -} -#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */ - - -/* -** 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 *p, int iReg){ - 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, 0, 0); -#endif - }else{ - int i; - iResult = pParse->nMem+1; - pParse->nMem += nResult; - for(i=0; ix.pList->a[i].pExpr, i+iResult); - } - } - } - return iResult; -} - - -/* -** 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 ); - if( v==0 ){ - assert( pParse->db->mallocFailed ); - return 0; - } - - if( pExpr==0 ){ - op = TK_NULL; - }else{ - op = pExpr->op; - } - switch( op ){ - case TK_AGG_COLUMN: { - AggInfo *pAggInfo = pExpr->pAggInfo; - struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg]; - if( !pAggInfo->directMode ){ - assert( pCol->iMem>0 ); - return pCol->iMem; - }else if( pAggInfo->useSortingIdx ){ - sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab, - pCol->iSorterColumn, target); - return target; - } - /* Otherwise, fall thru into the TK_COLUMN case */ - } - case TK_COLUMN: { - int iTab = pExpr->iTable; - if( iTab<0 ){ - if( pParse->iSelfTab<0 ){ - /* Generating CHECK constraints or inserting into partial index */ - return pExpr->iColumn - pParse->iSelfTab; - }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; - } - } - return sqlite3ExprCodeGetColumn(pParse, pExpr->pTab, - pExpr->iColumn, iTab, target, - pExpr->op2); - } - case TK_INTEGER: { - codeInteger(pParse, pExpr, 0, 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; - } - case 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]=='?' || strcmp(pExpr->u.zToken, z)==0 ); - 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)); - testcase( usedAsColumnCache(pParse, inReg, inReg) ); - sqlite3ExprCacheAffinityChange(pParse, inReg, 1); - 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); - 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; - 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_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 ){ - 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 */ - - if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){ - /* SQL functions can be expensive. So try to move constant functions - ** out of the inner loop, even if that means an extra OP_Copy. */ - return sqlite3ExprCodeAtInit(pParse, pExpr, -1); - } - assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); - if( ExprHasProperty(pExpr, EP_TokenOnly) ){ - pFarg = 0; - }else{ - 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; - } - - /* Attempt a direct implementation of the built-in COALESCE() and - ** IFNULL() functions. This avoids unnecessary evaluation of - ** arguments past the first non-NULL argument. - */ - if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){ - int endCoalesce = sqlite3VdbeMakeLabel(v); - assert( nFarg>=2 ); - sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target); - for(i=1; ia[i].pExpr, target); - sqlite3ExprCachePop(pParse); - } - sqlite3VdbeResolveLabel(v, endCoalesce); - break; - } - - /* The UNLIKELY() function is a no-op. The result is the value - ** of the first argument. - */ - if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){ - assert( nFarg>=1 ); - return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target); - } - -#ifdef SQLITE_DEBUG - /* 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. - */ - if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){ - const char *azAff[] = { "blob", "text", "numeric", "integer", "real" }; - char aff; - assert( nFarg==1 ); - aff = sqlite3ExprAffinity(pFarg->a[0].pExpr); - sqlite3VdbeLoadString(v, target, - aff ? azAff[aff-SQLITE_AFF_BLOB] : "none"); - return target; - } -#endif - - 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); - } - } - - sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */ - sqlite3ExprCodeExprList(pParse, pFarg, r1, 0, - SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR); - sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */ - }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 && (pExpr->flags & EP_InfixFunc) ){ - pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr); - }else if( nFarg>0 ){ - pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr); - } -#endif - if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){ - if( !pColl ) pColl = db->pDfltColl; - sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ); - } - sqlite3VdbeAddOp4(v, pParse->iSelfTab ? OP_PureFunc0 : OP_Function0, - constMask, r1, target, (char*)pDef, P4_FUNCDEF); - sqlite3VdbeChangeP5(v, (u8)nFarg); - if( nFarg && constMask==0 ){ - sqlite3ReleaseTempRange(pParse, r1, nFarg); - } - return target; - } -#ifndef SQLITE_OMIT_SUBQUERY - case TK_EXISTS: - case TK_SELECT: { - int nCol; - testcase( op==TK_EXISTS ); - testcase( op==TK_SELECT ); - if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){ - sqlite3SubselectError(pParse, nCol, 1); - }else{ - return sqlite3CodeSubselect(pParse, pExpr, 0, 0); - } - break; - } - case TK_SELECT_COLUMN: { - int n; - if( pExpr->pLeft->iTable==0 ){ - pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0); - } - assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT ); - if( pExpr->iTable - && 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(v); - int destIfNull = sqlite3VdbeMakeLabel(v); - sqlite3VdbeAddOp2(v, OP_Null, 0, target); - sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); - sqlite3VdbeAddOp2(v, OP_Integer, 1, target); - sqlite3VdbeResolveLabel(v, destIfFalse); - sqlite3VdbeAddOp2(v, OP_AddImm, target, 0); - sqlite3VdbeResolveLabel(v, destIfNull); - 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: { - return sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); - } - - case TK_TRIGGER: { - /* If the opcode is TK_TRIGGER, then the expression is a reference - ** to a column in the new.* or old.* pseudo-tables available to - ** trigger programs. In this case Expr.iTable is set to 1 for the - ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn - ** is set to the column of the pseudo-table to read, or to -1 to - ** read the rowid field. - ** - ** The expression is implemented using an OP_Param opcode. The p1 - ** parameter is set to 0 for an old.rowid reference, or to (i+1) - ** to reference another column of the old.* pseudo-table, where - ** i is the index of the column. For a new.rowid reference, p1 is - ** set to (n+1), where n is the number of columns in each pseudo-table. - ** For a reference to any other column in the new.* pseudo-table, p1 - ** is set to (n+2+i), where n and i are as defined previously. For - ** example, if the table on which triggers are being fired is - ** declared as: - ** - ** CREATE TABLE t1(a, b); - ** - ** Then p1 is interpreted as follows: - ** - ** p1==0 -> old.rowid p1==3 -> new.rowid - ** p1==1 -> old.a p1==4 -> new.a - ** p1==2 -> old.b p1==5 -> new.b - */ - Table *pTab = pExpr->pTab; - int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn; - - assert( pExpr->iTable==0 || pExpr->iTable==1 ); - assert( pExpr->iColumn>=-1 && pExpr->iColumnnCol ); - assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey ); - assert( p1>=0 && p1<(pTab->nCol*2+2) ); - - sqlite3VdbeAddOp2(v, OP_Param, p1, target); - VdbeComment((v, "%s.%s -> $%d", - (pExpr->iTable ? "new" : "old"), - (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName), - target - )); - -#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( pExpr->iColumn>=0 - && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL - ){ - sqlite3VdbeAddOp1(v, OP_RealAffinity, target); - } -#endif - break; - } - - case TK_VECTOR: { - sqlite3ErrorMsg(pParse, "row value misused"); - break; - } - - case TK_IF_NULL_ROW: { - int addrINR; - addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable); - sqlite3ExprCachePush(pParse); - inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); - sqlite3ExprCachePop(pParse); - 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. - */ - default: assert( op==TK_CASE ); { - int endLabel; /* GOTO label for end of CASE stmt */ - int nextCase; /* GOTO label for next WHEN clause */ - int nExpr; /* 2x number of WHEN terms */ - int i; /* Loop counter */ - ExprList *pEList; /* List of WHEN terms */ - 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) */ - VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; ) - - 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(v); - if( (pX = pExpr->pLeft)!=0 ){ - tempX = *pX; - testcase( pX->op==TK_COLUMN ); - exprToRegister(&tempX, exprCodeVector(pParse, &tempX, ®Free1)); - testcase( regFree1==0 ); - memset(&opCompare, 0, sizeof(opCompare)); - opCompare.op = TK_EQ; - opCompare.pLeft = &tempX; - 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); - sqlite3ExprCachePop(pParse); - sqlite3VdbeResolveLabel(v, nextCase); - } - if( (nExpr&1)!=0 ){ - sqlite3ExprCachePush(pParse); - sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target); - sqlite3ExprCachePop(pParse); - }else{ - sqlite3VdbeAddOp2(v, OP_Null, 0, target); - } - assert( pParse->db->mallocFailed || pParse->nErr>0 - || pParse->iCacheLevel==iCacheLevel ); - sqlite3VdbeResolveLabel(v, endLabel); - break; - } -#ifndef SQLITE_OMIT_TRIGGER - case TK_RAISE: { - assert( pExpr->affinity==OE_Rollback - || pExpr->affinity==OE_Abort - || pExpr->affinity==OE_Fail - || pExpr->affinity==OE_Ignore - ); - if( !pParse->pTriggerTab ){ - sqlite3ErrorMsg(pParse, - "RAISE() may only be used within a trigger-program"); - return 0; - } - if( pExpr->affinity==OE_Abort ){ - sqlite3MayAbort(pParse); - } - assert( !ExprHasProperty(pExpr, EP_IntValue) ); - if( pExpr->affinity==OE_Ignore ){ - sqlite3VdbeAddOp4( - v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0); - VdbeCoverage(v); - }else{ - sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER, - pExpr->affinity, pExpr->u.zToken, 0, 0); - } - - break; - } -#endif - } - sqlite3ReleaseTempReg(pParse, regFree1); - sqlite3ReleaseTempReg(pParse, regFree2); - return inReg; -} - -/* -** Factor out the code of the given expression to initialization time. -** -** 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 will -** code to the same register. -*/ -SQLITE_PRIVATE int sqlite3ExprCodeAtInit( - 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); - 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 = sqlite3ExprSkipCollate(pExpr); - if( ConstFactorOk(pParse) - && pExpr->op!=TK_REGISTER - && sqlite3ExprIsConstantNotJoin(pExpr) - ){ - *pReg = 0; - r2 = sqlite3ExprCodeAtInit(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( target>0 && target<=pParse->nMem ); - if( pExpr && pExpr->op==TK_REGISTER ){ - sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target); - }else{ - inReg = sqlite3ExprCodeTarget(pParse, pExpr, target); - assert( pParse->pVdbe!=0 || pParse->db->mallocFailed ); - if( inReg!=target && pParse->pVdbe ){ - sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, 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 && sqlite3ExprIsConstant(pExpr) ){ - sqlite3ExprCodeAtInit(pParse, pExpr, target); - }else{ - sqlite3ExprCode(pParse, pExpr, target); - } -} - -/* -** Generate code that evaluates the given expression and puts the result -** in register target. -** -** Also make a copy of the expression results into another "cache" register -** and modify the expression so that the next time it is evaluated, -** the result is a copy of the cache register. -** -** This routine is used for expressions that are used multiple -** times. They are evaluated once and the results of the expression -** are reused. -*/ -SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){ - Vdbe *v = pParse->pVdbe; - int iMem; - - assert( target>0 ); - assert( pExpr->op!=TK_REGISTER ); - sqlite3ExprCode(pParse, pExpr, target); - iMem = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Copy, target, iMem); - exprToRegister(pExpr, iMem); -} - -/* -** 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; - 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 && sqlite3ExprIsConstant(pExpr) ){ - sqlite3ExprCodeAtInit(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->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 */ - Expr exprX; /* The x subexpression */ - int regFree1 = 0; /* Temporary use register */ - - - memset(&compLeft, 0, sizeof(Expr)); - memset(&compRight, 0, sizeof(Expr)); - memset(&exprAnd, 0, sizeof(Expr)); - - assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); - exprX = *pExpr->pLeft; - exprAnd.op = TK_AND; - exprAnd.pLeft = &compLeft; - exprAnd.pRight = &compRight; - compLeft.op = TK_GE; - compLeft.pLeft = &exprX; - compLeft.pRight = pExpr->x.pList->a[0].pExpr; - compRight.op = TK_LE; - compRight.pLeft = &exprX; - compRight.pRight = pExpr->x.pList->a[1].pExpr; - exprToRegister(&exprX, exprCodeVector(pParse, &exprX, ®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. */ - exprX.flags |= EP_FromJoin; - sqlite3ExprCodeTarget(pParse, &exprAnd, dest); - } - sqlite3ReleaseTempReg(pParse, regFree1); - - /* 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 */ - op = pExpr->op; - switch( op ){ - case TK_AND: { - int d2 = sqlite3VdbeMakeLabel(v); - testcase( jumpIfNull==0 ); - sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL); - sqlite3ExprCachePush(pParse); - sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); - sqlite3VdbeResolveLabel(v, d2); - sqlite3ExprCachePop(pParse); - break; - } - case TK_OR: { - testcase( jumpIfNull==0 ); - sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); - sqlite3ExprCachePush(pParse); - sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); - sqlite3ExprCachePop(pParse); - break; - } - case TK_NOT: { - testcase( jumpIfNull==0 ); - sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); - 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; - /* Fall thru */ - 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); - 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(v); - 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; - - /* 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: { - testcase( jumpIfNull==0 ); - sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); - sqlite3ExprCachePush(pParse); - sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); - sqlite3ExprCachePop(pParse); - break; - } - case TK_OR: { - int d2 = sqlite3VdbeMakeLabel(v); - testcase( jumpIfNull==0 ); - sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL); - sqlite3ExprCachePush(pParse); - sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); - sqlite3VdbeResolveLabel(v, d2); - sqlite3ExprCachePop(pParse); - break; - } - case TK_NOT: { - testcase( jumpIfNull==0 ); - sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, 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; - /* Fall thru */ - 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); - 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(v); - 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 ){ - 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 ){ - if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2; - }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){ - return pA->op==TK_COLLATE ? 1 : 2; - } - } - if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2; - if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){ - if( combinedFlags & EP_xIsSelect ) return 2; - if( 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( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){ - if( pA->iColumn!=pB->iColumn ) return 2; - if( pA->iTable!=pB->iTable - && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2; - } - } - return 0; -} - -/* -** Compare two ExprList objects. Return 0 if they are identical and -** non-zero if they differ in any way. -** -** 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++){ - Expr *pExprA = pA->a[i].pExpr; - Expr *pExprB = pB->a[i].pExpr; - if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1; - if( sqlite3ExprCompare(0, pExprA, pExprB, iTab) ) return 1; - } - 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, - sqlite3ExprSkipCollate(pA), - sqlite3ExprSkipCollate(pB), - iTab); -} - -/* -** 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 && pE1->op!=TK_ISNULL && pE1->op!=TK_IS ){ - Expr *pX = sqlite3ExprSkipCollate(pE1->pLeft); - testcase( pX!=pE1->pLeft ); - if( sqlite3ExprCompare(pParse, pX, pE2->pLeft, iTab)==0 ) return 1; - } - return 0; -} - -/* -** 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 - && sqlite3ColumnOfIndex(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 nThis; /* Number of references to columns in pSrcList */ - int nOther; /* Number of references to columns in other FROM clauses */ -}; - -/* -** Count the number of references to columns. -*/ -static int exprSrcCount(Walker *pWalker, Expr *pExpr){ - /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc() - ** is always called before sqlite3ExprAnalyzeAggregates() and so the - ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If - ** sqlite3FunctionUsesThisSrc() is used differently in the future, the - ** NEVER() will need to be removed. */ - if( pExpr->op==TK_COLUMN || NEVER(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{ - 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 ); - w.xExprCallback = exprSrcCount; - w.xSelectCallback = 0; - w.u.pSrcCount = &cnt; - cnt.pSrc = pSrcList; - cnt.nThis = 0; - cnt.nOther = 0; - sqlite3WalkExprList(&w, pExpr->x.pList); - return cnt.nThis>0 || cnt.nOther==0; -} - -/* -** Add a new element to the pAggInfo->aCol[] array. Return the index of -** the new element. Return a negative number if malloc fails. -*/ -static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){ - int i; - 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->pAggInfo; - - switch( pExpr->op ){ - case TK_AGG_COLUMN: - case TK_COLUMN: { - testcase( pExpr->op==TK_AGG_COLUMN ); - testcase( pExpr->op==TK_COLUMN ); - /* Check to see if the column is in one of the tables in the FROM - ** clause of the aggregate query */ - if( ALWAYS(pSrcList!=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->pTab; - pCol->iTable = pExpr->iTable; - pCol->iColumn = pExpr->iColumn; - pCol->iMem = ++pParse->nMem; - pCol->iSorterColumn = -1; - pCol->pExpr = 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->pExpr, 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->pExpr = 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; -} -static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){ - UNUSED_PARAMETER(pSelect); - pWalker->walkerDepth++; - return WRC_Continue; -} -static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){ - UNUSED_PARAMETER(pSelect); - pWalker->walkerDepth--; -} - -/* -** 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 = analyzeAggregatesInSelect; - w.xSelectCallback2 = analyzeAggregatesInSelectEnd; - w.walkerDepth = 0; - w.u.pNC = pNC; - 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. -** -** If a register is currently being used by the column cache, then -** the deallocation is deferred until the column cache line that uses -** the register becomes stale. -*/ -SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){ - if( iReg && pParse->nTempRegaTempReg) ){ - int i; - struct yColCache *p; - for(i=0, p=pParse->aColCache; inColCache; i++, p++){ - if( p->iReg==iReg ){ - p->tempReg = 1; - return; - } - } - 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 ){ - assert( !usedAsColumnCache(pParse, i, i+n-1) ); - 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; - } - sqlite3ExprCacheRemove(pParse, iReg, nReg); - if( nReg>pParse->nRangeReg ){ - pParse->nRangeReg = nReg; - pParse->iRangeReg = iReg; - } -} - -/* -** Mark all temporary registers as being unavailable for reuse. -*/ -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 - - -/* -** This function is used by SQL generated to implement the -** ALTER TABLE command. The first argument is the text of a CREATE TABLE or -** CREATE INDEX command. The second is a table name. The table name in -** the CREATE TABLE or CREATE INDEX statement is replaced with the third -** argument and the result returned. Examples: -** -** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def') -** -> 'CREATE TABLE def(a, b, c)' -** -** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def') -** -> 'CREATE INDEX i ON def(a, b, c)' -*/ -static void renameTableFunc( - sqlite3_context *context, - int NotUsed, - sqlite3_value **argv -){ - unsigned char const *zSql = sqlite3_value_text(argv[0]); - unsigned char const *zTableName = sqlite3_value_text(argv[1]); - - int token; - Token tname; - unsigned char const *zCsr = zSql; - int len = 0; - char *zRet; - - sqlite3 *db = sqlite3_context_db_handle(context); - - UNUSED_PARAMETER(NotUsed); - - /* The principle used to locate the table name in the CREATE TABLE - ** statement is that the table name is the first non-space token that - ** is immediately followed by a TK_LP or TK_USING token. - */ - if( zSql ){ - do { - if( !*zCsr ){ - /* Ran out of input before finding an opening bracket. Return NULL. */ - return; - } - - /* Store the token that zCsr points to in tname. */ - tname.z = (char*)zCsr; - tname.n = len; - - /* Advance zCsr to the next token. Store that token type in 'token', - ** and its length in 'len' (to be used next iteration of this loop). - */ - do { - zCsr += len; - len = sqlite3GetToken(zCsr, &token); - } while( token==TK_SPACE ); - assert( len>0 ); - } while( token!=TK_LP && token!=TK_USING ); - - zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql), - zSql, zTableName, tname.z+tname.n); - sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC); - } -} - -/* -** This C function implements an SQL user function that is used by SQL code -** generated by the ALTER TABLE ... RENAME command to modify the definition -** of any foreign key constraints that use the table being renamed as the -** parent table. It is passed three arguments: -** -** 1) The complete text of the CREATE TABLE statement being modified, -** 2) The old name of the table being renamed, and -** 3) The new name of the table being renamed. -** -** It returns the new CREATE TABLE statement. For example: -** -** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3') -** -> 'CREATE TABLE t1(a REFERENCES t3)' -*/ -#ifndef SQLITE_OMIT_FOREIGN_KEY -static void renameParentFunc( - sqlite3_context *context, - int NotUsed, - sqlite3_value **argv -){ - sqlite3 *db = sqlite3_context_db_handle(context); - char *zOutput = 0; - char *zResult; - unsigned char const *zInput = sqlite3_value_text(argv[0]); - unsigned char const *zOld = sqlite3_value_text(argv[1]); - unsigned char const *zNew = sqlite3_value_text(argv[2]); - - unsigned const char *z; /* Pointer to token */ - int n; /* Length of token z */ - int token; /* Type of token */ - - UNUSED_PARAMETER(NotUsed); - if( zInput==0 || zOld==0 ) return; - for(z=zInput; *z; z=z+n){ - n = sqlite3GetToken(z, &token); - if( token==TK_REFERENCES ){ - char *zParent; - do { - z += n; - n = sqlite3GetToken(z, &token); - }while( token==TK_SPACE ); - - if( token==TK_ILLEGAL ) break; - zParent = sqlite3DbStrNDup(db, (const char *)z, n); - if( zParent==0 ) break; - sqlite3Dequote(zParent); - if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){ - char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", - (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew - ); - sqlite3DbFree(db, zOutput); - zOutput = zOut; - zInput = &z[n]; - } - sqlite3DbFree(db, zParent); - } - } - - zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), - sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC); - sqlite3DbFree(db, zOutput); -} -#endif - -#ifndef SQLITE_OMIT_TRIGGER -/* This function is used by SQL generated to implement the -** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER -** statement. The second is a table name. The table name in the CREATE -** TRIGGER statement is replaced with the third argument and the result -** returned. This is analagous to renameTableFunc() above, except for CREATE -** TRIGGER, not CREATE INDEX and CREATE TABLE. -*/ -static void renameTriggerFunc( - sqlite3_context *context, - int NotUsed, - sqlite3_value **argv -){ - unsigned char const *zSql = sqlite3_value_text(argv[0]); - unsigned char const *zTableName = sqlite3_value_text(argv[1]); - - int token; - Token tname; - int dist = 3; - unsigned char const *zCsr = zSql; - int len = 0; - char *zRet; - sqlite3 *db = sqlite3_context_db_handle(context); - - UNUSED_PARAMETER(NotUsed); - - /* The principle used to locate the table name in the CREATE TRIGGER - ** statement is that the table name is the first token that is immediately - ** preceded by either TK_ON or TK_DOT and immediately followed by one - ** of TK_WHEN, TK_BEGIN or TK_FOR. - */ - if( zSql ){ - do { - - if( !*zCsr ){ - /* Ran out of input before finding the table name. Return NULL. */ - return; - } - - /* Store the token that zCsr points to in tname. */ - tname.z = (char*)zCsr; - tname.n = len; - - /* Advance zCsr to the next token. Store that token type in 'token', - ** and its length in 'len' (to be used next iteration of this loop). - */ - do { - zCsr += len; - len = sqlite3GetToken(zCsr, &token); - }while( token==TK_SPACE ); - assert( len>0 ); - - /* Variable 'dist' stores the number of tokens read since the most - ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN - ** token is read and 'dist' equals 2, the condition stated above - ** to be met. - ** - ** Note that ON cannot be a database, table or column name, so - ** there is no need to worry about syntax like - ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc. - */ - dist++; - if( token==TK_DOT || token==TK_ON ){ - dist = 0; - } - } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) ); - - /* Variable tname now contains the token that is the old table-name - ** in the CREATE TRIGGER statement. - */ - zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql), - zSql, zTableName, tname.z+tname.n); - sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC); - } -} -#endif /* !SQLITE_OMIT_TRIGGER */ - -/* -** Register built-in functions used to help implement ALTER TABLE -*/ -SQLITE_PRIVATE void sqlite3AlterFunctions(void){ - static FuncDef aAlterTableFuncs[] = { - FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc), -#ifndef SQLITE_OMIT_TRIGGER - FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc), -#endif -#ifndef SQLITE_OMIT_FOREIGN_KEY - FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc), -#endif - }; - sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs)); -} - -/* -** This function is used to create the text of expressions of the form: -** -** name= OR name= OR ... -** -** If argument zWhere is NULL, then a pointer string containing the text -** "name=" is returned, where is the quoted version -** of the string passed as argument zConstant. The returned buffer is -** allocated using sqlite3DbMalloc(). It is the responsibility of the -** caller to ensure that it is eventually freed. -** -** If argument zWhere is not NULL, then the string returned is -** " OR name=", where is the contents of zWhere. -** In this case zWhere is passed to sqlite3DbFree() before returning. -** -*/ -static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){ - char *zNew; - if( !zWhere ){ - zNew = sqlite3MPrintf(db, "name=%Q", zConstant); - }else{ - zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant); - sqlite3DbFree(db, zWhere); - } - return zNew; -} - -#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) -/* -** Generate the text of a WHERE expression which can be used to select all -** tables that have foreign key constraints that refer to table pTab (i.e. -** constraints for which pTab is the parent table) from the sqlite_master -** table. -*/ -static char *whereForeignKeys(Parse *pParse, Table *pTab){ - FKey *p; - char *zWhere = 0; - for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ - zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName); - } - return zWhere; -} -#endif - -/* -** Generate the text of a WHERE expression which can be used to select all -** temporary triggers on table pTab from the sqlite_temp_master table. If -** table pTab has no temporary triggers, or is itself stored in the -** temporary database, NULL is returned. -*/ -static char *whereTempTriggers(Parse *pParse, Table *pTab){ - Trigger *pTrig; - char *zWhere = 0; - const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */ - - /* If the table is not located in the temp-db (in which case NULL is - ** returned, loop through the tables list of triggers. For each trigger - ** that is not part of the temp-db schema, add a clause to the WHERE - ** expression being built up in zWhere. - */ - if( pTab->pSchema!=pTempSchema ){ - sqlite3 *db = pParse->db; - for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){ - if( pTrig->pSchema==pTempSchema ){ - zWhere = whereOrName(db, zWhere, pTrig->zName); - } - } - } - if( zWhere ){ - char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere); - sqlite3DbFree(pParse->db, zWhere); - zWhere = zNew; - } - return zWhere; -} - -/* -** Generate code to drop and reload the internal representation of table -** pTab from the database, including triggers and temporary triggers. -** Argument zName is the name of the table in the database schema at -** the time the generated code is executed. This can be different from -** pTab->zName if this function is being called to code part of an -** "ALTER TABLE RENAME TO" statement. -*/ -static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){ - Vdbe *v; - char *zWhere; - int iDb; /* Index of database containing pTab */ -#ifndef SQLITE_OMIT_TRIGGER - Trigger *pTrig; -#endif - - v = sqlite3GetVdbe(pParse); - if( NEVER(v==0) ) return; - assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); - iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); - assert( iDb>=0 ); - -#ifndef SQLITE_OMIT_TRIGGER - /* Drop any table triggers from the internal schema. */ - for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){ - int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema); - assert( iTrigDb==iDb || iTrigDb==1 ); - sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0); - } -#endif - - /* Drop the table and index from the internal schema. */ - sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); - - /* Reload the table, index and permanent trigger schemas. */ - zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName); - if( !zWhere ) return; - sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere); - -#ifndef SQLITE_OMIT_TRIGGER - /* Now, if the table is not stored in the temp database, reload any temp - ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. - */ - if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){ - sqlite3VdbeAddParseSchemaOp(v, 1, zWhere); - } -#endif -} - -/* -** Parameter zName is the name of a table that is about to be altered -** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN). -** If the table is a system table, this function leaves an error message -** in pParse->zErr (system tables may not be altered) and returns non-zero. -** -** Or, if zName is not a system table, zero is returned. -*/ -static int isSystemTable(Parse *pParse, const char *zName){ - if( 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){ - sqlite3ErrorMsg(pParse, "table %s may not be altered", zName); - return 1; - } - return 0; -} - -/* -** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" -** command. -*/ -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; -#ifndef SQLITE_OMIT_TRIGGER - char *zWhere = 0; /* Where clause to locate temp triggers */ -#endif - 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) ){ - sqlite3ErrorMsg(pParse, - "there is already another table or index with this name: %s", zName); - goto exit_rename_table; - } - - /* Make sure it is not a system table being altered, or a reserved name - ** that the table is being renamed to. - */ - if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){ - goto exit_rename_table; - } - if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto - exit_rename_table; - } - -#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). Open a statement transaction if the table is a virtual - ** table. - */ - v = sqlite3GetVdbe(pParse); - if( v==0 ){ - goto exit_rename_table; - } - sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb); - sqlite3ChangeCookie(pParse, iDb); - - /* If this is a virtual table, invoke the xRename() function if - ** one is defined. The xRename() callback will modify the names - ** of any resources used by the v-table implementation (including other - ** SQLite tables) that are identified by the name of the virtual table. - */ -#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); - sqlite3MayAbort(pParse); - } -#endif - - /* figure out how many UTF-8 characters are in zName */ - zTabName = pTab->zName; - nTabName = sqlite3Utf8CharLen(zTabName, -1); - -#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) - if( db->flags&SQLITE_ForeignKeys ){ - /* If foreign-key support is enabled, rewrite the CREATE TABLE - ** statements corresponding to all child tables of foreign key constraints - ** for which the renamed table is the parent table. */ - if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){ - sqlite3NestedParse(pParse, - "UPDATE \"%w\".%s SET " - "sql = sqlite_rename_parent(sql, %Q, %Q) " - "WHERE %s;", zDb, MASTER_NAME, zTabName, zName, zWhere); - sqlite3DbFree(db, zWhere); - } - } -#endif - - /* Modify the sqlite_master table to use the new table name. */ - sqlite3NestedParse(pParse, - "UPDATE %Q.%s SET " -#ifdef SQLITE_OMIT_TRIGGER - "sql = sqlite_rename_table(sql, %Q), " -#else - "sql = CASE " - "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)" - "ELSE sqlite_rename_table(sql, %Q) END, " -#endif - "tbl_name = %Q, " - "name = CASE " - "WHEN type='table' THEN %Q " - "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN " - "'sqlite_autoindex_' || %Q || substr(name,%d+18) " - "ELSE name END " - "WHERE tbl_name=%Q COLLATE nocase AND " - "(type='table' OR type='index' OR type='trigger');", - zDb, MASTER_NAME, zName, zName, zName, -#ifndef SQLITE_OMIT_TRIGGER - zName, -#endif - 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 - -#ifndef SQLITE_OMIT_TRIGGER - /* If there are TEMP triggers on this table, modify the sqlite_temp_master - ** table. Don't do this if the table being ALTERed is itself located in - ** the temp database. - */ - if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){ - sqlite3NestedParse(pParse, - "UPDATE sqlite_temp_master SET " - "sql = sqlite_rename_trigger(sql, %Q), " - "tbl_name = %Q " - "WHERE %s;", zName, zName, zWhere); - sqlite3DbFree(db, zWhere); - } -#endif - -#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER) - if( db->flags&SQLITE_ForeignKeys ){ - FKey *p; - for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){ - Table *pFrom = p->pFrom; - if( pFrom!=pTab ){ - reloadTableSchema(pParse, p->pFrom, pFrom->zName); - } - } - } -#endif - - /* Drop and reload the internal table schema. */ - reloadTableSchema(pParse, pTab, zName); - -exit_rename_table: - sqlite3SrcListDelete(db, pSrc); - sqlite3DbFree(db, zName); - db->mDbFlags = savedDbFlags; -} - -/* -** 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 = pParse->pVdbe; /* The prepared statement under construction */ - int r1; /* Temporary registers */ - - db = pParse->db; - if( pParse->nErr || db->mallocFailed ) return; - assert( v!=0 ); - 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 - - /* 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; - } - - /* 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( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){ - sqlite3ErrorMsg(pParse, - "Cannot add a REFERENCES column with non-NULL default value"); - return; - } - if( pCol->notNull && !pDflt ){ - sqlite3ErrorMsg(pParse, - "Cannot add a NOT NULL column with default value NULL"); - return; - } - - /* Ensure the default expression is something that sqlite3ValueFromExpr() - ** can handle (i.e. not CURRENT_TIME etc.) - */ - if( pDflt ){ - 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 ){ - sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default"); - return; - } - sqlite3ValueFree(pVal); - } - - /* 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\".%s SET " - "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) " - "WHERE type = 'table' AND name = %Q", - zDb, MASTER_NAME, 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. - */ - 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 schema of the modified table. */ - reloadTableSchema(pParse, pTab, pTab->zName); -} - -/* -** This function is called by the parser after the table-name in -** an "ALTER TABLE ADD" statement is parsed. Argument -** pSrc is the full-name of the table being altered. -** -** This routine makes a (partial) copy of the Table structure -** for the table being altered and sets Parse.pNewTable to point -** to it. Routines called by the parser as the column definition -** is parsed (i.e. sqlite3AddColumn()) add the new Column data to -** the copy. The copy of the Table structure is deleted by tokenize.c -** after parsing is finished. -** -** Routine sqlite3AlterFinishAddColumn() will be called to complete -** coding the "ALTER TABLE ... ADD" statement. -*/ -SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){ - Table *pNew; - Table *pTab; - Vdbe *v; - int iDb; - int i; - int nAlloc; - sqlite3 *db = pParse->db; - - /* Look up the table being altered. */ - 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!=isSystemTable(pParse, pTab->zName) ){ - goto exit_begin_add_column; - } - - 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->zColl = 0; - pCol->pDflt = 0; - } - pNew->pSchema = db->aDb[iDb].pSchema; - pNew->addColOffset = pTab->addColOffset; - pNew->nTabRef = 1; - - /* Begin a transaction and increment the schema cookie. */ - sqlite3BeginWriteOperation(pParse, 0, iDb); - v = sqlite3GetVdbe(pParse); - if( !v ) goto exit_begin_add_column; - sqlite3ChangeCookie(pParse, iDb); - -exit_begin_add_column: - sqlite3SrcListDelete(db, pSrc); - return; -} -#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 and later and with -** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3 -** is a superset of sqlite_stat2. 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. It is -** not possible to enable both STAT3 and STAT4 at the same time. If they -** are both enabled, then STAT4 takes precedence. -** -** 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 -# define IsStat3 0 -#elif defined(SQLITE_ENABLE_STAT3) -# define IsStat4 0 -# define IsStat3 1 -#else -# define IsStat4 0 -# define IsStat3 0 -# undef SQLITE_STAT4_SAMPLES -# define SQLITE_STAT4_SAMPLES 1 -#endif -#define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */ - -/* -** 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" }, - { "sqlite_stat3", 0 }, -#elif defined(SQLITE_ENABLE_STAT3) - { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" }, - { "sqlite_stat4", 0 }, -#else - { "sqlite_stat3", 0 }, - { "sqlite_stat4", 0 }, -#endif - }; - int i; - sqlite3 *db = pParse->db; - Db *pDb; - Vdbe *v = sqlite3GetVdbe(pParse); - int aRoot[ArraySize(aTable)]; - u8 aCreateTbl[ArraySize(aTable)]; - - 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( aTable[i].zCols ){ - /* The sqlite_statN table does not exist. Create it. Note that a - ** side-effect of the CREATE TABLE statement is to leave the rootpage - ** of the new table in register pParse->regRoot. This is important - ** because the OpenWrite opcode below will be needing it. */ - sqlite3NestedParse(pParse, - "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols - ); - aRoot[i] = 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; - aCreateTbl[i] = 0; - sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab); - if( zWhere ){ - sqlite3NestedParse(pParse, - "DELETE FROM %Q.%s WHERE %s=%Q", - pDb->zDbSName, zTab, zWhereType, zWhere - ); - }else{ - /* The sqlite_stat[134] table already exists. Delete all rows. */ - sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb); - } - } - } - - /* Open the sqlite_stat[134] tables for writing. */ - for(i=0; aTable[i].zCols; i++){ - assert( inRowid ){ - sqlite3DbFree(db, p->u.aRowid); - p->nRowid = 0; - } -} -#endif - -/* Initialize the BLOB value of a ROWID -*/ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 -static void sampleSetRowid(sqlite3 *db, Stat4Sample *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_STAT3_OR_STAT4 -static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *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_STAT3_OR_STAT4 -static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *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 Stat4Accum structure. -*/ -static void stat4Destructor(void *pOld){ - Stat4Accum *p = (Stat4Accum*)pOld; -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - 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) SQL function. The three 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: The number of rows in the index (note 2) -** -** 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. -** -** Note 2: C is only used for STAT3 and STAT4. -** -** 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 Stat4Accum object in heap memory. The return -** value is a pointer to the Stat4Accum object. The datatype of the -** return value is BLOB, but it is really just a pointer to the Stat4Accum -** object. -*/ -static void statInit( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - Stat4Accum *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; /* Database connection */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - int mxSample = SQLITE_STAT4_SAMPLES; -#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 Stat4Accum object */ - n = sizeof(*p) - + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */ - + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */ - + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.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->nRow = 0; - p->nCol = nCol; - p->nKeyCol = nKeyCol; - p->current.anDLt = (tRowcnt*)&p[1]; - p->current.anEq = &p->current.anDLt[nColUp]; - -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - { - u8 *pSpace; /* Allocated space not yet assigned */ - int i; /* Used to iterate through p->aSample[] */ - - p->iGet = -1; - p->mxSample = mxSample; - p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(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 Stat4Accum.a[] and aBest[] arrays */ - p->a = (struct Stat4Sample*)&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), stat4Destructor); -} -static const FuncDef statInitFuncdef = { - 2+IsStat34, /* nArg */ - SQLITE_UTF8, /* funcFlags */ - 0, /* pUserData */ - 0, /* pNext */ - statInit, /* xSFunc */ - 0, /* xFinalize */ - "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( - Stat4Accum *pAccum, - Stat4Sample *pNew, - Stat4Sample *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_STAT3_OR_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( - Stat4Accum *pAccum, - Stat4Sample *pNew, - Stat4Sample *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; -#ifdef SQLITE_ENABLE_STAT4 - if( nEqNew==nEqOld ){ - if( pNew->iColiCol ) return 1; - return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld)); - } - return 0; -#else - return (nEqNew==nEqOld && pNew->iHash>pOld->iHash); -#endif -} - -/* -** 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(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){ - Stat4Sample *pSample = 0; - int i; - - assert( IsStat4 || nEqZero==0 ); - -#ifdef SQLITE_ENABLE_STAT4 - /* Stat4Accum.nMaxEqZero is set to the maximum number of leading 0 - ** values in the anEq[] array of any sample in Stat4Accum.a[]. In - ** other words, if nMaxEqZero is n, then it is guaranteed that there - ** are no samples with Stat4Sample.anEq[m]==0 for (m>=n). */ - if( nEqZero>p->nMaxEqZero ){ - p->nMaxEqZero = nEqZero; - } - if( pNew->isPSample==0 ){ - Stat4Sample *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--){ - Stat4Sample *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; - } - } -#endif - - /* If necessary, remove sample iMin to make room for the new sample. */ - if( p->nSample>=p->mxSample ){ - Stat4Sample *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. */ -#ifdef SQLITE_ENABLE_STAT4 - assert( p->nSample==0 - || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] ); -#endif - - /* 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); - -#ifdef SQLITE_ENABLE_STAT4 - find_new_min: -#endif - 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_STAT3_OR_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(Stat4Accum *p, int iChng){ -#ifdef SQLITE_ENABLE_STAT4 - 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--){ - Stat4Sample *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 - -#if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4) - if( iChng==0 ){ - tRowcnt nLt = p->current.anLt[0]; - tRowcnt nEq = p->current.anEq[0]; - - /* Check if this is to be a periodic sample. If so, add it. */ - if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){ - p->current.isPSample = 1; - sampleInsert(p, &p->current, 0); - p->current.isPSample = 0; - }else - - /* Or if it is a non-periodic sample. Add it in this case too. */ - if( p->nSamplemxSample - || sampleIsBetter(p, &p->current, &p->a[p->iMin]) - ){ - sampleInsert(p, &p->current, 0); - } - } -#endif - -#ifndef SQLITE_ENABLE_STAT3_OR_STAT4 - UNUSED_PARAMETER( p ); - UNUSED_PARAMETER( iChng ); -#endif -} - -/* -** Implementation of the stat_push SQL function: stat_push(P,C,R) -** Arguments: -** -** P Pointer to the Stat4Accum 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. -** -** This SQL function always returns NULL. It's purpose it to accumulate -** statistical data and/or samples in the Stat4Accum object about the -** index being analyzed. The stat_get() SQL function will later be used to -** extract relevant information for constructing the sqlite_statN tables. -** -** The R parameter is only used for STAT3 and STAT4 -*/ -static void statPush( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - int i; - - /* The three function arguments */ - Stat4Accum *p = (Stat4Accum*)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 */ - samplePushPrevious(p, iChng); - - /* 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_STAT3_OR_STAT4 - p->current.anLt[i] += p->current.anEq[i]; -#endif - p->current.anEq[i] = 1; - } - } - p->nRow++; -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - 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; -#endif - -#ifdef SQLITE_ENABLE_STAT4 - { - tRowcnt 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); - } - } - } -#endif -} -static const FuncDef statPushFuncdef = { - 2+IsStat34, /* nArg */ - SQLITE_UTF8, /* funcFlags */ - 0, /* pUserData */ - 0, /* pNext */ - statPush, /* xSFunc */ - 0, /* xFinalize */ - "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 Stat4Accum object by prior calls to stat_push(). The P parameter -** has type BLOB but it is really just a pointer to the Stat4Accum 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 poiner to a Stat4Accum object, never a -** NULL. -** -** If neither STAT3 nor STAT4 are 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 -){ - Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]); -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - /* STAT3 and STAT4 have 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 - ); - 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 stabbing 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", (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_STAT3_OR_STAT4 - else if( eCall==STAT_GET_ROWID ){ - if( p->iGet<0 ){ - samplePushPrevious(p, 0); - p->iGet = 0; - } - if( p->iGetnSample ){ - Stat4Sample *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; - } - } - - if( IsStat3 ){ - sqlite3_result_int64(context, (i64)aCnt[0]); - }else{ - 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_STAT3_OR_STAT4 */ -#ifndef SQLITE_DEBUG - UNUSED_PARAMETER( argc ); -#endif -} -static const FuncDef statGetFuncdef = { - 1+IsStat34, /* nArg */ - SQLITE_UTF8, /* funcFlags */ - 0, /* pUserData */ - 0, /* pNext */ - statGet, /* xSFunc */ - 0, /* xFinalize */ - "stat_get", /* zName */ - {0} -}; - -static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){ - assert( regOut!=regStat4 && regOut!=regStat4+1 ); -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1); -#elif SQLITE_DEBUG - assert( iParam==STAT_GET_STAT1 ); -#else - UNUSED_PARAMETER( iParam ); -#endif - sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut, - (char*)&statGetFuncdef, P4_FUNCDEF); - sqlite3VdbeChangeP5(v, 1 + IsStat34); -} - -/* -** 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 regStat4 = iMem++; /* Register to hold Stat4Accum object */ - int regChng = iMem++; /* Index of changed index field */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - int regRowid = iMem++; /* Rowid argument passed to stat_push() */ -#endif - int regTemp = iMem++; /* 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) */ - - 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)==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 - - /* 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) the number of rows in the index, - ** - ** - ** The third argument is only used for STAT3 and STAT4 - */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3); -#endif - sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1); - sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2); - sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4, - (char*)&statInitFuncdef, P4_FUNCDEF); - sqlite3VdbeChangeP5(v, 2+IsStat34); - - /* Implementation of the following: - ** - ** Rewind csr - ** if eof(csr) goto end_of_scan; - ** regChng = 0 - ** goto next_push_0; - ** - */ - addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur); - VdbeCoverage(v); - sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng); - addrNextRow = sqlite3VdbeCurrentAddr(v); - - if( nColTest>0 ){ - int endDistinctTest = sqlite3VdbeMakeLabel(v); - 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); - 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 = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]); - assert( k>=0 && knColumn ); - sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j); - VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName)); - } - sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid); - sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol); - } -#endif - assert( regChng==(regStat4+1) ); - sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp, - (char*)&statPushFuncdef, P4_FUNCDEF); - sqlite3VdbeChangeP5(v, 2+IsStat34); - sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v); - - /* Add the entry to the stat1 table. */ - callStatGet(v, regStat4, 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); - sqlite3VdbeChangeP5(v, OPFLAG_APPEND); - - /* Add the entries to the stat3 or stat4 table. */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 - { - 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(v, regStat4, STAT_GET_ROWID, regSampleRowid); - addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid); - VdbeCoverage(v); - callStatGet(v, regStat4, STAT_GET_NEQ, regEq); - callStatGet(v, regStat4, STAT_GET_NLT, regLt); - callStatGet(v, regStat4, STAT_GET_NDLT, regDLt); - sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0); - /* We know that the regSampleRowid row exists because it was read by - ** the previous loop. Thus the not-found jump of seekOp will never - ** be taken */ - VdbeCoverageNeverTaken(v); -#ifdef SQLITE_ENABLE_STAT3 - sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample); -#else - 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); - 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_STAT3_OR_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_STAT3_OR_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_STAT3_OR_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 ){ - pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3)); - }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_STAT3_OR_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_STAT3_OR_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_STAT3_OR_STAT4 */ -} - -#ifdef SQLITE_ENABLE_STAT3_OR_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 or sqlite_stat3 table -** into the relevant Index.aSample[] arrays. -** -** Arguments zSql1 and zSql2 must point to SQL statements that return -** data equivalent to the following (statements are different for stat3, -** see the caller of this function for details): -** -** 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 */ - int bStat3, /* Assume single column records only */ - 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 || bStat3 || pIdx->nSample==0 ); - /* Index.nSample is non-zero at this point if data has already been - ** loaded from the stat4 table. In this case ignore stat3 data. */ - if( pIdx==0 || pIdx->nSample ) continue; - if( bStat3==0 ){ - 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. In this case ignore stat3 data. */ - nCol = pIdx->nSampleCol; - if( bStat3 && nCol>1 ) continue; - 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 and sqlite_stat3 tables 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, 0, - "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx", - "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4", - zDb - ); - } - - if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){ - rc = loadStatTbl(db, 1, - "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx", - "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3", - zDb - ); - } - - return rc; -} -#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ - -/* -** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The -** contents of sqlite_stat1 are used to populate the Index.aiRowEst[] -** arrays. The contents of sqlite_stat3/4 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_STAT3/4 was defined -** during compilation and the sqlite_stat3/4 table is present, no data is -** read from it. -** -** If SQLITE_ENABLE_STAT3/4 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_STAT3_OR_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_STAT3_OR_STAT4 - if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){ - db->lookaside.bDisable++; - rc = loadStat4(db, sInfo.zDatabase); - db->lookaside.bDisable--; - } - 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; -} - -/* -** An SQL user-function registered to do the work of an ATTACH statement. The -** three arguments to the function come directly from an attach statement: -** -** ATTACH DATABASE x AS y KEY z -** -** SELECT sqlite_attach(x, y, z) -** -** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the -** third argument. -*/ -static void attachFunc( - sqlite3_context *context, - int NotUsed, - sqlite3_value **argv -){ - int i; - int rc = 0; - sqlite3 *db = sqlite3_context_db_handle(context); - 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 = ""; - - /* 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++){ - char *z = db->aDb[i].zDbSName; - assert( z && zName ); - if( sqlite3StrICmp(z, zName)==0 ){ - zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName); - goto attach_error; - } - } - - /* Allocate the new entry in the db->aDb[] array and 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); - sqlite3_free( zPath ); - db->nDb++; - db->skipBtreeMutex = 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; - pNew->zDbSName = sqlite3DbStrDup(db, zName); - if( rc==SQLITE_OK && pNew->zDbSName==0 ){ - rc = SQLITE_NOMEM_BKPT; - } - - -#ifdef SQLITE_HAS_CODEC - if( rc==SQLITE_OK ){ - extern int sqlite3CodecAttach(sqlite3*, int, const void*, int); - extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*); - int nKey; - char *zKey; - int t = sqlite3_value_type(argv[2]); - switch( t ){ - case SQLITE_INTEGER: - case SQLITE_FLOAT: - zErrDyn = sqlite3DbStrDup(db, "Invalid key value"); - rc = SQLITE_ERROR; - break; - - case SQLITE_TEXT: - case SQLITE_BLOB: - nKey = sqlite3_value_bytes(argv[2]); - zKey = (char *)sqlite3_value_blob(argv[2]); - rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey); - break; - - case SQLITE_NULL: - /* No key specified. Use the key from the main database */ - sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey); - if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){ - rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey); - } - break; - } - } -#endif - - /* If the file was opened successfully, read the schema for the new database. - ** If this fails, or if opening the file failed, then close the file and - ** remove the entry from the db->aDb[] array. i.e. put everything back the way - ** we found it. - */ - if( rc==SQLITE_OK ){ - sqlite3BtreeEnterAll(db); - rc = sqlite3Init(db, &zErrDyn); - sqlite3BtreeLeaveAll(db); - } -#ifdef SQLITE_USER_AUTHENTICATION - if( rc==SQLITE_OK ){ - u8 newAuth = 0; - rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth); - if( newAuthauth.authLevel ){ - rc = SQLITE_AUTH_USER; - } - } -#endif - if( rc ){ - 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; - 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( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) 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; - } - - 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 ){ - sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3, - (char *)pFunc, P4_FUNCDEF); - assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg ); - sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg)); - - /* 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 */ - "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 */ - "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->bVarOnly = (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; - const char *zDb; - struct SrcList_item *pItem; - - if( NEVER(pList==0) ) return 0; - zDb = pFix->zDb; - for(i=0, pItem=pList->a; inSrc; i++, pItem++){ - if( pFix->bVarOnly==0 ){ - if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){ - sqlite3ErrorMsg(pFix->pParse, - "%s %T cannot reference objects in database %s", - pFix->zType, pFix->pName, pItem->zDatabase); - return 1; - } - sqlite3DbFree(pFix->pParse->db, pItem->zDatabase); - pItem->zDatabase = 0; - pItem->pSchema = pFix->pSchema; - } -#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) - if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1; - if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1; -#endif - } - 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( sqlite3FixExpr(pFix, pSelect->pOffset) ){ - 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( 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; - } - 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; - sqlite3ExpirePreparedStatements(db); - sqlite3_mutex_leave(db->mutex); - return SQLITE_OK; -} - -/* -** Write an error message into pParse->zErrMsg that explains that the -** user-supplied authorization function returned an illegal value. -*/ -static void sqliteAuthBadReturnCode(Parse *pParse){ - sqlite3ErrorMsg(pParse, "authorizer malfunction"); - pParse->rc = SQLITE_ERROR; -} - -/* -** Invoke the authorization callback for permission to read column zCol from -** table zTab in database zDb. This function assumes that an authorization -** callback has been registered (i.e. that sqlite3.xAuth is not NULL). -** -** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed -** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE -** is treated as SQLITE_DENY. In this case an error is left in pParse. -*/ -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 */ - - 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; - } - - assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER ); - 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. - */ - if( db->init.busy || IN_DECLARE_VTAB ){ - 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 */ - int 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 */ - int 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 */ - if( pParse->pConstExpr ){ - ExprList *pEL = pParse->pConstExpr; - pParse->okConstFactor = 0; - for(i=0; inExpr; i++){ - sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg); - } - } - - /* 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 ){ - assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */ - /* A minimum of one cursor is required if autoincrement is used - * See ticket [a696379c1f08866] */ - if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1; - 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 SQLITE_MASTER. 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 ){ - return; /* A malloc must have failed */ - } - 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++){ - int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ - if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){ - assert( sqlite3SchemaMutexHeld(db, j, 0) ); - p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName); - if( p ) return p; - } - } - /* Not found. If the name we were looking for was temp.sqlite_master - ** then change the name to sqlite_temp_master and try again. */ - if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break; - if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break; - zName = TEMP_MASTER_NAME; - } - return 0; -} - -/* -** 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; - - /* 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 0; - } - - p = sqlite3FindTable(pParse->db, zName, zDbase); - if( p==0 ){ - const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table"; -#ifndef SQLITE_OMIT_VIRTUALTABLE - if( sqlite3FindDbName(pParse->db, zDbase)<1 ){ - /* 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. */ - Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName); - if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){ - pMod = sqlite3PragmaVtabRegister(pParse->db, zName); - } - if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){ - return pMod->pEpoTab; - } - } -#endif - if( (flags & LOCATE_NOERR)==0 ){ - if( zDbase ){ - sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName); - }else{ - sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName); - } - pParse->checkSchema = 1; - } - } - - 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 && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue; - assert( sqlite3SchemaMutexHeld(db, j, 0) ); - p = sqlite3HashFind(&pSchema->idxHash, zName); - if( p ) break; - } - return p; -} - -/* -** Reclaim the memory used by an index -*/ -static void freeIndex(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_STAT3_OR_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; - } - } - freeIndex(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); - } - - 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); - assert( db->nSchemaLock==0 ); - for(i=0; inDb; i++){ - Db *pDb = &db->aDb[i]; - if( pDb->pSchema ){ - sqlite3SchemaClear(pDb->pSchema); - } - } - db->mDbFlags &= ~DBFLAG_SchemaChange; - sqlite3VtabUnlockList(db); - sqlite3BtreeLeaveAll(db); - 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++){ - 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. */ - int nLookaside = 0; - if( db && (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 ); - } - freeIndex(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_master table stored in database number iDb for -** writing. The table is opened using cursor 0. -*/ -SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){ - Vdbe *v = sqlite3GetVdbe(p); - sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME); - sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_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 - || (db->mDbFlags & DBFLAG_Vacuum)!=0); - iDb = db->init.iDb; - *pUnqual = pName1; - } - return iDb; -} - -/* -** This routine is used to check if the UTF-8 string zName is a legal -** unqualified name for a new schema object (table, index, view or -** trigger). All names are legal except those that begin with the string -** "sqlite_" (in upper, lower or mixed case). This portion of the namespace -** is reserved for internal use. -*/ -SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){ - if( !pParse->db->init.busy && pParse->nested==0 - && (pParse->db->flags & SQLITE_WriteSchema)==0 - && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){ - sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName); - return SQLITE_ERROR; - } - return SQLITE_OK; -} - -/* -** 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; -} - -/* -** Return the column of index pIdx that corresponds to table -** column iCol. Return -1 if not found. -*/ -SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){ - int i; - for(i=0; inColumn; i++){ - if( iCol==pIdx->aiColumn[i] ) return i; - } - return -1; -} - -/* -** 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_master or sqlite_temp_master 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); - } - pParse->sNameToken = *pName; - if( zName==0 ) return; - if( SQLITE_OK!=sqlite3CheckObjectName(pParse, 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_DECLARE_VTAB ){ - 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 SQLITE_MASTER table. Note in particular that we must go ahead - ** and allocate the record number for the table entry now. Before any - ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause - ** indices to be created and the table record must come before the - ** indices. Hence, the record number for the table must be allocated - ** now. - */ - if( !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_master table. - ** The record created does not contain anything yet. It will be replaced - ** by the real entry in code generated at sqlite3EndTable(). - ** - ** The rowid for the new entry is left in register pParse->regRowid. - ** The root page number of the new table is left in reg pParse->regRoot. - ** The rowid and root page number values are needed by the code that - ** sqlite3EndTable will generate. - */ -#if !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); - } - sqlite3OpenMasterTable(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; - 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; - sqlite3ColumnPropertiesFromName(p, pCol); - - if( pType->n==0 ){ - /* If there is no type specified, columns have the default affinity - ** 'BLOB'. */ - pCol->affinity = SQLITE_AFF_BLOB; - pCol->szEst = 1; - }else{ - zType = z + sqlite3Strlen30(z) + 1; - memcpy(zType, pType->z, pType->n); - zType[pType->n] = 0; - sqlite3Dequote(zType); - pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst); - pCol->colFlags |= COLFLAG_HASTYPE; - } - p->nCol++; - 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; - p = pParse->pNewTable; - if( p==0 || NEVER(p->nCol<1) ) return; - p->aCol[p->nCol-1].notNull = (u8)onError; - p->tabFlags |= TF_HasNotNull; -} - -/* -** 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, u8 *pszEst){ - 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 pszEst is not NULL, store an estimate of the field size. The - ** estimate is scaled so that the size of an integer is 1. */ - if( pszEst ){ - *pszEst = 1; /* default size is approx 4 bytes */ - if( aff255 ) v = 255; - *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */ - break; - } - zChar++; - } - }else{ - *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/ - } - } - } - 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, ExprSpan *pSpan){ - Table *p; - Column *pCol; - sqlite3 *db = pParse->db; - p = pParse->pNewTable; - if( p!=0 ){ - pCol = &(p->aCol[p->nCol-1]); - if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){ - sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant", - pCol->zName); - }else{ - /* A copy of pExpr is used instead of the original, as pExpr contains - ** tokens that point to volatile memory. The 'span' of the expression - ** is required by pragma table_info. - */ - Expr x; - sqlite3ExprDelete(db, pCol->pDflt); - memset(&x, 0, sizeof(x)); - x.op = TK_SPAN; - x.u.zToken = sqlite3DbStrNDup(db, (char*)pSpan->zStart, - (int)(pSpan->zEnd - pSpan->zStart)); - x.pLeft = pSpan->pExpr; - x.flags = EP_Skip; - pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE); - sqlite3DbFree(db, x.u.zToken); - } - } - sqlite3ExprDelete(db, pSpan->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 epxression 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; - } -} - -/* -** 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]; - pCol->colFlags |= COLFLAG_PRIMKEY; - 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]; - pCol->colFlags |= COLFLAG_PRIMKEY; - break; - } - } - } - } - } - if( nTerm==1 - && pCol - && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0 - && sortOrder!=SQLITE_SO_DESC - ){ - pTab->iPKey = iCol; - pTab->keyConf = (u8)onError; - assert( autoInc==0 || autoInc==1 ); - pTab->tabFlags |= autoInc*TF_Autoincrement; - if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder; - }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); - } -} - -/* -** This function returns the collation sequence for database native text -** encoding identified by the string zName, length nName. -** -** If the requested collation sequence is not available, or not available -** in the database native encoding, the collation factory is invoked to -** request it. If the collation factory does not supply such a sequence, -** and the sequence is available in another text encoding, then that is -** returned instead. -** -** If no versions of the requested collations sequence are available, or -** another error occurs, NULL is returned and an error message written into -** pParse. -** -** This routine is a wrapper around sqlite3FindCollSeq(). This routine -** invokes the collation factory if the named collation cannot be found -** and generates an error message. -** -** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq() -*/ -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; -} - - -/* -** 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, - db->aDb[iDb].pSchema->schema_cookie+1); -} - -/* -** 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 value x is found any of the first nCol entries of aiCol[] -*/ -static int hasColumn(const i16 *aiCol, int nCol, int x){ - while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1; - return 0; -} - -/* -** 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_master table entry -** for the PRIMARY KEY as the primary key index is now -** identified by the sqlite_master 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 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; - } - } - } - - /* The remaining transformations only apply to b-tree tables, not to - ** virtual tables */ - if( IN_DECLARE_VTAB ) return; - - /* 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; - pList->a[0].sortOrder = pParse->iPkSortOrder; - assert( pParse->pNewTable==pTab ); - sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0, - SQLITE_IDXTYPE_PRIMARYKEY); - if( db->mallocFailed ) return; - pPk = sqlite3PrimaryKeyIndex(pTab); - pTab->iPKey = -1; - }else{ - pPk = sqlite3PrimaryKeyIndex(pTab); - - /* - ** 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( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){ - pPk->nColumn--; - }else{ - pPk->aiColumn[j++] = pPk->aiColumn[i]; - } - } - pPk->nKeyCol = j; - } - assert( pPk!=0 ); - pPk->isCovering = 1; - if( !db->init.imposterTable ) pPk->uniqNotNull = 1; - nPk = pPk->nKeyCol; - - /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master - ** 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, 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; iaiColumn, 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; iaiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){ - pIdx->aiColumn[j] = pPk->aiColumn[i]; - pIdx->azColl[j] = pPk->azColl[i]; - j++; - } - } - assert( pIdx->nColumn>=pIdx->nKeyCol+n ); - assert( pIdx->nColumn>=j ); - } - - /* Add all table columns to the PRIMARY KEY index - */ - if( nPknCol ){ - if( resizeIndexObject(db, pPk, pTab->nCol) ) return; - for(i=0, j=nPk; inCol; i++){ - if( !hasColumn(pPk->aiColumn, j, i) ){ - assert( jnColumn ); - pPk->aiColumn[j] = i; - pPk->azColl[j] = sqlite3StrBINARY; - j++; - } - } - assert( pPk->nColumn==j ); - assert( pTab->nCol==j ); - }else{ - pPk->nColumn = pTab->nCol; - } -} - -/* -** This routine is called to report the final ")" that terminates -** a CREATE TABLE statement. -** -** The table structure that other action routines have been building -** is added to the internal hash tables, assuming no errors have -** occurred. -** -** An entry for the table is made in the master table on disk, unless -** this is a temporary table or db->init.busy==1. When db->init.busy==1 -** it means we are reading the sqlite_master table because we just -** connected to the database or because the sqlite_master table has -** recently changed, so the entry for this table already exists in -** the sqlite_master table. We do not want to create it again. -** -** If the pSelect argument is not NULL, it means that this routine -** was called to create a table generated from a -** "CREATE TABLE ... AS SELECT ..." statement. The column names of -** the new table will match the result set of the SELECT. -*/ -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; - - assert( !db->init.busy || !pSelect ); - - /* If the db->init.busy is 1 it means we are reading the SQL off the - ** "sqlite_master" or "sqlite_temp_master" table on the disk. - ** So do not write to the disk again. Extract the root page number - ** for the table from the db->init.newTnum field. (The page number - ** should have been put there by the sqliteOpenCb routine.) - ** - ** If the root page number is 1, that means this is the sqlite_master - ** table itself. So mark it read-only. - */ - if( db->init.busy ){ - p->tnum = db->init.newTnum; - if( p->tnum==1 ) p->tabFlags |= TF_Readonly; - } - - /* 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); - }else{ - 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); - } -#endif /* !defined(SQLITE_OMIT_CHECK) */ - - /* 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 SQLITE_MASTER table of the database. - ** - ** If this is a TEMPORARY table, write the entry into the auxiliary - ** file instead of into the main database file. - */ - if( !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); - sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield); - sqlite3Select(pParse, pSelect, &dest); - sqlite3VdbeEndCoroutine(v, regYield); - sqlite3VdbeJumpHere(v, addrTop - 1); - if( pParse->nErr ) return; - pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect); - if( pSelTab==0 ) return; - assert( p->aCol==0 ); - p->nCol = pSelTab->nCol; - p->aCol = pSelTab->aCol; - pSelTab->nCol = 0; - pSelTab->aCol = 0; - sqlite3DeleteTable(db, pSelTab); - 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 - ** SQLITE_MASTER table. We just need to update that slot with all - ** the information we've collected. - */ - sqlite3NestedParse(pParse, - "UPDATE %Q.%s " - "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q " - "WHERE rowid=#%d", - db->aDb[iDb].zDbSName, MASTER_NAME, - 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. - */ - 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 ); - 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 SQLITE_MASTER table */ - sqlite3EndTable(pParse, 0, &sEnd, 0, 0); - -create_view_fail: - sqlite3SelectDelete(db, pSelect); - 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 ){ - n = pParse->nTab; - sqlite3SrcListAssignCursors(pParse, pSel->pSrc); - pTable->nCol = -1; - db->lookaside.bDisable++; -#ifndef SQLITE_OMIT_AUTHORIZATION - xAuth = db->xAuth; - db->xAuth = 0; - pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); - db->xAuth = xAuth; -#else - pSelTab = sqlite3ResultSetOfSelect(pParse, pSel); -#endif - pParse->nTab = n; - 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); - } - }else if( pSelTab ){ - /* 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) ); - }else{ - pTable->nCol = 0; - nErr++; - } - sqlite3DeleteTable(db, pSelTab); - sqlite3SelectDelete(db, pSel); - db->lookaside.bDisable--; - } else { - nErr++; - } - pTable->pSchema->schemaFlags |= DB_UnresetViews; -#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, int iFrom, int 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_master table and internal schema -** if a root-page of another table is moved by the btree-layer whilst -** erasing iTable (this can happen with an auto-vacuum database). -*/ -static void destroyRootPage(Parse *pParse, int iTable, int iDb){ - Vdbe *v = sqlite3GetVdbe(pParse); - int r1 = sqlite3GetTempReg(pParse); - assert( iTable>1 ); - 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_master table to - ** reflect this. - ** - ** The "#NNN" in the SQL is a special constant that means whatever value - ** is in register NNN. See grammar rules associated with the TK_REGISTER - ** token for additional information. - */ - sqlite3NestedParse(pParse, - "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d", - pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1); -#endif - sqlite3ReleaseTempReg(pParse, r1); -} - -/* -** Write VDBE code to erase table pTab and all associated indices on disk. -** Code to update the sqlite_master tables and internal schema definitions -** in case a root-page belonging to another table is moved by the btree layer -** is also added (this can happen with an auto-vacuum database). -*/ -static void destroyTable(Parse *pParse, Table *pTab){ - /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM - ** is not defined), then it is important to call OP_Destroy on the - ** table and index root-pages in order, starting with the numerically - ** largest root-page number. This guarantees that none of the root-pages - ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the - ** following were coded: - ** - ** OP_Destroy 4 0 - ** ... - ** OP_Destroy 5 0 - ** - ** and root page 5 happened to be the largest root-page number in the - ** database, then root page 5 would be moved to page 4 by the - ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit - ** a free-list page. - */ - int iTab = pTab->tnum; - int iDestroyed = 0; - - while( 1 ){ - Index *pIdx; - int iLargest = 0; - - if( iDestroyed==0 || iTabpIndex; pIdx; pIdx=pIdx->pNext){ - int 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_master and/or - ** sqlite_temp_master 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 SQLITE_MASTER table and index entries that refer to the - ** table. The program name loops through the master table and deletes - ** every row that refers to a table of the same name as the one being - ** dropped. Triggers are handled separately because a trigger can be - ** created in the temp database that refers to a table in another - ** database. - */ - sqlite3NestedParse(pParse, - "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'", - pDb->zDbSName, MASTER_NAME, 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); - } - sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); - sqlite3ChangeCookie(pParse, iDb); - sqliteViewResetAll(db, iDb); -} - -/* -** 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( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 - && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){ - 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 master table - ** on disk. - */ - v = sqlite3GetVdbe(pParse); - if( v ){ - sqlite3BeginWriteOperation(pParse, 1, iDb); - 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].zName) + 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; - 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].zName)==0 ){ - pFKey->aCol[i].iFrom = j; - break; - } - } - if( j>=p->nCol ){ - sqlite3ErrorMsg(pParse, - "unknown column \"%s\" in foreign key definition", - pFromCol->a[i].zName); - goto fk_end; - } - } - } - if( pToCol ){ - for(i=0; ia[i].zName); - pFKey->aCol[i].zCol = z; - memcpy(z, pToCol->a[i].zName, n); - z[n] = 0; - z += n+1; - } - } - pFKey->isDeferred = 0; - pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */ - pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */ - - 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 */ - int 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 = 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); - - 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, 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 = sqlite3VdbeCurrentAddr(v) + 3; - sqlite3VdbeGoto(v, j2); - addr2 = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord, - pIndex->nKeyCol); VdbeCoverage(v); - sqlite3UniqueConstraint(pParse, OE_Abort, pIndex); - }else{ - addr2 = sqlite3VdbeCurrentAddr(v); - } - sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx); - 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; -} - -/* -** 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; - } - - /* - ** 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 -#if SQLITE_USER_AUTHENTICATION - && sqlite3UserAuthTable(pTab->zName)==0 -#endif - && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){ - 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_master table (because some other process changed the schema) and - ** one of the index names collides with the name of a temporary table or - ** index, then we will continue to process this index. - ** - ** If pName==0 it means that we are - ** dealing with a primary key or UNIQUE constraint. We have to invent our - ** own name. - */ - if( pName ){ - zName = sqlite3NameFromToken(db, pName); - if( zName==0 ) goto exit_create_index; - assert( pName->z!=0 ); - if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ - goto exit_create_index; - } - 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_DECLARE_VTAB ) zName[7]++; - } - - /* Check for authorization to create an index. - */ -#ifndef SQLITE_OMIT_AUTHORIZATION - { - 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; - sqlite3TokenInit(&prevCol, pTab->aCol[pTab->nCol-1].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); - }else{ - sqlite3ExprListCheckLength(pParse, pList, "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; - 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. - */ - for(i=0, pListItem=pList->a; inExpr; 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 ){ - ExprList *pCopy = sqlite3ExprListDup(db, pList, 0); - pIndex->aColExpr = pCopy; - if( !db->mallocFailed ){ - assert( pCopy!=0 ); - pListItem = &pCopy->a[i]; - } - } - 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; - } - 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->sortOrder & 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( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){ - pIndex->nColumn--; - }else{ - 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 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 ); - if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){ - pIndex->isCovering = 1; - for(j=0; jnCol; j++){ - if( j==pTab->iPKey ) continue; - if( sqlite3ColumnOfIndex(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; - goto exit_create_index; - } - } - } - - /* 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_DECLARE_VTAB ); - assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) ); - 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( pTblName!=0 ){ - pIndex->tnum = db->init.newTnum; - } - } - - /* 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_master table and populate the index with - ** content. But, do not do this if we are simply reading the sqlite_master - ** 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 = 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 - */ - 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_master for this index - */ - sqlite3NestedParse(pParse, - "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);", - db->aDb[iDb].zDbSName, MASTER_NAME, - 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)); - sqlite3VdbeAddOp0(v, OP_Expire); - } - - sqlite3VdbeJumpHere(v, pIndex->tnum); - } - - /* When adding an index to the list of indices for a table, make - ** sure all indices labeled OE_Replace come after all those labeled - ** OE_Ignore. This is necessary for the correct constraint check - ** processing (in sqlite3GenerateConstraintChecks()) as part of - ** UPDATE and INSERT statements. - */ - if( db->init.busy || pTblName==0 ){ - if( onError!=OE_Replace || pTab->pIndex==0 - || pTab->pIndex->onError==OE_Replace){ - pIndex->pNext = pTab->pIndex; - pTab->pIndex = pIndex; - }else{ - Index *pOther = pTab->pIndex; - while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){ - pOther = pOther->pNext; - } - pIndex->pNext = pOther->pNext; - pOther->pNext = pIndex; - } - pIndex = 0; - } - - /* Clean up before exiting */ -exit_create_index: - if( pIndex ) freeIndex(db, pIndex); - 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 */ - LogEst aVal[] = { 33, 32, 30, 28, 26 }; - LogEst *a = pIdx->aiRowLogEst; - 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. But do not let the estimate drop below 10. */ - a[0] = pIdx->pTable->nRowLogEst; - if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10; assert( 10==sqlite3LogEst(2) ); - if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) ); - - /* 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 master table */ - v = sqlite3GetVdbe(pParse); - if( v ){ - sqlite3BeginWriteOperation(pParse, 1, iDb); - sqlite3NestedParse(pParse, - "DELETE FROM %Q.%s WHERE name=%Q AND type='index'", - db->aDb[iDb].zDbSName, MASTER_NAME, 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; - int n = *pnEntry; - if( (n & (n-1))==0 ){ - int 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); - *pIdx = n; - ++*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(sqlite3 *db, IdList *pList, Token *pToken){ - 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); - 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; -} - -/* -** Expand the space allocated for the given SrcList object by -** creating nExtra new slots beginning at iStart. iStart is zero based. -** New slots are zeroed. -** -** For example, suppose a SrcList initially contains two entries: A,B. -** To append 3 new entries onto the end, do this: -** -** sqlite3SrcListEnlarge(db, pSrclist, 3, 2); -** -** After the call above it would contain: A, B, nil, nil, nil. -** If the iStart argument had been 1 instead of 2, then the result -** would have been: A, nil, nil, nil, B. To prepend the new slots, -** the iStart value would be 0. The result then would -** be: nil, nil, nil, A, B. -** -** If a memory allocation fails the SrcList is unchanged. The -** db->mallocFailed flag will be set to true. -*/ -SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge( - sqlite3 *db, /* Database connection to notify of OOM errors */ - SrcList *pSrc, /* The SrcList to be enlarged */ - int nExtra, /* Number of new slots to add to pSrc->a[] */ - int iStart /* Index in pSrc->a[] of first new slot */ -){ - int i; - - /* Sanity checking on calling parameters */ - 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; - int nAlloc = pSrc->nSrc*2+nExtra; - int nGot; - pNew = sqlite3DbRealloc(db, pSrc, - sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) ); - if( pNew==0 ){ - assert( db->mallocFailed ); - return pSrc; - } - pSrc = pNew; - nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1; - pSrc->nAlloc = nGot; - } - - /* Move existing slots that come after the newly inserted slots - ** out of the way */ - for(i=pSrc->nSrc-1; i>=iStart; i--){ - pSrc->a[i+nExtra] = pSrc->a[i]; - } - pSrc->nSrc += 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. 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( - sqlite3 *db, /* Connection to notify of malloc failures */ - SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */ - Token *pTable, /* Table to append */ - Token *pDatabase /* Database of the table */ -){ - struct SrcList_item *pItem; - assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */ - assert( db!=0 ); - if( pList==0 ){ - pList = sqlite3DbMallocRawNN(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{ - pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc); - } - if( db->mallocFailed ){ - sqlite3SrcListDelete(db, pList); - return 0; - } - 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(db, p, pTable, pDatabase); - if( p==0 || NEVER(p->nSrc==0) ){ - goto append_from_error; - } - pItem = &p->a[p->nSrc-1]; - 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; - } - } -} - -/* -** 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, -1, 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 ); - 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, 200); - if( pIdx->aColExpr ){ - sqlite3XPrintf(&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 ) sqlite3StrAccumAppend(&errMsg, ", ", 2); - sqlite3StrAccumAppendAll(&errMsg, pTab->zName); - sqlite3StrAccumAppend(&errMsg, ".", 1); - sqlite3StrAccumAppendAll(&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){ - 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->aSortOrder[i] = pIdx->aSortOrder[i]; - } - if( pParse->nErr ){ - 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 ){ - int 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 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); - } - return p; -} - -/* -** This routine is called on a collation sequence before it is used to -** check that it is defined. An undefined collation sequence exists when -** a database is loaded that contains references to collation sequences -** that have not been defined by sqlite3_create_collation() etc. -** -** If required, this routine calls the 'collation needed' callback to -** request a definition of the collating sequence. If this doesn't work, -** an equivalent collating sequence that uses a text encoding different -** from the main database is substituted, if one is available. -*/ -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, - u8 enc, - const char *zName, - int create -){ - CollSeq *pColl; - if( zName ){ - pColl = findCollSeqEntry(db, zName, create); - }else{ - pColl = db->pDfltColl; - } - assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 ); - assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE ); - if( pColl ) pColl += enc-1; - 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; - - /* nArg of -2 is a special case */ - if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH; - - /* Wrong number of arguments means "no match" */ - if( p->nArg!=nArg && 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. -*/ -static FuncDef *functionSearch( - 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 = functionSearch(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 = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ; - p = functionSearch(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); - 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; -} - -/* -** 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){ - /* A table is not writable under the following circumstances: - ** - ** 1) It is a virtual table and no implementation of the xUpdate method - ** has been provided, or - ** 2) It is a system table (i.e. sqlite_master), this call is not - ** part of a nested parse and writable_schema pragma has not - ** been specified. - ** - ** In either case leave an error message in pParse and return non-zero. - */ - if( ( IsVirtual(pTab) - && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 ) - || ( (pTab->tabFlags & TF_Readonly)!=0 - && (pParse->db->flags & SQLITE_WriteSchema)==0 - && pParse->nested==0 ) - ){ - sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName); - return 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 */ - 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(db, 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, 0, - SF_IncludeHidden, 0, 0); - 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 */ - Expr *pOffset, /* The OFFSET clause. May be null */ - char *zStmtType /* Either DELETE or UPDATE. For err msgs. */ -){ - Expr *pWhereRowid = NULL; /* WHERE rowid .. */ - Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */ - Expr *pSelectRowid = NULL; /* SELECT rowid ... */ - ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */ - SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */ - Select *pSelect = NULL; /* Complete SELECT tree */ - - /* Check that there isn't an ORDER BY without a LIMIT clause. - */ - if( pOrderBy && (pLimit == 0) ) { - sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType); - goto limit_where_cleanup; - } - - /* We only need to generate a select expression if there - ** is a limit/offset term to enforce. - */ - if( pLimit == 0 ) { - /* if pLimit is null, pOffset will always be null as well. */ - assert( pOffset == 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 - ** ); - */ - - pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0); - if( pSelectRowid == 0 ) goto limit_where_cleanup; - pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid); - if( pEList == 0 ) goto limit_where_cleanup; - - /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree - ** and the SELECT subtree. */ - pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0); - if( pSelectSrc == 0 ) { - sqlite3ExprListDelete(pParse->db, pEList); - goto limit_where_cleanup; - } - - /* generate the SELECT expression tree. */ - pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0, - pOrderBy,0,pLimit,pOffset); - if( pSelect == 0 ) return 0; - - /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */ - pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0); - pInClause = pWhereRowid ? sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0) : 0; - sqlite3PExprAddSelect(pParse, pInClause, pSelect); - return pInClause; - -limit_where_cleanup: - sqlite3ExprDelete(pParse->db, pWhere); - sqlite3ExprListDelete(pParse->db, pOrderBy); - sqlite3ExprDelete(pParse->db, pLimit); - sqlite3ExprDelete(pParse->db, pOffset); - return 0; -} -#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 */ -){ - 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 = -1; /* 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; - bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0); -#else -# define pTrigger 0 -# define isView 0 -#endif -#ifdef SQLITE_OMIT_VIEW -# undef isView -# define isView 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, 1, 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, iTabCur); - iDataCur = iIdxCur = iTabCur; - } -#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 ){ - 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, - 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 ); - - /* Keep track of the number of rows to be deleted */ - if( db->flags & SQLITE_CountRows ){ - 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 + 1; - iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0); - if( iKey>pParse->nMem ) pParse->nMem = 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(v); - }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 ) sqlite3VdbeJumpHere(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); - sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB); - sqlite3VdbeChangeP5(v, OE_Abort); - assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE ); - sqlite3MayAbort(pParse); - if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){ - pParse->isMultiWrite = 0; - } - }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( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){ - 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); - 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(v); - 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) ){ - sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+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 ){ - 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); - 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(v); - pParse->iSelfTab = iDataCur + 1; - sqlite3ExprCachePush(pParse); - sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel, - SQLITE_JUMPIFNULL); - pParse->iSelfTab = 0; - }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); - sqlite3ExprCachePop(pParse); - } -} - -/************** 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 */ -/* #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){ - 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 && i0 ){ - if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){ - zHaystack = sqlite3_value_blob(argv[0]); - zNeedle = sqlite3_value_blob(argv[1]); - isText = 0; - }else{ - zHaystack = sqlite3_value_text(argv[0]); - zNeedle = sqlite3_value_text(argv[1]); - isText = 1; - } - if( zNeedle==0 || (nHaystack && zHaystack==0) ) return; - while( nNeedle<=nHaystack && 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); -} - -/* -** 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; - sqlite3XPrintf(&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( n==0 && r>=0 && r0 ); - 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 ){ - u32 cx; - int bMatch; - if( noCase ){ - cx = sqlite3Toupper(c); - c = sqlite3Tolower(c); - }else{ - cx = c; - } - while( (c2 = *(zString++))!=0 ){ - if( c2!=c && c2!=cx ) continue; - 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); - -#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 - zB = sqlite3_value_text(argv[0]); - zA = sqlite3_value_text(argv[1]); - - /* Limit the length of the LIKE or GLOB pattern to avoid problems - ** of deep recursion and N*N behavior in patternCompare(). - */ - nPat = sqlite3_value_bytes(argv[0]); - testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ); - testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 ); - if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){ - sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1); - return; - } - assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */ - - if( argc==3 ){ - /* The escape character string must consist of a single UTF-8 character. - ** Otherwise, return an error. - */ - 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); - }else{ - escape = pInfo->matchSet; - } - 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 */ - - 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( nOutaLimit[SQLITE_LIMIT_LENGTH] ); - testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] ); - if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){ - sqlite3_result_error_toobig(context); - sqlite3_free(zOut); - return; - } - zOld = zOut; - zOut = sqlite3_realloc64(zOut, (int)nOut); - if( zOut==0 ){ - sqlite3_result_error_nomem(context); - sqlite3_free(zOld); - return; - } - memcpy(&zOut[j], zRep, nRep); - j += nRep; - i += nPattern-1; - } - } - 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->overflow = 1; - } - }else{ - p->rSum += sqlite3_value_double(argv[0]); - p->approx = 1; - } - } -} -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; -}; - -/* -** 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->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); -} - -/* -** 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(argv[0])==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 minMaxFinalize(sqlite3_context *context){ - sqlite3_value *pRes; - pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0); - if( pRes ){ - if( pRes->flags ){ - sqlite3_result_value(context, pRes); - } - sqlite3VdbeMemRelease(pRes); - } -} - -/* -** 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 ) sqlite3StrAccumAppend(pAccum, zSep, nSep); - } - zVal = (char*)sqlite3_value_text(argv[0]); - nVal = sqlite3_value_bytes(argv[0]); - if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal); - } -} -static void groupConcatFinalize(sqlite3_context *context){ - StrAccum *pAccum; - pAccum = sqlite3_aggregate_context(context, 0); - if( pAccum ){ - if( pAccum->accError==STRACCUM_TOOBIG ){ - sqlite3_result_error_toobig(context); - }else if( pAccum->accError==STRACCUM_NOMEM ){ - sqlite3_result_error_nomem(context); - }else{ - sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, - sqlite3_free); - } - } -} - -/* -** This routine does per-connection function registration. Most -** of the built-in functions above are part of the global function set. -** This routine only deals with those that are not global. -*/ -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); - } -} - -/* -** Set the LIKEOPT flag on the 2-argument function with the given name. -*/ -static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){ - FuncDef *pDef; - pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0); - if( ALWAYS(pDef) ){ - pDef->funcFlags |= flagVal; - } -} - -/* -** Register the built-in LIKE and GLOB functions. The caseSensitive -** parameter determines whether or not the LIKE operator is case -** sensitive. GLOB is always case sensitive. -*/ -SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){ - struct compareInfo *pInfo; - if( caseSensitive ){ - pInfo = (struct compareInfo*)&likeInfoAlt; - }else{ - pInfo = (struct compareInfo*)&likeInfoNorm; - } - sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0); - sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0); - sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, - (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0); - setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE); - setLikeOptFlag(db, "like", - caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE); -} - -/* -** pExpr points to an expression which implements a function. If -** it is appropriate to apply the LIKE optimization to that function -** then set aWc[0] through aWc[2] to the wildcard characters and 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); - if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){ - return 0; - } - 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; - aWc[3] = zEscape[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 ); - *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[] = { -#ifdef SQLITE_SOUNDEX - FUNCTION(soundex, 1, 0, 0, soundexFunc ), -#endif -#ifndef SQLITE_OMIT_LOAD_EXTENSION - VFUNCTION(load_extension, 1, 0, 0, loadExt ), - VFUNCTION(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 */ - FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY), - FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY), - FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY), -#ifdef SQLITE_DEBUG - FUNCTION2(affinity, 1, 0, 0, noopFunc, SQLITE_FUNC_AFFINITY), -#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 ), - AGGREGATE2(min, 1, 0, 1, minmaxStep, minMaxFinalize, - SQLITE_FUNC_MINMAX ), - FUNCTION(max, -1, 1, 1, minmaxFunc ), - FUNCTION(max, 0, 1, 1, 0 ), - AGGREGATE2(max, 1, 1, 1, minmaxStep, minMaxFinalize, - 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 ), - FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE), - 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 ), - AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ), - AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ), - AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ), - AGGREGATE2(count, 0, 0, 0, countStep, countFinalize, - SQLITE_FUNC_COUNT ), - AGGREGATE(count, 1, 0, 0, countStep, countFinalize ), - AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize), - AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize), - - LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE), -#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 ), - FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE), - }; -#ifndef SQLITE_OMIT_ALTERTABLE - sqlite3AlterFunctions(); -#endif -#if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4) - sqlite3AnalyzeFunctions(); -#endif - 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(v); /* jump here if parent key found */ - - /* If nIncr is less than zero, then check at runtime if there are any - ** outstanding constraints to resolve. If there are not, there is no need - ** to check if deleting this row resolves any outstanding violations. - ** - ** Check if any of the key columns in the child table row are NULL. If - ** any are, then the constraint is considered satisfied. No need to - ** search for a matching row in the parent table. */ - if( nIncr<0 ){ - sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk); - VdbeCoverage(v); - } - for(i=0; inCol; i++){ - int iReg = 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, 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 && nIncr==1 ){ - int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1; - for(i=0; iaiColumn[i]+1+regData; - 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 + iCol + 1; - pExpr->affinity = pCol->affinity; - zColl = pCol->zColl; - if( zColl==0 ) zColl = db->pDfltColl->zName; - pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl); - }else{ - pExpr->iTable = regBase; - pExpr->affinity = 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->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(db, 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 primary key is - ** (a,b,...) - */ - 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; - Index *pPk = sqlite3PrimaryKeyIndex(pTab); - assert( pIdx!=0 ); - for(i=0; inKeyCol; i++){ - i16 iCol = pIdx->aiColumn[i]; - assert( iCol>=0 ); - pLeft = exprTableRegister(pParse, pTab, regData, iCol); - pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol); - pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight); - pAll = sqlite3ExprAnd(db, pAll, pEq); - } - pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0); - } - pWhere = sqlite3ExprAnd(db, 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 ){ - sqlite3VdbeJumpHere(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) && !pTab->pSelect ){ - int iSkip = 0; - Vdbe *v = sqlite3GetVdbe(pParse); - - assert( v ); /* VDBE has already been allocated */ - 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(v); - sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v); - } - - pParse->disableTriggers = 1; - sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 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 ){ - 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 iReg = pFKey->aCol[i].iFrom + 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(db, 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(db, pWhere, pEq); - - /* For ON UPDATE, construct the next term of the WHEN clause. - ** The final WHEN clause will be like this: - ** - ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN) - */ - if( pChanges ){ - 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(db, 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 ){ - Expr *pDflt = pFKey->pFrom->aCol[iFromCol].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->affinity = OE_Abort; - } - pSelect = sqlite3SelectNew(pParse, - sqlite3ExprListAppend(pParse, 0, pRaise), - sqlite3SrcListAppend(db, 0, &tFrom, 0), - pWhere, - 0, 0, 0, 0, 0, 0 - ); - pWhere = 0; - } - - /* Disable lookaside memory allocation */ - db->lookaside.bDisable++; - - 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. */ - db->lookaside.bDisable--; - - sqlite3ExprDelete(db, pWhere); - sqlite3ExprDelete(db, pWhen); - sqlite3ExprListDelete(db, pList); - sqlite3SelectDelete(db, pSelect); - if( db->mallocFailed==1 ){ - fkTriggerDelete(db, pTrigger); - return 0; - } - assert( pStep!=0 ); - - switch( action ){ - case OE_Restrict: - pStep->op = TK_SELECT; - break; - case OE_Cascade: - if( !pChanges ){ - pStep->op = TK_DELETE; - break; - } - 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->nCol); - 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]; - if( x>=0 ){ - pIdx->zColAff[n] = pTab->aCol[x].affinity; - }else if( x==XN_ROWID ){ - pIdx->zColAff[n] = SQLITE_AFF_INTEGER; - }else{ - char aff; - assert( x==XN_EXPR ); - assert( pIdx->aColExpr!=0 ); - aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr); - if( aff==0 ) aff = SQLITE_AFF_BLOB; - 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; - 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=0; inCol; i++){ - zColAff[i] = pTab->aCol[i].affinity; - } - do{ - zColAff[i--] = 0; - }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB ); - pTab->zColAff = zColAff; - } - i = sqlite3Strlen30(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; - int 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; -} - -#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. -** -** Three memory locations are allocated: -** -** (1) Register to hold the name of the pTab table. -** (2) Register to hold the maximum ROWID of pTab. -** (3) Register to hold the rowid in sqlite_sequence of pTab -** -** The 2nd register is the one that is returned. That is all the -** insert routine needs to know about. -*/ -static int autoIncBegin( - Parse *pParse, /* Parsing context */ - int iDb, /* Index of the database holding pTab */ - Table *pTab /* The table we are writing to */ -){ - int memId = 0; /* Register holding maximum rowid */ - if( (pTab->tabFlags & TF_Autoincrement)!=0 - && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0 - ){ - Parse *pToplevel = sqlite3ParseToplevel(pParse); - AutoincInfo *pInfo; - - 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++; /* Rowid in sqlite_sequence */ - } - memId = pInfo->regCtr; - } - return memId; -} - -/* -** This routine generates code that will initialize all of the -** register used by the autoincrement tracker. -*/ -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, 9, 0}, - /* 2 */ {OP_Column, 0, 0, 0}, - /* 3 */ {OP_Ne, 0, 7, 0}, - /* 4 */ {OP_Rowid, 0, 0, 0}, - /* 5 */ {OP_Column, 0, 1, 0}, - /* 6 */ {OP_Goto, 0, 9, 0}, - /* 7 */ {OP_Next, 0, 2, 0}, - /* 8 */ {OP_Integer, 0, 0, 0}, - /* 9 */ {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+1; - 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[8].p2 = memId; - } -} - -/* -** 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) ); - 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. */ - int onError /* How to handle constraint errors */ -){ - 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 */ - - /* 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 registers for holding the rowid of the new row, - ** the content of the new row, and the assembled row record. - */ - 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.) - */ - bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==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 ); - } - 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; - } - - /* 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++){ - nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0); - } - 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 ){ - 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+1)); - if( aRegIdx==0 ){ - goto insert_cleanup; - } - for(i=0, pIdx=pTab->pIndex; ipNext, i++){ - assert( pIdx ); - aRegIdx[i] = ++pParse->nMem; - pParse->nMem += pIdx->nColumn; - } - } - - /* 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: ... - */ - addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); - VdbeCoverage(v); - } - - /* Run the BEFORE and INSTEAD OF triggers, if there are any - */ - endOfLoop = sqlite3VdbeMakeLabel(v); - 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) ); - - /* Create the new column data - */ - for(i=j=0; inCol; i++){ - if( pColumn ){ - for(j=0; jnId; j++){ - if( pColumn->a[j].idx==i ) break; - } - } - if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) - || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){ - sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1); - }else if( useTempTable ){ - sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); - }else{ - assert( pSelect==0 ); /* Otherwise useTempTable is true */ - sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1); - } - if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++; - } - - /* 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); - } - - /* Compute the content of the next row to insert into a range of - ** registers beginning at regIns. - */ - if( !isView ){ - if( IsVirtual(pTab) ){ - /* The row that the VUpdate opcode will delete: none */ - sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); - } - if( ipkColumn>=0 ){ - if( useTempTable ){ - sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid); - }else if( pSelect ){ - sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid); - }else{ - VdbeOp *pOp; - sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid); - pOp = sqlite3VdbeGetOp(v, -1); - if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){ - appendFlag = 1; - pOp->opcode = OP_NewRowid; - pOp->p1 = iDataCur; - pOp->p2 = regRowid; - pOp->p3 = regAutoinc; - } - } - /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid - ** to generate a unique primary key value. - */ - if( !appendFlag ){ - int 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); - - /* Compute data for all columns of the new entry, beginning - ** with the first column. - */ - nHidden = 0; - for(i=0; inCol; i++){ - int iRegStore = regRowid+1+i; - if( i==pTab->iPKey ){ - /* The value of the INTEGER PRIMARY KEY column is always a NULL. - ** Whenever this column is read, the rowid will be substituted - ** in its place. Hence, fill this column with a NULL to avoid - ** taking up data space with information that will never be used. - ** As there may be shallow copies of this value, make it a soft-NULL */ - sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore); - continue; - } - if( pColumn==0 ){ - if( IsHiddenColumn(&pTab->aCol[i]) ){ - j = -1; - nHidden++; - }else{ - j = i - nHidden; - } - }else{ - for(j=0; jnId; j++){ - if( pColumn->a[j].idx==i ) break; - } - } - if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){ - sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore); - }else if( useTempTable ){ - sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); - }else if( pSelect ){ - if( regFromSelect!=regData ){ - sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore); - } - }else{ - sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore); - } - } - - /* Generate code to check constraints and generate index keys and - ** do the insertion. - */ -#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 - ); - 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 || (pTrigger==0 && - ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0) - )); - sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur, - regIns, aRegIdx, 0, appendFlag, bUseSeek - ); - } - } - - /* Update the count of rows that are inserted - */ - if( (db->flags & SQLITE_CountRows)!=0 ){ - 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); - 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( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){ - 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); - 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 checkConstraintUnchanged() -*/ -#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 checkConstraintUnchanged(). Set -** bit 0x01 of pWalker->eCode if -** pWalker->eCode to 0 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 does not use any of the -** changing columns (or the rowid if it is changing). In other words, -** return true if this CHECK constraint can be skipped when validating -** the new row in the UPDATE statement. -*/ -static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){ - 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; -} - -/* -** 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. -** -** 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 */ -){ - 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 addr1; /* Address of jump instruction */ - 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 */ - int ipkTop = 0; /* Top of the rowid change constraint check */ - int ipkBottom = 0; /* Bottom of the rowid change constraint check */ - u8 isUpdate; /* True if this is an UPDATE operation */ - u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */ - - 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. - */ - for(i=0; iiPKey ){ - continue; /* ROWID is never NULL */ - } - if( aiChng && aiChng[i]<0 ){ - /* Don't bother checking for NOT NULL on columns that do not change */ - continue; - } - onError = pTab->aCol[i].notNull; - if( onError==OE_None ) continue; /* This column is allowed to be NULL */ - if( overrideError!=OE_Default ){ - onError = overrideError; - }else if( onError==OE_Default ){ - onError = OE_Abort; - } - if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ - onError = OE_Abort; - } - assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail - || onError==OE_Ignore || onError==OE_Replace ); - switch( onError ){ - case OE_Abort: - sqlite3MayAbort(pParse); - /* Fall through */ - case OE_Rollback: - case OE_Fail: { - char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName, - pTab->aCol[i].zName); - sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError, - regNewData+1+i); - sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC); - sqlite3VdbeChangeP5(v, P5_ConstraintNotNull); - VdbeCoverage(v); - break; - } - case OE_Ignore: { - sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest); - VdbeCoverage(v); - break; - } - default: { - assert( onError==OE_Replace ); - addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); - VdbeCoverage(v); - sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i); - sqlite3VdbeJumpHere(v, addr1); - break; - } - } - } - - /* 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 *pExpr = pCheck->a[i].pExpr; - if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue; - allOk = sqlite3VdbeMakeLabel(v); - sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL); - if( onError==OE_Ignore ){ - sqlite3VdbeGoto(v, ignoreDest); - }else{ - char *zName = pCheck->a[i].zName; - if( zName==0 ) zName = pTab->zName; - if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */ - sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK, - onError, zName, P4_TRANSIENT, - P5_ConstraintCheck); - } - sqlite3VdbeResolveLabel(v, allOk); - } - pParse->iSelfTab = 0; - } -#endif /* !defined(SQLITE_OMIT_CHECK) */ - - /* If rowid is changing, make sure the new rowid does not previously - ** exist in the table. - */ - if( pkChng && pPk==0 ){ - int addrRowidOk = sqlite3VdbeMakeLabel(v); - - /* 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; - } - - 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); - } - - /* 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 && overrideError!=OE_Replace ){ - for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){ - ipkTop = sqlite3VdbeAddOp0(v, OP_Goto); - break; - } - } - } - - /* Check to see if the new rowid already exists in the table. Skip - ** the following conflict logic if it does not. */ - sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData); - VdbeCoverage(v); - - /* Generate code that deals with a rowid collision */ - switch( onError ){ - default: { - onError = OE_Abort; - /* Fall thru into the next case */ - } - case OE_Rollback: - case OE_Abort: - case 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. - */ - Trigger *pTrigger = 0; - if( db->flags&SQLITE_RecTriggers ){ - pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); - } - if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){ - sqlite3MultiWrite(pParse); - sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, - regNewData, 1, 0, OE_Replace, 1, -1); - }else{ -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK - if( 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; - } - case OE_Ignore: { - /*assert( seenReplace==0 );*/ - sqlite3VdbeGoto(v, ignoreDest); - break; - } - } - sqlite3VdbeResolveLabel(v, addrRowidOk); - if( ipkTop ){ - ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto); - sqlite3VdbeJumpHere(v, ipkTop); - } - } - - /* 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 */ - - if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */ - if( bAffinityDone==0 ){ - sqlite3TableAffinity(v, pTab, regNewData+1); - bAffinityDone = 1; - } - iThisCur = iIdxCur+ix; - addrUniqueOk = sqlite3VdbeMakeLabel(v); - - /* 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; - }else{ - x = iField + regNewData + 1; - } - sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i); - VdbeComment((v, "%s", iField<0 ? "rowid" : 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==2 ) sqlite3SetMakeRecordP5(v, pIdx->pTable); -#endif - - /* 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; - } - - /* 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. - */ - 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; - } - - /* Check to see if the new index entry will be unique */ - 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 = sqlite3ColumnOfIndex(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; - } - 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 ); - switch( onError ){ - case OE_Rollback: - case OE_Abort: - case OE_Fail: { - sqlite3UniqueConstraint(pParse, onError, pIdx); - break; - } - case OE_Ignore: { - sqlite3VdbeGoto(v, ignoreDest); - break; - } - default: { - Trigger *pTrigger = 0; - assert( onError==OE_Replace ); - sqlite3MultiWrite(pParse); - if( db->flags&SQLITE_RecTriggers ){ - pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0); - } - sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur, - regR, nPkField, 0, OE_Replace, - (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur); - seenReplace = 1; - break; - } - } - sqlite3VdbeResolveLabel(v, addrUniqueOk); - if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField); - } - if( ipkTop ){ - sqlite3VdbeGoto(v, ipkTop+1); - sqlite3VdbeJumpHere(v, ipkBottom); - } - - *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 regData; /* Content registers (after the rowid) */ - int regRec; /* Register holding assembled record for the table */ - int i; /* Loop counter */ - u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */ - - 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++){ - if( aRegIdx[i]==0 ) continue; - bAffinityDone = 1; - 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 ){ - sqlite3VdbeAddOp4(v, OP_InsertInt, - iIdxCur+i, aRegIdx[i], 0, (char*)pTab, P4_TABLE - ); - sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP); - } -#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; - regData = regNewData + 1; - regRec = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec); - sqlite3SetMakeRecordP5(v, pTab); - if( !bAffinityDone ){ - sqlite3TableAffinity(v, pTab, 0); - sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol); - } - 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, regRec, 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 ){ - 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 */ - } - assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */ - 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==pDest ){ - 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 - 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( 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 */ - } - } -#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); - 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 ){ - addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); - }else{ - addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); - assert( (pDest->tabFlags & TF_Autoincrement)==0 ); - } - sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1); - if( db->mDbFlags & DBFLAG_Vacuum ){ - sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest); - insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID| - OPFLAG_APPEND|OPFLAG_USESEEKRESULT; - }else{ - insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND; - } - 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); - sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1); - 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); - } - } - if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){ - idxInsFlags |= OPFLAG_NCHANGE; - } - 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; - 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; - nCol = sqlite3_column_count(pStmt); - - 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 ){ - 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*); -}; - -/* -** 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 -#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 -#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 -}; - -/* -** 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 && 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 &= ~(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_MASTER -** 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_MASTER); -#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_MASTER); -#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_MASTER); -#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_HEADER_VALUE 0 -#define PragTyp_AUTO_VACUUM 1 -#define PragTyp_FLAG 2 -#define PragTyp_BUSY_TIMEOUT 3 -#define PragTyp_CACHE_SIZE 4 -#define PragTyp_CACHE_SPILL 5 -#define PragTyp_CASE_SENSITIVE_LIKE 6 -#define PragTyp_COLLATION_LIST 7 -#define PragTyp_COMPILE_OPTIONS 8 -#define PragTyp_DATA_STORE_DIRECTORY 9 -#define PragTyp_DATABASE_LIST 10 -#define PragTyp_DEFAULT_CACHE_SIZE 11 -#define PragTyp_ENCODING 12 -#define PragTyp_FOREIGN_KEY_CHECK 13 -#define PragTyp_FOREIGN_KEY_LIST 14 -#define PragTyp_FUNCTION_LIST 15 -#define PragTyp_INCREMENTAL_VACUUM 16 -#define PragTyp_INDEX_INFO 17 -#define PragTyp_INDEX_LIST 18 -#define PragTyp_INTEGRITY_CHECK 19 -#define PragTyp_JOURNAL_MODE 20 -#define PragTyp_JOURNAL_SIZE_LIMIT 21 -#define PragTyp_LOCK_PROXY_FILE 22 -#define PragTyp_LOCKING_MODE 23 -#define PragTyp_PAGE_COUNT 24 -#define PragTyp_MMAP_SIZE 25 -#define PragTyp_MODULE_LIST 26 -#define PragTyp_OPTIMIZE 27 -#define PragTyp_PAGE_SIZE 28 -#define PragTyp_PRAGMA_LIST 29 -#define PragTyp_SECURE_DELETE 30 -#define PragTyp_SHRINK_MEMORY 31 -#define PragTyp_SOFT_HEAP_LIMIT 32 -#define PragTyp_SYNCHRONOUS 33 -#define PragTyp_TABLE_INFO 34 -#define PragTyp_TEMP_STORE 35 -#define PragTyp_TEMP_STORE_DIRECTORY 36 -#define PragTyp_THREADS 37 -#define PragTyp_WAL_AUTOCHECKPOINT 38 -#define PragTyp_WAL_CHECKPOINT 39 -#define PragTyp_ACTIVATE_EXTENSIONS 40 -#define PragTyp_HEXKEY 41 -#define PragTyp_KEY 42 -#define PragTyp_REKEY 43 -#define PragTyp_LOCK_STATUS 44 -#define PragTyp_PARSER_TRACE 45 -#define PragTyp_STATS 46 - -/* 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 */ "cache_size", /* Used by: default_cache_size */ - /* 1 */ "cid", /* Used by: table_info */ - /* 2 */ "name", - /* 3 */ "type", - /* 4 */ "notnull", - /* 5 */ "dflt_value", - /* 6 */ "pk", - /* 7 */ "tbl", /* Used by: stats */ - /* 8 */ "idx", - /* 9 */ "wdth", - /* 10 */ "hght", - /* 11 */ "flgs", - /* 12 */ "seqno", /* Used by: index_info */ - /* 13 */ "cid", - /* 14 */ "name", - /* 15 */ "seqno", /* Used by: index_xinfo */ - /* 16 */ "cid", - /* 17 */ "name", - /* 18 */ "desc", - /* 19 */ "coll", - /* 20 */ "key", - /* 21 */ "seq", /* Used by: index_list */ - /* 22 */ "name", - /* 23 */ "unique", - /* 24 */ "origin", - /* 25 */ "partial", - /* 26 */ "seq", /* Used by: database_list */ - /* 27 */ "name", - /* 28 */ "file", - /* 29 */ "name", /* Used by: function_list */ - /* 30 */ "builtin", - /* 31 */ "name", /* Used by: module_list pragma_list */ - /* 32 */ "seq", /* Used by: collation_list */ - /* 33 */ "name", - /* 34 */ "id", /* Used by: foreign_key_list */ - /* 35 */ "seq", - /* 36 */ "table", - /* 37 */ "from", - /* 38 */ "to", - /* 39 */ "on_update", - /* 40 */ "on_delete", - /* 41 */ "match", - /* 42 */ "table", /* Used by: foreign_key_check */ - /* 43 */ "rowid", - /* 44 */ "parent", - /* 45 */ "fkid", - /* 46 */ "busy", /* Used by: wal_checkpoint */ - /* 47 */ "log", - /* 48 */ "checkpointed", - /* 49 */ "timeout", /* Used by: busy_timeout */ - /* 50 */ "database", /* Used by: lock_status */ - /* 51 */ "status", -}; - -/* 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 */ - u32 iArg; /* Extra argument */ -} PragmaName; -static const PragmaName aPragmaName[] = { -#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD) - {/* zName: */ "activate_extensions", - /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS, - /* ePragFlg: */ 0, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif -#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: */ 49, 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 - {/* zName: */ "case_sensitive_like", - /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE, - /* ePragFlg: */ PragFlg_NoColumns, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, - {/* 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: */ 26, 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: */ 0, 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, - /* ColNames: */ 42, 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: */ 34, 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_INTROSPECTION_PRAGMAS) - {/* zName: */ "function_list", - /* ePragTyp: */ PragTyp_FUNCTION_LIST, - /* ePragFlg: */ PragFlg_Result0, - /* ColNames: */ 29, 2, - /* iArg: */ 0 }, -#endif -#endif -#if defined(SQLITE_HAS_CODEC) - {/* zName: */ "hexkey", - /* ePragTyp: */ PragTyp_HEXKEY, - /* ePragFlg: */ 0, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, - {/* zName: */ "hexrekey", - /* ePragTyp: */ PragTyp_HEXKEY, - /* ePragFlg: */ 0, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif -#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: */ 12, 3, - /* iArg: */ 0 }, - {/* zName: */ "index_list", - /* ePragTyp: */ PragTyp_INDEX_LIST, - /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt, - /* ColNames: */ 21, 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_HAS_CODEC) - {/* zName: */ "key", - /* ePragTyp: */ PragTyp_KEY, - /* ePragFlg: */ 0, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - {/* zName: */ "legacy_file_format", - /* ePragTyp: */ PragTyp_FLAG, - /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1, - /* ColNames: */ 0, 0, - /* iArg: */ SQLITE_LegacyFileFmt }, -#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: */ 50, 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_INTROSPECTION_PRAGMAS) - {/* zName: */ "module_list", - /* ePragTyp: */ PragTyp_MODULE_LIST, - /* ePragFlg: */ PragFlg_Result0, - /* ColNames: */ 31, 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_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE) - {/* zName: */ "parser_trace", - /* ePragTyp: */ PragTyp_PARSER_TRACE, - /* ePragFlg: */ 0, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif -#if defined(SQLITE_INTROSPECTION_PRAGMAS) - {/* zName: */ "pragma_list", - /* ePragTyp: */ PragTyp_PRAGMA_LIST, - /* ePragFlg: */ PragFlg_Result0, - /* ColNames: */ 31, 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 }, -#endif -#if defined(SQLITE_HAS_CODEC) - {/* zName: */ "rekey", - /* ePragTyp: */ PragTyp_REKEY, - /* ePragFlg: */ 0, - /* ColNames: */ 0, 0, - /* iArg: */ 0 }, -#endif -#if !defined(SQLITE_OMIT_FLAG_PRAGMAS) - {/* 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: */ 7, 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: */ 1, 6, - /* iArg: */ 0 }, -#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_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: */ 46, 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 }, -#endif -}; -/* Number of pragmas: 60 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]; -} - -/* -** 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,-1,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; - sqlite3CodeVerifySchema(pParse, iDb); - iReg = ++pParse->nMem; - if( sqlite3Tolower(zLeft[0])=='p' ){ - sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg); - }else{ - sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, - sqlite3AbsInt32(sqlite3Atoi(zRight))); - } - 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_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 &= ~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{ - int 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. - */ - case PragTyp_TABLE_INFO: if( zRight ){ - Table *pTab; - pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb); - if( pTab ){ - int i, k; - int nHidden = 0; - Column *pCol; - Index *pPk = sqlite3PrimaryKeyIndex(pTab); - pParse->nMem = 6; - sqlite3CodeVerifySchema(pParse, iDb); - sqlite3ViewGetColumnNames(pParse, pTab); - for(i=0, pCol=pTab->aCol; inCol; i++, pCol++){ - if( IsHiddenColumn(pCol) ){ - nHidden++; - continue; - } - 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 ); - sqlite3VdbeMultiLoad(v, 1, "issisi", - i-nHidden, - pCol->zName, - sqlite3ColumnType(pCol,""), - pCol->notNull ? 1 : 0, - pCol->pDflt ? pCol->pDflt->u.zToken : 0, - k); - } - } - } - 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 ){ - 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, iDb); - 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 ){ - pParse->nMem = 5; - sqlite3CodeVerifySchema(pParse, iDb); - 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; - -#ifdef SQLITE_INTROSPECTION_PRAGMAS - case PragTyp_FUNCTION_LIST: { - int i; - HashElem *j; - FuncDef *p; - pParse->nMem = 2; - for(i=0; iu.pHash ){ - sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 1); - } - } - for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){ - p = (FuncDef*)sqliteHashData(j); - sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 0); - } - } - 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 i = 0; - pParse->nMem = 8; - sqlite3CodeVerifySchema(pParse, iDb); - 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; - sqlite3CodeVerifySchema(pParse, iDb); - 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; - 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(v); - - /* 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 NDEBUG - case PragTyp_PARSER_TRACE: { - if( zRight ){ - if( sqlite3GetBoolean(zRight, 0) ){ - sqlite3ParserTrace(stdout, "parser: "); - }else{ - sqlite3ParserTrace(0, 0); - } - } - } - break; -#endif - - /* 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; - -#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). - */ - case PragTyp_INTEGRITY_CHECK: { - int i, j, addr, mxErr; - - 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 ){ - sqlite3GetInt32(zRight, &mxErr); - if( mxErr<=0 ){ - mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; - } - } - 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( HasRowid(pTab) ) cnt++; - for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; } - if( nIdx>mxIdx ) mxIdx = nIdx; - } - aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1)); - if( aRoot==0 ) break; - for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ - Table *pTab = sqliteHashData(x); - Index *pIdx; - 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 */ - pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); - sqlite3ExprCacheClear(pParse); - 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); - /* 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); - 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(v); - int addrCkOk = sqlite3VdbeMakeLabel(v); - char *zErr; - int k; - pParse->iSelfTab = iDataCur + 1; - sqlite3ExprCachePush(pParse); - 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); - sqlite3ExprCachePop(pParse); - } - sqlite3ExprListDelete(db, pCheck); - } - if( !isQuick ){ /* Omit the remaining tests for quick_check */ - /* Sanity check on record header decoding */ - sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nCol-1, 3); - sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); - /* 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(v); - 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(v); - 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); -#ifndef SQLITE_OMIT_BTREECOUNT - 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); - } - } -#endif /* SQLITE_OMIT_BTREECOUNT */ - } - } - { - 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( - !(DbHasProperty(db, 0, DB_SchemaLoaded)) || - DbHasProperty(db, 0, DB_Empty) - ){ - for(pEnc=&encnames[0]; pEnc->zName; pEnc++){ - if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){ - SCHEMA_ENC(db) = ENC(db) = - pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE; - 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); - }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 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; - } - -#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 - -#ifdef SQLITE_HAS_CODEC - case PragTyp_KEY: { - if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight)); - break; - } - case PragTyp_REKEY: { - if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight)); - break; - } - case PragTyp_HEXKEY: { - if( zRight ){ - u8 iByte; - int i; - char zKey[40]; - for(i=0, iByte=0; imPragFlg & 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); - sqlite3StrAccumAppendAll(&acc, "CREATE TABLE x"); - for(i=0, j=pPragma->iPragCName; inPragCName; i++, j++){ - sqlite3XPrintf(&acc, "%c\"%s\"", cSep, pragCName[j]); - cSep = ','; - } - if( i==0 ){ - sqlite3XPrintf(&acc, "(\"%s\"", pPragma->zName); - cSep = ','; - i++; - } - j = 0; - if( pPragma->mPragFlg & PragFlg_Result1 ){ - sqlite3StrAccumAppendAll(&acc, ",arg HIDDEN"); - j++; - } - if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){ - sqlite3StrAccumAppendAll(&acc, ",schema HIDDEN"); - j++; - } - sqlite3StrAccumAppend(&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]); - sqlite3StrAccumAppendAll(&acc, "PRAGMA "); - if( pCsr->azArg[1] ){ - sqlite3XPrintf(&acc, "%Q.", pCsr->azArg[1]); - } - sqlite3StrAccumAppendAll(&acc, pTab->pName->zName); - if( pCsr->azArg[0] ){ - sqlite3XPrintf(&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 */ -}; - -/* -** 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 && (db->flags & SQLITE_WriteSchema)==0 ){ - char *z; - if( zObj==0 ) zObj = "?"; - z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj); - if( zExtra ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra); - sqlite3DbFree(db, *pData->pzErrMsg); - *pData->pzErrMsg = z; - } - pData->rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_CORRUPT_BKPT; -} - -/* -** This is the callback routine for the code that initializes the -** database. See sqlite3Init() below for additional information. -** This routine is also called from the OP_ParseSchema opcode of the VDBE. -** -** Each callback contains the following information: -** -** argv[0] = name of thing being created -** argv[1] = root page number for table or index. 0 for trigger or view. -** argv[2] = SQL text for the CREATE statement. -** -*/ -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==3 ); - UNUSED_PARAMETER2(NotUsed, argc); - assert( sqlite3_mutex_held(db->mutex) ); - DbClearProperty(db, iDb, DB_Empty); - if( db->mallocFailed ){ - corruptSchema(pData, argv[0], 0); - return 1; - } - - assert( iDb>=0 && iDbnDb ); - if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */ - if( argv[1]==0 ){ - corruptSchema(pData, argv[0], 0); - }else if( sqlite3_strnicmp(argv[2],"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; - db->init.newTnum = sqlite3Atoi(argv[1]); - db->init.orphanTrigger = 0; - TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &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{ - pData->rc = rc; - if( rc==SQLITE_NOMEM ){ - sqlite3OomFault(db); - }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){ - corruptSchema(pData, argv[0], sqlite3_errmsg(db)); - } - } - } - sqlite3_finalize(pStmt); - }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){ - corruptSchema(pData, argv[0], 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[0], db->aDb[iDb].zDbSName); - if( pIndex==0 ){ - /* This can occur if there exists an index on a TEMP table which - ** has the same name as another index on a permanent index. Since - ** the permanent table is hidden by the TEMP table, we can also - ** safely ignore the index on the permanent table. - */ - /* Do Nothing */; - }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){ - corruptSchema(pData, argv[0], "invalid rootpage"); - } - } - return 0; -} - -/* -** Attempt to read the database schema and initialize internal -** data structures for a single database file. The index of the -** database file is given by iDb. iDb==0 is used for the main -** database. iDb==1 should never be used. iDb>=2 is used for -** auxiliary databases. Return one of the SQLITE_ error codes to -** indicate success or failure. -*/ -static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ - int rc; - int i; -#ifndef SQLITE_OMIT_DEPRECATED - int size; -#endif - Db *pDb; - char const *azArg[4]; - int meta[5]; - InitData initData; - const char *zMasterName; - int openedTransaction = 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_master or - ** sqlite_temp_master) 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] = zMasterName = SCHEMA_TABLE(iDb); - azArg[1] = "1"; - azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text," - "rootpage int,sql text)"; - azArg[3] = 0; - initData.db = db; - initData.iDb = iDb; - initData.rc = SQLITE_OK; - initData.pzErrMsg = pzErrMsg; - sqlite3InitCallback(&initData, 3, (char **)azArg, 0); - 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); - 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]); - } - 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 ){ -#ifndef SQLITE_OMIT_UTF16 - u8 encoding; - /* If opening the main database, set ENC(db). */ - encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3; - if( encoding==0 ) encoding = SQLITE_UTF8; - ENC(db) = encoding; -#else - ENC(db) = SQLITE_UTF8; -#endif - }else{ - /* If opening an attached database, the encoding much match ENC(db) */ - if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){ - sqlite3SetString(pzErrMsg, db, "attached databases must use the same" - " text encoding as main database"); - rc = SQLITE_ERROR; - goto initone_error_out; - } - } - }else{ - DbSetProperty(db, iDb, DB_Empty); - } - pDb->pSchema->enc = ENC(db); - - if( pDb->pSchema->cache_size==0 ){ -#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 &= ~SQLITE_LegacyFileFmt; - } - - /* Read the schema information out of the schema tables - */ - assert( db->init.busy ); - { - char *zSql; - zSql = sqlite3MPrintf(db, - "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid", - db->aDb[iDb].zDbSName, zMasterName); -#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_WriteSchema)){ - /* Black magic: If the SQLITE_WriteSchema flag is set, then consider - ** the schema loaded, even if errors occurred. In this situation the - ** current sqlite3_prepare() operation will fail, but the following one - ** will attempt to compile the supplied statement against whatever subset - ** of the schema was loaded before the error occurred. The primary - ** purpose of this is to allow access to the sqlite_master table - ** even when its contents have been corrupted. - */ - DbSetProperty(db, iDb, DB_SchemaLoaded); - rc = SQLITE_OK; - } - - /* Jump here for an error that occurs after successfully allocating - ** curMain and calling sqlite3BtreeEnter(). For an error that occurs - ** before that point, jump to error_out. - */ -initone_error_out: - if( openedTransaction ){ - 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. If the database -** file was of zero-length, then the DB_Empty flag is also set. -*/ -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); - 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--){ - if( !DbHasProperty(db, i, DB_SchemaLoaded) ){ - rc = sqlite3InitOne(db, i, pzErrMsg); - 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++; - } - 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); - 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 = -1000000; - - /* If pSchema is NULL, then return -1000000. This happens when code in - ** expr.c is trying to resolve a reference to a transient table (i.e. one - ** created by a sub-select). In this case the return value of this - ** function should never be used. - ** - ** We return -1000000 instead of the more usual -1 simply because using - ** -1000000 as the incorrect index into db->aDb[] is much - ** more likely to cause a segfault than -1 (of course there are assert() - ** statements too, but it never hurts to play the odds). - */ - assert( sqlite3_mutex_held(db->mutex) ); - if( pSchema ){ - for(i=0; ALWAYS(inDb); i++){ - if( db->aDb[i].pSchema==pSchema ){ - break; - } - } - assert( i>=0 && inDb ); - } - return i; -} - -/* -** Free all memory allocations in the pParse object -*/ -SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){ - sqlite3 *db = pParse->db; - sqlite3DbFree(db, pParse->aLabel); - sqlite3ExprListDelete(db, pParse->pConstExpr); - if( db ){ - assert( db->lookaside.bDisable >= pParse->disableLookaside ); - db->lookaside.bDisable -= pParse->disableLookaside; - } - 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++; - db->lookaside.bDisable++; - } - - /* Check to verify that it is possible to get a read lock on all - ** database schemas. The inability to get a read lock indicates that - ** some other database connection is holding a write-lock, which in - ** turn means that the other connection has made uncommitted changes - ** to the schema. - ** - ** Were we to proceed and prepare the statement against the uncommitted - ** schema changes and if those schema changes are subsequently rolled - ** back and different changes are made in their place, then when this - ** prepared statement goes to run the schema cookie would fail to detect - ** the schema change. Disaster would follow. - ** - ** This thread is currently holding mutexes on all Btrees (because - ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it - ** is not possible for another thread to start a new schema change - ** while this routine is running. Hence, we do not need to hold - ** locks on the schema, we just need to make sure nobody else is - ** holding them. - ** - ** Note that setting READ_UNCOMMITTED overrides most lock detection, - ** but it does *not* override schema lock detection, so this all still - ** works even if READ_UNCOMMITTED is set. - */ - for(i=0; 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( db->mallocFailed ){ - sParse.rc = SQLITE_NOMEM_BKPT; - } - if( pzTail ){ - *pzTail = sParse.zTail; - } - rc = sParse.rc; - -#ifndef SQLITE_OMIT_EXPLAIN - if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){ - static const char * const azColName[] = { - "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment", - "selectid", "order", "from", "detail" - }; - int iFirst, mx; - if( sParse.explain==2 ){ - sqlite3VdbeSetNumCols(sParse.pVdbe, 4); - iFirst = 8; - mx = 12; - }else{ - sqlite3VdbeSetNumCols(sParse.pVdbe, 8); - iFirst = 0; - mx = 8; - } - for(i=iFirst; iinit.busy==0 ){ - sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags); - } - if( sParse.pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){ - 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); - rc = sqlite3ApiExit(db, rc); - assert( (rc&db->errMask)==rc ); - 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; - -#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); - rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail); - if( rc==SQLITE_SCHEMA ){ - sqlite3ResetOneSchema(db, -1); - sqlite3_finalize(*ppStmt); - rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail); - } - sqlite3BtreeLeaveAll(db); - sqlite3_mutex_leave(db->mutex); - assert( rc==SQLITE_OK || *ppStmt==0 ); - return rc; -} - -/* -** Rerun the compilation of a statement after a schema change. -** -** If the statement is successfully recompiled, return SQLITE_OK. Otherwise, -** if the statement cannot be recompiled because another connection has -** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error -** occurs, return SQLITE_SCHEMA. -*/ -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" */ - -/* -** Trace output macros -*/ -#if SELECTTRACE_ENABLED -/***/ int sqlite3SelectTrace = 0; -# define SELECTTRACE(K,P,S,X) \ - if(sqlite3SelectTrace&(K)) \ - sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\ - (S)->zSelName,(S)),\ - sqlite3DebugPrintf X -#else -# define SELECTTRACE(K,P,S,X) -#endif - - -/* -** 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. -*/ -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 */ - u8 sortFlags; /* Zero or more SORTFLAG_* bits */ - u8 bOrderedInnerLoop; /* ORDER BY correctly sorts the inner loop */ -}; -#define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */ - -/* -** Delete all the content of a Select structure. Deallocate the structure -** itself only if bFree is true. -*/ -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); - sqlite3ExprDelete(db, p->pOffset); - 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->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 */ - Expr *pOffset /* OFFSET value. NULL means no offset */ -){ - Select *pNew; - Select standin; - 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; -#if SELECTTRACE_ENABLED - pNew->zSelName[0] = 0; -#endif - 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->pOffset = pOffset; - pNew->pWith = 0; - assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 - || pParse->db->mallocFailed!=0 ); - if( pParse->db->mallocFailed ) { - clearSelect(pParse->db, pNew, pNew!=&standin); - pNew = 0; - }else{ - assert( pNew->pSrc!=0 || pParse->nErr>0 ); - } - assert( pNew!=&standin ); - return pNew; -} - -#if SELECTTRACE_ENABLED -/* -** Set the name of a Select object -*/ -SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){ - if( p && zName ){ - sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName); - } -} -#endif - - -/* -** 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; - for(i=0; inCol; i++){ - if( sqlite3StrICmp(pTab->aCol[i].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 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 ){ - 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(db, *ppWhere, pEq); -} - -/* -** Set the EP_FromJoin property on all terms of the given expression. -** And set the Expr.iRightJoinTable to iTable for every term in the -** expression. -** -** The EP_FromJoin property is used on terms of an expression to tell -** the LEFT OUTER JOIN processing logic that this term is part of the -** join restriction specified in the ON or USING clause and not a part -** of the more general WHERE clause. These terms are moved over to the -** WHERE clause during join processing but we need to remember that they -** originated in the ON or USING clause. -** -** The Expr.iRightJoinTable tells the WHERE clause processing that the -** expression depends on table iRightJoinTable even if that table is not -** explicitly mentioned in the expression. That information is needed -** for cases like this: -** -** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 -** -** The where clause needs to defer the handling of the t1.x=5 -** term until after the t2 loop of the join. In that way, a -** NULL t2 row will be inserted whenever t1.x!=5. If we do not -** defer the handling of t1.x=5, it will be processed immediately -** after the t1 loop and rows with t1.x!=5 will never appear in -** the output, which is incorrect. -*/ -static void setJoinExpr(Expr *p, int iTable){ - while( p ){ - 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++){ - setJoinExpr(p->x.pList->a[i].pExpr, iTable); - } - } - setJoinExpr(p->pLeft, iTable); - p = p->pRight; - } -} - -/* -** This routine processes the join information for a SELECT statement. -** ON and USING clauses are converted into extra terms of the WHERE clause. -** NATURAL joins also create extra WHERE clause terms. -** -** The terms of a FROM clause are contained in the Select.pSrc structure. -** The left most table is the first entry in Select.pSrc. The right-most -** table is the last entry. The join operator is held in the entry to -** the left. Thus entry 0 contains the join operator for the join between -** entries 0 and 1. Any ON or USING clauses associated with the join are -** also attached to the left entry. -** -** This routine returns the number of errors encountered. -*/ -static int sqliteProcessJoin(Parse *pParse, Select *p){ - SrcList *pSrc; /* All tables in the FROM clause */ - int i, 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 */ - - zName = pRightTab->aCol[j].zName; - if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){ - 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 ) setJoinExpr(pRight->pOn, pRight->iCursor); - p->pWhere = sqlite3ExprAnd(pParse->db, 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) - ){ - 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; -} - -/* Forward reference */ -static KeyInfo *keyInfoFromExprList( - 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 */ -); - -/* -** 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 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 = ++pParse->nMem; /* 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 */ - - assert( bSeq==0 || bSeq==1 ); - assert( nData==1 || regData==regOrigData || regOrigData==0 ); - if( nPrefixReg ){ - assert( nPrefixReg==nExpr+bSeq ); - regBase = regData - nExpr - bSeq; - }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(v); - 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); - } - sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord); - 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 */ - - 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->aSortOrder, 0, pKI->nKeyField); /* Makes OP_Jump testable */ - sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO); - testcase( pKI->nAllField > pKI->nKeyField+2 ); - pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat, - pKI->nAllField-pKI->nKeyField-1); - addrJmp = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v); - pSort->labelBkOut = sqlite3VdbeMakeLabel(v); - 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( pSort->sortFlags & SORTFLAG_UseSorter ){ - op = OP_SorterInsert; - }else{ - op = OP_IdxInsert; - } - sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord, - regBase+nOBSat, nBase-nOBSat); - if( iLimit ){ - int addr; - int r1 = 0; - /* Fill the sorter until it contains LIMIT+OFFSET entries. (The iLimit - ** register is initialized with value of LIMIT+OFFSET.) After the sorter - ** fills up, delete the least entry in the sorter after each insert. - ** Thus we never hold more than the LIMIT+OFFSET rows in memory at once */ - addr = sqlite3VdbeAddOp1(v, OP_IfNotZero, iLimit); VdbeCoverage(v); - sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor); - if( pSort->bOrderedInnerLoop ){ - r1 = ++pParse->nMem; - sqlite3VdbeAddOp3(v, OP_Column, pSort->iECursor, nExpr, r1); - VdbeComment((v, "seq")); - } - sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor); - if( pSort->bOrderedInnerLoop ){ - /* If the inner loop is driven by an index such that values from - ** the same iteration of the inner loop are in sorted order, then - ** immediately jump to the next iteration of an inner loop if the - ** entry from the current iteration does not fit into the top - ** LIMIT+OFFSET entries of the sorter. */ - int iBrk = sqlite3VdbeCurrentAddr(v) + 2; - sqlite3VdbeAddOp3(v, OP_Eq, regBase+nExpr, iBrk, r1); - sqlite3VdbeChangeP5(v, SQLITE_NULLEQ); - VdbeCoverage(v); - } - sqlite3VdbeJumpHere(v, addr); - } -} - -/* -** 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); -} - -/* -** 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 */ - - /* 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].zName)); - } - }else if( eDest!=SRT_Exists ){ - /* If the destination is an EXISTS(...) expression, the actual - ** values returned by the SELECT are not required. - */ - u8 ecelFlags; - 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; - } - } - regOrig = 0; - assert( eDest==SRT_Set || eDest==SRT_Mem - || eDest==SRT_Coroutine || eDest==SRT_Output ); - } - nResultCol = sqlite3ExprCodeExprList(pParse,p->pEList,regResult, - 0,ecelFlags); - } - - /* 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; - - 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 ){ - pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,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; - } - -#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); - sqlite3ExprCacheAffinityChange(pParse, regResult, 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); - sqlite3ExprCacheAffinityChange(pParse, 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->aSortOrder = (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. -*/ -static KeyInfo *keyInfoFromExprList( - 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->aSortOrder[i-iStart] = pItem->sortOrder; - } - } - 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){ - if( pParse->explain==2 ){ - Vdbe *v = pParse->pVdbe; - char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage); - sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); - } -} - -/* -** Assign expression b to lvalue a. A second, no-op, version of this macro -** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code -** in sqlite3Select() to assign values to structure member variables that -** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the -** code with #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 !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT) -/* -** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function -** is a no-op. Otherwise, it adds a single row of output to the EQP result, -** where the caption is of one of the two forms: -** -** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)" -** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)" -** -** where iSub1 and iSub2 are the integers passed as the corresponding -** function parameters, and op is the text representation of the parameter -** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT, -** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is -** false, or the second form if it is true. -*/ -static void explainComposite( - Parse *pParse, /* Parse context */ - int op, /* One of TK_UNION, TK_EXCEPT etc. */ - int iSub1, /* Subquery id 1 */ - int iSub2, /* Subquery id 2 */ - int bUseTmp /* True if a temp table was used */ -){ - assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL ); - if( pParse->explain==2 ){ - Vdbe *v = pParse->pVdbe; - char *zMsg = sqlite3MPrintf( - pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2, - bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op) - ); - sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC); - } -} -#else -/* No-op versions of the explainXXX() functions and macros. */ -# define explainComposite(v,w,x,y,z) -#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(v); /* Jump here for next cycle */ - int addr; - 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; - int iSortTab; /* Sorter cursor to read from */ - int nSortData; /* Trailing values to read from sorter */ - int i; - int bSeq; /* True if sorter record includes seq. no. */ - 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); - } - iTab = pSort->iECursor; - if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){ - regRowid = 0; - regRow = pDest->iSdst; - nSortData = nColumn; - }else{ - regRowid = sqlite3GetTempReg(pParse); - regRow = sqlite3GetTempRange(pParse, nColumn); - nSortData = 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+nSortData); - 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; izAffSdst) ); - sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid, - pDest->zAffSdst, nColumn); - sqlite3ExprCacheAffinityChange(pParse, regRow, nColumn); - sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn); - break; - } - case SRT_Mem: { - /* The LIMIT clause will terminate the loop for us */ - break; - } -#endif - 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); - sqlite3ExprCacheAffinityChange(pParse, 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_AGG_COLUMN: - case TK_COLUMN: { - /* The expression is a column. Locate the table the column is being - ** extracted from in NameContext.pSrcList. This table may be real - ** database table or a subquery. - */ - Table *pTab = 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 */ - testcase( pExpr->op==TK_AGG_COLUMN ); - testcase( pExpr->op==TK_COLUMN ); - 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->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 || db->mallocFailed ) return; - /* Column names are determined by the left-most term of a compound select */ - while( pSelect->pPrior ) pSelect = pSelect->pPrior; - 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->pTab!=0 ); /* Covering idx not yet coded */ - if( pEList->a[i].zName ){ - /* An AS clause always takes first priority */ - char *zName = pEList->a[i].zName; - sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT); - }else if( srcName && p->op==TK_COLUMN ){ - char *zCol; - int iCol = p->iColumn; - pTab = p->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].zSpan; - 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].zName)!=0 ){ - /* If the column contains an "AS " phrase, use as the name */ - }else{ - Expr *pColExpr = sqlite3ExprSkipCollate(pEList->a[i].pExpr); - while( pColExpr->op==TK_DOT ){ - pColExpr = pColExpr->pRight; - assert( pColExpr!=0 ); - } - if( (pColExpr->op==TK_COLUMN || pColExpr->op==TK_AGG_COLUMN) - && pColExpr->pTab!=0 - ){ - /* For columns use the column name name */ - int iCol = pColExpr->iColumn; - Table *pTab = pColExpr->pTab; - 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].zSpan; - } - } - if( 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; - 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==0 ) pCol->affinity = SQLITE_AFF_BLOB; - 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){ - Table *pTab; - sqlite3 *db = pParse->db; - int savedFlags; - - savedFlags = db->flags; - db->flags &= ~SQLITE_FullColNames; - db->flags |= SQLITE_ShortColNames; - sqlite3SelectPrep(pParse, pSelect, 0); - if( pParse->nErr ) return 0; - while( pSelect->pPrior ) pSelect = pSelect->pPrior; - db->flags = savedFlags; - pTab = sqlite3DbMallocZero(db, sizeof(Table) ); - if( pTab==0 ){ - return 0; - } - /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside - ** is disabled */ - assert( db->lookaside.bDisable ); - 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); - 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 and pOffset expressions. pLimit and pOffset hold the expressions -** that appear in the original SQL statement after the LIMIT and OFFSET -** keywords. Or NULL if those keywords are omitted. iLimit and iOffset -** are the integer memory register numbers for counters used to compute -** the limit and offset. If there is no limit and/or offset, then -** iLimit and iOffset are negative. -** -** This routine changes the values of iLimit and iOffset only if -** a limit or offset is defined by pLimit and pOffset. iLimit and -** iOffset should have been preset to appropriate default values (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!=0 or pOffset!=0 do the limit registers get -** redefined. The UNION ALL operator uses this property to force -** the reuse of the same limit and offset registers across multiple -** SELECT statements. -*/ -static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ - Vdbe *v = 0; - int iLimit = 0; - int iOffset; - int n; - 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. - */ - sqlite3ExprCacheClear(pParse); - assert( p->pOffset==0 || p->pLimit!=0 ); - if( p->pLimit ){ - p->iLimit = iLimit = ++pParse->nMem; - v = sqlite3GetVdbe(pParse); - assert( v!=0 ); - if( sqlite3ExprIsInteger(p->pLimit, &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, p->pLimit, iLimit); - sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v); - VdbeComment((v, "LIMIT counter")); - sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v); - } - if( p->pOffset ){ - p->iOffset = iOffset = ++pParse->nMem; - pParse->nMem++; /* Allocate an extra register for limit+offset */ - sqlite3ExprCode(pParse, p->pOffset, 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->aSortOrder[i] = pOrderBy->a[i].sortOrder; - } - } - - 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, *pOffset; /* Saved LIMIT and OFFSET */ - int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */ - - /* 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(v); - p->nSelectRow = 320; /* 4 billion rows */ - computeLimitRegisters(pParse, p, addrBreak); - pLimit = p->pLimit; - pOffset = p->pOffset; - regLimit = p->iLimit; - regOffset = p->iOffset; - p->pLimit = p->pOffset = 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; - 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(v); - 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; - 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; - p->pOffset = pOffset; - 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) It has no LIMIT or OFFSET -** (2) All terms are UNION ALL -** (3) There is no ORDER BY clause -*/ -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 */ -){ - Select *pPrior; - int nRow = 1; - int rc = 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->pLimit==0 ); - assert( p->pOffset==0 ); - assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr ); - if( p->pPrior==0 ) break; - assert( p->pPrior->pNext==p ); - p = p->pPrior; - nRow++; - }while(1); - while( p ){ - pPrior = p->pPrior; - p->pPrior = 0; - rc = sqlite3Select(pParse, p, pDest); - p->pPrior = pPrior; - if( rc ) 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 */ -#ifndef SQLITE_OMIT_EXPLAIN - int iSub1 = 0; /* EQP id of left-hand query */ - int iSub2 = 0; /* EQP id of right-hand query */ -#endif - - /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only - ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. - */ - assert( p && p->pPrior ); /* Calling function guarantees this much */ - assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION ); - 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); - goto multi_select_end; - } - - /* 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 - - /* 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; - pPrior->pOffset = p->pOffset; - explainSetInteger(iSub1, pParse->iNextSelectId); - rc = sqlite3Select(pParse, pPrior, &dest); - p->pLimit = 0; - p->pOffset = 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); - } - } - explainSetInteger(iSub2, pParse->iNextSelectId); - 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, &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 temporary table holding result */ - u8 op = 0; /* One of the SRT_ operations to apply to self */ - int priorOp; /* The SRT_ operation to apply to prior selects */ - Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */ - int addr; - SelectDest uniondest; - - 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 */ - assert( p->pOffset==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); - explainSetInteger(iSub1, pParse->iNextSelectId); - 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; - pOffset = p->pOffset; - p->pOffset = 0; - uniondest.eDest = op; - explainSetInteger(iSub2, pParse->iNextSelectId); - rc = sqlite3Select(pParse, p, &uniondest); - testcase( rc!=SQLITE_OK ); - /* Query flattening in sqlite3Select() might refill p->pOrderBy. - ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ - sqlite3ExprListDelete(db, p->pOrderBy); - 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->pOffset = pOffset; - 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 ); - if( dest.eDest!=priorOp ){ - int iCont, iBreak, iStart; - assert( p->pEList ); - iBreak = sqlite3VdbeMakeLabel(v); - iCont = sqlite3VdbeMakeLabel(v); - 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, *pOffset; - 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); - explainSetInteger(iSub1, pParse->iNextSelectId); - 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; - pOffset = p->pOffset; - p->pOffset = 0; - intersectdest.iSDParm = tab2; - explainSetInteger(iSub2, pParse->iNextSelectId); - 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; - p->pOffset = pOffset; - - /* Generate code to take the intersection of the two temporary - ** tables. - */ - assert( p->pEList ); - iBreak = sqlite3VdbeMakeLabel(v); - iCont = sqlite3VdbeMakeLabel(v); - 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; - } - } - - explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL); - - /* Compute collating sequences used by - ** temporary tables needed to implement the compound select. - ** Attach the KeyInfo structure to all temporary tables. - ** - ** This section is run by the right-most SELECT statement only. - ** SELECT statements to the left always skip this part. The right-most - ** SELECT might also skip this part if it has no ORDER BY clause and - ** no temp tables are required. - */ - if( p->selFlags & SF_UsesEphemeral ){ - 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(v); - - /* 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); - sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 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. - */ - case SRT_Mem: { - assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 ); - sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1); - /* 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); - sqlite3ExprCacheAffinityChange(pParse, 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 */ - int *aPermute; /* Mapping from ORDER BY terms to result set columns */ -#ifndef SQLITE_OMIT_EXPLAIN - int iSub1; /* EQP id of left-hand query */ - int iSub2; /* EQP id of right-hand query */ -#endif - - 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(v); - labelCmpr = sqlite3VdbeMakeLabel(v); - - - /* 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(int)*(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->aSortOrder[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; - sqlite3ExprDelete(db, p->pOffset); - p->pOffset = 0; - - regAddrA = ++pParse->nMem; - regAddrB = ++pParse->nMem; - regOutA = ++pParse->nMem; - regOutB = ++pParse->nMem; - sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA); - sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB); - - /* 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; - explainSetInteger(iSub1, pParse->iNextSelectId); - 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; - explainSetInteger(iSub2, pParse->iNextSelectId); - 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 ****/ - explainComposite(pParse, p->op, iSub1, iSub2, 0); - 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 ){ - 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->pLeft==0 && 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; - pCopy = &ifNullRow; - } - 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; - } - } - }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); - } - } - 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) -/* -** 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. -** -** (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. -** -** 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. -** -** (**) Subsumed into (17d3). Was: If the sub-query is a compound select, -** then it must not use an ORDER BY clause - Ticket #3773. Because -** of (17d3), then only way to have a compound subquery is if it is -** the only term in the FROM clause of the outer query. But if the -** only term in the FROM clause has an ORDER BY, then it will be -** implemented as a co-routine and the flattener will never be called. -** -** (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.) -** -** -** 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; - - /* 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 ); - - 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->pOffset ) 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 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){ - /* (3a) (3c) (3b) */ - 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( 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) */ - ){ - 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 ); - - /* Ex-restriction (20): - ** A compound subquery must be the only term in the FROM clause of the - ** outer query by restriction (17d3). But if that term also has an - ** ORDER BY clause, then the subquery will be implemented by co-routine - ** and so the flattener will never be invoked. Hence, it is not possible - ** for the subquery to be a compound and have an ORDER BY clause. - */ - assert( pSub->pPrior==0 || pSub->pOrderBy==0 ); - - /***** If we reach this point, flattening is permitted. *****/ - SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n", - pSub->zSelName, 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; - Expr *pOffset = p->pOffset; - Select *pPrior = p->pPrior; - p->pOrderBy = 0; - p->pSrc = 0; - p->pPrior = 0; - p->pLimit = 0; - p->pOffset = 0; - pNew = sqlite3SelectDup(db, p, 0); - sqlite3SelectSetName(pNew, pSub->zSelName); - p->pOffset = pOffset; - 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 %s.%p as peer\n", - pNew->zSelName, pNew)); - } - 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; - 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 = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0); - if( pSrc==0 ){ - assert( db->mallocFailed ); - break; - } - } - - /* The subquery uses a single slot of the FROM clause of the outer - ** query. If the subquery has more than one element in its FROM clause, - ** then expand the outer query to make space for it to hold all elements - ** of the subquery. - ** - ** Example: - ** - ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB; - ** - ** The outer query has 3 slots in its FROM clause. One slot of the - ** outer query (the middle slot) is used by the subquery. The next - ** block of code will expand the 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 ){ - pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1); - if( db->mallocFailed ){ - break; - } - } - - /* 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 ){ - /* 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 ); - assert( pSub->pPrior==0 ); - pParent->pOrderBy = pOrderBy; - pSub->pOrderBy = 0; - } - pWhere = sqlite3ExprDup(db, pSub->pWhere, 0); - if( isLeftJoin>0 ){ - setJoinExpr(pWhere, iNewParent); - } - pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->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 distinct if either the inner or the - ** outer query is distinct. - */ - pParent->selFlags |= pSub->selFlags & SF_Distinct; - - /* - ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; - ** - ** One is tempted to try to add a and b to combine the limits. But this - ** does not work if either limit is negative. - */ - if( pSub->pLimit ){ - pParent->pLimit = pSub->pLimit; - pSub->pLimit = 0; - } - } - - /* Finially, delete what is left of the subquery and return - ** success. - */ - sqlite3SelectDelete(db, pSub1); - -#if SELECTTRACE_ENABLED - if( sqlite3SelectTrace & 0x100 ){ - SELECTTRACE(0x100,pParse,p,("After flattening:\n")); - sqlite3TreeViewSelect(0, p, 0); - } -#endif - - return 1; -} -#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ - - - -#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 -** close would change the meaning of the LIMIT). -** -** (4) The inner query is the right operand of a LEFT JOIN. (The caller -** enforces this restriction since this routine does not have enough -** information to know.) -** -** (5) The WHERE clause expression originates in the ON or USING clause -** of a LEFT JOIN. -** -** 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 */ -){ - Expr *pNew; - int nChng = 0; - if( pWhere==0 ) return 0; - if( pSubq->selFlags & SF_Recursive ) return 0; /* restriction (2) */ - -#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); - pWhere = pWhere->pLeft; - } - if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction (5) */ - if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){ - nChng++; - while( pSubq ){ - SubstContext x; - pNew = sqlite3ExprDup(pParse->db, pWhere, 0); - 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->db, pSubq->pHaving, pNew); - }else{ - pSubq->pWhere = sqlite3ExprAnd(pParse->db, pSubq->pWhere, pNew); - } - pSubq = pSubq->pPrior; - } - } - return nChng; -} -#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */ - -/* -** Based on the contents of the AggInfo structure indicated by the first -** argument, this function checks if the following are true: -** -** * the query contains just a single aggregate function, -** * the aggregate function is either min() or max(), and -** * the argument to the aggregate function is a column value. -** -** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX -** is returned as appropriate. Also, *ppMinMax is set to point to the -** list of arguments passed to the aggregate before returning. -** -** Or, if the conditions above are not met, *ppMinMax is set to 0 and -** WHERE_ORDERBY_NORMAL is returned. -*/ -static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){ - int eRet = WHERE_ORDERBY_NORMAL; /* Return value */ - - *ppMinMax = 0; - if( pAggInfo->nFunc==1 ){ - Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */ - ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */ - - assert( pExpr->op==TK_AGG_FUNCTION ); - if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){ - const char *zFunc = pExpr->u.zToken; - if( sqlite3StrICmp(zFunc, "min")==0 ){ - eRet = WHERE_ORDERBY_MIN; - *ppMinMax = pEList; - }else if( sqlite3StrICmp(zFunc, "max")==0 ){ - eRet = WHERE_ORDERBY_MAX; - *ppMinMax = pEList; - } - } - } - - assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 ); - 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( pExpr->flags&EP_Distinct ) 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; - 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; - 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; - pNew->pOffset = 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 ); - - 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->pWith = pWith->pOuter; - } - } -} -#else -#define selectPopWith 0 -#endif - -/* -** 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; - - p->selFlags |= SF_Expanded; - if( db->mallocFailed ){ - return WRC_Abort; - } - if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){ - return WRC_Prune; - } - pTabList = p->pSrc; - pEList = p->pEList; - if( OK_IF_ALWAYS_TRUE(p->pWith) ){ - 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->fg.isRecursive ) continue; - assert( pFrom->pTab==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; - pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table)); - if( pTab==0 ) return WRC_Abort; - pTab->nTabRef = 1; - if( pFrom->zAlias ){ - pTab->zName = sqlite3DbStrDup(db, pFrom->zAlias); - }else{ - pTab->zName = sqlite3MPrintf(db, "subquery_%p", (void*)pTab); - } - 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; -#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; - if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort; - assert( pFrom->pSelect==0 ); - pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0); - sqlite3SelectSetName(pFrom->pSelect, pTab->zName); - nCol = pTab->nCol; - pTab->nCol = -1; - sqlite3WalkSelect(pWalker, pFrom->pSelect); - 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( 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; - } - 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; - 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].zName = a[k].zName; - pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan; - a[k].zName = 0; - a[k].zSpan = 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 - && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 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) - ){ - /* 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 ){ - struct ExprList_item *pX = &pNew->a[pNew->nExpr-1]; - if( pSub ){ - pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan); - testcase( pX->zSpan==0 ); - }else{ - pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s", - zSchemaName, zTabName, zColname); - testcase( pX->zSpan==0 ); - } - pX->bSpanIsTab = 1; - } - 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 && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ - sqlite3ErrorMsg(pParse, "too many columns in result set"); - return WRC_Abort; - } - return WRC_Continue; -} - -/* -** No-op routine for the parse-tree walker. -** -** When this routine is the Walker.xExprCallback then expression trees -** are walked without any actions being taken at each node. Presumably, -** when this routine is used for Walker.xExprCallback then -** Walker.xSelectCallback is set to do something useful for every -** subquery in the parser tree. -*/ -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; -} - -#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; - 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 ); - assert( (p->selFlags & SF_HasTypeInfo)==0 ); - 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); - } - } - } -} -#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; -#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->pExpr; - 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 = keyInfoFromExprList(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->pExpr->x.pList; - assert( !ExprHasProperty(pF->pExpr, 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. -*/ -static void updateAccumulator(Parse *pParse, 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->pExpr->x.pList; - assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) ); - 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 ){ - addrNext = sqlite3VdbeMakeLabel(v); - 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_AggStep0, 0, regAgg, pF->iMem); - sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF); - sqlite3VdbeChangeP5(v, (u8)nArg); - sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg); - sqlite3ReleaseTempRange(pParse, regAgg, nArg); - if( addrNext ){ - sqlite3VdbeResolveLabel(v, addrNext); - sqlite3ExprCacheClear(pParse); - } - } - - /* Before populating the accumulator registers, clear the column cache. - ** Otherwise, if any of the required column values are already present - ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value - ** to pC->iMem. But by the time the value is used, the original register - ** may have been used, invalidating the underlying buffer holding the - ** text or blob value. See ticket [883034dcb5]. - ** - ** Another solution would be to change the OP_SCopy used to copy cached - ** values to an OP_Copy. - */ - if( regHit ){ - addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v); - } - sqlite3ExprCacheClear(pParse); - for(i=0, pC=pAggInfo->aCol; inAccumulator; i++, pC++){ - sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); - } - pAggInfo->directMode = 0; - sqlite3ExprCacheClear(pParse); - if( addrHitTest ){ - sqlite3VdbeJumpHere(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))); - char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s", - pTab->zName, - bCover ? " USING COVERING INDEX " : "", - bCover ? pIdx->zName : "" - ); - sqlite3VdbeAddOp4( - pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC - ); - } -} -#else -# define explainSimpleCount(a,b,c) -#endif - -/* -** Context object for havingToWhereExprCb(). -*/ -struct HavingToWhereCtx { - Expr **ppWhere; - ExprList *pGroupBy; -}; - -/* -** 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 ){ - struct HavingToWhereCtx *p = pWalker->u.pHavingCtx; - if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, p->pGroupBy) ){ - sqlite3 *db = pWalker->pParse->db; - Expr *pNew = sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[1], 0); - if( pNew ){ - Expr *pWhere = *(p->ppWhere); - SWAP(Expr, *pNew, *pExpr); - pNew = sqlite3ExprAnd(db, pWhere, pNew); - *(p->ppWhere) = pNew; - } - } - 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, - ExprList *pGroupBy, - Expr *pHaving, - Expr **ppWhere -){ - struct HavingToWhereCtx sCtx; - Walker sWalker; - - sCtx.ppWhere = ppWhere; - sCtx.pGroupBy = pGroupBy; - - memset(&sWalker, 0, sizeof(sWalker)); - sWalker.pParse = pParse; - sWalker.xExprCallback = havingToWhereExprCb; - sWalker.u.pHavingCtx = &sCtx; - sqlite3WalkExpr(&sWalker, pHaving); -} - -/* -** 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; - if( sqlite3_stricmp(pItem->zDatabase, pThis->zDatabase)!=0 ) continue; - if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue; - if( sqlite3ExprCompare(0, - pThis->pSelect->pWhere, pItem->pSelect->pWhere, -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 -** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries -** * The outer query is a simple count(*) -** -** 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 */ - 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->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( sqlite3SelectTrace & 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 */ - 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 */ - AggInfo sAggInfo; /* Information used by aggregate queries */ - int iEnd; /* Address of the end of the query */ - sqlite3 *db; /* The database connection */ - -#ifndef SQLITE_OMIT_EXPLAIN - int iRestoreSelectId = pParse->iSelectId; - pParse->iSelectId = pParse->iNextSelectId++; -#endif - - db = pParse->db; - if( p==0 || db->mallocFailed || pParse->nErr ){ - return 1; - } - if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; - memset(&sAggInfo, 0, sizeof(sAggInfo)); -#if SELECTTRACE_ENABLED - pParse->nSelectIndent++; - SELECTTRACE(1,pParse,p, ("begin processing:\n")); - if( sqlite3SelectTrace & 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; - } - sqlite3SelectPrep(pParse, p, 0); - memset(&sSort, 0, sizeof(sSort)); - sSort.pOrderBy = p->pOrderBy; - pTabList = p->pSrc; - if( pParse->nErr || db->mallocFailed ){ - goto select_end; - } - assert( p->pEList!=0 ); - isAgg = (p->selFlags & SF_Aggregate)!=0; -#if SELECTTRACE_ENABLED - if( sqlite3SelectTrace & 0x100 ){ - SELECTTRACE(0x100,pParse,p, ("after name resolution:\n")); - sqlite3TreeViewSelect(0, p, 0); - } -#endif - - /* Get a pointer the VDBE under construction, allocating a new VDBE if one - ** does not already exist */ - v = sqlite3GetVdbe(pParse); - if( v==0 ) goto select_end; - if( pDest->eDest==SRT_Output ){ - generateColumnNames(pParse, p); - } - - /* Try to flatten subqueries 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; - 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 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. - */ - if( pSub->pOrderBy!=0 - && i==0 - && (pTabList->nSrc==1 - || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) - ){ - continue; - } - - if( flattenSubquery(pParse, p, i, isAgg) ){ - /* 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); - explainSetInteger(pParse->iSelectId, iRestoreSelectId); -#if SELECTTRACE_ENABLED - SELECTTRACE(1,pParse,p,("end compound-select processing\n")); - pParse->nSelectIndent--; -#endif - return rc; - } -#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 ){ - 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; - - /* Sometimes the code for a subquery will be generated more than - ** once, if the subquery is part of the WHERE clause in a LEFT JOIN, - ** for example. In that case, do not regenerate the code to manifest - ** a view or the co-routine to implement a view. The first instance - ** is sufficient, though the subroutine to manifest the view does need - ** to be invoked again. */ - if( pItem->addrFillSub ){ - if( pItem->fg.viaCoroutine==0 ){ - /* The subroutine that manifests the view might be a one-time routine, - ** or it might need to be rerun on each iteration because it - ** encodes a correlated subquery. */ - testcase( sqlite3VdbeGetOp(v, pItem->addrFillSub)->opcode==OP_Once ); - sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub); - } - continue; - } - - /* 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( (pItem->fg.jointype & JT_OUTER)==0 - && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor) - ){ -#if SELECTTRACE_ENABLED - if( sqlite3SelectTrace & 0x100 ){ - SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n")); - sqlite3TreeViewSelect(0, p, 0); - } -#endif - } - - 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); - explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); - 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; - - assert( pItem->addrFillSub==0 ); - 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); - explainSetInteger(pItem->iSelectId, pPrior->iSelectId); - assert( pPrior->pSelect!=0 ); - pSub->nSelectRow = pPrior->pSelect->nSelectRow; - }else{ - sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); - explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId); - 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( sqlite3SelectTrace & 0x400 ){ - SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n")); - sqlite3TreeViewSelect(0, p, 0); - } -#endif - -#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 - - /* 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 - ){ - p->selFlags &= ~SF_Distinct; - pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0); - /* 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( sqlite3SelectTrace & 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 = keyInfoFromExprList(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(v); - 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*)keyInfoFromExprList(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); - assert( WHERE_USE_LIMIT==SF_FixedLimit ); - wctrlFlags |= p->selFlags & SF_FixedLimit; - - /* Begin the database scan. */ - 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.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(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); - } - - /* Use the standard inner loop. */ - assert( p->pEList==pEList ); - 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; - }else{ - assert( 0==sqlite3LogEst(1) ); - p->nSelectRow = 0; - } - - /* 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( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){ - orderByGrp = 1; - } - - /* Create a label to jump to when we want to abort the query */ - addrEnd = sqlite3VdbeMakeLabel(v); - - /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in - ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the - ** SELECT statement. - */ - memset(&sNC, 0, sizeof(sNC)); - sNC.pParse = pParse; - sNC.pSrcList = pTabList; - sNC.pAggInfo = &sAggInfo; - sAggInfo.mnReg = pParse->nMem+1; - sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0; - sAggInfo.pGroupBy = pGroupBy; - sqlite3ExprAnalyzeAggList(&sNC, pEList); - sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy); - if( pHaving ){ - if( pGroupBy ){ - assert( pWhere==p->pWhere ); - havingToWhere(pParse, pGroupBy, pHaving, &p->pWhere); - pWhere = p->pWhere; - } - sqlite3ExprAnalyzeAggregates(&sNC, pHaving); - } - sAggInfo.nAccumulator = sAggInfo.nColumn; - for(i=0; ix.pList); - sNC.ncFlags &= ~NC_InAggFunc; - } - sAggInfo.mxReg = pParse->nMem; - if( db->mallocFailed ) goto select_end; - - /* 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. - */ - sAggInfo.sortingIdx = pParse->nTab++; - pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn); - addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, - sAggInfo.sortingIdx, sAggInfo.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(v); - regReset = ++pParse->nMem; - addrReset = sqlite3VdbeMakeLabel(v); - iAMem = pParse->nMem + 1; - pParse->nMem += pGroupBy->nExpr; - iBMem = pParse->nMem + 1; - pParse->nMem += pGroupBy->nExpr; - sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); - VdbeComment((v, "clear abort flag")); - sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); - VdbeComment((v, "indicate accumulator empty")); - 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); - 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; i=j ){ - nCol++; - j++; - } - } - regBase = sqlite3GetTempRange(pParse, nCol); - sqlite3ExprCacheClear(pParse); - sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0); - j = nGroupBy; - for(i=0; iiSorterColumn>=j ){ - int r1 = j + regBase; - sqlite3ExprCodeGetColumnToReg(pParse, - pCol->pTab, pCol->iColumn, pCol->iTable, r1); - j++; - } - } - regRecord = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); - sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord); - sqlite3ReleaseTempReg(pParse, regRecord); - sqlite3ReleaseTempRange(pParse, regBase, nCol); - sqlite3WhereEnd(pWInfo); - sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++; - sortOut = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol); - sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd); - VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v); - sAggInfo.useSortingIdx = 1; - sqlite3ExprCacheClear(pParse); - - } - - /* 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); - sqlite3ExprCacheClear(pParse); - if( groupBySort ){ - sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx, - sortOut, sortPTab); - } - for(j=0; jnExpr; j++){ - if( groupBySort ){ - sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j); - }else{ - sAggInfo.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, &sAggInfo); - sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); - VdbeComment((v, "indicate data in accumulator")); - - /* End of the loop - */ - if( groupBySort ){ - sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.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, &sAggInfo); - 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, &sAggInfo); - sqlite3VdbeAddOp1(v, OP_Return, regReset); - - } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */ - else { - ExprList *pDel = 0; -#ifndef SQLITE_OMIT_BTREECOUNT - Table *pTab; - if( (pTab = isSimpleCount(p, &sAggInfo))!=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 */ - int iRoot = pTab->tnum; /* Root page of scanned b-tree */ - - sqlite3CodeVerifySchema(pParse, iDb); - sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); - - /* Search for the index that has the 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); - 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, iRoot, iDb, 1); - if( pKeyInfo ){ - sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO); - } - sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem); - sqlite3VdbeAddOp1(v, OP_Close, iCsr); - explainSimpleCount(pParse, pTab, pBest); - }else -#endif /* SQLITE_OMIT_BTREECOUNT */ - { - /* Check if the query is of one of the following forms: - ** - ** SELECT min(x) FROM ... - ** SELECT max(x) FROM ... - ** - ** If it is, then ask the code in where.c to attempt to sort results - ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. - ** If where.c is able to produce results sorted in this order, then - ** add vdbe code to break out of the processing loop after the - ** first iteration (since the first iteration of the loop is - ** guaranteed to operate on the row with the minimum or maximum - ** value of x, the only row required). - ** - ** A special flag must be passed to sqlite3WhereBegin() to slightly - ** modify behavior as follows: - ** - ** + If the query is a "SELECT min(x)", then the loop coded by - ** where.c should not iterate over any values with a NULL value - ** for x. - ** - ** + The optimizer code in where.c (the thing that decides which - ** index or indices to use) should place a different priority on - ** satisfying the 'ORDER BY' clause than it does in other cases. - ** Refer to code and comments in where.c for details. - */ - ExprList *pMinMax = 0; - u8 flag = WHERE_ORDERBY_NORMAL; - - assert( p->pGroupBy==0 ); - assert( flag==0 ); - if( p->pHaving==0 ){ - flag = minMaxQuery(&sAggInfo, &pMinMax); - } - assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) ); - - if( flag ){ - pMinMax = sqlite3ExprListDup(db, pMinMax, 0); - pDel = pMinMax; - assert( db->mallocFailed || pMinMax!=0 ); - if( !db->mallocFailed ){ - pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0; - pMinMax->a[0].pExpr->op = TK_COLUMN; - } - } - - /* This case runs if the aggregate has no GROUP BY clause. The - ** processing is much simpler since there is only a single row - ** of output. - */ - resetAccumulator(pParse, &sAggInfo); - pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax, 0,flag,0); - if( pWInfo==0 ){ - sqlite3ExprListDelete(db, pDel); - goto select_end; - } - updateAccumulator(pParse, &sAggInfo); - assert( pMinMax==0 || pMinMax->nExpr==1 ); - if( sqlite3WhereIsOrdered(pWInfo)>0 ){ - sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo)); - VdbeComment((v, "%s() by index", - (flag==WHERE_ORDERBY_MIN?"min":"max"))); - } - sqlite3WhereEnd(pWInfo); - finalizeAggFunctions(pParse, &sAggInfo); - } - - sSort.pOrderBy = 0; - sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); - selectInnerLoop(pParse, p, -1, 0, 0, - pDest, addrEnd, addrEnd); - sqlite3ExprListDelete(db, pDel); - } - 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"); - 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: - explainSetInteger(pParse->iSelectId, iRestoreSelectId); - - sqlite3DbFree(db, sAggInfo.aCol); - sqlite3DbFree(db, sAggInfo.aFunc); -#if SELECTTRACE_ENABLED - SELECTTRACE(1,pParse,p,("end processing\n")); - pParse->nSelectIndent--; -#endif - 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 = sqlite3_realloc64( 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 = sqlite3_realloc64( 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); - - 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 SQLITE_MASTER. - */ - 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 || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ - goto trigger_cleanup; - } - assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); - 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 - { - 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; - pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE); - pTrigger->pColumns = sqlite3IdListDup(db, pColumns); - 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; - } - - /* if we are not initializing, - ** build the sqlite_master entry - */ - if( !db->init.busy ){ - Vdbe *v; - char *z; - - /* Make an entry in the sqlite_master 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.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')", - db->aDb[iDb].zDbSName, MASTER_NAME, 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) ); - 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( !pParse->pNewTrigger ); - sqlite3DeleteTriggerStep(db, pStepList); -} - -/* -** 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, Select *pSelect){ - 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; - 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( - sqlite3 *db, /* Database connection */ - u8 op, /* Trigger opcode */ - Token *pName /* The target name */ -){ - 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; - } - 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( - sqlite3 *db, /* The database connection */ - 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.) */ -){ - TriggerStep *pTriggerStep; - - assert(pSelect != 0 || db->mallocFailed); - - pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName); - if( pTriggerStep ){ - pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE); - pTriggerStep->pIdList = pColumn; - pTriggerStep->orconf = orconf; - }else{ - sqlite3IdListDelete(db, pColumn); - } - 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( - sqlite3 *db, /* The database connection */ - Token *pTableName, /* Name of the table to be updated */ - 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) */ -){ - TriggerStep *pTriggerStep; - - pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName); - if( pTriggerStep ){ - pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE); - pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE); - pTriggerStep->orconf = orconf; - } - sqlite3ExprListDelete(db, pEList); - sqlite3ExprDelete(db, pWhere); - 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( - sqlite3 *db, /* Database connection */ - Token *pTableName, /* The table from which rows are deleted */ - Expr *pWhere /* The WHERE clause */ -){ - TriggerStep *pTriggerStep; - - pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName); - if( pTriggerStep ){ - 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 && sqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) 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 ); - assert( pTable->pSchema==pTrigger->pSchema || iDb==1 ); -#ifndef SQLITE_OMIT_AUTHORIZATION - { - 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. - */ - assert( pTable!=0 ); - if( (v = sqlite3GetVdbe(pParse))!=0 ){ - sqlite3NestedParse(pParse, - "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'", - db->aDb[iDb].zDbSName, MASTER_NAME, 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); - Trigger **pp; - for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext)); - *pp = (*pp)->pNext; - } - 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].zName)>=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. -*/ -static SrcList *targetSrcList( - Parse *pParse, /* The parsing context */ - TriggerStep *pStep /* The trigger containing the target token */ -){ - sqlite3 *db = pParse->db; - int iDb; /* Index of the database to use */ - SrcList *pSrc; /* SrcList to be returned */ - - pSrc = sqlite3SrcListAppend(db, 0, 0, 0); - if( pSrc ){ - assert( pSrc->nSrc>0 ); - pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget); - iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema); - if( iDb==0 || iDb>=2 ){ - const char *zDb; - assert( iDbnDb ); - zDb = db->aDb[iDb].zDbSName; - pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, zDb); - } - } - 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 ); - - switch( pStep->op ){ - case TK_UPDATE: { - sqlite3Update(pParse, - targetSrcList(pParse, pStep), - sqlite3ExprListDup(db, pStep->pExprList, 0), - sqlite3ExprDup(db, pStep->pWhere, 0), - pParse->eOrconf - ); - break; - } - case TK_INSERT: { - sqlite3Insert(pParse, - targetSrcList(pParse, pStep), - sqlite3SelectDup(db, pStep->pSelect, 0), - sqlite3IdListDup(db, pStep->pIdList), - pParse->eOrconf - ); - break; - } - case TK_DELETE: { - sqlite3DeleteFrom(pParse, - targetSrcList(pParse, pStep), - sqlite3ExprDup(db, pStep->pWhere, 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; - - 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 - 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(v); - 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 ){ - 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_master 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 parameter iReg is not negative, code an OP_RealAffinity instruction -** on register iReg. This is used when an equivalent integer value is -** stored in place of an 8-byte floating point value in order to save -** space. -*/ -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 ){ - sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg); - } -#endif -} - -/* -** Process an UPDATE statement. -** -** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL; -** \_______/ \________/ \______/ \________________/ -* onError pTabList pChanges pWhere -*/ -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 */ -){ - int i, j; /* Loop counters */ - Table *pTab; /* The table to be updated */ - int addrTop = 0; /* VDBE instruction address of the start of the loop */ - WhereInfo *pWInfo; /* 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 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; /* First register in array assigned to each index */ - 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 */ - 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 */ - - /* 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; - } - assert( pTabList->nSrc==1 ); - - /* 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( 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. - */ - pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++; - iIdxCur = iDataCur+1; - pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); - for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ - if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){ - iDataCur = pParse->nTab; - pTabList->a[0].iCursor = iDataCur; - } - pParse->nTab++; - } - - /* Allocate space for aXRef[], aRegIdx[], and aToOpen[]. - ** Initialize aXRef[] and aToOpen[] to their default values. - */ - aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 ); - if( aXRef==0 ) goto update_cleanup; - aRegIdx = aXRef+pTab->nCol; - aToOpen = (u8*)(aRegIdx+nIdx); - 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; - - /* 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( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){ - goto update_cleanup; - } - for(j=0; jnCol; j++){ - if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){ - if( j==pTab->iPKey ){ - chngRowid = 1; - pRowidExpr = pChanges->a[i].pExpr; - }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){ - chngPk = 1; - } - aXRef[j] = i; - break; - } - } - if( j>=pTab->nCol ){ - if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){ - j = -1; - chngRowid = 1; - pRowidExpr = pChanges->a[i].pExpr; - }else{ - sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName); - 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; - - /* 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. - ** - ** FIXME: Be smarter about omitting indexes that use expressions. - */ - for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ - int reg; - if( chngKey || hasFK>1 || pIdx->pPartIdxWhere || pIdx==pPk ){ - reg = ++pParse->nMem; - pParse->nMem += pIdx->nColumn; - }else{ - reg = 0; - for(i=0; inKeyCol; i++){ - i16 iIdxCol = pIdx->aiColumn[i]; - if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){ - reg = ++pParse->nMem; - pParse->nMem += pIdx->nColumn; - if( (onError==OE_Replace) - || (onError==OE_Default && pIdx->onError==OE_Replace) - ){ - bReplace = 1; - } - break; - } - } - } - if( reg==0 ) aToOpen[j+1] = 0; - aRegIdx[j] = reg; - } - 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); - } - - /* Begin generating code. */ - v = sqlite3GetVdbe(pParse); - if( v==0 ) goto update_cleanup; - if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); - sqlite3BeginWriteOperation(pParse, 1, iDb); - - /* Allocate required registers. */ - if( !IsVirtual(pTab) ){ - regRowSet = ++pParse->nMem; - 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( isView ){ - sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur); - } -#endif - - /* Resolve the column names in all the expressions in the - ** WHERE clause. - */ - if( 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 - - /* Initialize the count of updated rows */ - if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){ - regRowCount = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); - } - - if( HasRowid(pTab) ){ - sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid); - }else{ - assert( pPk!=0 ); - nPk = pPk->nKeyCol; - iPk = pParse->nMem+1; - pParse->nMem += nPk; - regKey = ++pParse->nMem; - iEph = pParse->nTab++; - - sqlite3VdbeAddOp2(v, OP_Null, 0, iPk); - addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk); - sqlite3VdbeSetP4KeyInfo(pParse, pPk); - } - - /* 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); - 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 ){ - 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 ){ - 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( eOnePass!=ONEPASS_MULTI ){ - sqlite3WhereEnd(pWInfo); - } - - labelBreak = sqlite3VdbeMakeLabel(v); - 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 ) sqlite3VdbeJumpHere(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); - VdbeCoverageNeverTaken(v); - } - if( eOnePass==ONEPASS_SINGLE ){ - labelContinue = labelBreak; - }else{ - labelContinue = sqlite3VdbeMakeLabel(v); - } - sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak); - VdbeCoverageIf(v, pPk==0); - VdbeCoverageIf(v, pPk!=0); - }else if( pPk ){ - labelContinue = sqlite3VdbeMakeLabel(v); - sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v); - addrTop = sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey); - sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0); - VdbeCoverage(v); - }else{ - labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak, - regOldRowid); - VdbeCoverage(v); - sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid); - VdbeCoverage(v); - } - - /* If the record number will change, set register regNewRowid to - ** contain the new value. If the record number is not being modified, - ** then regNewRowid is the same register as regOldRowid, which is - ** already populated. */ - assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid ); - if( chngRowid ){ - sqlite3ExprCode(pParse, pRowidExpr, 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++){ - if( oldmask==0xffffffff - || (i<32 && (oldmask & MASKBIT32(i))!=0) - || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 - ){ - testcase( oldmask!=0xffffffff && i==31 ); - sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i); - }else{ - sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i); - } - } - 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; inCol; i++){ - if( i==pTab->iPKey ){ - sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i); - }else{ - j = aXRef[i]; - if( j>=0 ){ - sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i); - }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 ); - sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i); - }else{ - sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i); - } - } - } - - /* 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); - - /* 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); - } - - /* If it did not delete it, the row-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. - */ - for(i=0; inCol; i++){ - if( aXRef[i]<0 && i!=pTab->iPKey ){ - sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i); - } - } - } - - if( !isView ){ - int addr1 = 0; /* Address of jump instruction */ - - /* Do constraint checks. */ - assert( regOldRowid>0 ); - sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur, - regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace, - aXRef); - - /* Do FK constraint checks. */ - if( hasFK ){ - sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey); - } - - /* Delete the index entries associated with the current record. */ - if( bReplace || chngKey ){ - if( pPk ){ - addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey); - }else{ - addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid); - } - VdbeCoverageNeverTaken(v); - } - sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1); - - /* 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( bReplace || chngKey ){ - sqlite3VdbeJumpHere(v, addr1); - } - - 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( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){ - 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 ){ - 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 ){ - sqlite3AutoincrementEnd(pParse); - } - - /* - ** Return the number of rows that were changed. If this routine is - ** generating code because of a call to sqlite3NestedParse(), do not - ** invoke the callback function. - */ - if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){ - 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); - 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; - 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 bOnePass; /* True to use onepass strategy */ - int addr; /* Address of OP_OpenEphemeral */ - - /* Allocate nArg registers to martial the arguments to 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; - 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++){ - if( aXRef[i]>=0 ){ - sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i); - }else{ - sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i); - } - } - 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); - } - - bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy); - - if( bOnePass ){ - /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded - ** above. Also, if this is a top-level parse (not a trigger), clear the - ** multi-write flag so that the VM does not open a statement journal */ - sqlite3VdbeChangeToNoop(v, addr); - if( sqlite3IsToplevel(pParse) ){ - pParse->isMultiWrite = 0; - } - }else{ - /* Create a record from the argument register contents and insert it into - ** the ephemeral table. */ - sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec); - sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid); - sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid); - } - - - if( bOnePass==0 ){ - /* End the virtual table scan */ - 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; idb, pNm); - if( iDb<0 ) iDb = 0; -#endif - } - if( iDb!=1 ){ - sqlite3VdbeAddOp1(v, OP_Vacuum, iDb); - sqlite3VdbeUsesBtree(v, iDb); - } - return; -} - -/* -** This routine implements the OP_Vacuum opcode of the VDBE. -*/ -SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){ - int rc = SQLITE_OK; /* Return code from service routines */ - Btree *pMain; /* The database being vacuumed */ - Btree *pTemp; /* The temporary database we vacuum into */ - u16 saved_mDbFlags; /* Saved value of db->mDbFlags */ - u32 saved_flags; /* Saved value of db->flags */ - int saved_nChange; /* Saved value of db->nChange */ - int saved_nTotalChange; /* Saved value of db->nTotalChange */ - 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 */ - - if( !db->autoCommit ){ - sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction"); - return SQLITE_ERROR; - } - if( db->nVdbeActive>1 ){ - sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress"); - return SQLITE_ERROR; - } - - /* 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 &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder | 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 = execSql(db, pzErrMsg, "ATTACH''AS vacuum_db"); - 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; - - /* The call to execSql() to attach the temp database has left the file - ** locked (as there was more than one active statement when the transaction - ** to read the schema was concluded. Unlock it here so that this doesn't - ** cause problems for the call to BtreeSetPageSize() below. */ - sqlite3BtreeCommit(pTemp); - - nRes = sqlite3BtreeGetOptimalReserve(pMain); - - /* A VACUUM cannot change the pagesize of an encrypted database. */ -#ifdef SQLITE_HAS_CODEC - if( db->nextPagesize ){ - extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*); - int nKey; - char *zKey; - sqlite3CodecGetKey(db, iDb, (void**)&zKey, &nKey); - if( nKey ) db->nextPagesize = 0; - } -#endif - - 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, 2); - 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_master" - " 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_master" - " WHERE type='index' AND length(sql)>10", - 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_master " - "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 SQLITE_MASTER table. - */ - rc = execSqlF(db, pzErrMsg, - "INSERT INTO vacuum_db.sqlite_master" - " SELECT*FROM \"%w\".sqlite_master" - " 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( 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, -1, 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. -*/ -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; - int nName = sqlite3Strlen30(zName); - pMod = (Module *)sqlite3Malloc(sizeof(Module) + nName + 1); - if( pMod==0 ){ - sqlite3OomFault(db); - }else{ - Module *pDel; - char *zCopy = (char *)(&pMod[1]); - memcpy(zCopy, zName, nName+1); - pMod->zName = zCopy; - pMod->pModule = pModule; - pMod->pAux = pAux; - pMod->xDestroy = xDestroy; - pMod->pEpoTab = 0; - pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod); - assert( pDel==0 || pDel==pMod ); - if( pDel ){ - sqlite3OomFault(db); - sqlite3DbFree(db, pDel); - pMod = 0; - } - } - 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); - if( sqlite3HashFind(&db->aModule, zName) ){ - rc = SQLITE_MISUSE_BKPT; - }else{ - (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); -} - -/* -** 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; - 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; - db->pDisconnect = 0; - - assert( sqlite3BtreeHoldsAllMutexes(db) ); - assert( sqlite3_mutex_held(db->mutex) ); - - if( p ){ - sqlite3ExpirePreparedStatements(db); - 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(sqlite3 *db, Table *pTable, char *zArg){ - int nBytes = sizeof(char *)*(2+pTable->nModuleArg); - char **azModuleArg; - 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 */ -){ - int iDb; /* The database the table is being created in */ - 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; - iDb = sqlite3SchemaToIndex(db, pTable->pSchema); - assert( iDb>=0 ); - - assert( pTable->nModuleArg==0 ); - addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName)); - addModuleArgument(db, pTable, 0); - addModuleArgument(db, 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_master table, has already been made by sqlite3StartTable(). - ** The second call, to obtain permission to create the table, is made now. - */ - if( pTable->azModuleArg ){ - 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(db, 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_master) then - ** do additional initialization work and store the statement text - ** in the sqlite_master table. - */ - if( !db->init.busy ){ - char *zStmt; - char *zWhere; - int iDb; - int iReg; - Vdbe *v; - - /* 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 - ** SQLITE_MASTER 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_master table tht was created for this vtab - ** by sqlite3StartTable(). - */ - iDb = sqlite3SchemaToIndex(db, pTab->pSchema); - sqlite3NestedParse(pParse, - "UPDATE %Q.%s " - "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q " - "WHERE rowid=#%d", - db->aDb[iDb].zDbSName, MASTER_NAME, - pTab->zName, - pTab->zName, - zStmt, - pParse->regRowid - ); - sqlite3DbFree(db, zStmt); - v = sqlite3GetVdbe(pParse); - sqlite3ChangeCookie(pParse, iDb); - - sqlite3VdbeAddOp0(v, OP_Expire); - zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName); - sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere); - - iReg = ++pParse->nMem; - sqlite3VdbeLoadString(v, iReg, pTab->zName); - sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg); - } - - /* If we are rereading the sqlite_master 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; - - 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; - 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; - u8 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; - int nBytes = sizeof(sqlite3_vtab *) * (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.declareVtab = 1; - 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.declareVtab = 0; - - 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; - assert( xDestroy!=0 ); /* Checked before the virtual table is created */ - 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); - } - } - - 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); - 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); - } - } - } - } - 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; - char *zLowerName; - unsigned char *z; - - - /* 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->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 - */ - zLowerName = sqlite3DbStrDup(db, pDef->zName); - if( zLowerName ){ - for(z=(unsigned char*)zLowerName; *z; z++){ - *z = sqlite3UpperToLower[*z]; - } - rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xSFunc, &pArg); - sqlite3DbFree(db, zLowerName); - } - 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 = sqlite3_realloc64(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(db, pTab, sqlite3DbStrDup(db, pTab->zName)); - addModuleArgument(db, pTab, 0); - addModuleArgument(db, 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; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT; -#endif - sqlite3_mutex_enter(db->mutex); - va_start(ap, op); - switch( op ){ - case SQLITE_VTAB_CONSTRAINT_SUPPORT: { - VtabCtx *p = db->pVtabCtx; - if( !p ){ - rc = SQLITE_MISUSE_BKPT; - }else{ - assert( p->pTab==0 || IsVirtual(p->pTab) ); - p->pVTable->bConstraint = (u8)va_arg(ap, int); - } - 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. -*/ - -/* -** Trace output macros -*/ -#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) -/***/ 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 */ -#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 ends 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 */ - 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 nIdxCol; /* Index column used for ORDER BY */ - 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 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */ -#define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */ -#define TERM_CODED 0x04 /* This term is already coded */ -#define TERM_COPIED 0x08 /* Has a child */ -#define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */ -#define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */ -#define TERM_OR_OK 0x40 /* Used during OR-clause processing */ -#ifdef SQLITE_ENABLE_STAT3_OR_STAT4 -# define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */ -#else -# define TERM_VNULL 0x00 /* Disabled if not using stat3 */ -#endif -#define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */ -#define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */ -#define TERM_LIKE 0x400 /* The original LIKE operator */ -#define TERM_IS 0x800 /* Term.pExpr is an IS operator */ -#define TERM_VARSELECT 0x1000 /* Term.pExpr contains a correlated sub-query */ - -/* -** 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 */ - 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_STAT3_OR_STAT4 - UnpackedRecord *pRec; /* Probe for stat4 (if required) */ - int nRecValid; /* Number of valid fields currently in pRec */ -#endif - unsigned int bldFlags; /* SQLITE_BLDF_* flags */ -}; - -/* Allowed values for WhereLoopBuider.bldFlags */ -#define SQLITE_BLDF_INDEXED 0x0001 /* An index is used */ -#define SQLITE_BLDF_UNIQUE 0x0002 /* All keys of a UNIQUE index used */ - -/* -** 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 */ - LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */ - 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() */ - u8 nLevel; /* Number of nested loop */ - i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */ - u8 sorted; /* True if really sorted (not just grouped) */ - u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */ - u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */ - u8 eDistinct; /* One of the WHERE_DISTINCT_* values */ - u8 bOrderedInnerLoop; /* True if only the inner-most loop is ordered */ - int iTop; /* The very beginning of the WHERE loop */ - WhereLoop *pLoops; /* List of all WhereLoop objects */ - Bitmask revMask; /* Mask of ORDER BY terms that need reversing */ - LogEst nRowOut; /* Estimated number of output rows */ - 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); -#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 */ - int iLevel, /* Value for "level" column of output */ - int iFrom, /* Value for "from" column of output */ - u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ -); -#else -# define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 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( - WhereInfo *pWInfo, /* Complete information about the WHERE clause */ - int iLevel, /* Which level of pWInfo->a[] should be coded */ - 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 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 ) sqlite3StrAccumAppend(pStr, " AND ", 5); - - if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1); - for(i=0; i1 ) sqlite3StrAccumAppend(pStr, ")", 1); - - sqlite3StrAccumAppend(pStr, zOp, 1); - - if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1); - for(i=0; i1 ) sqlite3StrAccumAppend(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; - sqlite3StrAccumAppend(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, "<"); - } - sqlite3StrAccumAppend(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 */ - int iLevel, /* Value for "level" column of output */ - int iFrom, /* Value for "from" column of output */ - u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ -){ - int ret = 0; -#if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS) - if( 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 iId = pParse->iSelectId; /* Select id (left-most output column) */ - 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); - sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN"); - if( pItem->pSelect ){ - sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId); - }else{ - sqlite3XPrintf(&str, " TABLE %s", pItem->zName); - } - - if( pItem->zAlias ){ - sqlite3XPrintf(&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 ){ - sqlite3StrAccumAppend(&str, " USING ", 7); - sqlite3XPrintf(&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 = "<"; - } - sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp); - } -#ifndef SQLITE_OMIT_VIRTUALTABLE - else if( (flags & WHERE_VIRTUALTABLE)!=0 ){ - sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s", - pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr); - } -#endif -#ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS - if( pLoop->nOut>=10 ){ - sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut)); - }else{ - sqlite3StrAccumAppend(&str, " (~1 row)", 9); - } -#endif - zMsg = sqlite3StrAccumFinish(&str); - ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, 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; - while( ALWAYS(pTerm!=0) - && (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]; - 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 entries (which are no-ops) at the -** beginning and end of zAff are ignored. If all entries in zAff are -** SQLITE_AFF_BLOB, 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 entries at the beginning - ** and end of the affinity string. - */ - while( n>0 && 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); - sqlite3ExprCacheAffinityChange(pParse, base, 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; ipExpr; - 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++){ - if( ALWAYS(pLoop->aLTerm[i]) && pLoop->aLTerm[i]->pExpr==pX ) nEq++; - } - - if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){ - eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0); - }else{ - Select *pSelect = pX->x.pSelect; - sqlite3 *db = pParse->db; - u16 savedDbOptFlags = db->dbOptFlags; - ExprList *pOrigRhs = pSelect->pEList; - ExprList *pOrigLhs = pX->pLeft->x.pList; - ExprList *pRhs = 0; /* New Select.pEList for RHS */ - ExprList *pLhs = 0; /* New pX->pLeft vector */ - - for(i=iEq;inLTerm; i++){ - if( pLoop->aLTerm[i]->pExpr==pX ){ - int iField = pLoop->aLTerm[i]->iField - 1; - Expr *pNewRhs = sqlite3ExprDup(db, pOrigRhs->a[iField].pExpr, 0); - Expr *pNewLhs = sqlite3ExprDup(db, pOrigLhs->a[iField].pExpr, 0); - - pRhs = sqlite3ExprListAppend(pParse, pRhs, pNewRhs); - pLhs = sqlite3ExprListAppend(pParse, pLhs, pNewLhs); - } - } - if( !db->mallocFailed ){ - Expr *pLeft = pX->pLeft; - - 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; - } - } - - /* 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. */ - if( pLhs->nExpr==1 ){ - pX->pLeft = pLhs->a[0].pExpr; - }else{ - pLeft->x.pList = pLhs; - aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int) * nEq); - testcase( aiMap==0 ); - } - pSelect->pEList = pRhs; - db->dbOptFlags |= SQLITE_QueryFlattener; - eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap); - db->dbOptFlags = savedDbOptFlags; - testcase( aiMap!=0 && aiMap[0]!=0 ); - pSelect->pEList = pOrigRhs; - pLeft->x.pList = pOrigLhs; - pX->pLeft = pLeft; - } - sqlite3ExprListDelete(pParse->db, pLhs); - sqlite3ExprListDelete(pParse->db, pRhs); - } - - if( eType==IN_INDEX_INDEX_DESC ){ - testcase( bRev ); - bRev = !bRev; - } - iTab = pX->iTable; - 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(v); - } - - 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 ){ - testcase( nEq>1 ); /* Happens with a UNIQUE index on 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_PrevIfOpen : OP_NextIfOpen; - }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 - && sqlite3ColumnOfIndex(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 ){ - Vdbe *v = pWalker->pParse->pVdbe; - int reg = ++pWalker->pParse->nMem; /* Register for column value */ - sqlite3ExprCodeGetColumnOfTable( - v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg - ); - pExpr->op = TK_REGISTER; - pExpr->iTable = reg; - }else if( pHint->pIdx!=0 ){ - pExpr->iTable = pHint->iIdxCur; - pExpr->iColumn = sqlite3ColumnOfIndex(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(db, 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 ); - - sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur); - if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE) - && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask) - ){ - int i; - Table *pTab = pIdx->pTable; - int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1)); - if( ai ){ - ai[0] = pTab->nCol; - for(i=0; inColumn-1; i++){ - assert( pIdx->aiColumn[i]nCol ); - if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+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 = sqlite3CodeSubselect(pParse, p, 0, 0); - 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 */ -} IdxExprTrans; - -/* 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 ){ - pExpr->op = TK_COLUMN; - pExpr->iTable = pX->iIdxCur; - pExpr->iColumn = pX->iIdxCol; - pExpr->pTab = 0; - return WRC_Prune; - }else{ - return WRC_Continue; - } -} - -/* -** 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. -*/ -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 */ - Walker w; - IdxExprTrans x; - aColExpr = pIdx->aColExpr; - if( aColExpr==0 ) return; /* Not an index on expressions */ - memset(&w, 0, sizeof(w)); - w.xExprCallback = whereIndexExprTransNode; - w.u.pIdxTrans = &x; - x.iTabCur = iTabCur; - x.iIdxCur = iIdxCur; - for(iIdxCol=0; iIdxColnExpr; iIdxCol++){ - if( pIdx->aiColumn[iIdxCol]!=XN_EXPR ) continue; - assert( aColExpr->a[iIdxCol].pExpr!=0 ); - x.iIdxCol = iIdxCol; - x.pIdxExpr = aColExpr->a[iIdxCol].pExpr; - sqlite3WalkExpr(&w, pWInfo->pWhere); - sqlite3WalkExprList(&w, pWInfo->pOrderBy); - sqlite3WalkExprList(&w, pWInfo->pResultSet); - } -} - -/* -** Generate code for the start of the iLevel-th loop in the WHERE clause -** implementation described by pWInfo. -*/ -SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart( - WhereInfo *pWInfo, /* Complete information about the WHERE clause */ - int iLevel, /* Which level of pWInfo->a[] should be coded */ - 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 omitTable; /* True if we use the index only */ - int bRev; /* True if we need to scan in reverse order */ - WhereLevel *pLevel; /* The where level to be coded */ - WhereLoop *pLoop; /* The WhereLoop object being coded */ - WhereClause *pWC; /* Decomposition of the entire WHERE clause */ - WhereTerm *pTerm; /* A WHERE clause term */ - Parse *pParse; /* Parsing context */ - sqlite3 *db; /* Database connection */ - Vdbe *v; /* The prepared stmt under constructions */ - 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 */ - - pParse = pWInfo->pParse; - v = pParse->pVdbe; - pWC = &pWInfo->sWC; - db = pParse->db; - pLevel = &pWInfo->a[iLevel]; - pLoop = pLevel->pWLoop; - pTabItem = &pWInfo->pTabList->a[pLevel->iFrom]; - iCur = pTabItem->iCursor; - pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); - bRev = (pWInfo->revMask>>iLevel)&1; - omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 - && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0; - VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName)); - - /* 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(v); - addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v); - - /* 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. - */ - 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 */ - - sqlite3ExprCachePush(pParse); - 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( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){ - disableTerm(pLevel, pTerm); - }else if( (pTerm->eOperator & WO_IN)!=0 ){ - 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 ); - 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, 0); - } - pCompare->pLeft = 0; - sqlite3ExprDelete(db, pCompare); - } - } - } - /* 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); - */ - sqlite3ExprCachePop(pParse); - }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 ); - assert( omitTable==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); - sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1); - sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); - VdbeComment((v, "pk")); - pLevel->op = OP_Noop; - }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; - - assert( omitTable==0 ); - 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); - op = aMoveOp[(pX->op - TK_GT) | 0x0001]; - }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); - sqlite3ExprCacheAffinityChange(pParse, r1, 1); - 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); - sqlite3ExprCacheStore(pParse, iCur, -1, 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 */ - - pIdx = pLoop->u.btree.pIndex; - iIdxCur = pLevel->iIdxCur; - assert( nEq>=pLoop->nSkip ); - - /* If this loop satisfies a sort order (pOrderBy) request that - ** was passed to this function to implement a "SELECT min(x) ..." - ** query, then the caller will only allow the loop to run for - ** a single iteration. This means that the first row returned - ** should not have a NULL value stored in 'x'. If column 'x' is - ** the first one after the nEq equality constraints in the index, - ** this requires some special handling. - */ - assert( pWInfo->pOrderBy==0 - || pWInfo->pOrderBy->nExpr==1 - || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 ); - if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0 - && pWInfo->nOBSat>0 - && (pIdx->nKeyCol>nEq) - ){ - assert( pLoop->nSkip==0 ); - bSeekPastNull = 1; - nExtraReg = 1; - } - - /* 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 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 = 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 ){ - sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); - nConstraint++; - startEq = 0; - start_constraints = 1; - } - 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{ - 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 ); - } - - /* Load the value for the inequality constraint at the end of the - ** range (if any). - */ - nConstraint = nEq; - if( pRangeEnd ){ - Expr *pRight = pRangeEnd->pExpr->pRight; - sqlite3ExprCacheRemove(pParse, regBase+nEq, 1); - 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 ){ - 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 ){ - 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 ); - } - - /* Seek the table cursor, if required */ - 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) - && (pWInfo->eOnePass==ONEPASS_SINGLE) - )){ - iRowidReg = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg); - sqlite3ExprCacheStore(pParse, iCur, -1, 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 = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]); - sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j); - } - sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont, - iRowidReg, pPk->nKeyCol); VdbeCoverage(v); - } - - /* 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. - */ - whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo); - - - /* 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(v); /* 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; - if( ExprHasProperty(pExpr, EP_FromJoin) ) 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(db, pAndExpr, pExpr); - } - if( pAndExpr ){ - pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 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); - 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 */ - if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){ - pAndExpr->pLeft = pOrExpr; - pOrExpr = pAndExpr; - } - /* Loop through table entries that match term pOrTerm. */ - 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], iLevel, pLevel->iFrom, 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 r; - int iSet = ((ii==pOrWc->nTerm-1)?-1:ii); - if( HasRowid(pTab) ){ - r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0); - jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, - r,iSet); - VdbeCoverage(v); - }else{ - Index *pPk = sqlite3PrimaryKeyIndex(pTab); - int nPk = pPk->nKeyCol; - int iPk; - - /* Read the PK into an array of temp registers. */ - r = sqlite3GetTempRange(pParse, nPk); - for(iPk=0; iPkaiColumn[iPk]; - sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, 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); - } - } - } - 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( pLevel->iLeftJoin && !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 ){ - /* 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; - assert( x>0 ); - skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If, (int)(x>>1)); - VdbeCoverage(v); -#endif - } -#ifdef WHERETRACE_ENABLED /* 0xffff */ - if( sqlite3WhereTrace ){ - VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d", - pWC->nTerm-j, pTerm, iLoop)); - } -#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( pLevel->iLeftJoin ) continue; - pE = pTerm->pExpr; - 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; - 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")); - sqlite3ExprCacheClear(pParse); - 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; - } - } - - 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 = sqlite3ExprSkipCollate(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". -** -** If left/right precedence rules come into play when determining the -** collating sequence, then COLLATE operators are adjusted to ensure -** that the collating sequence does not change. For example: -** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on -** the left hand side of a comparison overrides any collation sequence -** attached to the right. For the same reason the EP_Collate flag -** is not commuted. -*/ -static void exprCommute(Parse *pParse, Expr *pExpr){ - u16 expRight = (pExpr->pRight->flags & EP_Collate); - u16 expLeft = (pExpr->pLeft->flags & EP_Collate); - assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN ); - if( expRight==expLeft ){ - /* Either X and Y both have COLLATE operator or neither do */ - if( expRight ){ - /* Both X and Y have COLLATE operators. Make sure X is always - ** used by clearing the EP_Collate flag from Y. */ - pExpr->pRight->flags &= ~EP_Collate; - }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){ - /* Neither X nor Y have COLLATE operators, but X has a non-default - ** collating sequence. So add the EP_Collate marker on X to cause - ** it to be searched first. */ - pExpr->pLeft->flags |= EP_Collate; - } - } - 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; - } -} - -/* -** 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 */ - int c; /* One character in z[] */ - int cnt; /* Number of non-wildcard prefix characters */ - char 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, 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 ){ - - /* If the RHS begins with a digit or a minus sign, then the LHS must - ** be an ordinary column (not a virtual table column) with TEXT affinity. - ** Otherwise the LHS might be numeric and "lhs >= rhs" would be false - ** even though "lhs LIKE rhs" is true. But if the RHS does not start - ** with a digit or '-', then "lhs LIKE rhs" will always be false if - ** the LHS is numeric and so the optimization still works. - */ - if( sqlite3Isdigit(z[0]) || z[0]=='-' ){ - if( pLeft->op!=TK_COLUMN - || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT - || IsVirtual(pLeft->pTab) /* Value might be numeric */ - ){ - sqlite3ValueFree(pVal); - return 0; - } - } - - /* 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. The second condition is necessary so - ** that we can increment the prefix key to find an upper bound for the - ** range search. - */ - if( cnt!=0 && 255!=(u8)z[cnt-1] ){ - 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; iFrompVdbe; - 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( - 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; - } - pCol = pList->a[1].pExpr; - if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){ - return 0; - } - for(i=0; iu.zToken, aOp[i].zOp)==0 ){ - *peOp2 = aOp[i].eOp2; - *ppRight = pList->a[0].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; - if( pLeft->op==TK_COLUMN && IsVirtual(pLeft->pTab) ){ - res++; - } - if( pRight && pRight->op==TK_COLUMN && IsVirtual(pRight->pTab) ){ - 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; - pTerm->eOperator = indexable==0 ? 0 : 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++){ - 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; - 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 ){ - 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]; - markTermAsChild(pWC, idxNew, idxTerm); - }else{ - sqlite3ExprListDelete(db, pList); - } - pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */ - } - } -} -#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 = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight); - if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) 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); - } - } - 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; /* 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 = sqlite3WhereExprUsage(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; - } - 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" : "BINARY"; - 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, *pLeft; - int res = isAuxiliaryVtabOperator(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); - } - 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 - */ - if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0 - && pExpr->pLeft->op==TK_VECTOR - && pExpr->x.pSelect->pPrior==0 - ){ - 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_STAT3_OR_STAT4 - /* When sqlite_stat3 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 - && OptimizationEnabled(db, SQLITE_Stat34) - ){ - 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_STAT3_OR_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 = sqlite3ExprSkipCollate(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->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 sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){ - Bitmask mask; - if( p==0 ) return 0; - if( p->op==TK_COLUMN ){ - return sqlite3WhereGetMask(pMaskSet, p->iTable); - } - mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0; - assert( !ExprHasProperty(p, EP_TokenOnly) ); - if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft); - if( p->pRight ){ - mask |= sqlite3WhereExprUsage(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); - } - return mask; -} -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++){ - 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->pTab = pTab; - pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, - sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0)); - 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" */ - -/* 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 TRUE if the WHERE clause returns rows in ORDER BY order. -** Return FALSE if the output needs to be sorted. -*/ -SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){ - return pWInfo->nOBSat; -} - -/* -** Return TRUE if the innermost loop of the WHERE clause implementation -** returns rows in ORDER BY order for complete run of the inner loop. -** -** Across multiple iterations of outer loops, the output rows need not be -** sorted. As long as rows are sorted for just the innermost loop, this -** routine can return TRUE. -*/ -SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo *pWInfo){ - return pWInfo->bOrderedInnerLoop; -} - -/* -** 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 rowis 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; -} - -/* -** 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 = sqlite3ExprSkipCollate(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 = sqlite3BinaryCompareCollSeq(pParse, - pX->pLeft, pX->pRight); - 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; -} - -/* -** 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; - 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]; - }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->opMask = opMask; - pScan->k = 0; - pScan->aiCur[0] = iCur; - pScan->aiColumn[0] = iColumn; - pScan->nEquiv = 1; - pScan->iEquiv = 1; - 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 = sqlite3ExprSkipCollate(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 = sqlite3ExprSkipCollate(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 bIncrRowid parameter is 0, then any OP_Rowid instructions on -** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero, -** then each OP_Rowid is transformed into an instruction to increment the -** value stored in its output register. -*/ -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 bIncrRowid /* If non-zero, transform OP_rowid to OP_AddImm(1) */ -){ - 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( bIncrRowid ){ - /* Increment the value stored in the P2 operand of the OP_Rowid. */ - pOp->opcode = OP_AddImm; - pOp->p1 = pOp->p2; - pOp->p2 = 1; - }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 TRACE_IDX_INPUTS(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 TRACE_IDX_OUTPUTS(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 TRACE_IDX_INPUTS(A) -#define TRACE_IDX_OUTPUTS(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->db, 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 = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight); - 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 */ - sqlite3ExprCachePush(pParse); - 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(v); - 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 ); - translateColumnToCopy(pParse, addrTop, pLevel->iTabCur, - pTabItem->regResult, 1); - 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); - sqlite3ExprCachePop(pParse); - - /* 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, - WhereClause *pWC, - Bitmask mUnusable, /* Ignore terms with these prereqs */ - struct SrcList_item *pSrc, - ExprList *pOrderBy, - 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; - 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( i==n){ - nOrderBy = n; - } - } - - /* Allocate the sqlite3_index_info structure - */ - pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo) - + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm - + sizeof(*pIdxOrderBy)*nOrderBy ); - if( pIdxInfo==0 ){ - sqlite3ErrorMsg(pParse, "out of memory"); - return 0; - } - - /* Initialize the structure. The sqlite3_index_info structure contains - ** many fields that are declared "const" to prevent xBestIndex from - ** changing them. We have to do some funky casting in order to - ** initialize those fields. - */ - pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1]; - pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm]; - pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy]; - *(int*)&pIdxInfo->nConstraint = nTerm; - *(int*)&pIdxInfo->nOrderBy = nOrderBy; - *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons; - *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy; - *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage = - pUsage; - - 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; - 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) - ){ - if( i<16 ) mNoOmit |= (1 << i); - if( op==WO_LT ) pIdxCons[j].op = WO_LE; - if( op==WO_GT ) pIdxCons[j].op = WO_GE; - } - } - - j++; - } - for(i=0; ia[i].pExpr; - pIdxOrderBy[i].iColumn = pExpr->iColumn; - pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder; - } - - *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 a -** non-zero value is returned. Otherwise, 0 is returned and the output -** part of the sqlite3_index_info structure is left populated. -** -** 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; - - TRACE_IDX_INPUTS(p); - rc = pVtab->pModule->xBestIndex(pVtab, p); - TRACE_IDX_OUTPUTS(p); - - if( rc!=SQLITE_OK ){ - 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; - -#if 0 - /* This error is now caught by the caller. - ** Search for "xBestIndex malfunction" below */ - for(i=0; inConstraint; i++){ - if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){ - sqlite3ErrorMsg(pParse, - "table %s: xBestIndex returned an invalid plan", pTab->zName); - } - } -#endif - - return pParse->nErr; -} -#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */ - -#ifdef SQLITE_ENABLE_STAT3_OR_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_STAT3_OR_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_STAT3_OR_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; - } - return pIdx->zColAff[iCol]; -} -#endif - - -#ifdef SQLITE_ENABLE_STAT3_OR_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_STAT3_OR_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_STAT3_OR_STAT4 - Index *p = pLoop->u.btree.pIndex; - int nEq = pLoop->u.btree.nEq; - - if( p->nSample>0 && nEqnSampleCol ){ - 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 STAT3/4 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_STAT3_OR_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_stat3 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_STAT3_OR_STAT4 */ - -#ifdef SQLITE_ENABLE_STAT3_OR_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_STAT3_OR_STAT4 */ - - -#ifdef WHERETRACE_ENABLED -/* -** Print the content of a WhereTerm object -*/ -static void whereTermPrint(WhereTerm *pTerm, int iTerm){ - if( pTerm==0 ){ - sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm); - }else{ - char zType[4]; - char zLeft[50]; - memcpy(zType, "...", 4); - 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->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 prob=%-3d op=0x%03x wtFlags=0x%04x", - iTerm, pTerm, zType, zLeft, pTerm->truthProb, - pTerm->eOperator, pTerm->wtFlags); - if( pTerm->iField ){ - sqlite3DebugPrintf(" iField=%d\n", pTerm->iField); - }else{ - 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++){ - whereTermPrint(&pWC->a[i], i); - } -} -#endif - -#ifdef WHERETRACE_ENABLED -/* -** Print a WhereLoop object for debugging purposes -*/ -static void whereLoopPrint(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++){ - whereTermPrint(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){ - if( ALWAYS(pWInfo) ){ - int i; - 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); - } - 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; - - /* 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); - whereLoopPrint(pTemplate, pBuilder->pWC); - } -#endif - } - return SQLITE_OK; - } - - /* Look for an existing WhereLoop to replace with pTemplate - */ - whereLoopAdjustCost(pWInfo->pLoops, 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: "); - whereLoopPrint(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: "); - whereLoopPrint(p, pBuilder->pWC); - sqlite3DebugPrintf(" with: "); - }else{ - sqlite3DebugPrintf(" add: "); - } - whereLoopPrint(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: "); - whereLoopPrint(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->tnum==0 ){ - 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, k; - 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++){ - 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) ){ - Expr *pRight = pTerm->pExpr->pRight; - testcase( pTerm->pExpr->op==TK_IS ); - if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){ - k = 10; - }else{ - k = 20; - } - if( iReducenOut > 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->tnum==0, 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 addBtreeIdx(%s), nEq=%d\n", - pProbe->zName, pNew->u.btree.nEq)); - - 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_STAT3_OR_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; - - /* Do not allow IS constraints from the WHERE clause to be used by the - ** right table of a LEFT JOIN. Only constraints in the ON clause are - ** allowed */ - if( (pSrc->fg.jointype & JT_LEFT)!=0 - && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) - && (eOp & (WO_IS|WO_ISNULL))!=0 - ){ - testcase( eOp & WO_IS ); - testcase( eOp & WO_ISNULL ); - continue; - } - - if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){ - pBuilder->bldFlags |= SQLITE_BLDF_UNIQUE; - }else{ - pBuilder->bldFlags |= SQLITE_BLDF_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; - pNew->wsFlags |= WHERE_COLUMN_IN; - 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); - assert( nIn>0 ); /* RHS always has 2 or more terms... The parser - ** changes "x IN (?)" into "x=?". */ - } - }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>=0 && pProbe->uniqNotNull==0 ){ - pNew->wsFlags |= WHERE_UNQ_WANTED; - }else{ - pNew->wsFlags |= WHERE_ONEROW; - } - } - }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 stat3/stat4 data. Or, if there is no stat3/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_STAT3_OR_STAT4 - tRowcnt nOut = 0; - if( nInMul==0 - && pProbe->nSample - && pNew->u.btree.nEq<=pProbe->nSampleCol - && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect)) - ){ - 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( 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. */ - 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_STAT3_OR_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 - && pProbe->noSkipScan==0 - && 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 addBtreeIdx(%s), nEq=%d, rc=%d\n", - 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 = sqlite3ExprSkipCollate(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; -} - -/* -** Return a bitmask where 1s indicate that the corresponding column of -** the table is used by an index. Only the first 63 columns are considered. -*/ -static Bitmask columnsInIndex(Index *pIdx){ - Bitmask m = 0; - int j; - for(j=pIdx->nColumn-1; j>=0; j--){ - int x = pIdx->aiColumn[j]; - if( x>=0 ){ - testcase( x==BMS-1 ); - testcase( x==BMS-2 ); - if( xpWInfo->pParse; - while( pWhere->op==TK_AND ){ - if( !whereUsablePartialIndex(iTab,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 = pTerm->pExpr; - if( (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab) - && 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; - 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 1.375 (LogEst=4) 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 + 4; - if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){ - pNew->rSetup += 24; - } - 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 - */ - for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){ - if( pProbe->pPartIdxWhere!=0 - && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){ - testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */ - continue; /* Partial index inappropriate for this query */ - } - 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->tnum<=0 ){ - /* 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 & ~columnsInIndex(pProbe); - pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED; - } - - /* Full scan via index */ - if( b - || !HasRowid(pTab) - || pProbe->pPartIdxWhere!=0 - || ( 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->bldFlags = 0; - rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0); - if( pBuilder->bldFlags==SQLITE_BLDF_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_STAT3_OR_STAT4 - sqlite3Stat4ProbeFree(pBuilder->pRec); - pBuilder->nRecValid = 0; - pBuilder->pRec = 0; -#endif - - /* If there was an INDEXED BY clause, then only that one index is - ** considered. */ - if( pSrc->pIBIndex ) break; - } - 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 ) 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 - ){ - rc = SQLITE_ERROR; - sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName); - return rc; - } - 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( iTerm<16 && pUsage[i].omit ) pNew->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->u.vtab.omitMask &= ~mNoOmit; - - pNew->nLTerm = mxTerm+1; - 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; -} - - -/* -** 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(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), - ** 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 ){ - 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); - 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 || sCur.n==0 ); - 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; - u8 priorJointype = 0; - - /* Loop over the tables in the join, from left to right */ - pNew = pBuilder->pNew; - whereLoopInit(pNew); - for(iTab=0, pItem=pTabList->a; pItemiTab = iTab; - pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor); - if( ((pItem->fg.jointype|priorJointype) & (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; - } - priorJointype = pItem->fg.jointype; -#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 ){ - rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable); - } - mPrior |= pNew->maskSelf; - if( rc || db->mallocFailed ) 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 ) 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 ) obSat = obDone; - break; - }else{ - pLoop->u.btree.nIdxCol = 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 ); - 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 ){ - if( sqlite3ExprCollSeqMatch(pWInfo->pParse, - pOrderBy->a[i].pExpr, pTerm->pExpr)==0 ){ - 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); - } - - /* 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). - ** - ** 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 ){ - 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]; - 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; - } - pLoop->u.btree.nIdxCol = 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].sortOrder ) isMatch = 0; - }else{ - rev = revIdx ^ pOrderBy->a[i].sortOrder; - if( rev ) *pRevMask |= MASKBIT(iLoop); - revSet = 1; - } - } - 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<10 ){ - /* Do not use an automatic index if the this loop is expected - ** to run less than 2 times. */ - 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; - } - } - 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; - } - } - } - } - } - 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 & ~columnsInIndex(pIdx))==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; -} - -/* -** 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(v); - 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; - } - }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->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 ){ /* Display all terms of the WHERE clause */ - sqlite3WhereClausePrint(sWLB.pWC); - } -#endif - - if( nTabList!=1 || whereShortCut(&sWLB)==0 ){ - rc = whereLoopAddAll(&sWLB); - if( rc ) goto whereBeginError; - -#ifdef WHERETRACE_ENABLED - 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)]; - whereLoopPrint(p, sWLB.pWC); - } - } -#endif - - 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++){ - whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC); - } - } -#endif - /* Attempt to omit tables from the join that do not effect the result */ - if( pWInfo->nLevel>=2 - && pResultSet!=0 - && OptimizationEnabled(db, SQLITE_OmitNoopJoin) - ){ - Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet); - if( sWLB.pOrderBy ){ - tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy); - } - while( pWInfo->nLevel>=2 ){ - WhereTerm *pTerm, *pEnd; - pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop; - if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break; - if( (wctrlFlags & WHERE_WANT_DISTINCT)==0 - && (pLoop->wsFlags & WHERE_ONEROW)==0 - ){ - break; - } - if( (tabUsed & pLoop->maskSelf)!=0 ) break; - pEnd = sWLB.pWC->a + sWLB.pWC->nTerm; - for(pTerm=sWLB.pWC->a; pTermprereqAll & pLoop->maskSelf)!=0 - && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) - ){ - break; - } - } - if( pTerm drop loop %c not used\n", pLoop->cId)); - pWInfo->nLevel--; - nTabList--; - } - } - WHERETRACE(0xffff,("*** Optimizer Finished ***\n")); - 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. - */ - 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; - if( bOnerow - || ((wctrlFlags & WHERE_ONEPASS_MULTIROW)!=0 - && 0==(wsFlags & WHERE_VIRTUALTABLE)) - ){ - 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->nColcolUsed; - 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 - && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 - && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED - ){ - sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */ - } - 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. - */ - notReady = ~(Bitmask)0; - 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, ii, pLevel->iFrom, wctrlFlags - ); - pLevel->addrBody = sqlite3VdbeCurrentAddr(v); - notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, 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; -} - -/* -** 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")); - sqlite3ExprCacheClear(pParse); - 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 - && (pLoop->wsFlags & WHERE_INDEXED)!=0 - && (pIdx = pLoop->u.btree.pIndex)->hasStat1 - && (n = pLoop->u.btree.nIdxCol)>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); -#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 ){ - sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop); - VdbeCoverage(v); - VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen); - VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen); - } - 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 ){ - sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor); - } - 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; - } - - /* 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; - pOp = sqlite3VdbeGetOp(v, k); - for(; kp1!=pLevel->iTabCur ) continue; - if( pOp->opcode==OP_Column ){ - int x = pOp->p2; - assert( pIdx->pTable==pTab ); - if( !HasRowid(pTab) ){ - Index *pPk = sqlite3PrimaryKeyIndex(pTab); - x = pPk->aiColumn[x]; - assert( x>=0 ); - } - x = sqlite3ColumnOfIndex(pIdx, x); - if( x>=0 ){ - pOp->p2 = x; - pOp->p1 = pLevel->iIdxCur; - } - 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; - }else if( pOp->opcode==OP_IfNullRow ){ - pOp->p1 = pLevel->iIdxCur; - } - } - } - } - - /* Final cleanup - */ - pParse->nQueryLoop = pWInfo->savedNQueryLoop; - whereInfoFree(db, pWInfo); - return; -} - -/************** End of where.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 */ -/************ 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 this structure holds information about the -** LIMIT clause of a SELECT statement. -*/ -struct LimitVal { - Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */ - Expr *pOffset; /* The OFFSET expression. NULL if there is none */ -}; - -/* -** 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; }; - -/* -** Disable lookaside memory allocation for objects that might be -** shared across database connections. -*/ -static void disableLookaside(Parse *pParse){ - pParse->disableLookaside++; - pParse->db->lookaside.bDisable++; -} - - - /* - ** 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){ - 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"); - } - } - } - - /* This is a utility routine used to set the ExprSpan.zStart and - ** ExprSpan.zEnd values of pOut so that the span covers the complete - ** range of text beginning with pStart and going to the end of pEnd. - */ - static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){ - pOut->zStart = pStart->z; - pOut->zEnd = &pEnd->z[pEnd->n]; - } - - /* Construct a new Expr object from a single identifier. Use the - ** new Expr to populate pOut. Set the span of pOut to be the identifier - ** that created the expression. - */ - static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token t){ - Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1); - if( p ){ - memset(p, 0, sizeof(Expr)); - p->op = (u8)op; - p->flags = EP_Leaf; - p->iAgg = -1; - 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]) ){ - if( p->u.zToken[0]=='"' ) p->flags |= EP_DblQuoted; - sqlite3Dequote(p->u.zToken); - } -#if SQLITE_MAX_EXPR_DEPTH>0 - p->nHeight = 1; -#endif - } - pOut->pExpr = p; - pOut->zStart = t.z; - pOut->zEnd = &t.z[t.n]; - } - - /* This routine constructs a binary expression node out of two ExprSpan - ** objects and uses the result to populate a new ExprSpan object. - */ - static void spanBinaryExpr( - Parse *pParse, /* The parsing context. Errors accumulate here */ - int op, /* The binary operation */ - ExprSpan *pLeft, /* The left operand, and output */ - ExprSpan *pRight /* The right operand */ - ){ - pLeft->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr); - pLeft->zEnd = pRight->zEnd; - } - - /* If doNot is true, then add a TK_NOT Expr-node wrapper around the - ** outside of *ppExpr. - */ - static void exprNot(Parse *pParse, int doNot, ExprSpan *pSpan){ - if( doNot ){ - pSpan->pExpr = sqlite3PExpr(pParse, TK_NOT, pSpan->pExpr, 0); - } - } - - /* Construct an expression node for a unary postfix operator - */ - static void spanUnaryPostfix( - Parse *pParse, /* Parsing context to record errors */ - int op, /* The operator */ - ExprSpan *pOperand, /* The operand, and output */ - Token *pPostOp /* The operand token for setting the span */ - ){ - pOperand->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0); - pOperand->zEnd = &pPostOp->z[pPostOp->n]; - } - - /* 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 ){ - pA->op = (u8)op; - sqlite3ExprDelete(db, pA->pRight); - pA->pRight = 0; - } - } - - /* Construct an expression node for a unary prefix operator - */ - static void spanUnaryPrefix( - ExprSpan *pOut, /* Write the new expression node here */ - Parse *pParse, /* Parsing context to record errors */ - int op, /* The operator */ - ExprSpan *pOperand, /* The operand */ - Token *pPreOp /* The operand token for setting the span */ - ){ - pOut->zStart = pPreOp->z; - pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0); - pOut->zEnd = pOperand->zEnd; - } - - /* 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; - } -/**************** 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_STORE Code to store %extra_argument into yypParser -** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser -** 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 -** 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_MIN_REDUCE Minimum value for reduce actions -** YY_MAX_REDUCE Maximum value for 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 -*/ -#ifndef INTERFACE -# define INTERFACE 1 -#endif -/************* Begin control #defines *****************************************/ -#define YYCODETYPE unsigned char -#define YYNOCODE 252 -#define YYACTIONTYPE unsigned short int -#define YYWILDCARD 83 -#define sqlite3ParserTOKENTYPE Token -typedef union { - int yyinit; - sqlite3ParserTOKENTYPE yy0; - Expr* yy72; - TriggerStep* yy145; - ExprList* yy148; - SrcList* yy185; - ExprSpan yy190; - int yy194; - Select* yy243; - IdList* yy254; - With* yy285; - struct TrigEvent yy332; - struct LimitVal yy354; - struct {int value; int mask;} yy497; -} YYMINORTYPE; -#ifndef YYSTACKDEPTH -#define YYSTACKDEPTH 100 -#endif -#define sqlite3ParserARG_SDECL Parse *pParse; -#define sqlite3ParserARG_PDECL ,Parse *pParse -#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse -#define sqlite3ParserARG_STORE yypParser->pParse = pParse -#define YYFALLBACK 1 -#define YYNSTATE 455 -#define YYNRULE 329 -#define YY_MAX_SHIFT 454 -#define YY_MIN_SHIFTREDUCE 664 -#define YY_MAX_SHIFTREDUCE 992 -#define YY_MIN_REDUCE 993 -#define YY_MAX_REDUCE 1321 -#define YY_ERROR_ACTION 1322 -#define YY_ACCEPT_ACTION 1323 -#define YY_NO_ACTION 1324 -/************* End control #defines *******************************************/ - -/* 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 between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE -** and YY_MAX_REDUCE -** -** 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. -** -** 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: -** (1) The yy_shift_ofst[S]+X value is out of range, or -** (2) yy_lookahead[yy_shift_ofst[S]+X] is not equal to X, or -** (3) yy_shift_ofst[S] equal YY_SHIFT_USE_DFLT. -** (Implementation note: YY_SHIFT_USE_DFLT is chosen so that -** YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X. -** Hence only tests (1) and (2) need to be evaluated.) -** -** 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 and YY_REDUCE_USE_DFLT is used in place of -** YY_SHIFT_USE_DFLT. -** -** The following are the tables generated in this section: -** -** yy_action[] A single table containing all actions. -** yy_lookahead[] A table containing the lookahead for each entry in -** yy_action. Used to detect hash collisions. -** yy_shift_ofst[] For each state, the offset into yy_action for -** shifting terminals. -** yy_reduce_ofst[] For each state, the offset into yy_action for -** shifting non-terminals after a reduce. -** yy_default[] Default action for each state. -** -*********** Begin parsing tables **********************************************/ -#define YY_ACTTAB_COUNT (1566) -static const YYACTIONTYPE yy_action[] = { - /* 0 */ 324, 1323, 155, 155, 2, 203, 94, 94, 94, 93, - /* 10 */ 350, 98, 98, 98, 98, 91, 95, 95, 94, 94, - /* 20 */ 94, 93, 350, 268, 99, 100, 90, 971, 971, 847, - /* 30 */ 850, 839, 839, 97, 97, 98, 98, 98, 98, 350, - /* 40 */ 969, 96, 96, 96, 96, 95, 95, 94, 94, 94, - /* 50 */ 93, 350, 950, 96, 96, 96, 96, 95, 95, 94, - /* 60 */ 94, 94, 93, 350, 250, 96, 96, 96, 96, 95, - /* 70 */ 95, 94, 94, 94, 93, 350, 224, 224, 969, 132, - /* 80 */ 888, 348, 347, 415, 172, 324, 1286, 449, 414, 950, - /* 90 */ 951, 952, 808, 977, 1032, 950, 300, 786, 428, 132, - /* 100 */ 975, 362, 976, 9, 9, 787, 132, 52, 52, 99, - /* 110 */ 100, 90, 971, 971, 847, 850, 839, 839, 97, 97, - /* 120 */ 98, 98, 98, 98, 372, 978, 241, 978, 262, 369, - /* 130 */ 261, 120, 950, 951, 952, 194, 58, 324, 401, 398, - /* 140 */ 397, 808, 427, 429, 75, 808, 1260, 1260, 132, 396, - /* 150 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, - /* 160 */ 350, 99, 100, 90, 971, 971, 847, 850, 839, 839, - /* 170 */ 97, 97, 98, 98, 98, 98, 786, 262, 369, 261, - /* 180 */ 826, 262, 364, 251, 787, 1084, 101, 1114, 72, 324, - /* 190 */ 227, 1113, 242, 411, 442, 819, 92, 89, 178, 818, - /* 200 */ 1022, 268, 96, 96, 96, 96, 95, 95, 94, 94, - /* 210 */ 94, 93, 350, 99, 100, 90, 971, 971, 847, 850, - /* 220 */ 839, 839, 97, 97, 98, 98, 98, 98, 449, 372, - /* 230 */ 818, 818, 820, 92, 89, 178, 60, 92, 89, 178, - /* 240 */ 1025, 324, 357, 930, 1316, 300, 61, 1316, 52, 52, - /* 250 */ 836, 836, 848, 851, 96, 96, 96, 96, 95, 95, - /* 260 */ 94, 94, 94, 93, 350, 99, 100, 90, 971, 971, - /* 270 */ 847, 850, 839, 839, 97, 97, 98, 98, 98, 98, - /* 280 */ 92, 89, 178, 427, 412, 198, 930, 1317, 454, 995, - /* 290 */ 1317, 355, 1024, 324, 243, 231, 114, 277, 348, 347, - /* 300 */ 1242, 950, 416, 1071, 928, 840, 96, 96, 96, 96, - /* 310 */ 95, 95, 94, 94, 94, 93, 350, 99, 100, 90, - /* 320 */ 971, 971, 847, 850, 839, 839, 97, 97, 98, 98, - /* 330 */ 98, 98, 449, 328, 449, 120, 23, 256, 950, 951, - /* 340 */ 952, 968, 978, 438, 978, 324, 329, 928, 954, 701, - /* 350 */ 200, 175, 52, 52, 52, 52, 939, 353, 96, 96, - /* 360 */ 96, 96, 95, 95, 94, 94, 94, 93, 350, 99, - /* 370 */ 100, 90, 971, 971, 847, 850, 839, 839, 97, 97, - /* 380 */ 98, 98, 98, 98, 354, 449, 954, 427, 417, 427, - /* 390 */ 426, 1290, 92, 89, 178, 268, 253, 324, 255, 1058, - /* 400 */ 1037, 694, 93, 350, 383, 52, 52, 380, 1058, 374, - /* 410 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, - /* 420 */ 350, 99, 100, 90, 971, 971, 847, 850, 839, 839, - /* 430 */ 97, 97, 98, 98, 98, 98, 228, 449, 167, 449, - /* 440 */ 427, 407, 157, 446, 446, 446, 349, 349, 349, 324, - /* 450 */ 310, 316, 991, 827, 320, 242, 411, 51, 51, 36, - /* 460 */ 36, 254, 96, 96, 96, 96, 95, 95, 94, 94, - /* 470 */ 94, 93, 350, 99, 100, 90, 971, 971, 847, 850, - /* 480 */ 839, 839, 97, 97, 98, 98, 98, 98, 194, 316, - /* 490 */ 929, 401, 398, 397, 224, 224, 1265, 939, 353, 1318, - /* 500 */ 317, 324, 396, 1063, 1063, 813, 414, 1061, 1061, 950, - /* 510 */ 299, 448, 992, 268, 96, 96, 96, 96, 95, 95, - /* 520 */ 94, 94, 94, 93, 350, 99, 100, 90, 971, 971, - /* 530 */ 847, 850, 839, 839, 97, 97, 98, 98, 98, 98, - /* 540 */ 757, 1041, 449, 893, 893, 386, 950, 951, 952, 410, - /* 550 */ 992, 747, 747, 324, 229, 268, 221, 296, 268, 771, - /* 560 */ 890, 378, 52, 52, 890, 421, 96, 96, 96, 96, - /* 570 */ 95, 95, 94, 94, 94, 93, 350, 99, 100, 90, - /* 580 */ 971, 971, 847, 850, 839, 839, 97, 97, 98, 98, - /* 590 */ 98, 98, 103, 449, 275, 384, 1241, 343, 157, 1207, - /* 600 */ 909, 669, 670, 671, 176, 197, 196, 195, 324, 298, - /* 610 */ 319, 1266, 2, 37, 37, 910, 1134, 1040, 96, 96, - /* 620 */ 96, 96, 95, 95, 94, 94, 94, 93, 350, 697, - /* 630 */ 911, 177, 99, 100, 90, 971, 971, 847, 850, 839, - /* 640 */ 839, 97, 97, 98, 98, 98, 98, 230, 146, 120, - /* 650 */ 735, 1235, 826, 270, 1141, 273, 1141, 771, 171, 170, - /* 660 */ 736, 1141, 82, 324, 80, 268, 697, 819, 158, 268, - /* 670 */ 378, 818, 78, 96, 96, 96, 96, 95, 95, 94, - /* 680 */ 94, 94, 93, 350, 120, 950, 393, 99, 100, 90, - /* 690 */ 971, 971, 847, 850, 839, 839, 97, 97, 98, 98, - /* 700 */ 98, 98, 818, 818, 820, 1141, 1070, 370, 331, 133, - /* 710 */ 1066, 1141, 1250, 198, 268, 324, 1016, 330, 245, 333, - /* 720 */ 24, 334, 950, 951, 952, 368, 335, 81, 96, 96, - /* 730 */ 96, 96, 95, 95, 94, 94, 94, 93, 350, 99, - /* 740 */ 100, 90, 971, 971, 847, 850, 839, 839, 97, 97, - /* 750 */ 98, 98, 98, 98, 132, 267, 260, 445, 330, 223, - /* 760 */ 175, 1289, 925, 752, 724, 318, 1073, 324, 751, 246, - /* 770 */ 385, 301, 301, 378, 329, 361, 344, 414, 1233, 280, - /* 780 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93, - /* 790 */ 350, 99, 88, 90, 971, 971, 847, 850, 839, 839, - /* 800 */ 97, 97, 98, 98, 98, 98, 337, 346, 721, 722, - /* 810 */ 449, 120, 118, 887, 162, 887, 810, 371, 324, 202, - /* 820 */ 202, 373, 249, 263, 202, 394, 74, 704, 208, 1069, - /* 830 */ 12, 12, 96, 96, 96, 96, 95, 95, 94, 94, - /* 840 */ 94, 93, 350, 100, 90, 971, 971, 847, 850, 839, - /* 850 */ 839, 97, 97, 98, 98, 98, 98, 449, 771, 232, - /* 860 */ 449, 278, 120, 286, 74, 704, 714, 713, 324, 342, - /* 870 */ 749, 877, 1209, 77, 285, 1255, 780, 52, 52, 202, - /* 880 */ 27, 27, 418, 96, 96, 96, 96, 95, 95, 94, - /* 890 */ 94, 94, 93, 350, 90, 971, 971, 847, 850, 839, - /* 900 */ 839, 97, 97, 98, 98, 98, 98, 86, 444, 877, - /* 910 */ 3, 1193, 422, 1013, 873, 435, 886, 208, 886, 689, - /* 920 */ 1091, 257, 116, 822, 447, 1230, 117, 1229, 86, 444, - /* 930 */ 177, 3, 381, 96, 96, 96, 96, 95, 95, 94, - /* 940 */ 94, 94, 93, 350, 339, 447, 120, 351, 120, 212, - /* 950 */ 169, 287, 404, 282, 403, 199, 771, 950, 433, 419, - /* 960 */ 439, 822, 280, 691, 1039, 264, 269, 132, 351, 153, - /* 970 */ 826, 376, 74, 272, 274, 276, 83, 84, 1054, 433, - /* 980 */ 147, 1038, 443, 85, 351, 451, 450, 281, 132, 818, - /* 990 */ 25, 826, 449, 120, 950, 951, 952, 83, 84, 86, - /* 1000 */ 444, 691, 3, 408, 85, 351, 451, 450, 449, 5, - /* 1010 */ 818, 203, 32, 32, 1107, 120, 447, 950, 225, 1140, - /* 1020 */ 818, 818, 820, 821, 19, 203, 226, 950, 38, 38, - /* 1030 */ 1087, 314, 314, 313, 215, 311, 120, 449, 678, 351, - /* 1040 */ 237, 818, 818, 820, 821, 19, 969, 409, 377, 1, - /* 1050 */ 433, 180, 706, 248, 950, 951, 952, 10, 10, 449, - /* 1060 */ 969, 247, 826, 1098, 950, 951, 952, 430, 83, 84, - /* 1070 */ 756, 336, 950, 20, 431, 85, 351, 451, 450, 10, - /* 1080 */ 10, 818, 86, 444, 969, 3, 950, 449, 302, 303, - /* 1090 */ 182, 950, 1146, 338, 1021, 1015, 1004, 183, 969, 447, - /* 1100 */ 132, 181, 76, 444, 21, 3, 449, 10, 10, 950, - /* 1110 */ 951, 952, 818, 818, 820, 821, 19, 715, 1279, 447, - /* 1120 */ 389, 233, 351, 950, 951, 952, 10, 10, 950, 951, - /* 1130 */ 952, 1003, 218, 433, 1005, 325, 1273, 773, 289, 291, - /* 1140 */ 424, 293, 351, 7, 159, 826, 363, 402, 315, 360, - /* 1150 */ 1129, 83, 84, 433, 1232, 716, 772, 259, 85, 351, - /* 1160 */ 451, 450, 358, 375, 818, 826, 360, 359, 399, 1211, - /* 1170 */ 157, 83, 84, 681, 98, 98, 98, 98, 85, 351, - /* 1180 */ 451, 450, 323, 252, 818, 295, 1211, 1213, 1235, 173, - /* 1190 */ 1037, 284, 434, 340, 1204, 818, 818, 820, 821, 19, - /* 1200 */ 308, 234, 449, 234, 96, 96, 96, 96, 95, 95, - /* 1210 */ 94, 94, 94, 93, 350, 818, 818, 820, 821, 19, - /* 1220 */ 909, 120, 39, 39, 1203, 449, 168, 360, 449, 1276, - /* 1230 */ 367, 449, 135, 449, 986, 910, 449, 1249, 449, 1247, - /* 1240 */ 449, 205, 983, 449, 370, 40, 40, 1211, 41, 41, - /* 1250 */ 911, 42, 42, 28, 28, 870, 29, 29, 31, 31, - /* 1260 */ 43, 43, 379, 44, 44, 449, 59, 449, 332, 449, - /* 1270 */ 432, 62, 144, 156, 449, 130, 449, 72, 449, 137, - /* 1280 */ 449, 365, 449, 392, 139, 45, 45, 11, 11, 46, - /* 1290 */ 46, 140, 1200, 449, 105, 105, 47, 47, 48, 48, - /* 1300 */ 33, 33, 49, 49, 1126, 449, 141, 366, 449, 185, - /* 1310 */ 142, 449, 1234, 50, 50, 449, 160, 449, 148, 449, - /* 1320 */ 1136, 382, 449, 67, 449, 34, 34, 449, 122, 122, - /* 1330 */ 449, 123, 123, 449, 1198, 124, 124, 56, 56, 35, - /* 1340 */ 35, 449, 106, 106, 53, 53, 449, 107, 107, 449, - /* 1350 */ 108, 108, 449, 104, 104, 449, 406, 449, 388, 449, - /* 1360 */ 189, 121, 121, 449, 190, 449, 119, 119, 449, 112, - /* 1370 */ 112, 449, 111, 111, 1218, 109, 109, 110, 110, 55, - /* 1380 */ 55, 266, 752, 57, 57, 54, 54, 751, 26, 26, - /* 1390 */ 1099, 30, 30, 219, 154, 390, 271, 191, 321, 1006, - /* 1400 */ 192, 405, 1057, 1056, 1055, 341, 1048, 706, 1047, 1029, - /* 1410 */ 322, 420, 1028, 71, 1095, 283, 288, 1027, 1288, 204, - /* 1420 */ 6, 297, 79, 1184, 437, 1096, 1094, 290, 345, 292, - /* 1430 */ 441, 1093, 294, 102, 425, 73, 423, 213, 1012, 22, - /* 1440 */ 452, 945, 214, 1077, 216, 217, 238, 453, 306, 304, - /* 1450 */ 307, 239, 240, 1001, 305, 125, 996, 126, 115, 235, - /* 1460 */ 127, 665, 352, 166, 244, 179, 356, 113, 885, 883, - /* 1470 */ 806, 136, 128, 738, 326, 138, 327, 258, 184, 899, - /* 1480 */ 143, 129, 145, 63, 64, 65, 66, 902, 186, 187, - /* 1490 */ 898, 8, 13, 188, 134, 265, 891, 202, 980, 387, - /* 1500 */ 150, 149, 680, 161, 391, 193, 285, 279, 395, 151, - /* 1510 */ 68, 717, 14, 15, 400, 69, 16, 131, 236, 825, - /* 1520 */ 824, 853, 746, 750, 4, 70, 174, 413, 220, 222, - /* 1530 */ 152, 779, 774, 77, 868, 74, 854, 201, 17, 852, - /* 1540 */ 908, 206, 907, 207, 18, 857, 934, 163, 436, 210, - /* 1550 */ 935, 164, 209, 165, 440, 856, 823, 312, 690, 87, - /* 1560 */ 211, 309, 1281, 940, 995, 1280, -}; -static const YYCODETYPE yy_lookahead[] = { - /* 0 */ 19, 144, 145, 146, 147, 24, 90, 91, 92, 93, - /* 10 */ 94, 54, 55, 56, 57, 58, 88, 89, 90, 91, - /* 20 */ 92, 93, 94, 152, 43, 44, 45, 46, 47, 48, - /* 30 */ 49, 50, 51, 52, 53, 54, 55, 56, 57, 94, - /* 40 */ 59, 84, 85, 86, 87, 88, 89, 90, 91, 92, - /* 50 */ 93, 94, 59, 84, 85, 86, 87, 88, 89, 90, - /* 60 */ 91, 92, 93, 94, 193, 84, 85, 86, 87, 88, - /* 70 */ 89, 90, 91, 92, 93, 94, 194, 195, 97, 79, - /* 80 */ 11, 88, 89, 152, 26, 19, 171, 152, 206, 96, - /* 90 */ 97, 98, 72, 100, 179, 59, 152, 31, 163, 79, - /* 100 */ 107, 219, 109, 172, 173, 39, 79, 172, 173, 43, - /* 110 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, - /* 120 */ 54, 55, 56, 57, 152, 132, 199, 134, 108, 109, - /* 130 */ 110, 196, 96, 97, 98, 99, 209, 19, 102, 103, - /* 140 */ 104, 72, 207, 208, 26, 72, 119, 120, 79, 113, - /* 150 */ 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, - /* 160 */ 94, 43, 44, 45, 46, 47, 48, 49, 50, 51, - /* 170 */ 52, 53, 54, 55, 56, 57, 31, 108, 109, 110, - /* 180 */ 82, 108, 109, 110, 39, 210, 68, 175, 130, 19, - /* 190 */ 218, 175, 119, 120, 250, 97, 221, 222, 223, 101, - /* 200 */ 172, 152, 84, 85, 86, 87, 88, 89, 90, 91, - /* 210 */ 92, 93, 94, 43, 44, 45, 46, 47, 48, 49, - /* 220 */ 50, 51, 52, 53, 54, 55, 56, 57, 152, 152, - /* 230 */ 132, 133, 134, 221, 222, 223, 66, 221, 222, 223, - /* 240 */ 172, 19, 193, 22, 23, 152, 24, 26, 172, 173, - /* 250 */ 46, 47, 48, 49, 84, 85, 86, 87, 88, 89, - /* 260 */ 90, 91, 92, 93, 94, 43, 44, 45, 46, 47, - /* 270 */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, - /* 280 */ 221, 222, 223, 207, 208, 46, 22, 23, 148, 149, - /* 290 */ 26, 242, 172, 19, 154, 218, 156, 23, 88, 89, - /* 300 */ 241, 59, 163, 163, 83, 101, 84, 85, 86, 87, - /* 310 */ 88, 89, 90, 91, 92, 93, 94, 43, 44, 45, - /* 320 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, - /* 330 */ 56, 57, 152, 157, 152, 196, 196, 16, 96, 97, - /* 340 */ 98, 26, 132, 250, 134, 19, 107, 83, 59, 23, - /* 350 */ 211, 212, 172, 173, 172, 173, 1, 2, 84, 85, - /* 360 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 43, - /* 370 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, - /* 380 */ 54, 55, 56, 57, 244, 152, 97, 207, 208, 207, - /* 390 */ 208, 185, 221, 222, 223, 152, 75, 19, 77, 179, - /* 400 */ 180, 23, 93, 94, 228, 172, 173, 231, 188, 152, - /* 410 */ 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, - /* 420 */ 94, 43, 44, 45, 46, 47, 48, 49, 50, 51, - /* 430 */ 52, 53, 54, 55, 56, 57, 193, 152, 123, 152, - /* 440 */ 207, 208, 152, 168, 169, 170, 168, 169, 170, 19, - /* 450 */ 160, 22, 23, 23, 164, 119, 120, 172, 173, 172, - /* 460 */ 173, 140, 84, 85, 86, 87, 88, 89, 90, 91, - /* 470 */ 92, 93, 94, 43, 44, 45, 46, 47, 48, 49, - /* 480 */ 50, 51, 52, 53, 54, 55, 56, 57, 99, 22, - /* 490 */ 23, 102, 103, 104, 194, 195, 0, 1, 2, 247, - /* 500 */ 248, 19, 113, 190, 191, 23, 206, 190, 191, 59, - /* 510 */ 225, 152, 83, 152, 84, 85, 86, 87, 88, 89, - /* 520 */ 90, 91, 92, 93, 94, 43, 44, 45, 46, 47, - /* 530 */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, - /* 540 */ 90, 181, 152, 108, 109, 110, 96, 97, 98, 115, - /* 550 */ 83, 117, 118, 19, 193, 152, 23, 152, 152, 26, - /* 560 */ 29, 152, 172, 173, 33, 152, 84, 85, 86, 87, - /* 570 */ 88, 89, 90, 91, 92, 93, 94, 43, 44, 45, - /* 580 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, - /* 590 */ 56, 57, 22, 152, 16, 64, 193, 207, 152, 193, - /* 600 */ 12, 7, 8, 9, 152, 108, 109, 110, 19, 152, - /* 610 */ 164, 146, 147, 172, 173, 27, 163, 181, 84, 85, - /* 620 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 59, - /* 630 */ 42, 98, 43, 44, 45, 46, 47, 48, 49, 50, - /* 640 */ 51, 52, 53, 54, 55, 56, 57, 238, 22, 196, - /* 650 */ 62, 163, 82, 75, 152, 77, 152, 124, 88, 89, - /* 660 */ 72, 152, 137, 19, 139, 152, 96, 97, 24, 152, - /* 670 */ 152, 101, 138, 84, 85, 86, 87, 88, 89, 90, - /* 680 */ 91, 92, 93, 94, 196, 59, 19, 43, 44, 45, - /* 690 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, - /* 700 */ 56, 57, 132, 133, 134, 152, 193, 219, 245, 246, - /* 710 */ 193, 152, 152, 46, 152, 19, 166, 167, 152, 217, - /* 720 */ 232, 217, 96, 97, 98, 237, 217, 138, 84, 85, - /* 730 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 43, - /* 740 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, - /* 750 */ 54, 55, 56, 57, 79, 193, 238, 166, 167, 211, - /* 760 */ 212, 23, 23, 116, 26, 26, 195, 19, 121, 152, - /* 770 */ 217, 152, 152, 152, 107, 100, 217, 206, 163, 112, - /* 780 */ 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, - /* 790 */ 94, 43, 44, 45, 46, 47, 48, 49, 50, 51, - /* 800 */ 52, 53, 54, 55, 56, 57, 187, 187, 7, 8, - /* 810 */ 152, 196, 22, 132, 24, 134, 23, 23, 19, 26, - /* 820 */ 26, 23, 152, 23, 26, 23, 26, 59, 26, 163, - /* 830 */ 172, 173, 84, 85, 86, 87, 88, 89, 90, 91, - /* 840 */ 92, 93, 94, 44, 45, 46, 47, 48, 49, 50, - /* 850 */ 51, 52, 53, 54, 55, 56, 57, 152, 26, 238, - /* 860 */ 152, 23, 196, 101, 26, 97, 100, 101, 19, 19, - /* 870 */ 23, 59, 152, 26, 112, 152, 23, 172, 173, 26, - /* 880 */ 172, 173, 19, 84, 85, 86, 87, 88, 89, 90, - /* 890 */ 91, 92, 93, 94, 45, 46, 47, 48, 49, 50, - /* 900 */ 51, 52, 53, 54, 55, 56, 57, 19, 20, 97, - /* 910 */ 22, 23, 207, 163, 23, 163, 132, 26, 134, 23, - /* 920 */ 213, 152, 26, 59, 36, 152, 22, 152, 19, 20, - /* 930 */ 98, 22, 152, 84, 85, 86, 87, 88, 89, 90, - /* 940 */ 91, 92, 93, 94, 94, 36, 196, 59, 196, 99, - /* 950 */ 100, 101, 102, 103, 104, 105, 124, 59, 70, 96, - /* 960 */ 163, 97, 112, 59, 181, 152, 152, 79, 59, 71, - /* 970 */ 82, 19, 26, 152, 152, 152, 88, 89, 152, 70, - /* 980 */ 22, 152, 163, 95, 96, 97, 98, 152, 79, 101, - /* 990 */ 22, 82, 152, 196, 96, 97, 98, 88, 89, 19, - /* 1000 */ 20, 97, 22, 163, 95, 96, 97, 98, 152, 22, - /* 1010 */ 101, 24, 172, 173, 152, 196, 36, 59, 22, 152, - /* 1020 */ 132, 133, 134, 135, 136, 24, 5, 59, 172, 173, - /* 1030 */ 152, 10, 11, 12, 13, 14, 196, 152, 17, 59, - /* 1040 */ 210, 132, 133, 134, 135, 136, 59, 207, 96, 22, - /* 1050 */ 70, 30, 106, 32, 96, 97, 98, 172, 173, 152, - /* 1060 */ 59, 40, 82, 152, 96, 97, 98, 152, 88, 89, - /* 1070 */ 90, 186, 59, 22, 191, 95, 96, 97, 98, 172, - /* 1080 */ 173, 101, 19, 20, 97, 22, 59, 152, 152, 152, - /* 1090 */ 69, 59, 152, 186, 152, 152, 152, 76, 97, 36, - /* 1100 */ 79, 80, 19, 20, 53, 22, 152, 172, 173, 96, - /* 1110 */ 97, 98, 132, 133, 134, 135, 136, 35, 122, 36, - /* 1120 */ 234, 186, 59, 96, 97, 98, 172, 173, 96, 97, - /* 1130 */ 98, 152, 233, 70, 152, 114, 152, 124, 210, 210, - /* 1140 */ 186, 210, 59, 198, 197, 82, 214, 65, 150, 152, - /* 1150 */ 201, 88, 89, 70, 201, 73, 124, 239, 95, 96, - /* 1160 */ 97, 98, 141, 239, 101, 82, 169, 170, 176, 152, - /* 1170 */ 152, 88, 89, 21, 54, 55, 56, 57, 95, 96, - /* 1180 */ 97, 98, 164, 214, 101, 214, 169, 170, 163, 184, - /* 1190 */ 180, 175, 227, 111, 175, 132, 133, 134, 135, 136, - /* 1200 */ 200, 183, 152, 185, 84, 85, 86, 87, 88, 89, - /* 1210 */ 90, 91, 92, 93, 94, 132, 133, 134, 135, 136, - /* 1220 */ 12, 196, 172, 173, 175, 152, 198, 230, 152, 155, - /* 1230 */ 78, 152, 243, 152, 60, 27, 152, 159, 152, 159, - /* 1240 */ 152, 122, 38, 152, 219, 172, 173, 230, 172, 173, - /* 1250 */ 42, 172, 173, 172, 173, 103, 172, 173, 172, 173, - /* 1260 */ 172, 173, 237, 172, 173, 152, 240, 152, 159, 152, - /* 1270 */ 62, 240, 22, 220, 152, 43, 152, 130, 152, 189, - /* 1280 */ 152, 18, 152, 18, 192, 172, 173, 172, 173, 172, - /* 1290 */ 173, 192, 140, 152, 172, 173, 172, 173, 172, 173, - /* 1300 */ 172, 173, 172, 173, 201, 152, 192, 159, 152, 158, - /* 1310 */ 192, 152, 201, 172, 173, 152, 220, 152, 189, 152, - /* 1320 */ 189, 159, 152, 137, 152, 172, 173, 152, 172, 173, - /* 1330 */ 152, 172, 173, 152, 201, 172, 173, 172, 173, 172, - /* 1340 */ 173, 152, 172, 173, 172, 173, 152, 172, 173, 152, - /* 1350 */ 172, 173, 152, 172, 173, 152, 90, 152, 61, 152, - /* 1360 */ 158, 172, 173, 152, 158, 152, 172, 173, 152, 172, - /* 1370 */ 173, 152, 172, 173, 236, 172, 173, 172, 173, 172, - /* 1380 */ 173, 235, 116, 172, 173, 172, 173, 121, 172, 173, - /* 1390 */ 159, 172, 173, 159, 22, 177, 159, 158, 177, 159, - /* 1400 */ 158, 107, 174, 174, 174, 63, 182, 106, 182, 174, - /* 1410 */ 177, 125, 176, 107, 216, 174, 215, 174, 174, 159, - /* 1420 */ 22, 159, 137, 224, 177, 216, 216, 215, 94, 215, - /* 1430 */ 177, 216, 215, 129, 126, 128, 127, 25, 162, 26, - /* 1440 */ 161, 13, 153, 205, 153, 6, 226, 151, 202, 204, - /* 1450 */ 201, 229, 229, 151, 203, 165, 151, 165, 178, 178, - /* 1460 */ 165, 4, 3, 22, 142, 15, 81, 16, 23, 23, - /* 1470 */ 120, 131, 111, 20, 249, 123, 249, 16, 125, 1, - /* 1480 */ 123, 111, 131, 53, 53, 53, 53, 96, 34, 122, - /* 1490 */ 1, 5, 22, 107, 246, 140, 67, 26, 74, 41, - /* 1500 */ 107, 67, 20, 24, 19, 105, 112, 23, 66, 22, - /* 1510 */ 22, 28, 22, 22, 66, 22, 22, 37, 66, 23, - /* 1520 */ 23, 23, 116, 23, 22, 26, 122, 26, 23, 23, - /* 1530 */ 22, 96, 124, 26, 23, 26, 23, 34, 34, 23, - /* 1540 */ 23, 26, 23, 22, 34, 11, 23, 22, 24, 122, - /* 1550 */ 23, 22, 26, 22, 24, 23, 23, 15, 23, 22, - /* 1560 */ 122, 23, 122, 1, 251, 122, -}; -#define YY_SHIFT_USE_DFLT (1566) -#define YY_SHIFT_COUNT (454) -#define YY_SHIFT_MIN (-84) -#define YY_SHIFT_MAX (1562) -static const short yy_shift_ofst[] = { - /* 0 */ 355, 888, 1021, 909, 1063, 1063, 1063, 1063, 20, -19, - /* 10 */ 66, 66, 170, 1063, 1063, 1063, 1063, 1063, 1063, 1063, - /* 20 */ -7, -7, 36, 73, 69, 27, 118, 222, 274, 326, - /* 30 */ 378, 430, 482, 534, 589, 644, 696, 696, 696, 696, - /* 40 */ 696, 696, 696, 696, 696, 696, 696, 696, 696, 696, - /* 50 */ 696, 696, 696, 748, 696, 799, 849, 849, 980, 1063, - /* 60 */ 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, - /* 70 */ 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, - /* 80 */ 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, - /* 90 */ 1083, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, 1063, - /* 100 */ 1063, 1063, 1063, 1063, -43, 1120, 1120, 1120, 1120, 1120, - /* 110 */ -31, -72, -84, 242, 1152, 667, 210, 210, 242, 309, - /* 120 */ 336, -55, 1566, 1566, 1566, 850, 850, 850, 626, 626, - /* 130 */ 588, 588, 898, 221, 264, 242, 242, 242, 242, 242, - /* 140 */ 242, 242, 242, 242, 242, 242, 242, 242, 242, 242, - /* 150 */ 242, 242, 242, 242, 242, 496, 675, 289, 289, 336, - /* 160 */ 0, 0, 0, 0, 0, 0, 1566, 1566, 1566, 570, - /* 170 */ 98, 98, 958, 389, 450, 968, 1013, 1032, 1027, 242, - /* 180 */ 242, 242, 242, 242, 242, 242, 242, 242, 242, 242, - /* 190 */ 242, 242, 242, 242, 242, 1082, 1082, 1082, 242, 242, - /* 200 */ 533, 242, 242, 242, 987, 242, 242, 1208, 242, 242, - /* 210 */ 242, 242, 242, 242, 242, 242, 242, 242, 435, 531, - /* 220 */ 1001, 1001, 1001, 832, 434, 1266, 594, 58, 863, 863, - /* 230 */ 952, 58, 952, 946, 738, 239, 145, 863, 525, 145, - /* 240 */ 145, 315, 647, 790, 1174, 1119, 1119, 1204, 1204, 1119, - /* 250 */ 1250, 1232, 1147, 1263, 1263, 1263, 1263, 1119, 1265, 1147, - /* 260 */ 1250, 1232, 1232, 1147, 1119, 1265, 1186, 1297, 1119, 1119, - /* 270 */ 1265, 1372, 1119, 1265, 1119, 1265, 1372, 1294, 1294, 1294, - /* 280 */ 1342, 1372, 1294, 1301, 1294, 1342, 1294, 1294, 1286, 1306, - /* 290 */ 1286, 1306, 1286, 1306, 1286, 1306, 1119, 1398, 1119, 1285, - /* 300 */ 1372, 1334, 1334, 1372, 1304, 1308, 1307, 1309, 1147, 1412, - /* 310 */ 1413, 1428, 1428, 1439, 1439, 1439, 1566, 1566, 1566, 1566, - /* 320 */ 1566, 1566, 1566, 1566, 204, 321, 429, 467, 578, 497, - /* 330 */ 904, 739, 1051, 793, 794, 798, 800, 802, 838, 768, - /* 340 */ 766, 801, 762, 847, 853, 812, 891, 681, 784, 896, - /* 350 */ 864, 996, 1457, 1459, 1441, 1322, 1450, 1385, 1451, 1445, - /* 360 */ 1446, 1350, 1340, 1361, 1352, 1453, 1353, 1461, 1478, 1357, - /* 370 */ 1351, 1430, 1431, 1432, 1433, 1370, 1391, 1454, 1367, 1489, - /* 380 */ 1486, 1470, 1386, 1355, 1429, 1471, 1434, 1424, 1458, 1393, - /* 390 */ 1479, 1482, 1485, 1394, 1400, 1487, 1442, 1488, 1490, 1484, - /* 400 */ 1491, 1448, 1483, 1493, 1452, 1480, 1496, 1497, 1498, 1499, - /* 410 */ 1406, 1494, 1500, 1502, 1501, 1404, 1505, 1506, 1435, 1503, - /* 420 */ 1508, 1408, 1507, 1504, 1509, 1510, 1511, 1507, 1513, 1516, - /* 430 */ 1517, 1515, 1519, 1521, 1534, 1523, 1525, 1524, 1526, 1527, - /* 440 */ 1529, 1530, 1526, 1532, 1531, 1533, 1535, 1537, 1427, 1438, - /* 450 */ 1440, 1443, 1538, 1542, 1562, -}; -#define YY_REDUCE_USE_DFLT (-144) -#define YY_REDUCE_COUNT (323) -#define YY_REDUCE_MIN (-143) -#define YY_REDUCE_MAX (1305) -static const short yy_reduce_ofst[] = { - /* 0 */ -143, -65, 140, 840, 76, 180, 182, 233, 488, -25, - /* 10 */ 12, 16, 59, 885, 907, 935, 390, 705, 954, 285, - /* 20 */ 997, 1017, 1018, -118, 1025, 139, 171, 171, 171, 171, - /* 30 */ 171, 171, 171, 171, 171, 171, 171, 171, 171, 171, - /* 40 */ 171, 171, 171, 171, 171, 171, 171, 171, 171, 171, - /* 50 */ 171, 171, 171, 171, 171, 171, 171, 171, -69, 287, - /* 60 */ 441, 658, 708, 856, 1050, 1073, 1076, 1079, 1081, 1084, - /* 70 */ 1086, 1088, 1091, 1113, 1115, 1117, 1122, 1124, 1126, 1128, - /* 80 */ 1130, 1141, 1153, 1156, 1159, 1163, 1165, 1167, 1170, 1172, - /* 90 */ 1175, 1178, 1181, 1189, 1194, 1197, 1200, 1203, 1205, 1207, - /* 100 */ 1211, 1213, 1216, 1219, 171, 171, 171, 171, 171, 171, - /* 110 */ 171, 171, 171, 49, 176, 220, 275, 278, 290, 171, - /* 120 */ 300, 171, 171, 171, 171, -85, -85, -85, -28, 77, - /* 130 */ 313, 317, -56, 252, 252, 446, -129, 243, 361, 403, - /* 140 */ 406, 513, 517, 409, 502, 518, 504, 509, 621, 553, - /* 150 */ 562, 619, 559, 93, 620, 465, 453, 550, 591, 571, - /* 160 */ 615, 666, 750, 752, 797, 819, 463, 548, -73, 28, - /* 170 */ 68, 120, 257, 206, 359, 405, 413, 452, 457, 560, - /* 180 */ 566, 617, 670, 720, 723, 769, 773, 775, 780, 813, - /* 190 */ 814, 821, 822, 823, 826, 360, 436, 783, 829, 835, - /* 200 */ 707, 862, 867, 878, 830, 911, 915, 883, 936, 937, - /* 210 */ 940, 359, 942, 943, 944, 979, 982, 984, 886, 899, - /* 220 */ 928, 929, 931, 707, 947, 945, 998, 949, 932, 969, - /* 230 */ 918, 953, 924, 992, 1005, 1010, 1016, 971, 965, 1019, - /* 240 */ 1049, 1000, 1028, 1074, 989, 1078, 1080, 1026, 1031, 1109, - /* 250 */ 1053, 1090, 1103, 1092, 1099, 1114, 1118, 1148, 1151, 1111, - /* 260 */ 1096, 1129, 1131, 1133, 1162, 1202, 1138, 1146, 1231, 1234, - /* 270 */ 1206, 1218, 1237, 1239, 1240, 1242, 1221, 1228, 1229, 1230, - /* 280 */ 1224, 1233, 1235, 1236, 1241, 1226, 1243, 1244, 1198, 1201, - /* 290 */ 1209, 1212, 1210, 1214, 1215, 1217, 1260, 1199, 1262, 1220, - /* 300 */ 1247, 1222, 1223, 1253, 1238, 1245, 1251, 1246, 1249, 1276, - /* 310 */ 1279, 1289, 1291, 1296, 1302, 1305, 1225, 1227, 1248, 1290, - /* 320 */ 1292, 1280, 1281, 1295, -}; -static const YYACTIONTYPE yy_default[] = { - /* 0 */ 1270, 1260, 1260, 1260, 1193, 1193, 1193, 1193, 1260, 1088, - /* 10 */ 1117, 1117, 1244, 1322, 1322, 1322, 1322, 1322, 1322, 1192, - /* 20 */ 1322, 1322, 1322, 1322, 1260, 1092, 1123, 1322, 1322, 1322, - /* 30 */ 1322, 1194, 1195, 1322, 1322, 1322, 1243, 1245, 1133, 1132, - /* 40 */ 1131, 1130, 1226, 1104, 1128, 1121, 1125, 1194, 1188, 1189, - /* 50 */ 1187, 1191, 1195, 1322, 1124, 1158, 1172, 1157, 1322, 1322, - /* 60 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, - /* 70 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, - /* 80 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, - /* 90 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, - /* 100 */ 1322, 1322, 1322, 1322, 1166, 1171, 1178, 1170, 1167, 1160, - /* 110 */ 1159, 1161, 1162, 1322, 1011, 1059, 1322, 1322, 1322, 1163, - /* 120 */ 1322, 1164, 1175, 1174, 1173, 1251, 1278, 1277, 1322, 1322, - /* 130 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, - /* 140 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, - /* 150 */ 1322, 1322, 1322, 1322, 1322, 1270, 1260, 1017, 1017, 1322, - /* 160 */ 1260, 1260, 1260, 1260, 1260, 1260, 1256, 1092, 1083, 1322, - /* 170 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, - /* 180 */ 1248, 1246, 1322, 1208, 1322, 1322, 1322, 1322, 1322, 1322, - /* 190 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, - /* 200 */ 1322, 1322, 1322, 1322, 1088, 1322, 1322, 1322, 1322, 1322, - /* 210 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1272, 1322, 1221, - /* 220 */ 1088, 1088, 1088, 1090, 1072, 1082, 997, 1127, 1106, 1106, - /* 230 */ 1311, 1127, 1311, 1034, 1292, 1031, 1117, 1106, 1190, 1117, - /* 240 */ 1117, 1089, 1082, 1322, 1314, 1097, 1097, 1313, 1313, 1097, - /* 250 */ 1138, 1062, 1127, 1068, 1068, 1068, 1068, 1097, 1008, 1127, - /* 260 */ 1138, 1062, 1062, 1127, 1097, 1008, 1225, 1308, 1097, 1097, - /* 270 */ 1008, 1201, 1097, 1008, 1097, 1008, 1201, 1060, 1060, 1060, - /* 280 */ 1049, 1201, 1060, 1034, 1060, 1049, 1060, 1060, 1110, 1105, - /* 290 */ 1110, 1105, 1110, 1105, 1110, 1105, 1097, 1196, 1097, 1322, - /* 300 */ 1201, 1205, 1205, 1201, 1122, 1111, 1120, 1118, 1127, 1014, - /* 310 */ 1052, 1275, 1275, 1271, 1271, 1271, 1319, 1319, 1256, 1287, - /* 320 */ 1287, 1036, 1036, 1287, 1322, 1322, 1322, 1322, 1322, 1322, - /* 330 */ 1282, 1322, 1210, 1322, 1322, 1322, 1322, 1322, 1322, 1322, - /* 340 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, - /* 350 */ 1322, 1143, 1322, 993, 1253, 1322, 1322, 1252, 1322, 1322, - /* 360 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, - /* 370 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1310, 1322, - /* 380 */ 1322, 1322, 1322, 1322, 1322, 1224, 1223, 1322, 1322, 1322, - /* 390 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, - /* 400 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, - /* 410 */ 1074, 1322, 1322, 1322, 1296, 1322, 1322, 1322, 1322, 1322, - /* 420 */ 1322, 1322, 1119, 1322, 1112, 1322, 1322, 1301, 1322, 1322, - /* 430 */ 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1262, 1322, - /* 440 */ 1322, 1322, 1261, 1322, 1322, 1322, 1322, 1322, 1145, 1322, - /* 450 */ 1144, 1148, 1322, 1002, 1322, -}; -/********** 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, /* 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, /* TRIGGER => ID */ - 59, /* VACUUM => ID */ - 59, /* VIEW => ID */ - 59, /* VIRTUAL => ID */ - 59, /* WITH => ID */ - 59, /* REINDEX => ID */ - 59, /* RENAME => ID */ - 59, /* CTIME_KW => ID */ -}; -#endif /* YYFALLBACK */ - -/* The following structure represents a single element of the -** parser's stack. Information stored includes: -** -** + The state number for the parser at this level of the stack. -** -** + The value of the token stored at this level of the stack. -** (In other words, the "major" token.) -** -** + The semantic value stored at this level of the stack. This is -** the information used by the action routines in the grammar. -** It is sometimes called the "minor" token. -** -** 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 */ -#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 */ - -#ifndef NDEBUG -/* For tracing shifts, the names of all terminals and nonterminals -** are required. The following table supplies these names */ -static const char *const yyTokenName[] = { - "$", "SEMI", "EXPLAIN", "QUERY", - "PLAN", "BEGIN", "TRANSACTION", "DEFERRED", - "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END", - "ROLLBACK", "SAVEPOINT", "RELEASE", "TO", - "TABLE", "CREATE", "IF", "NOT", - "EXISTS", "TEMP", "LP", "RP", - "AS", "WITHOUT", "COMMA", "ABORT", - "ACTION", "AFTER", "ANALYZE", "ASC", - "ATTACH", "BEFORE", "BY", "CASCADE", - "CAST", "CONFLICT", "DATABASE", "DESC", - "DETACH", "EACH", "FAIL", "OR", - "AND", "IS", "MATCH", "LIKE_KW", - "BETWEEN", "IN", "ISNULL", "NOTNULL", - "NE", "EQ", "GT", "LE", - "LT", "GE", "ESCAPE", "ID", - "COLUMNKW", "FOR", "IGNORE", "INITIALLY", - "INSTEAD", "NO", "KEY", "OF", - "OFFSET", "PRAGMA", "RAISE", "RECURSIVE", - "REPLACE", "RESTRICT", "ROW", "TRIGGER", - "VACUUM", "VIEW", "VIRTUAL", "WITH", - "REINDEX", "RENAME", "CTIME_KW", "ANY", - "BITAND", "BITOR", "LSHIFT", "RSHIFT", - "PLUS", "MINUS", "STAR", "SLASH", - "REM", "CONCAT", "COLLATE", "BITNOT", - "INDEXED", "STRING", "JOIN_KW", "CONSTRAINT", - "DEFAULT", "NULL", "PRIMARY", "UNIQUE", - "CHECK", "REFERENCES", "AUTOINCR", "ON", - "INSERT", "DELETE", "UPDATE", "SET", - "DEFERRABLE", "FOREIGN", "DROP", "UNION", - "ALL", "EXCEPT", "INTERSECT", "SELECT", - "VALUES", "DISTINCT", "DOT", "FROM", - "JOIN", "USING", "ORDER", "GROUP", - "HAVING", "LIMIT", "WHERE", "INTO", - "FLOAT", "BLOB", "INTEGER", "VARIABLE", - "CASE", "WHEN", "THEN", "ELSE", - "INDEX", "ALTER", "ADD", "error", - "input", "cmdlist", "ecmd", "explain", - "cmdx", "cmd", "transtype", "trans_opt", - "nm", "savepoint_opt", "create_table", "create_table_args", - "createkw", "temp", "ifnotexists", "dbnm", - "columnlist", "conslist_opt", "table_options", "select", - "columnname", "carglist", "typetoken", "typename", - "signed", "plus_num", "minus_num", "ccons", - "term", "expr", "onconf", "sortorder", - "autoinc", "eidlist_opt", "refargs", "defer_subclause", - "refarg", "refact", "init_deferred_pred_opt", "conslist", - "tconscomma", "tcons", "sortlist", "eidlist", - "defer_subclause_opt", "orconf", "resolvetype", "raisetype", - "ifexists", "fullname", "selectnowith", "oneselect", - "with", "multiselect_op", "distinct", "selcollist", - "from", "where_opt", "groupby_opt", "having_opt", - "orderby_opt", "limit_opt", "values", "nexprlist", - "exprlist", "sclp", "as", "seltablist", - "stl_prefix", "joinop", "indexed_opt", "on_opt", - "using_opt", "idlist", "setlist", "insert_cmd", - "idlist_opt", "likeop", "between_op", "in_op", - "paren_exprlist", "case_operand", "case_exprlist", "case_else", - "uniqueflag", "collate", "nmnum", "trigger_decl", - "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause", - "when_clause", "trigger_cmd", "trnm", "tridxby", - "database_kw_opt", "key_opt", "add_column_fullname", "kwcolumn_opt", - "create_vtab", "vtabarglist", "vtabarg", "vtabargtoken", - "lp", "anylist", "wqlist", -}; -#endif /* 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 */ "ccons ::= CONSTRAINT nm", - /* 29 */ "ccons ::= DEFAULT term", - /* 30 */ "ccons ::= DEFAULT LP expr RP", - /* 31 */ "ccons ::= DEFAULT PLUS term", - /* 32 */ "ccons ::= DEFAULT MINUS term", - /* 33 */ "ccons ::= DEFAULT ID|INDEXED", - /* 34 */ "ccons ::= NOT NULL onconf", - /* 35 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc", - /* 36 */ "ccons ::= UNIQUE onconf", - /* 37 */ "ccons ::= CHECK LP expr RP", - /* 38 */ "ccons ::= REFERENCES nm eidlist_opt refargs", - /* 39 */ "ccons ::= defer_subclause", - /* 40 */ "ccons ::= COLLATE ID|STRING", - /* 41 */ "autoinc ::=", - /* 42 */ "autoinc ::= AUTOINCR", - /* 43 */ "refargs ::=", - /* 44 */ "refargs ::= refargs refarg", - /* 45 */ "refarg ::= MATCH nm", - /* 46 */ "refarg ::= ON INSERT refact", - /* 47 */ "refarg ::= ON DELETE refact", - /* 48 */ "refarg ::= ON UPDATE refact", - /* 49 */ "refact ::= SET NULL", - /* 50 */ "refact ::= SET DEFAULT", - /* 51 */ "refact ::= CASCADE", - /* 52 */ "refact ::= RESTRICT", - /* 53 */ "refact ::= NO ACTION", - /* 54 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt", - /* 55 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt", - /* 56 */ "init_deferred_pred_opt ::=", - /* 57 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED", - /* 58 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE", - /* 59 */ "conslist_opt ::=", - /* 60 */ "tconscomma ::= COMMA", - /* 61 */ "tcons ::= CONSTRAINT nm", - /* 62 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf", - /* 63 */ "tcons ::= UNIQUE LP sortlist RP onconf", - /* 64 */ "tcons ::= CHECK LP expr RP onconf", - /* 65 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt", - /* 66 */ "defer_subclause_opt ::=", - /* 67 */ "onconf ::=", - /* 68 */ "onconf ::= ON CONFLICT resolvetype", - /* 69 */ "orconf ::=", - /* 70 */ "orconf ::= OR resolvetype", - /* 71 */ "resolvetype ::= IGNORE", - /* 72 */ "resolvetype ::= REPLACE", - /* 73 */ "cmd ::= DROP TABLE ifexists fullname", - /* 74 */ "ifexists ::= IF EXISTS", - /* 75 */ "ifexists ::=", - /* 76 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select", - /* 77 */ "cmd ::= DROP VIEW ifexists fullname", - /* 78 */ "cmd ::= select", - /* 79 */ "select ::= with selectnowith", - /* 80 */ "selectnowith ::= selectnowith multiselect_op oneselect", - /* 81 */ "multiselect_op ::= UNION", - /* 82 */ "multiselect_op ::= UNION ALL", - /* 83 */ "multiselect_op ::= EXCEPT|INTERSECT", - /* 84 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt", - /* 85 */ "values ::= VALUES LP nexprlist RP", - /* 86 */ "values ::= values COMMA LP exprlist RP", - /* 87 */ "distinct ::= DISTINCT", - /* 88 */ "distinct ::= ALL", - /* 89 */ "distinct ::=", - /* 90 */ "sclp ::=", - /* 91 */ "selcollist ::= sclp expr as", - /* 92 */ "selcollist ::= sclp STAR", - /* 93 */ "selcollist ::= sclp nm DOT STAR", - /* 94 */ "as ::= AS nm", - /* 95 */ "as ::=", - /* 96 */ "from ::=", - /* 97 */ "from ::= FROM seltablist", - /* 98 */ "stl_prefix ::= seltablist joinop", - /* 99 */ "stl_prefix ::=", - /* 100 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt", - /* 101 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt", - /* 102 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt", - /* 103 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt", - /* 104 */ "dbnm ::=", - /* 105 */ "dbnm ::= DOT nm", - /* 106 */ "fullname ::= nm dbnm", - /* 107 */ "joinop ::= COMMA|JOIN", - /* 108 */ "joinop ::= JOIN_KW JOIN", - /* 109 */ "joinop ::= JOIN_KW nm JOIN", - /* 110 */ "joinop ::= JOIN_KW nm nm JOIN", - /* 111 */ "on_opt ::= ON expr", - /* 112 */ "on_opt ::=", - /* 113 */ "indexed_opt ::=", - /* 114 */ "indexed_opt ::= INDEXED BY nm", - /* 115 */ "indexed_opt ::= NOT INDEXED", - /* 116 */ "using_opt ::= USING LP idlist RP", - /* 117 */ "using_opt ::=", - /* 118 */ "orderby_opt ::=", - /* 119 */ "orderby_opt ::= ORDER BY sortlist", - /* 120 */ "sortlist ::= sortlist COMMA expr sortorder", - /* 121 */ "sortlist ::= expr sortorder", - /* 122 */ "sortorder ::= ASC", - /* 123 */ "sortorder ::= DESC", - /* 124 */ "sortorder ::=", - /* 125 */ "groupby_opt ::=", - /* 126 */ "groupby_opt ::= GROUP BY nexprlist", - /* 127 */ "having_opt ::=", - /* 128 */ "having_opt ::= HAVING expr", - /* 129 */ "limit_opt ::=", - /* 130 */ "limit_opt ::= LIMIT expr", - /* 131 */ "limit_opt ::= LIMIT expr OFFSET expr", - /* 132 */ "limit_opt ::= LIMIT expr COMMA expr", - /* 133 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt", - /* 134 */ "where_opt ::=", - /* 135 */ "where_opt ::= WHERE expr", - /* 136 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt", - /* 137 */ "setlist ::= setlist COMMA nm EQ expr", - /* 138 */ "setlist ::= setlist COMMA LP idlist RP EQ expr", - /* 139 */ "setlist ::= nm EQ expr", - /* 140 */ "setlist ::= LP idlist RP EQ expr", - /* 141 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select", - /* 142 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES", - /* 143 */ "insert_cmd ::= INSERT orconf", - /* 144 */ "insert_cmd ::= REPLACE", - /* 145 */ "idlist_opt ::=", - /* 146 */ "idlist_opt ::= LP idlist RP", - /* 147 */ "idlist ::= idlist COMMA nm", - /* 148 */ "idlist ::= nm", - /* 149 */ "expr ::= LP expr RP", - /* 150 */ "expr ::= ID|INDEXED", - /* 151 */ "expr ::= JOIN_KW", - /* 152 */ "expr ::= nm DOT nm", - /* 153 */ "expr ::= nm DOT nm DOT nm", - /* 154 */ "term ::= NULL|FLOAT|BLOB", - /* 155 */ "term ::= STRING", - /* 156 */ "term ::= INTEGER", - /* 157 */ "expr ::= VARIABLE", - /* 158 */ "expr ::= expr COLLATE ID|STRING", - /* 159 */ "expr ::= CAST LP expr AS typetoken RP", - /* 160 */ "expr ::= ID|INDEXED LP distinct exprlist RP", - /* 161 */ "expr ::= ID|INDEXED LP STAR RP", - /* 162 */ "term ::= CTIME_KW", - /* 163 */ "expr ::= LP nexprlist COMMA expr RP", - /* 164 */ "expr ::= expr AND expr", - /* 165 */ "expr ::= expr OR expr", - /* 166 */ "expr ::= expr LT|GT|GE|LE expr", - /* 167 */ "expr ::= expr EQ|NE expr", - /* 168 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr", - /* 169 */ "expr ::= expr PLUS|MINUS expr", - /* 170 */ "expr ::= expr STAR|SLASH|REM expr", - /* 171 */ "expr ::= expr CONCAT expr", - /* 172 */ "likeop ::= NOT LIKE_KW|MATCH", - /* 173 */ "expr ::= expr likeop expr", - /* 174 */ "expr ::= expr likeop expr ESCAPE expr", - /* 175 */ "expr ::= expr ISNULL|NOTNULL", - /* 176 */ "expr ::= expr NOT NULL", - /* 177 */ "expr ::= expr IS expr", - /* 178 */ "expr ::= expr IS NOT expr", - /* 179 */ "expr ::= NOT expr", - /* 180 */ "expr ::= BITNOT expr", - /* 181 */ "expr ::= MINUS expr", - /* 182 */ "expr ::= PLUS expr", - /* 183 */ "between_op ::= BETWEEN", - /* 184 */ "between_op ::= NOT BETWEEN", - /* 185 */ "expr ::= expr between_op expr AND expr", - /* 186 */ "in_op ::= IN", - /* 187 */ "in_op ::= NOT IN", - /* 188 */ "expr ::= expr in_op LP exprlist RP", - /* 189 */ "expr ::= LP select RP", - /* 190 */ "expr ::= expr in_op LP select RP", - /* 191 */ "expr ::= expr in_op nm dbnm paren_exprlist", - /* 192 */ "expr ::= EXISTS LP select RP", - /* 193 */ "expr ::= CASE case_operand case_exprlist case_else END", - /* 194 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr", - /* 195 */ "case_exprlist ::= WHEN expr THEN expr", - /* 196 */ "case_else ::= ELSE expr", - /* 197 */ "case_else ::=", - /* 198 */ "case_operand ::= expr", - /* 199 */ "case_operand ::=", - /* 200 */ "exprlist ::=", - /* 201 */ "nexprlist ::= nexprlist COMMA expr", - /* 202 */ "nexprlist ::= expr", - /* 203 */ "paren_exprlist ::=", - /* 204 */ "paren_exprlist ::= LP exprlist RP", - /* 205 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt", - /* 206 */ "uniqueflag ::= UNIQUE", - /* 207 */ "uniqueflag ::=", - /* 208 */ "eidlist_opt ::=", - /* 209 */ "eidlist_opt ::= LP eidlist RP", - /* 210 */ "eidlist ::= eidlist COMMA nm collate sortorder", - /* 211 */ "eidlist ::= nm collate sortorder", - /* 212 */ "collate ::=", - /* 213 */ "collate ::= COLLATE ID|STRING", - /* 214 */ "cmd ::= DROP INDEX ifexists fullname", - /* 215 */ "cmd ::= VACUUM", - /* 216 */ "cmd ::= VACUUM nm", - /* 217 */ "cmd ::= PRAGMA nm dbnm", - /* 218 */ "cmd ::= PRAGMA nm dbnm EQ nmnum", - /* 219 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP", - /* 220 */ "cmd ::= PRAGMA nm dbnm EQ minus_num", - /* 221 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP", - /* 222 */ "plus_num ::= PLUS INTEGER|FLOAT", - /* 223 */ "minus_num ::= MINUS INTEGER|FLOAT", - /* 224 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END", - /* 225 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause", - /* 226 */ "trigger_time ::= BEFORE|AFTER", - /* 227 */ "trigger_time ::= INSTEAD OF", - /* 228 */ "trigger_time ::=", - /* 229 */ "trigger_event ::= DELETE|INSERT", - /* 230 */ "trigger_event ::= UPDATE", - /* 231 */ "trigger_event ::= UPDATE OF idlist", - /* 232 */ "when_clause ::=", - /* 233 */ "when_clause ::= WHEN expr", - /* 234 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI", - /* 235 */ "trigger_cmd_list ::= trigger_cmd SEMI", - /* 236 */ "trnm ::= nm DOT nm", - /* 237 */ "tridxby ::= INDEXED BY nm", - /* 238 */ "tridxby ::= NOT INDEXED", - /* 239 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt", - /* 240 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select", - /* 241 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt", - /* 242 */ "trigger_cmd ::= select", - /* 243 */ "expr ::= RAISE LP IGNORE RP", - /* 244 */ "expr ::= RAISE LP raisetype COMMA nm RP", - /* 245 */ "raisetype ::= ROLLBACK", - /* 246 */ "raisetype ::= ABORT", - /* 247 */ "raisetype ::= FAIL", - /* 248 */ "cmd ::= DROP TRIGGER ifexists fullname", - /* 249 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt", - /* 250 */ "cmd ::= DETACH database_kw_opt expr", - /* 251 */ "key_opt ::=", - /* 252 */ "key_opt ::= KEY expr", - /* 253 */ "cmd ::= REINDEX", - /* 254 */ "cmd ::= REINDEX nm dbnm", - /* 255 */ "cmd ::= ANALYZE", - /* 256 */ "cmd ::= ANALYZE nm dbnm", - /* 257 */ "cmd ::= ALTER TABLE fullname RENAME TO nm", - /* 258 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist", - /* 259 */ "add_column_fullname ::= fullname", - /* 260 */ "cmd ::= create_vtab", - /* 261 */ "cmd ::= create_vtab LP vtabarglist RP", - /* 262 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm", - /* 263 */ "vtabarg ::=", - /* 264 */ "vtabargtoken ::= ANY", - /* 265 */ "vtabargtoken ::= lp anylist RP", - /* 266 */ "lp ::= LP", - /* 267 */ "with ::=", - /* 268 */ "with ::= WITH wqlist", - /* 269 */ "with ::= WITH RECURSIVE wqlist", - /* 270 */ "wqlist ::= nm eidlist_opt AS LP select RP", - /* 271 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP", - /* 272 */ "input ::= cmdlist", - /* 273 */ "cmdlist ::= cmdlist ecmd", - /* 274 */ "cmdlist ::= ecmd", - /* 275 */ "ecmd ::= SEMI", - /* 276 */ "ecmd ::= explain cmdx SEMI", - /* 277 */ "explain ::=", - /* 278 */ "trans_opt ::=", - /* 279 */ "trans_opt ::= TRANSACTION", - /* 280 */ "trans_opt ::= TRANSACTION nm", - /* 281 */ "savepoint_opt ::= SAVEPOINT", - /* 282 */ "savepoint_opt ::=", - /* 283 */ "cmd ::= create_table create_table_args", - /* 284 */ "columnlist ::= columnlist COMMA columnname carglist", - /* 285 */ "columnlist ::= columnname carglist", - /* 286 */ "nm ::= ID|INDEXED", - /* 287 */ "nm ::= STRING", - /* 288 */ "nm ::= JOIN_KW", - /* 289 */ "typetoken ::= typename", - /* 290 */ "typename ::= ID|STRING", - /* 291 */ "signed ::= plus_num", - /* 292 */ "signed ::= minus_num", - /* 293 */ "carglist ::= carglist ccons", - /* 294 */ "carglist ::=", - /* 295 */ "ccons ::= NULL onconf", - /* 296 */ "conslist_opt ::= COMMA conslist", - /* 297 */ "conslist ::= conslist tconscomma tcons", - /* 298 */ "conslist ::= tcons", - /* 299 */ "tconscomma ::=", - /* 300 */ "defer_subclause_opt ::= defer_subclause", - /* 301 */ "resolvetype ::= raisetype", - /* 302 */ "selectnowith ::= oneselect", - /* 303 */ "oneselect ::= values", - /* 304 */ "sclp ::= selcollist COMMA", - /* 305 */ "as ::= ID|STRING", - /* 306 */ "expr ::= term", - /* 307 */ "likeop ::= LIKE_KW|MATCH", - /* 308 */ "exprlist ::= nexprlist", - /* 309 */ "nmnum ::= plus_num", - /* 310 */ "nmnum ::= nm", - /* 311 */ "nmnum ::= ON", - /* 312 */ "nmnum ::= DELETE", - /* 313 */ "nmnum ::= DEFAULT", - /* 314 */ "plus_num ::= INTEGER|FLOAT", - /* 315 */ "foreach_clause ::=", - /* 316 */ "foreach_clause ::= FOR EACH ROW", - /* 317 */ "trnm ::= nm", - /* 318 */ "tridxby ::=", - /* 319 */ "database_kw_opt ::= DATABASE", - /* 320 */ "database_kw_opt ::=", - /* 321 */ "kwcolumn_opt ::=", - /* 322 */ "kwcolumn_opt ::= COLUMNKW", - /* 323 */ "vtabarglist ::= vtabarg", - /* 324 */ "vtabarglist ::= vtabarglist COMMA vtabarg", - /* 325 */ "vtabarg ::= vtabarg vtabargtoken", - /* 326 */ "anylist ::=", - /* 327 */ "anylist ::= anylist LP anylist RP", - /* 328 */ "anylist ::= anylist ANY", -}; -#endif /* NDEBUG */ - - -#if YYSTACKDEPTH<=0 -/* -** Try to increase the size of the parser stack. 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 *yypParser){ - yyParser *pParser = (yyParser*)yypParser; -#ifdef YYTRACKMAXSTACKDEPTH - pParser->yyhwm = 0; -#endif -#if YYSTACKDEPTH<=0 - pParser->yytos = NULL; - pParser->yystack = NULL; - pParser->yystksz = 0; - if( yyGrowStack(pParser) ){ - pParser->yystack = &pParser->yystk0; - pParser->yystksz = 1; - } -#endif -#ifndef YYNOERRORRECOVERY - pParser->yyerrcnt = -1; -#endif - pParser->yytos = pParser->yystack; - pParser->yystack[0].stateno = 0; - pParser->yystack[0].major = 0; -#if YYSTACKDEPTH>0 - pParser->yystackEnd = &pParser->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)){ - yyParser *pParser; - pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) ); - if( pParser ) sqlite3ParserInit(pParser); - return pParser; -} -#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; - 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 163: /* select */ - case 194: /* selectnowith */ - case 195: /* oneselect */ - case 206: /* values */ -{ -sqlite3SelectDelete(pParse->db, (yypminor->yy243)); -} - break; - case 172: /* term */ - case 173: /* expr */ -{ -sqlite3ExprDelete(pParse->db, (yypminor->yy190).pExpr); -} - break; - case 177: /* eidlist_opt */ - case 186: /* sortlist */ - case 187: /* eidlist */ - case 199: /* selcollist */ - case 202: /* groupby_opt */ - case 204: /* orderby_opt */ - case 207: /* nexprlist */ - case 208: /* exprlist */ - case 209: /* sclp */ - case 218: /* setlist */ - case 224: /* paren_exprlist */ - case 226: /* case_exprlist */ -{ -sqlite3ExprListDelete(pParse->db, (yypminor->yy148)); -} - break; - case 193: /* fullname */ - case 200: /* from */ - case 211: /* seltablist */ - case 212: /* stl_prefix */ -{ -sqlite3SrcListDelete(pParse->db, (yypminor->yy185)); -} - break; - case 196: /* with */ - case 250: /* wqlist */ -{ -sqlite3WithDelete(pParse->db, (yypminor->yy285)); -} - break; - case 201: /* where_opt */ - case 203: /* having_opt */ - case 215: /* on_opt */ - case 225: /* case_operand */ - case 227: /* case_else */ - case 236: /* when_clause */ - case 241: /* key_opt */ -{ -sqlite3ExprDelete(pParse->db, (yypminor->yy72)); -} - break; - case 216: /* using_opt */ - case 217: /* idlist */ - case 220: /* idlist_opt */ -{ -sqlite3IdListDelete(pParse->db, (yypminor->yy254)); -} - break; - case 232: /* trigger_cmd_list */ - case 237: /* trigger_cmd */ -{ -sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy145)); -} - break; - case 234: /* trigger_event */ -{ -sqlite3IdListDelete(pParse->db, (yypminor->yy332).b); -} - 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 - -/* -** Find the appropriate action for a parser given the terminal -** look-ahead token iLookAhead. -*/ -static unsigned int yy_find_shift_action( - yyParser *pParser, /* The parser */ - YYCODETYPE iLookAhead /* The look-ahead token */ -){ - int i; - int stateno = pParser->yytos->stateno; - - if( stateno>=YY_MIN_REDUCE ) return stateno; - assert( stateno <= YY_SHIFT_COUNT ); - do{ - i = yy_shift_ofst[stateno]; - assert( iLookAhead!=YYNOCODE ); - i += iLookAhead; - if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ -#ifdef YYFALLBACK - YYCODETYPE iFallback; /* Fallback token */ - if( 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; - if( -#if YY_SHIFT_MIN+YYWILDCARD<0 - j>=0 && -#endif -#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT - j0 - ){ -#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{ - return yy_action[i]; - } - }while(1); -} - -/* -** Find the appropriate action for a parser given the non-terminal -** look-ahead token iLookAhead. -*/ -static int yy_find_reduce_action( - int stateno, /* Current state number */ - YYCODETYPE iLookAhead /* The look-ahead token */ -){ - int i; -#ifdef YYERRORSYMBOL - if( stateno>YY_REDUCE_COUNT ){ - return yy_default[stateno]; - } -#else - assert( stateno<=YY_REDUCE_COUNT ); -#endif - i = yy_reduce_ofst[stateno]; - assert( i!=YY_REDUCE_USE_DFLT ); - 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 */ -} - -/* -** Print tracing information for a SHIFT action -*/ -#ifndef NDEBUG -static void yyTraceShift(yyParser *yypParser, int yyNewState){ - if( yyTraceFILE ){ - if( yyNewStateyytos->major], - yyNewState); - }else{ - fprintf(yyTraceFILE,"%sShift '%s'\n", - yyTracePrompt,yyTokenName[yypParser->yytos->major]); - } - } -} -#else -# define yyTraceShift(X,Y) -#endif - -/* -** Perform a shift action. -*/ -static void yy_shift( - yyParser *yypParser, /* The parser to be shifted */ - int yyNewState, /* The new state to shift in */ - int yyMajor, /* The major token to shift in */ - 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 = (YYACTIONTYPE)yyNewState; - yytos->major = (YYCODETYPE)yyMajor; - yytos->minor.yy0 = yyMinor; - yyTraceShift(yypParser, yyNewState); -} - -/* The following table contains information about every rule that -** is used during the reduce. -*/ -static const struct { - YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */ - signed char nrhs; /* Negative of the number of RHS symbols in the rule */ -} yyRuleInfo[] = { - { 147, -1 }, - { 147, -3 }, - { 148, -1 }, - { 149, -3 }, - { 150, 0 }, - { 150, -1 }, - { 150, -1 }, - { 150, -1 }, - { 149, -2 }, - { 149, -2 }, - { 149, -2 }, - { 149, -3 }, - { 149, -5 }, - { 154, -6 }, - { 156, -1 }, - { 158, 0 }, - { 158, -3 }, - { 157, -1 }, - { 157, 0 }, - { 155, -5 }, - { 155, -2 }, - { 162, 0 }, - { 162, -2 }, - { 164, -2 }, - { 166, 0 }, - { 166, -4 }, - { 166, -6 }, - { 167, -2 }, - { 171, -2 }, - { 171, -2 }, - { 171, -4 }, - { 171, -3 }, - { 171, -3 }, - { 171, -2 }, - { 171, -3 }, - { 171, -5 }, - { 171, -2 }, - { 171, -4 }, - { 171, -4 }, - { 171, -1 }, - { 171, -2 }, - { 176, 0 }, - { 176, -1 }, - { 178, 0 }, - { 178, -2 }, - { 180, -2 }, - { 180, -3 }, - { 180, -3 }, - { 180, -3 }, - { 181, -2 }, - { 181, -2 }, - { 181, -1 }, - { 181, -1 }, - { 181, -2 }, - { 179, -3 }, - { 179, -2 }, - { 182, 0 }, - { 182, -2 }, - { 182, -2 }, - { 161, 0 }, - { 184, -1 }, - { 185, -2 }, - { 185, -7 }, - { 185, -5 }, - { 185, -5 }, - { 185, -10 }, - { 188, 0 }, - { 174, 0 }, - { 174, -3 }, - { 189, 0 }, - { 189, -2 }, - { 190, -1 }, - { 190, -1 }, - { 149, -4 }, - { 192, -2 }, - { 192, 0 }, - { 149, -9 }, - { 149, -4 }, - { 149, -1 }, - { 163, -2 }, - { 194, -3 }, - { 197, -1 }, - { 197, -2 }, - { 197, -1 }, - { 195, -9 }, - { 206, -4 }, - { 206, -5 }, - { 198, -1 }, - { 198, -1 }, - { 198, 0 }, - { 209, 0 }, - { 199, -3 }, - { 199, -2 }, - { 199, -4 }, - { 210, -2 }, - { 210, 0 }, - { 200, 0 }, - { 200, -2 }, - { 212, -2 }, - { 212, 0 }, - { 211, -7 }, - { 211, -9 }, - { 211, -7 }, - { 211, -7 }, - { 159, 0 }, - { 159, -2 }, - { 193, -2 }, - { 213, -1 }, - { 213, -2 }, - { 213, -3 }, - { 213, -4 }, - { 215, -2 }, - { 215, 0 }, - { 214, 0 }, - { 214, -3 }, - { 214, -2 }, - { 216, -4 }, - { 216, 0 }, - { 204, 0 }, - { 204, -3 }, - { 186, -4 }, - { 186, -2 }, - { 175, -1 }, - { 175, -1 }, - { 175, 0 }, - { 202, 0 }, - { 202, -3 }, - { 203, 0 }, - { 203, -2 }, - { 205, 0 }, - { 205, -2 }, - { 205, -4 }, - { 205, -4 }, - { 149, -6 }, - { 201, 0 }, - { 201, -2 }, - { 149, -8 }, - { 218, -5 }, - { 218, -7 }, - { 218, -3 }, - { 218, -5 }, - { 149, -6 }, - { 149, -7 }, - { 219, -2 }, - { 219, -1 }, - { 220, 0 }, - { 220, -3 }, - { 217, -3 }, - { 217, -1 }, - { 173, -3 }, - { 173, -1 }, - { 173, -1 }, - { 173, -3 }, - { 173, -5 }, - { 172, -1 }, - { 172, -1 }, - { 172, -1 }, - { 173, -1 }, - { 173, -3 }, - { 173, -6 }, - { 173, -5 }, - { 173, -4 }, - { 172, -1 }, - { 173, -5 }, - { 173, -3 }, - { 173, -3 }, - { 173, -3 }, - { 173, -3 }, - { 173, -3 }, - { 173, -3 }, - { 173, -3 }, - { 173, -3 }, - { 221, -2 }, - { 173, -3 }, - { 173, -5 }, - { 173, -2 }, - { 173, -3 }, - { 173, -3 }, - { 173, -4 }, - { 173, -2 }, - { 173, -2 }, - { 173, -2 }, - { 173, -2 }, - { 222, -1 }, - { 222, -2 }, - { 173, -5 }, - { 223, -1 }, - { 223, -2 }, - { 173, -5 }, - { 173, -3 }, - { 173, -5 }, - { 173, -5 }, - { 173, -4 }, - { 173, -5 }, - { 226, -5 }, - { 226, -4 }, - { 227, -2 }, - { 227, 0 }, - { 225, -1 }, - { 225, 0 }, - { 208, 0 }, - { 207, -3 }, - { 207, -1 }, - { 224, 0 }, - { 224, -3 }, - { 149, -12 }, - { 228, -1 }, - { 228, 0 }, - { 177, 0 }, - { 177, -3 }, - { 187, -5 }, - { 187, -3 }, - { 229, 0 }, - { 229, -2 }, - { 149, -4 }, - { 149, -1 }, - { 149, -2 }, - { 149, -3 }, - { 149, -5 }, - { 149, -6 }, - { 149, -5 }, - { 149, -6 }, - { 169, -2 }, - { 170, -2 }, - { 149, -5 }, - { 231, -11 }, - { 233, -1 }, - { 233, -2 }, - { 233, 0 }, - { 234, -1 }, - { 234, -1 }, - { 234, -3 }, - { 236, 0 }, - { 236, -2 }, - { 232, -3 }, - { 232, -2 }, - { 238, -3 }, - { 239, -3 }, - { 239, -2 }, - { 237, -7 }, - { 237, -5 }, - { 237, -5 }, - { 237, -1 }, - { 173, -4 }, - { 173, -6 }, - { 191, -1 }, - { 191, -1 }, - { 191, -1 }, - { 149, -4 }, - { 149, -6 }, - { 149, -3 }, - { 241, 0 }, - { 241, -2 }, - { 149, -1 }, - { 149, -3 }, - { 149, -1 }, - { 149, -3 }, - { 149, -6 }, - { 149, -7 }, - { 242, -1 }, - { 149, -1 }, - { 149, -4 }, - { 244, -8 }, - { 246, 0 }, - { 247, -1 }, - { 247, -3 }, - { 248, -1 }, - { 196, 0 }, - { 196, -2 }, - { 196, -3 }, - { 250, -6 }, - { 250, -8 }, - { 144, -1 }, - { 145, -2 }, - { 145, -1 }, - { 146, -1 }, - { 146, -3 }, - { 147, 0 }, - { 151, 0 }, - { 151, -1 }, - { 151, -2 }, - { 153, -1 }, - { 153, 0 }, - { 149, -2 }, - { 160, -4 }, - { 160, -2 }, - { 152, -1 }, - { 152, -1 }, - { 152, -1 }, - { 166, -1 }, - { 167, -1 }, - { 168, -1 }, - { 168, -1 }, - { 165, -2 }, - { 165, 0 }, - { 171, -2 }, - { 161, -2 }, - { 183, -3 }, - { 183, -1 }, - { 184, 0 }, - { 188, -1 }, - { 190, -1 }, - { 194, -1 }, - { 195, -1 }, - { 209, -2 }, - { 210, -1 }, - { 173, -1 }, - { 221, -1 }, - { 208, -1 }, - { 230, -1 }, - { 230, -1 }, - { 230, -1 }, - { 230, -1 }, - { 230, -1 }, - { 169, -1 }, - { 235, 0 }, - { 235, -3 }, - { 238, -1 }, - { 239, 0 }, - { 240, -1 }, - { 240, 0 }, - { 243, 0 }, - { 243, -1 }, - { 245, -1 }, - { 245, -3 }, - { 246, -2 }, - { 249, 0 }, - { 249, -4 }, - { 249, -2 }, -}; - -static void yy_accept(yyParser*); /* Forward Declaration */ - -/* -** Perform a reduce action and the shift that must immediately -** follow the reduce. -*/ -static void yy_reduce( - yyParser *yypParser, /* The parser */ - unsigned int yyruleno /* Number of the rule by which to reduce */ -){ - int yygoto; /* The next state */ - int yyact; /* The next action */ - yyStackEntry *yymsp; /* The top of the parser's stack */ - int yysize; /* Amount to pop the stack */ - sqlite3ParserARG_FETCH; - yymsp = yypParser->yytos; -#ifndef NDEBUG - if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){ - yysize = yyRuleInfo[yyruleno].nrhs; - fprintf(yyTraceFILE, "%sReduce [%s], go to state %d.\n", yyTracePrompt, - yyRuleName[yyruleno], yymsp[yysize].stateno); - } -#endif /* NDEBUG */ - - /* Check that the stack is large enough to grow by a single entry - ** if the RHS of the rule is empty. This ensures that there is room - ** enough on the stack to push the LHS value */ - if( yyRuleInfo[yyruleno].nrhs==0 ){ -#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 ){ - yyStackOverflow(yypParser); - return; - } -#else - if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){ - if( yyGrowStack(yypParser) ){ - yyStackOverflow(yypParser); - return; - } - 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.yy194);} - break; - case 4: /* transtype ::= */ -{yymsp[1].minor.yy194 = TK_DEFERRED;} - break; - case 5: /* transtype ::= DEFERRED */ - case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6); - case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7); -{yymsp[0].minor.yy194 = 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.yy194,0,0,yymsp[-2].minor.yy194); -} - 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 41: /* autoinc ::= */ yytestcase(yyruleno==41); - case 56: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==56); - case 66: /* defer_subclause_opt ::= */ yytestcase(yyruleno==66); - case 75: /* ifexists ::= */ yytestcase(yyruleno==75); - case 89: /* distinct ::= */ yytestcase(yyruleno==89); - case 212: /* collate ::= */ yytestcase(yyruleno==212); -{yymsp[1].minor.yy194 = 0;} - break; - case 16: /* ifnotexists ::= IF NOT EXISTS */ -{yymsp[-2].minor.yy194 = 1;} - break; - case 17: /* temp ::= TEMP */ - case 42: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==42); -{yymsp[0].minor.yy194 = 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.yy194,0); -} - break; - case 20: /* create_table_args ::= AS select */ -{ - sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy243); - sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243); -} - 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.yy194 = TF_WithoutRowid | TF_NoVisibleRowid; - }else{ - yymsp[-1].minor.yy194 = 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 59: /* conslist_opt ::= */ yytestcase(yyruleno==59); - case 95: /* as ::= */ yytestcase(yyruleno==95); -{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: /* ccons ::= CONSTRAINT nm */ - case 61: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==61); -{pParse->constraintName = yymsp[0].minor.yy0;} - break; - case 29: /* ccons ::= DEFAULT term */ - case 31: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==31); -{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy190);} - break; - case 30: /* ccons ::= DEFAULT LP expr RP */ -{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy190);} - break; - case 32: /* ccons ::= DEFAULT MINUS term */ -{ - ExprSpan v; - v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy190.pExpr, 0); - v.zStart = yymsp[-1].minor.yy0.z; - v.zEnd = yymsp[0].minor.yy190.zEnd; - sqlite3AddDefaultValue(pParse,&v); -} - break; - case 33: /* ccons ::= DEFAULT ID|INDEXED */ -{ - ExprSpan v; - spanExpr(&v, pParse, TK_STRING, yymsp[0].minor.yy0); - sqlite3AddDefaultValue(pParse,&v); -} - break; - case 34: /* ccons ::= NOT NULL onconf */ -{sqlite3AddNotNull(pParse, yymsp[0].minor.yy194);} - break; - case 35: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */ -{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy194,yymsp[0].minor.yy194,yymsp[-2].minor.yy194);} - break; - case 36: /* ccons ::= UNIQUE onconf */ -{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy194,0,0,0,0, - SQLITE_IDXTYPE_UNIQUE);} - break; - case 37: /* ccons ::= CHECK LP expr RP */ -{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy190.pExpr);} - break; - case 38: /* ccons ::= REFERENCES nm eidlist_opt refargs */ -{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy148,yymsp[0].minor.yy194);} - break; - case 39: /* ccons ::= defer_subclause */ -{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy194);} - break; - case 40: /* ccons ::= COLLATE ID|STRING */ -{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);} - break; - case 43: /* refargs ::= */ -{ yymsp[1].minor.yy194 = OE_None*0x0101; /* EV: R-19803-45884 */} - break; - case 44: /* refargs ::= refargs refarg */ -{ yymsp[-1].minor.yy194 = (yymsp[-1].minor.yy194 & ~yymsp[0].minor.yy497.mask) | yymsp[0].minor.yy497.value; } - break; - case 45: /* refarg ::= MATCH nm */ -{ yymsp[-1].minor.yy497.value = 0; yymsp[-1].minor.yy497.mask = 0x000000; } - break; - case 46: /* refarg ::= ON INSERT refact */ -{ yymsp[-2].minor.yy497.value = 0; yymsp[-2].minor.yy497.mask = 0x000000; } - break; - case 47: /* refarg ::= ON DELETE refact */ -{ yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194; yymsp[-2].minor.yy497.mask = 0x0000ff; } - break; - case 48: /* refarg ::= ON UPDATE refact */ -{ yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194<<8; yymsp[-2].minor.yy497.mask = 0x00ff00; } - break; - case 49: /* refact ::= SET NULL */ -{ yymsp[-1].minor.yy194 = OE_SetNull; /* EV: R-33326-45252 */} - break; - case 50: /* refact ::= SET DEFAULT */ -{ yymsp[-1].minor.yy194 = OE_SetDflt; /* EV: R-33326-45252 */} - break; - case 51: /* refact ::= CASCADE */ -{ yymsp[0].minor.yy194 = OE_Cascade; /* EV: R-33326-45252 */} - break; - case 52: /* refact ::= RESTRICT */ -{ yymsp[0].minor.yy194 = OE_Restrict; /* EV: R-33326-45252 */} - break; - case 53: /* refact ::= NO ACTION */ -{ yymsp[-1].minor.yy194 = OE_None; /* EV: R-33326-45252 */} - break; - case 54: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ -{yymsp[-2].minor.yy194 = 0;} - break; - case 55: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */ - case 70: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==70); - case 143: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==143); -{yymsp[-1].minor.yy194 = yymsp[0].minor.yy194;} - break; - case 57: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ - case 74: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==74); - case 184: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==184); - case 187: /* in_op ::= NOT IN */ yytestcase(yyruleno==187); - case 213: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==213); -{yymsp[-1].minor.yy194 = 1;} - break; - case 58: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ -{yymsp[-1].minor.yy194 = 0;} - break; - case 60: /* tconscomma ::= COMMA */ -{pParse->constraintName.n = 0;} - break; - case 62: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */ -{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy148,yymsp[0].minor.yy194,yymsp[-2].minor.yy194,0);} - break; - case 63: /* tcons ::= UNIQUE LP sortlist RP onconf */ -{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy148,yymsp[0].minor.yy194,0,0,0,0, - SQLITE_IDXTYPE_UNIQUE);} - break; - case 64: /* tcons ::= CHECK LP expr RP onconf */ -{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy190.pExpr);} - break; - case 65: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */ -{ - sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy148, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[-1].minor.yy194); - sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy194); -} - break; - case 67: /* onconf ::= */ - case 69: /* orconf ::= */ yytestcase(yyruleno==69); -{yymsp[1].minor.yy194 = OE_Default;} - break; - case 68: /* onconf ::= ON CONFLICT resolvetype */ -{yymsp[-2].minor.yy194 = yymsp[0].minor.yy194;} - break; - case 71: /* resolvetype ::= IGNORE */ -{yymsp[0].minor.yy194 = OE_Ignore;} - break; - case 72: /* resolvetype ::= REPLACE */ - case 144: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==144); -{yymsp[0].minor.yy194 = OE_Replace;} - break; - case 73: /* cmd ::= DROP TABLE ifexists fullname */ -{ - sqlite3DropTable(pParse, yymsp[0].minor.yy185, 0, yymsp[-1].minor.yy194); -} - break; - case 76: /* 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.yy148, yymsp[0].minor.yy243, yymsp[-7].minor.yy194, yymsp[-5].minor.yy194); -} - break; - case 77: /* cmd ::= DROP VIEW ifexists fullname */ -{ - sqlite3DropTable(pParse, yymsp[0].minor.yy185, 1, yymsp[-1].minor.yy194); -} - break; - case 78: /* cmd ::= select */ -{ - SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0}; - sqlite3Select(pParse, yymsp[0].minor.yy243, &dest); - sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243); -} - break; - case 79: /* select ::= with selectnowith */ -{ - Select *p = yymsp[0].minor.yy243; - if( p ){ - p->pWith = yymsp[-1].minor.yy285; - parserDoubleLinkSelect(pParse, p); - }else{ - sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy285); - } - yymsp[-1].minor.yy243 = p; /*A-overwrites-W*/ -} - break; - case 80: /* selectnowith ::= selectnowith multiselect_op oneselect */ -{ - Select *pRhs = yymsp[0].minor.yy243; - Select *pLhs = yymsp[-2].minor.yy243; - 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,0); - } - if( pRhs ){ - pRhs->op = (u8)yymsp[-1].minor.yy194; - pRhs->pPrior = pLhs; - if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue; - pRhs->selFlags &= ~SF_MultiValue; - if( yymsp[-1].minor.yy194!=TK_ALL ) pParse->hasCompound = 1; - }else{ - sqlite3SelectDelete(pParse->db, pLhs); - } - yymsp[-2].minor.yy243 = pRhs; -} - break; - case 81: /* multiselect_op ::= UNION */ - case 83: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==83); -{yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-OP*/} - break; - case 82: /* multiselect_op ::= UNION ALL */ -{yymsp[-1].minor.yy194 = TK_ALL;} - break; - case 84: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */ -{ -#if SELECTTRACE_ENABLED - Token s = yymsp[-8].minor.yy0; /*A-overwrites-S*/ -#endif - yymsp[-8].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy148,yymsp[-5].minor.yy185,yymsp[-4].minor.yy72,yymsp[-3].minor.yy148,yymsp[-2].minor.yy72,yymsp[-1].minor.yy148,yymsp[-7].minor.yy194,yymsp[0].minor.yy354.pLimit,yymsp[0].minor.yy354.pOffset); -#if SELECTTRACE_ENABLED - /* Populate the Select.zSelName[] string that is used to help with - ** query planner debugging, to differentiate between multiple Select - ** objects in a complex query. - ** - ** If the SELECT keyword is immediately followed by a C-style comment - ** then extract the first few alphanumeric characters from within that - ** comment to be the zSelName value. Otherwise, the label is #N where - ** is an integer that is incremented with each SELECT statement seen. - */ - if( yymsp[-8].minor.yy243!=0 ){ - const char *z = s.z+6; - int i; - sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "#%d", - ++pParse->nSelect); - while( z[0]==' ' ) z++; - if( z[0]=='/' && z[1]=='*' ){ - z += 2; - while( z[0]==' ' ) z++; - for(i=0; sqlite3Isalnum(z[i]); i++){} - sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "%.*s", i, z); - } - } -#endif /* SELECTRACE_ENABLED */ -} - break; - case 85: /* values ::= VALUES LP nexprlist RP */ -{ - yymsp[-3].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values,0,0); -} - break; - case 86: /* values ::= values COMMA LP exprlist RP */ -{ - Select *pRight, *pLeft = yymsp[-4].minor.yy243; - pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values|SF_MultiValue,0,0); - if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue; - if( pRight ){ - pRight->op = TK_ALL; - pRight->pPrior = pLeft; - yymsp[-4].minor.yy243 = pRight; - }else{ - yymsp[-4].minor.yy243 = pLeft; - } -} - break; - case 87: /* distinct ::= DISTINCT */ -{yymsp[0].minor.yy194 = SF_Distinct;} - break; - case 88: /* distinct ::= ALL */ -{yymsp[0].minor.yy194 = SF_All;} - break; - case 90: /* sclp ::= */ - case 118: /* orderby_opt ::= */ yytestcase(yyruleno==118); - case 125: /* groupby_opt ::= */ yytestcase(yyruleno==125); - case 200: /* exprlist ::= */ yytestcase(yyruleno==200); - case 203: /* paren_exprlist ::= */ yytestcase(yyruleno==203); - case 208: /* eidlist_opt ::= */ yytestcase(yyruleno==208); -{yymsp[1].minor.yy148 = 0;} - break; - case 91: /* selcollist ::= sclp expr as */ -{ - yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy148, yymsp[-1].minor.yy190.pExpr); - if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-2].minor.yy148, &yymsp[0].minor.yy0, 1); - sqlite3ExprListSetSpan(pParse,yymsp[-2].minor.yy148,&yymsp[-1].minor.yy190); -} - break; - case 92: /* selcollist ::= sclp STAR */ -{ - Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0); - yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy148, p); -} - break; - case 93: /* selcollist ::= sclp 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[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, pDot); -} - break; - case 94: /* as ::= AS nm */ - case 105: /* dbnm ::= DOT nm */ yytestcase(yyruleno==105); - case 222: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==222); - case 223: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==223); -{yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;} - break; - case 96: /* from ::= */ -{yymsp[1].minor.yy185 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy185));} - break; - case 97: /* from ::= FROM seltablist */ -{ - yymsp[-1].minor.yy185 = yymsp[0].minor.yy185; - sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy185); -} - break; - case 98: /* stl_prefix ::= seltablist joinop */ -{ - if( ALWAYS(yymsp[-1].minor.yy185 && yymsp[-1].minor.yy185->nSrc>0) ) yymsp[-1].minor.yy185->a[yymsp[-1].minor.yy185->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy194; -} - break; - case 99: /* stl_prefix ::= */ -{yymsp[1].minor.yy185 = 0;} - break; - case 100: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */ -{ - yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); - sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy185, &yymsp[-2].minor.yy0); -} - break; - case 101: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */ -{ - yymsp[-8].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy185,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); - sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy185, yymsp[-4].minor.yy148); -} - break; - case 102: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */ -{ - yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy243,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); - } - break; - case 103: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */ -{ - if( yymsp[-6].minor.yy185==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy72==0 && yymsp[0].minor.yy254==0 ){ - yymsp[-6].minor.yy185 = yymsp[-4].minor.yy185; - }else if( yymsp[-4].minor.yy185->nSrc==1 ){ - yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); - if( yymsp[-6].minor.yy185 ){ - struct SrcList_item *pNew = &yymsp[-6].minor.yy185->a[yymsp[-6].minor.yy185->nSrc-1]; - struct SrcList_item *pOld = yymsp[-4].minor.yy185->a; - pNew->zName = pOld->zName; - pNew->zDatabase = pOld->zDatabase; - pNew->pSelect = pOld->pSelect; - pOld->zName = pOld->zDatabase = 0; - pOld->pSelect = 0; - } - sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy185); - }else{ - Select *pSubquery; - sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy185); - pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy185,0,0,0,0,SF_NestedFrom,0,0); - yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy72,yymsp[0].minor.yy254); - } - } - break; - case 104: /* dbnm ::= */ - case 113: /* indexed_opt ::= */ yytestcase(yyruleno==113); -{yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;} - break; - case 106: /* fullname ::= nm dbnm */ -{yymsp[-1].minor.yy185 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/} - break; - case 107: /* joinop ::= COMMA|JOIN */ -{ yymsp[0].minor.yy194 = JT_INNER; } - break; - case 108: /* joinop ::= JOIN_KW JOIN */ -{yymsp[-1].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/} - break; - case 109: /* joinop ::= JOIN_KW nm JOIN */ -{yymsp[-2].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/} - break; - case 110: /* joinop ::= JOIN_KW nm nm JOIN */ -{yymsp[-3].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/} - break; - case 111: /* on_opt ::= ON expr */ - case 128: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==128); - case 135: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==135); - case 196: /* case_else ::= ELSE expr */ yytestcase(yyruleno==196); -{yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr;} - break; - case 112: /* on_opt ::= */ - case 127: /* having_opt ::= */ yytestcase(yyruleno==127); - case 134: /* where_opt ::= */ yytestcase(yyruleno==134); - case 197: /* case_else ::= */ yytestcase(yyruleno==197); - case 199: /* case_operand ::= */ yytestcase(yyruleno==199); -{yymsp[1].minor.yy72 = 0;} - break; - case 114: /* indexed_opt ::= INDEXED BY nm */ -{yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;} - break; - case 115: /* indexed_opt ::= NOT INDEXED */ -{yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;} - break; - case 116: /* using_opt ::= USING LP idlist RP */ -{yymsp[-3].minor.yy254 = yymsp[-1].minor.yy254;} - break; - case 117: /* using_opt ::= */ - case 145: /* idlist_opt ::= */ yytestcase(yyruleno==145); -{yymsp[1].minor.yy254 = 0;} - break; - case 119: /* orderby_opt ::= ORDER BY sortlist */ - case 126: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==126); -{yymsp[-2].minor.yy148 = yymsp[0].minor.yy148;} - break; - case 120: /* sortlist ::= sortlist COMMA expr sortorder */ -{ - yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148,yymsp[-1].minor.yy190.pExpr); - sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy148,yymsp[0].minor.yy194); -} - break; - case 121: /* sortlist ::= expr sortorder */ -{ - yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy190.pExpr); /*A-overwrites-Y*/ - sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy148,yymsp[0].minor.yy194); -} - break; - case 122: /* sortorder ::= ASC */ -{yymsp[0].minor.yy194 = SQLITE_SO_ASC;} - break; - case 123: /* sortorder ::= DESC */ -{yymsp[0].minor.yy194 = SQLITE_SO_DESC;} - break; - case 124: /* sortorder ::= */ -{yymsp[1].minor.yy194 = SQLITE_SO_UNDEFINED;} - break; - case 129: /* limit_opt ::= */ -{yymsp[1].minor.yy354.pLimit = 0; yymsp[1].minor.yy354.pOffset = 0;} - break; - case 130: /* limit_opt ::= LIMIT expr */ -{yymsp[-1].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr; yymsp[-1].minor.yy354.pOffset = 0;} - break; - case 131: /* limit_opt ::= LIMIT expr OFFSET expr */ -{yymsp[-3].minor.yy354.pLimit = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pOffset = yymsp[0].minor.yy190.pExpr;} - break; - case 132: /* limit_opt ::= LIMIT expr COMMA expr */ -{yymsp[-3].minor.yy354.pOffset = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr;} - break; - case 133: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */ -{ - sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1); - sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy185, &yymsp[-1].minor.yy0); - sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy185,yymsp[0].minor.yy72); -} - break; - case 136: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */ -{ - sqlite3WithPush(pParse, yymsp[-7].minor.yy285, 1); - sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy185, &yymsp[-3].minor.yy0); - sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy148,"set list"); - sqlite3Update(pParse,yymsp[-4].minor.yy185,yymsp[-1].minor.yy148,yymsp[0].minor.yy72,yymsp[-5].minor.yy194); -} - break; - case 137: /* setlist ::= setlist COMMA nm EQ expr */ -{ - yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr); - sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, 1); -} - break; - case 138: /* setlist ::= setlist COMMA LP idlist RP EQ expr */ -{ - yymsp[-6].minor.yy148 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy148, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr); -} - break; - case 139: /* setlist ::= nm EQ expr */ -{ - yylhsminor.yy148 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy190.pExpr); - sqlite3ExprListSetName(pParse, yylhsminor.yy148, &yymsp[-2].minor.yy0, 1); -} - yymsp[-2].minor.yy148 = yylhsminor.yy148; - break; - case 140: /* setlist ::= LP idlist RP EQ expr */ -{ - yymsp[-4].minor.yy148 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr); -} - break; - case 141: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */ -{ - sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1); - sqlite3Insert(pParse, yymsp[-2].minor.yy185, yymsp[0].minor.yy243, yymsp[-1].minor.yy254, yymsp[-4].minor.yy194); -} - break; - case 142: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */ -{ - sqlite3WithPush(pParse, yymsp[-6].minor.yy285, 1); - sqlite3Insert(pParse, yymsp[-3].minor.yy185, 0, yymsp[-2].minor.yy254, yymsp[-5].minor.yy194); -} - break; - case 146: /* idlist_opt ::= LP idlist RP */ -{yymsp[-2].minor.yy254 = yymsp[-1].minor.yy254;} - break; - case 147: /* idlist ::= idlist COMMA nm */ -{yymsp[-2].minor.yy254 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy254,&yymsp[0].minor.yy0);} - break; - case 148: /* idlist ::= nm */ -{yymsp[0].minor.yy254 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/} - break; - case 149: /* expr ::= LP expr RP */ -{spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/ yymsp[-2].minor.yy190.pExpr = yymsp[-1].minor.yy190.pExpr;} - break; - case 150: /* expr ::= ID|INDEXED */ - case 151: /* expr ::= JOIN_KW */ yytestcase(yyruleno==151); -{spanExpr(&yymsp[0].minor.yy190,pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/} - break; - case 152: /* 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); - spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ - yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2); -} - break; - case 153: /* 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); - spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ - yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4); -} - break; - case 154: /* term ::= NULL|FLOAT|BLOB */ - case 155: /* term ::= STRING */ yytestcase(yyruleno==155); -{spanExpr(&yymsp[0].minor.yy190,pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/} - break; - case 156: /* term ::= INTEGER */ -{ - yylhsminor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1); - yylhsminor.yy190.zStart = yymsp[0].minor.yy0.z; - yylhsminor.yy190.zEnd = yymsp[0].minor.yy0.z + yymsp[0].minor.yy0.n; -} - yymsp[0].minor.yy190 = yylhsminor.yy190; - break; - case 157: /* expr ::= VARIABLE */ -{ - if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){ - u32 n = yymsp[0].minor.yy0.n; - spanExpr(&yymsp[0].minor.yy190, pParse, TK_VARIABLE, yymsp[0].minor.yy0); - sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy190.pExpr, 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 ); - spanSet(&yymsp[0].minor.yy190, &t, &t); - if( pParse->nested==0 ){ - sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t); - yymsp[0].minor.yy190.pExpr = 0; - }else{ - yymsp[0].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0); - if( yymsp[0].minor.yy190.pExpr ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy190.pExpr->iTable); - } - } -} - break; - case 158: /* expr ::= expr COLLATE ID|STRING */ -{ - yymsp[-2].minor.yy190.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy190.pExpr, &yymsp[0].minor.yy0, 1); - yymsp[-2].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; -} - break; - case 159: /* expr ::= CAST LP expr AS typetoken RP */ -{ - spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ - yymsp[-5].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1); - sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, 0); -} - break; - case 160: /* expr ::= ID|INDEXED LP distinct exprlist RP */ -{ - if( yymsp[-1].minor.yy148 && yymsp[-1].minor.yy148->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){ - sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0); - } - yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy148, &yymsp[-4].minor.yy0); - spanSet(&yylhsminor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); - if( yymsp[-2].minor.yy194==SF_Distinct && yylhsminor.yy190.pExpr ){ - yylhsminor.yy190.pExpr->flags |= EP_Distinct; - } -} - yymsp[-4].minor.yy190 = yylhsminor.yy190; - break; - case 161: /* expr ::= ID|INDEXED LP STAR RP */ -{ - yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0); - spanSet(&yylhsminor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); -} - yymsp[-3].minor.yy190 = yylhsminor.yy190; - break; - case 162: /* term ::= CTIME_KW */ -{ - yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0); - spanSet(&yylhsminor.yy190, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0); -} - yymsp[0].minor.yy190 = yylhsminor.yy190; - break; - case 163: /* expr ::= LP nexprlist COMMA expr RP */ -{ - ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy148, yymsp[-1].minor.yy190.pExpr); - yylhsminor.yy190.pExpr = sqlite3PExpr(pParse, TK_VECTOR, 0, 0); - if( yylhsminor.yy190.pExpr ){ - yylhsminor.yy190.pExpr->x.pList = pList; - spanSet(&yylhsminor.yy190, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0); - }else{ - sqlite3ExprListDelete(pParse->db, pList); - } -} - yymsp[-4].minor.yy190 = yylhsminor.yy190; - break; - case 164: /* expr ::= expr AND expr */ - case 165: /* expr ::= expr OR expr */ yytestcase(yyruleno==165); - case 166: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==166); - case 167: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==167); - case 168: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==168); - case 169: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==169); - case 170: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==170); - case 171: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==171); -{spanBinaryExpr(pParse,yymsp[-1].major,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);} - break; - case 172: /* 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 173: /* 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.yy190.pExpr); - pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy190.pExpr); - yymsp[-2].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0); - exprNot(pParse, bNot, &yymsp[-2].minor.yy190); - yymsp[-2].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd; - if( yymsp[-2].minor.yy190.pExpr ) yymsp[-2].minor.yy190.pExpr->flags |= EP_InfixFunc; -} - break; - case 174: /* 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.yy190.pExpr); - pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy190.pExpr); - pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr); - yymsp[-4].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0); - exprNot(pParse, bNot, &yymsp[-4].minor.yy190); - yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd; - if( yymsp[-4].minor.yy190.pExpr ) yymsp[-4].minor.yy190.pExpr->flags |= EP_InfixFunc; -} - break; - case 175: /* expr ::= expr ISNULL|NOTNULL */ -{spanUnaryPostfix(pParse,yymsp[0].major,&yymsp[-1].minor.yy190,&yymsp[0].minor.yy0);} - break; - case 176: /* expr ::= expr NOT NULL */ -{spanUnaryPostfix(pParse,TK_NOTNULL,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy0);} - break; - case 177: /* expr ::= expr IS expr */ -{ - spanBinaryExpr(pParse,TK_IS,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190); - binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-2].minor.yy190.pExpr, TK_ISNULL); -} - break; - case 178: /* expr ::= expr IS NOT expr */ -{ - spanBinaryExpr(pParse,TK_ISNOT,&yymsp[-3].minor.yy190,&yymsp[0].minor.yy190); - binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, TK_NOTNULL); -} - break; - case 179: /* expr ::= NOT expr */ - case 180: /* expr ::= BITNOT expr */ yytestcase(yyruleno==180); -{spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,yymsp[-1].major,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/} - break; - case 181: /* expr ::= MINUS expr */ -{spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UMINUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/} - break; - case 182: /* expr ::= PLUS expr */ -{spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UPLUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/} - break; - case 183: /* between_op ::= BETWEEN */ - case 186: /* in_op ::= IN */ yytestcase(yyruleno==186); -{yymsp[0].minor.yy194 = 0;} - break; - case 185: /* expr ::= expr between_op expr AND expr */ -{ - ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr); - pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr); - yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy190.pExpr, 0); - if( yymsp[-4].minor.yy190.pExpr ){ - yymsp[-4].minor.yy190.pExpr->x.pList = pList; - }else{ - sqlite3ExprListDelete(pParse->db, pList); - } - exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190); - yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd; -} - break; - case 188: /* expr ::= expr in_op LP exprlist RP */ -{ - if( yymsp[-1].minor.yy148==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. - */ - sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy190.pExpr); - yymsp[-4].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[yymsp[-3].minor.yy194],1); - }else if( yymsp[-1].minor.yy148->nExpr==1 ){ - /* Expressions of the form: - ** - ** expr1 IN (?1) - ** expr1 NOT IN (?2) - ** - ** with exactly one value on the RHS can be simplified to something - ** like this: - ** - ** expr1 == ?1 - ** expr1 <> ?2 - ** - ** But, the RHS of the == or <> is marked with the EP_Generic flag - ** so that it may not contribute to the computation of comparison - ** affinity or the collating sequence to use for comparison. Otherwise, - ** the semantics would be subtly different from IN or NOT IN. - */ - Expr *pRHS = yymsp[-1].minor.yy148->a[0].pExpr; - yymsp[-1].minor.yy148->a[0].pExpr = 0; - sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148); - /* pRHS cannot be NULL because a malloc error would have been detected - ** before now and control would have never reached this point */ - if( ALWAYS(pRHS) ){ - pRHS->flags &= ~EP_Collate; - pRHS->flags |= EP_Generic; - } - yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy194 ? TK_NE : TK_EQ, yymsp[-4].minor.yy190.pExpr, pRHS); - }else{ - yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0); - if( yymsp[-4].minor.yy190.pExpr ){ - yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy148; - sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr); - }else{ - sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148); - } - exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190); - } - yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; - } - break; - case 189: /* expr ::= LP select RP */ -{ - spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/ - yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0); - sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy190.pExpr, yymsp[-1].minor.yy243); - } - break; - case 190: /* expr ::= expr in_op LP select RP */ -{ - yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0); - sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, yymsp[-1].minor.yy243); - exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190); - yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n]; - } - break; - case 191: /* expr ::= expr in_op nm dbnm paren_exprlist */ -{ - SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); - Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0); - if( yymsp[0].minor.yy148 ) sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy148); - yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0); - sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, pSelect); - exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190); - yymsp[-4].minor.yy190.zEnd = yymsp[-1].minor.yy0.z ? &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n] : &yymsp[-2].minor.yy0.z[yymsp[-2].minor.yy0.n]; - } - break; - case 192: /* expr ::= EXISTS LP select RP */ -{ - Expr *p; - spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/ - p = yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0); - sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy243); - } - break; - case 193: /* expr ::= CASE case_operand case_exprlist case_else END */ -{ - spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-C*/ - yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy72, 0); - if( yymsp[-4].minor.yy190.pExpr ){ - yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy72 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[-1].minor.yy72) : yymsp[-2].minor.yy148; - sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr); - }else{ - sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy148); - sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy72); - } -} - break; - case 194: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */ -{ - yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[-2].minor.yy190.pExpr); - yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr); -} - break; - case 195: /* case_exprlist ::= WHEN expr THEN expr */ -{ - yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr); - yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, yymsp[0].minor.yy190.pExpr); -} - break; - case 198: /* case_operand ::= expr */ -{yymsp[0].minor.yy72 = yymsp[0].minor.yy190.pExpr; /*A-overwrites-X*/} - break; - case 201: /* nexprlist ::= nexprlist COMMA expr */ -{yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[0].minor.yy190.pExpr);} - break; - case 202: /* nexprlist ::= expr */ -{yymsp[0].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy190.pExpr); /*A-overwrites-Y*/} - break; - case 204: /* paren_exprlist ::= LP exprlist RP */ - case 209: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==209); -{yymsp[-2].minor.yy148 = yymsp[-1].minor.yy148;} - break; - case 205: /* 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->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy148, yymsp[-10].minor.yy194, - &yymsp[-11].minor.yy0, yymsp[0].minor.yy72, SQLITE_SO_ASC, yymsp[-8].minor.yy194, SQLITE_IDXTYPE_APPDEF); -} - break; - case 206: /* uniqueflag ::= UNIQUE */ - case 246: /* raisetype ::= ABORT */ yytestcase(yyruleno==246); -{yymsp[0].minor.yy194 = OE_Abort;} - break; - case 207: /* uniqueflag ::= */ -{yymsp[1].minor.yy194 = OE_None;} - break; - case 210: /* eidlist ::= eidlist COMMA nm collate sortorder */ -{ - yymsp[-4].minor.yy148 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194); -} - break; - case 211: /* eidlist ::= nm collate sortorder */ -{ - yymsp[-2].minor.yy148 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194); /*A-overwrites-Y*/ -} - break; - case 214: /* cmd ::= DROP INDEX ifexists fullname */ -{sqlite3DropIndex(pParse, yymsp[0].minor.yy185, yymsp[-1].minor.yy194);} - break; - case 215: /* cmd ::= VACUUM */ -{sqlite3Vacuum(pParse,0);} - break; - case 216: /* cmd ::= VACUUM nm */ -{sqlite3Vacuum(pParse,&yymsp[0].minor.yy0);} - break; - case 217: /* cmd ::= PRAGMA nm dbnm */ -{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);} - break; - case 218: /* cmd ::= PRAGMA nm dbnm EQ nmnum */ -{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);} - break; - case 219: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */ -{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);} - break; - case 220: /* cmd ::= PRAGMA nm dbnm EQ minus_num */ -{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);} - break; - case 221: /* 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 224: /* 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.yy145, &all); -} - break; - case 225: /* 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.yy194, yymsp[-4].minor.yy332.a, yymsp[-4].minor.yy332.b, yymsp[-2].minor.yy185, yymsp[0].minor.yy72, yymsp[-10].minor.yy194, yymsp[-8].minor.yy194); - yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/ -} - break; - case 226: /* trigger_time ::= BEFORE|AFTER */ -{ yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-X*/ } - break; - case 227: /* trigger_time ::= INSTEAD OF */ -{ yymsp[-1].minor.yy194 = TK_INSTEAD;} - break; - case 228: /* trigger_time ::= */ -{ yymsp[1].minor.yy194 = TK_BEFORE; } - break; - case 229: /* trigger_event ::= DELETE|INSERT */ - case 230: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==230); -{yymsp[0].minor.yy332.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy332.b = 0;} - break; - case 231: /* trigger_event ::= UPDATE OF idlist */ -{yymsp[-2].minor.yy332.a = TK_UPDATE; yymsp[-2].minor.yy332.b = yymsp[0].minor.yy254;} - break; - case 232: /* when_clause ::= */ - case 251: /* key_opt ::= */ yytestcase(yyruleno==251); -{ yymsp[1].minor.yy72 = 0; } - break; - case 233: /* when_clause ::= WHEN expr */ - case 252: /* key_opt ::= KEY expr */ yytestcase(yyruleno==252); -{ yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr; } - break; - case 234: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */ -{ - assert( yymsp[-2].minor.yy145!=0 ); - yymsp[-2].minor.yy145->pLast->pNext = yymsp[-1].minor.yy145; - yymsp[-2].minor.yy145->pLast = yymsp[-1].minor.yy145; -} - break; - case 235: /* trigger_cmd_list ::= trigger_cmd SEMI */ -{ - assert( yymsp[-1].minor.yy145!=0 ); - yymsp[-1].minor.yy145->pLast = yymsp[-1].minor.yy145; -} - break; - case 236: /* 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 237: /* tridxby ::= INDEXED BY nm */ -{ - sqlite3ErrorMsg(pParse, - "the INDEXED BY clause is not allowed on UPDATE or DELETE statements " - "within triggers"); -} - break; - case 238: /* tridxby ::= NOT INDEXED */ -{ - sqlite3ErrorMsg(pParse, - "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements " - "within triggers"); -} - break; - case 239: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */ -{yymsp[-6].minor.yy145 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy148, yymsp[0].minor.yy72, yymsp[-5].minor.yy194);} - break; - case 240: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */ -{yymsp[-4].minor.yy145 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy254, yymsp[0].minor.yy243, yymsp[-4].minor.yy194);/*A-overwrites-R*/} - break; - case 241: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */ -{yymsp[-4].minor.yy145 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy72);} - break; - case 242: /* trigger_cmd ::= select */ -{yymsp[0].minor.yy145 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy243); /*A-overwrites-X*/} - break; - case 243: /* expr ::= RAISE LP IGNORE RP */ -{ - spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ - yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0); - if( yymsp[-3].minor.yy190.pExpr ){ - yymsp[-3].minor.yy190.pExpr->affinity = OE_Ignore; - } -} - break; - case 244: /* expr ::= RAISE LP raisetype COMMA nm RP */ -{ - spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/ - yymsp[-5].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1); - if( yymsp[-5].minor.yy190.pExpr ) { - yymsp[-5].minor.yy190.pExpr->affinity = (char)yymsp[-3].minor.yy194; - } -} - break; - case 245: /* raisetype ::= ROLLBACK */ -{yymsp[0].minor.yy194 = OE_Rollback;} - break; - case 247: /* raisetype ::= FAIL */ -{yymsp[0].minor.yy194 = OE_Fail;} - break; - case 248: /* cmd ::= DROP TRIGGER ifexists fullname */ -{ - sqlite3DropTrigger(pParse,yymsp[0].minor.yy185,yymsp[-1].minor.yy194); -} - break; - case 249: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ -{ - sqlite3Attach(pParse, yymsp[-3].minor.yy190.pExpr, yymsp[-1].minor.yy190.pExpr, yymsp[0].minor.yy72); -} - break; - case 250: /* cmd ::= DETACH database_kw_opt expr */ -{ - sqlite3Detach(pParse, yymsp[0].minor.yy190.pExpr); -} - break; - case 253: /* cmd ::= REINDEX */ -{sqlite3Reindex(pParse, 0, 0);} - break; - case 254: /* cmd ::= REINDEX nm dbnm */ -{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);} - break; - case 255: /* cmd ::= ANALYZE */ -{sqlite3Analyze(pParse, 0, 0);} - break; - case 256: /* cmd ::= ANALYZE nm dbnm */ -{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);} - break; - case 257: /* cmd ::= ALTER TABLE fullname RENAME TO nm */ -{ - sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy185,&yymsp[0].minor.yy0); -} - break; - case 258: /* 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 259: /* add_column_fullname ::= fullname */ -{ - disableLookaside(pParse); - sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy185); -} - break; - case 260: /* cmd ::= create_vtab */ -{sqlite3VtabFinishParse(pParse,0);} - break; - case 261: /* cmd ::= create_vtab LP vtabarglist RP */ -{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);} - break; - case 262: /* 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.yy194); -} - break; - case 263: /* vtabarg ::= */ -{sqlite3VtabArgInit(pParse);} - break; - case 264: /* vtabargtoken ::= ANY */ - case 265: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==265); - case 266: /* lp ::= LP */ yytestcase(yyruleno==266); -{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);} - break; - case 267: /* with ::= */ -{yymsp[1].minor.yy285 = 0;} - break; - case 268: /* with ::= WITH wqlist */ -{ yymsp[-1].minor.yy285 = yymsp[0].minor.yy285; } - break; - case 269: /* with ::= WITH RECURSIVE wqlist */ -{ yymsp[-2].minor.yy285 = yymsp[0].minor.yy285; } - break; - case 270: /* wqlist ::= nm eidlist_opt AS LP select RP */ -{ - yymsp[-5].minor.yy285 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243); /*A-overwrites-X*/ -} - break; - case 271: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */ -{ - yymsp[-7].minor.yy285 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy285, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243); -} - break; - default: - /* (272) input ::= cmdlist */ yytestcase(yyruleno==272); - /* (273) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==273); - /* (274) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=274); - /* (275) ecmd ::= SEMI */ yytestcase(yyruleno==275); - /* (276) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==276); - /* (277) explain ::= */ yytestcase(yyruleno==277); - /* (278) trans_opt ::= */ yytestcase(yyruleno==278); - /* (279) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==279); - /* (280) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==280); - /* (281) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==281); - /* (282) savepoint_opt ::= */ yytestcase(yyruleno==282); - /* (283) cmd ::= create_table create_table_args */ yytestcase(yyruleno==283); - /* (284) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==284); - /* (285) columnlist ::= columnname carglist */ yytestcase(yyruleno==285); - /* (286) nm ::= ID|INDEXED */ yytestcase(yyruleno==286); - /* (287) nm ::= STRING */ yytestcase(yyruleno==287); - /* (288) nm ::= JOIN_KW */ yytestcase(yyruleno==288); - /* (289) typetoken ::= typename */ yytestcase(yyruleno==289); - /* (290) typename ::= ID|STRING */ yytestcase(yyruleno==290); - /* (291) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=291); - /* (292) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=292); - /* (293) carglist ::= carglist ccons */ yytestcase(yyruleno==293); - /* (294) carglist ::= */ yytestcase(yyruleno==294); - /* (295) ccons ::= NULL onconf */ yytestcase(yyruleno==295); - /* (296) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==296); - /* (297) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==297); - /* (298) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=298); - /* (299) tconscomma ::= */ yytestcase(yyruleno==299); - /* (300) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=300); - /* (301) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=301); - /* (302) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=302); - /* (303) oneselect ::= values */ yytestcase(yyruleno==303); - /* (304) sclp ::= selcollist COMMA */ yytestcase(yyruleno==304); - /* (305) as ::= ID|STRING */ yytestcase(yyruleno==305); - /* (306) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=306); - /* (307) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==307); - /* (308) exprlist ::= nexprlist */ yytestcase(yyruleno==308); - /* (309) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=309); - /* (310) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=310); - /* (311) nmnum ::= ON */ yytestcase(yyruleno==311); - /* (312) nmnum ::= DELETE */ yytestcase(yyruleno==312); - /* (313) nmnum ::= DEFAULT */ yytestcase(yyruleno==313); - /* (314) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==314); - /* (315) foreach_clause ::= */ yytestcase(yyruleno==315); - /* (316) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==316); - /* (317) trnm ::= nm */ yytestcase(yyruleno==317); - /* (318) tridxby ::= */ yytestcase(yyruleno==318); - /* (319) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==319); - /* (320) database_kw_opt ::= */ yytestcase(yyruleno==320); - /* (321) kwcolumn_opt ::= */ yytestcase(yyruleno==321); - /* (322) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==322); - /* (323) vtabarglist ::= vtabarg */ yytestcase(yyruleno==323); - /* (324) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==324); - /* (325) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==325); - /* (326) anylist ::= */ yytestcase(yyruleno==326); - /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327); - /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328); - 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 ); - - if( yyact==YY_ACCEPT_ACTION ){ - yypParser->yytos += yysize; - yy_accept(yypParser); - }else{ - yymsp += yysize+1; - yypParser->yytos = yymsp; - yymsp->stateno = (YYACTIONTYPE)yyact; - yymsp->major = (YYCODETYPE)yygoto; - yyTraceShift(yypParser, yyact); - } -} - -/* -** The following code executes when the parse fails -*/ -#ifndef YYNOERRORRECOVERY -static void yy_parse_failed( - yyParser *yypParser /* The parser */ -){ - sqlite3ParserARG_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 */ -} -#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; -#define TOKEN yyminor -/************ Begin %syntax_error code ****************************************/ - - UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */ - assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */ - sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN); -/************ End %syntax_error code ******************************************/ - sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ -} - -/* -** The following is executed when the parser accepts -*/ -static void yy_accept( - yyParser *yypParser /* The parser */ -){ - sqlite3ParserARG_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 */ -} - -/* 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; - unsigned int 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; /* The parser */ - - yypParser = (yyParser*)yyp; - assert( yypParser->yytos!=0 ); -#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY) - yyendofinput = (yymajor==0); -#endif - sqlite3ParserARG_STORE; - -#ifndef NDEBUG - if( yyTraceFILE ){ - fprintf(yyTraceFILE,"%sInput '%s'\n",yyTracePrompt,yyTokenName[yymajor]); - } -#endif - - do{ - yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor); - if( yyact <= YY_MAX_SHIFTREDUCE ){ - yy_shift(yypParser,yyact,yymajor,yyminor); -#ifndef YYNOERRORRECOVERY - yypParser->yyerrcnt--; -#endif - yymajor = YYNOCODE; - }else if( yyact <= YY_MAX_REDUCE ){ - yy_reduce(yypParser,yyact-YY_MIN_REDUCE); - }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 - && yymx != YYERRORSYMBOL - && (yyact = yy_find_reduce_action( - yypParser->yytos->stateno, - YYERRORSYMBOL)) >= YY_MIN_REDUCE - ){ - 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; -#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); - yymajor = YYNOCODE; - -#else /* YYERRORSYMBOL is not defined */ - /* This is what we do if the grammar does not define ERROR: - ** - ** * Report an error message, and throw away the input token. - ** - ** * If the input token is $, then fail the parse. - ** - ** As before, subsequent error messages are suppressed until - ** three input tokens have been successfully shifted. - */ - if( yypParser->yyerrcnt<=0 ){ - yy_syntax_error(yypParser,yymajor, yyminor); - } - yypParser->yyerrcnt = 3; - yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); - if( yyendofinput ){ - yy_parse_failed(yypParser); -#ifndef YYNOERRORRECOVERY - yypParser->yyerrcnt = -1; -#endif - } - yymajor = YYNOCODE; -#endif - } - }while( yymajor!=YYNOCODE && 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; -} - -/************** 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 */ - -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 */ 27, 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: 182 */ -/* zKWText[] encodes 834 bytes of keyword text in 554 bytes */ -/* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */ -/* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */ -/* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */ -/* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */ -/* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */ -/* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */ -/* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */ -/* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */ -/* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */ -/* VACUUMVIEWINITIALLY */ -static const char zKWText[553] = { - 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H', - 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G', - 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A', - 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F', - 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N', - 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I', - 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E', - 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E', - 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T', - 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q', - 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S', - 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A', - 'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E', - 'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A', - 'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A', - 'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A', - 'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J', - 'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L', - 'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E', - 'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H', - 'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E', - 'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E', - 'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M', - 'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R', - 'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A', - 'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D', - 'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O', - 'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T', - 'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R', - 'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M', - 'V','I','E','W','I','N','I','T','I','A','L','L','Y', -}; -/* aKWHash[i] is the hash value for the i-th keyword */ -static const unsigned char aKWHash[127] = { - 76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0, - 42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0, - 121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71, - 0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44, - 0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25, - 96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0, - 100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14, - 39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113, - 62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0, - 29, 0, 86, 63, 64, 0, 20, 61, 0, 56, -}; -/* 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[124] = { - 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0, - 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50, - 0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38, - 0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0, - 0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34, - 10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8, - 0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37, - 73, 83, 0, 35, 68, 0, 0, -}; -/* aKWLen[i] is the length (in bytes) of the i-th keyword */ -static const unsigned char aKWLen[124] = { - 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6, - 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6, - 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10, - 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7, - 6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4, - 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4, - 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7, - 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8, - 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8, - 3, 5, 5, 6, 4, 9, 3, -}; -/* aKWOffset[i] is the index into zKWText[] of the start of -** the text for the i-th keyword. */ -static const unsigned short int aKWOffset[124] = { - 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33, - 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81, - 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152, - 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192, - 199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246, - 250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318, - 320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380, - 387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459, - 460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513, - 521, 524, 529, 534, 540, 544, 549, -}; -/* aKWCode[i] is the parser symbol code for the i-th keyword */ -static const unsigned char aKWCode[124] = { - TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE, - TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN, - TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD, - TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE, - TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE, - TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW, - TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT, - TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO, - TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP, - TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH, - TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP, - TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN, - TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW, - TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE, - TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN, - TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA, - TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN, - TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND, - TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST, - TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW, - TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS, - TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW, - TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT, - TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING, - TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL, -}; -/* 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; - j = 0; - zKW = &zKWText[aKWOffset[i]]; -#ifdef SQLITE_ASCII - while( j=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) -#endif - -/* Make the IdChar function accessible from ctime.c */ -#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS -SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); } -#endif - - -/* -** 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 */ - } - 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 */ - } - case CC_ID: { - i = 1; - break; - } - 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 - - assert( zSql!=0 ); - mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH]; - if( db->nVdbeActive==0 ){ - db->u1.isInterrupted = 0; - } - pParse->rc = SQLITE_OK; - pParse->zTail = zSql; - assert( pzErrMsg!=0 ); - /* sqlite3ParserTrace(stdout, "parser: "); */ -#ifdef sqlite3Parser_ENGINEALWAYSONSTACK - pEngine = &sEngine; - sqlite3ParserInit(pEngine); -#else - pEngine = sqlite3ParserAlloc(sqlite3Malloc); - 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 ); - while( 1 ){ - if( zSql[0]!=0 ){ - n = sqlite3GetToken((u8*)zSql, &tokenType); - mxSqlLen -= n; - if( mxSqlLen<0 ){ - pParse->rc = SQLITE_TOOBIG; - break; - } - }else{ - /* 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; - } - zSql -= n; - } - if( tokenType>=TK_SPACE ){ - assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL ); - if( db->u1.isInterrupted ){ - pParse->rc = SQLITE_INTERRUPT; - break; - } - if( tokenType==TK_ILLEGAL ){ - sqlite3ErrorMsg(pParse, "unrecognized token: \"%.*s\"", n, zSql); - break; - } - zSql += n; - }else{ - pParse->sLastToken.z = zSql; - pParse->sLastToken.n = n; - sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse); - lastTokenParsed = tokenType; - zSql += n; - if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break; - } - } - assert( nErr==0 ); - pParse->zTail = zSql; -#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", *pzErrMsg); - pParse->zErrMsg = 0; - nErr++; - } - 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_DECLARE_VTAB ){ - /* 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( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree); - sqlite3DeleteTrigger(db, pParse->pNewTrigger); - 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); - } - assert( nErr==0 || pParse->rc!=SQLITE_OK ); - return nErr; -} - -/************** 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" */ - -#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 -#ifdef SQLITE_ENABLE_ICU -/************** 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 -#ifdef SQLITE_ENABLE_JSON1 -SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*); -#endif -#ifdef SQLITE_ENABLE_STMTVTAB -SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3*); -#endif -#ifdef SQLITE_ENABLE_FTS5 -SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*); -#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 *pMaster; ) /* 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 ) 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_MASTER mutex. Note that - ** MutexAlloc() is called for a static mutex prior to initializing the - ** malloc subsystem - this implies that the allocation of a static - ** mutex must not require support from the malloc subsystem. - */ - MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) - sqlite3_mutex_enter(pMaster); - 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(pMaster); - - /* If rc is not SQLITE_OK at this point, then either the malloc - ** subsystem could not be initialized or the system failed to allocate - ** the pInitMutex mutex. Return an error in either case. */ - if( rc!=SQLITE_OK ){ - return rc; - } - - /* Do the rest of the initialization under the recursive mutex so - ** that we will be able to handle recursive calls into - ** sqlite3_initialize(). The recursive calls normally come through - ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other - ** recursive calls might also be possible. - ** - ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls - ** to the xInit method, so the xInit method need not be threadsafe. - ** - ** The following mutex is what serializes access to the appdef pcache xInit - ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the - ** call to sqlite3PcacheInitialize(). - */ - sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex); - 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(); - } - if( rc==SQLITE_OK ){ - sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, - sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage); - 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(pMaster); - sqlite3GlobalConfig.nRefInitMutex--; - if( sqlite3GlobalConfig.nRefInitMutex<=0 ){ - assert( sqlite3GlobalConfig.nRefInitMutex==0 ); - sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex); - sqlite3GlobalConfig.pInitMutex = 0; - } - sqlite3_mutex_leave(pMaster); - - /* The following is just a sanity check to make sure SQLite has - ** been compiled correctly. It is important to run this code, but - ** we don't want to run it too often and soak up CPU cycles for no - ** reason. So we run it once during initialization. - */ -#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; - } - - 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; - - 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( sz*cnt ); /* IMP: R-61949-35727 */ - sqlite3EndBenignMalloc(); - if( pStart ) cnt = sqlite3MallocSize(pStart)/sz; - }else{ - pStart = pBuf; - } - db->lookaside.pStart = pStart; - db->lookaside.pInit = 0; - db->lookaside.pFree = 0; - db->lookaside.sz = (u16)sz; - if( pStart ){ - int i; - LookasideSlot *p; - assert( sz > (int)sizeof(LookasideSlot*) ); - db->lookaside.nSlot = cnt; - p = (LookasideSlot*)pStart; - for(i=cnt-1; i>=0; i--){ - p->pNext = db->lookaside.pInit; - db->lookaside.pInit = p; - p = (LookasideSlot*)&((u8*)p)[sz]; - } - db->lookaside.pEnd = p; - db->lookaside.bDisable = 0; - db->lookaside.bMalloced = pBuf==0 ?1:0; - }else{ - db->lookaside.pStart = db; - db->lookaside.pEnd = db; - db->lookaside.bDisable = 1; - db->lookaside.bMalloced = 0; - db->lookaside.nSlot = 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_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 }, - }; - 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 &= ~aFlagOp[i].mask; - } - if( oldFlags!=db->flags ){ - sqlite3ExpirePreparedStatements(db); - } - if( pRes ){ - *pRes = (db->flags & aFlagOp[i].mask)!=0; - } - rc = SQLITE_OK; - break; - } - } - break; - } - } - va_end(ap); - return rc; -} - - -/* -** Return true if the buffer z[0..n-1] contains all spaces. -*/ -static int allSpaces(const char *z, int n){ - while( n>0 && z[n-1]==' ' ){ n--; } - return n==0; -} - -/* -** This is the default collating function named "BINARY" which is always -** available. -** -** If the padFlag argument is not NULL then space padding at the end -** of strings is ignored. This implements the RTRIM collation. -*/ -static int binCollFunc( - void *padFlag, - int nKey1, const void *pKey1, - int nKey2, const void *pKey2 -){ - int rc, n; - n = 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( db->aDb[i].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->xTrace(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); - if( pMod->xDestroy ){ - pMod->xDestroy(pMod->pAux); - } - sqlite3VtabEponymousTableClear(db, pMod); - sqlite3DbFree(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( (db->mDbFlags&DBFLAG_SchemaChange)!=0 && db->init.busy==0 ){ - sqlite3ExpirePreparedStatements(db); - sqlite3ResetAllSchemasOfConnection(db); - } - sqlite3BtreeLeaveAll(db); - - /* Any deferred constraint violations have now been resolved. */ - db->nDeferredCons = 0; - db->nDeferredImmCons = 0; - db->flags &= ~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_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_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break; - case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break; - case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; 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_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", - }; - const char *zErr = "unknown error"; - switch( rc ){ - case SQLITE_ABORT_ROLLBACK: { - zErr = "abort due to ROLLBACK"; - 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 > timeout ){ - delay = timeout - prior; - if( delay<=0 ) return 0; - } - sqlite3OsSleep(db->pVfs, delay*1000); - return 1; -#else - sqlite3 *db = (sqlite3 *)ptr; - int timeout = ((sqlite3 *)ptr)->busyTimeout; - if( (count+1)*1000 > timeout ){ - return 0; - } - sqlite3OsSleep(db->pVfs, 1000000); - return 1; -#endif -} - -/* -** Invoke the given busy handler. -** -** This routine is called when an operation failed with a lock. -** If this routine returns non-zero, the lock is retried. If it -** returns 0, the operation aborts with an SQLITE_BUSY error. -*/ -SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){ - int rc; - if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0; - rc = p->xFunc(p->pArg, p->nBusy); - if( rc==0 ){ - p->nBusy = -1; - }else{ - p->nBusy++; - } - return rc; -} - -/* -** This routine sets the busy callback for an Sqlite database to the -** given callback function with the given argument. -*/ -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.xFunc = xBusy; - db->busyHandler.pArg = 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, 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 - 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*), - FuncDestructor *pDestructor -){ - FuncDef *p; - int nName; - int extraFlags; - - assert( sqlite3_mutex_held(db->mutex) ); - if( zFunctionName==0 || - (xSFunc && (xFinal || xStep)) || - (!xSFunc && (xFinal && !xStep)) || - (!xSFunc && (!xFinal && xStep)) || - (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) || - (255<(nName = sqlite3Strlen30( zFunctionName))) ){ - return SQLITE_MISUSE_BKPT; - } - - assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC ); - extraFlags = enc & SQLITE_DETERMINISTIC; - enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY); - -#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, - pUserData, xSFunc, xStep, xFinal, pDestructor); - if( rc==SQLITE_OK ){ - rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags, - pUserData, xSFunc, xStep, xFinal, pDestructor); - } - if( rc!=SQLITE_OK ){ - return rc; - } - enc = SQLITE_UTF16BE; - } -#else - enc = SQLITE_UTF8; -#endif - - /* Check if an existing function is being overridden or deleted. If so, - ** and there are active VMs, then return SQLITE_BUSY. If a function - ** is being overridden/deleted but there are no active VMs, allow the - ** operation to continue but invalidate all precompiled statements. - */ - p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0); - if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==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); - } - } - - 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 ); - p->xSFunc = xSFunc ? xSFunc : xStep; - p->xFinalize = xFinal; - p->pUserData = pUserData; - p->nArg = (u16)nArg; - return SQLITE_OK; -} - -/* -** 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 sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep, - xFinal, 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 *) -){ - 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 *)sqlite3DbMallocZero(db, sizeof(FuncDestructor)); - if( !pArg ){ - xDestroy(p); - goto out; - } - pArg->xDestroy = xDestroy; - pArg->pUserData = p; - } - rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg); - if( pArg && pArg->nRef==0 ){ - assert( rc!=SQLITE_OK ); - xDestroy(p); - sqlite3DbFree(db, pArg); - } - - out: - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); - return rc; -} - -#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); - sqlite3DbFree(db, zFunc8); - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); - return rc; -} -#endif - - -/* -** Declare that a function has been overloaded by a virtual table. -** -** If the function already exists as a regular global function, then -** this routine is a no-op. If the function does not exist, then create -** a new one that always throws a run-time error. -** -** When virtual tables intend to provide an overloaded function, they -** should call this routine to make sure the global function exists. -** A global function must exist in order for name resolution to work -** properly. -*/ -SQLITE_API int sqlite3_overload_function( - sqlite3 *db, - const char *zName, - int nArg -){ - int rc = SQLITE_OK; - -#ifdef SQLITE_ENABLE_API_ARMOR - if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){ - return SQLITE_MISUSE_BKPT; - } -#endif - sqlite3_mutex_enter(db->mutex); - if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){ - rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8, - 0, sqlite3InvalidFunction, 0, 0, 0); - } - rc = sqlite3ApiExit(db, rc); - sqlite3_mutex_leave(db->mutex); - return rc; -} - -#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->xTrace = (int(*)(u32,void*,void*,void*))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->xTrace = 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; - 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 ){ - 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 = (char*)sqlite3_value_text(db->pErr); - 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); - - /* 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. It is the -** responsibility of the caller to eventually call sqlite3_free() to release -** this buffer. -** -** If an error occurs, then an SQLite error code is returned and *pzErrMsg -** may be set to point to a buffer containing an English language error -** message. It is the responsibility of the caller to eventually release -** this buffer by calling sqlite3_free(). -*/ -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+2; /* Bytes of space to allocate */ - - /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen - ** method that there may be extra parameters following the file-name. */ - flags |= SQLITE_OPEN_URI; - - for(iIn=0; iIn=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'; - zFile[iOut++] = '\0'; - zFile[iOut++] = '\0'; - - /* Check if there were any options specified that should be interpreted - ** here. Options that are interpreted here include "vfs" and those that - ** correspond to flags that may be passed to the sqlite3_open_v2() - ** method. */ - zOpt = &zFile[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+2); - if( !zFile ) return SQLITE_NOMEM_BKPT; - if( nUri ){ - memcpy(zFile, zUri, nUri); - } - zFile[nUri] = '\0'; - zFile[nUri+1] = '\0'; - 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(zFile); - zFile = 0; - } - *pFlags = flags; - *pzFile = zFile; - return rc; -} - - -/* -** This routine does the work of opening a database on behalf of -** sqlite3_open() and sqlite3_open16(). The database filename "zFilename" -** is UTF-8 encoded. -*/ -static int openDatabase( - 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() */ - -#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_MASTER_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 ){ - db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); - if( db->mutex==0 ){ - sqlite3_free(db); - db = 0; - goto opendb_out; - } - } - sqlite3_mutex_enter(db->mutex); - db->errMask = 0xff; - db->nDb = 2; - db->magic = SQLITE_MAGIC_BUSY; - db->aDb = db->aDbStatic; - - 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_CacheSpill -#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 - ; - 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, (void*)1, binCollFunc, 0); - if( db->mallocFailed ){ - goto opendb_out; - } - /* EVIDENCE-OF: R-08308-17224 The default collating function for all - ** strings is BINARY. - */ - db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0); - assert( db->pDfltColl!=0 ); - - /* 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-65497-44594 */ - }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 ) ENC(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); - -#ifdef SQLITE_ENABLE_FTS5 - /* Register any built-in FTS5 module before loading the automatic - ** extensions. This allows automatic extensions to register FTS5 - ** tokenizers and auxiliary functions. */ - if( !db->mallocFailed && rc==SQLITE_OK ){ - rc = sqlite3Fts5Init(db); - } -#endif - - /* Load automatic extensions - extensions that have been registered - ** using the sqlite3_automatic_extension() API. - */ - if( rc==SQLITE_OK ){ - sqlite3AutoLoadExtensions(db); - rc = sqlite3_errcode(db); - if( rc!=SQLITE_OK ){ - goto opendb_out; - } - } - -#ifdef SQLITE_ENABLE_FTS1 - if( !db->mallocFailed ){ - extern int sqlite3Fts1Init(sqlite3*); - rc = sqlite3Fts1Init(db); - } -#endif - -#ifdef SQLITE_ENABLE_FTS2 - if( !db->mallocFailed && rc==SQLITE_OK ){ - extern int sqlite3Fts2Init(sqlite3*); - rc = sqlite3Fts2Init(db); - } -#endif - -#ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */ - if( !db->mallocFailed && rc==SQLITE_OK ){ - rc = sqlite3Fts3Init(db); - } -#endif - -#ifdef SQLITE_ENABLE_ICU - if( !db->mallocFailed && rc==SQLITE_OK ){ - rc = sqlite3IcuInit(db); - } -#endif - -#ifdef SQLITE_ENABLE_RTREE - if( !db->mallocFailed && rc==SQLITE_OK){ - rc = sqlite3RtreeInit(db); - } -#endif - -#ifdef SQLITE_ENABLE_DBPAGE_VTAB - if( !db->mallocFailed && rc==SQLITE_OK){ - rc = sqlite3DbpageRegister(db); - } -#endif - -#ifdef SQLITE_ENABLE_DBSTAT_VTAB - if( !db->mallocFailed && rc==SQLITE_OK){ - rc = sqlite3DbstatRegister(db); - } -#endif - -#ifdef SQLITE_ENABLE_JSON1 - if( !db->mallocFailed && rc==SQLITE_OK){ - rc = sqlite3Json1Init(db); - } -#endif - -#ifdef SQLITE_ENABLE_STMTVTAB - if( !db->mallocFailed && rc==SQLITE_OK){ - rc = sqlite3StmtVtabInit(db); - } -#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 -#if defined(SQLITE_HAS_CODEC) - if( rc==SQLITE_OK ){ - const char *zKey; - if( (zKey = sqlite3_uri_parameter(zOpen, "hexkey"))!=0 && zKey[0] ){ - u8 iByte; - int i; - char zDecoded[40]; - for(i=0, iByte=0; imutex); - 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. -*/ -static int reportError(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 reportError(SQLITE_CORRUPT, lineno, "database corruption"); -} -SQLITE_PRIVATE int sqlite3MisuseError(int lineno){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - return reportError(SQLITE_MISUSE, lineno, "misuse"); -} -SQLITE_PRIVATE int sqlite3CantopenError(int lineno){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - return reportError(SQLITE_CANTOPEN, lineno, "cannot open file"); -} -#ifdef SQLITE_DEBUG -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 reportError(SQLITE_CORRUPT, lineno, zMsg); -} -SQLITE_PRIVATE int sqlite3NomemError(int lineno){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - return reportError(SQLITE_NOMEM, lineno, "OOM"); -} -SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){ - testcase( sqlite3GlobalConfig.xLog!=0 ); - return reportError(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( fd->pMethods ){ - rc = sqlite3OsFileControl(fd, op, pArg); - }else{ - rc = SQLITE_NOTFOUND; - } - 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; - } - - /* - ** Reset the PRNG back to its uninitialized state. The next call - ** to sqlite3_randomness() will reseed the PRNG using a single call - ** to the xRandomness method of the default VFS. - */ - case SQLITE_TESTCTRL_PRNG_RESET: { - sqlite3_randomness(0,0); - break; - } - - /* - ** sqlite3_test_control(BITVEC_TEST, size, program) - ** - ** Run a test against a Bitvec object of size. The program argument - ** is an array of integers that defines the test. Return -1 on a - ** memory allocation error, 0 on success, or non-zero for an error. - ** See the sqlite3BitvecBuiltinTest() for additional information. - */ - case SQLITE_TESTCTRL_BITVEC_TEST: { - int sz = va_arg(ap, 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_RESERVE, sqlite3 *db, int N) - ** - ** Set the nReserve size to N for the main database on the database - ** connection db. - */ - case SQLITE_TESTCTRL_RESERVE: { - sqlite3 *db = va_arg(ap, sqlite3*); - int x = va_arg(ap,int); - sqlite3_mutex_enter(db->mutex); - sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0); - sqlite3_mutex_leave(db->mutex); - break; - } - - /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N) - ** - ** Enable or disable various optimizations for testing purposes. The - ** argument N is a bitmask of optimizations to be disabled. For normal - ** operation N should be 0. The idea is that a test program (like the - ** SQL Logic Test or SLT test module) can run the same SQL multiple times - ** with various optimizations disabled to verify that the same answer - ** is obtained in every case. - */ - case SQLITE_TESTCTRL_OPTIMIZATIONS: { - sqlite3 *db = va_arg(ap, sqlite3*); - db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff); - break; - } - -#ifdef SQLITE_N_KEYWORD - /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord) - ** - ** If zWord is a keyword recognized by the parser, then return the - ** number of keywords. Or if zWord is not a keyword, return 0. - ** - ** This test feature is only available in the amalgamation since - ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite - ** is built using separate source files. - */ - case SQLITE_TESTCTRL_ISKEYWORD: { - const char *zWord = va_arg(ap, const char*); - int n = sqlite3Strlen30(zWord); - rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0; - break; - } -#endif - - /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff); - ** - ** If parameter onoff is non-zero, configure the wrappers so that all - ** subsequent calls to localtime() and variants fail. If onoff is zero, - ** undo this setting. - */ - case SQLITE_TESTCTRL_LOCALTIME_FAULT: { - sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int); - 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; - } - - /* 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*,int,u8,u8); - 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; - } - } - va_end(ap); -#endif /* SQLITE_UNTESTABLE */ - return rc; -} - -/* -** This is a utility routine, useful to VFS implementations, that checks -** to see if a database file was a URI that contained a specific query -** parameter, and if so obtains the value of the query parameter. -** -** The zFilename argument is the filename pointer passed into the xOpen() -** method of a VFS implementation. The zParam argument is the name of the -** query parameter we seek. This routine returns the value of the zParam -** parameter if it exists. If the parameter does not exist, this routine -** returns a NULL pointer. -*/ -SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){ - if( zFilename==0 || zParam==0 ) return 0; - 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; -} - -/* -** 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; -} - -/* -** 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); - 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( 0==sqlite3BtreeIsInReadTrans(pBt) ){ - rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot); - if( rc==SQLITE_OK ){ - rc = sqlite3BtreeBeginTrans(pBt, 0); - sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0); - } - } - } - } - - 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); - 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_MASTER mutex. -*/ -static void enterMutex(void){ - sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); - checkListProperties(0); -} - -/* -** Release the STATIC_MASTER mutex. -*/ -static void leaveMutex(void){ - assertMutexHeld(); - checkListProperties(0); - sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)); -} - -/* -** Register an unlock-notify callback. -** -** This is called after connection "db" has attempted some operation -** but has received an SQLITE_LOCKED error because another connection -** (call it pOther) in the same process was busy using the same shared -** cache. pOther is found by looking at db->pBlockingConnection. -** -** If there is no blocking connection, the callback is invoked immediately, -** before this routine returns. -** -** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate -** a deadlock. -** -** Otherwise, make arrangements to invoke xNotify when pOther drops -** its locks. -** -** Each call to this routine overrides any prior callbacks registered -** on the same "db". If xNotify==0 then any prior callbacks are immediately -** cancelled. -*/ -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_MASTER mutex */ - - /* This loop runs once for each entry in the blocked-connections list. */ - for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){ - sqlite3 *p = *pp; - - /* Step 1. */ - if( p->pBlockingConnection==db ){ - p->pBlockingConnection = 0; - } - - /* Step 2. */ - if( p->pUnlockConnection==db ){ - assert( p->xUnlockNotify ); - if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){ - xUnlockNotify(aArg, nArg); - nArg = 0; - } - - sqlite3BeginBenignMalloc(); - assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) ); - assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn ); - if( (!aDyn && nArg==(int)ArraySize(aStatic)) - || (aDyn && nArg==(int)(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_MASTER 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 - -/* -** 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 */ - -/* -** 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 - -#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 */ - - /* 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 - -#ifdef SQLITE_TEST - /* True to disable the incremental doclist optimization. This is controled - ** by special insert command 'test-no-incr-doclist'. */ - int bNoIncrDoclist; -#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 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); - -/* 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); -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 - -/* -** 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) | ( (*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; } - -/* -** 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){ - 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); -} - -/* -** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to -** a non-negative 32-bit integer before it is returned. -*/ -SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){ - u32 a; - -#ifndef fts3GetVarint32 - GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1); -#else - a = (*p++); - assert( a & 0x80 ); -#endif - - GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2); - GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3); - GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4); - a = (a & 0x0FFFFFFF ); - *pi = (int)(a | ((u32)(*p & 0x07) << 28)); - assert( 0==(a & 0x80000000) ); - assert( *pi>=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 */ - if( p->zContentTbl==0 ){ - fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName); - } - fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName); - fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName); - fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName); - fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", 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){ - int nRet; - char *zRet; - nRet = 2 + (int)strlen(zInput)*2 + 1; - zRet = sqlite3_malloc(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; -} - -/* -** 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; - const char *p; /* Iterator pointer */ - int nInt = 0; /* Output value */ - - for(p=*pp; p[0]>='0' && p[0]<='9'; p++){ - nInt = nInt * 10 + (p[0] - '0'); - if( nInt>MAX_NPREFIX ){ - nInt = 0; - break; - } - } - if( p==*pp ) return SQLITE_ERROR; - *pnOut = nInt; - *pp = p; - 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_malloc(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 */ - int 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 */ - int 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_malloc(nByte); - if( aCol ){ - memset((void*)aCol, 0, nByte); - azNotindexed = (char **)sqlite3_malloc(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; - - /* 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; - - /* 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; - rc = sqlite3_prepare_v3(p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0); - 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 ){ - sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId); - pCsr->isRequireSeek = 0; - if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){ - return SQLITE_OK; - }else{ - 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 */ - int 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 */ - - /* 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( zCsr=0 && nSuffix>=0 ); - if( &zCsr[nSuffix]>zEnd ){ - rc = FTS_CORRUPT_VTAB; - goto finish_scan; - } - if( nPrefix+nSuffix>nAlloc ){ - char *zNew; - nAlloc = (nPrefix+nSuffix) * 2; - zNew = (char *)sqlite3_realloc(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( !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 ){ - 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( 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 is safe because -** it is not possible to have a document with 2^31 terms. -*/ -#define POSITION_LIST_END 0x7fffffff - -/* -** 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 ){ - fts3GetDeltaVarint(pp, pi); - *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 void 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); - else if( *p1==POS_END ) iCol1 = POSITION_LIST_END; - else iCol1 = 0; - - if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2); - else if( *p2==POS_END ) iCol2 = POSITION_LIST_END; - 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); - 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( 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); - } - - assert( *p1!=POS_END && *p1!=POS_COLUMN ); - assert( *p2!=POS_END && *p2!=POS_COLUMN ); - fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2; - fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2; - - 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{ - sqlite3_int64 iVal; - *pp += sqlite3Fts3GetVarint(*pp, &iVal); - if( bDescIdx ){ - *pVal -= iVal; - }else{ - *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_int64 iWrite; - if( bDescIdx==0 || *pbFirst==0 ){ - iWrite = iVal - *piPrev; - }else{ - iWrite = *piPrev - iVal; - } - assert( *pbFirst || *piPrev==0 ); - assert( *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) * (i1-i2)) - -/* -** 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 */ -){ - 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_malloc(n1+n2+FTS3_VARINT_MAX-1); - 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); - fts3PoslistMerge(&p, &p1, &p2); - 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); - } - } - - *paOut = aOut; - *pnOut = (int)(p-aOut); - assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 ); - return SQLITE_OK; -} - -/* -** 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_malloc(*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); - }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; - int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*); - apNew = (Fts3SegReader **)sqlite3_realloc(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 ){ - 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 ){ - 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 ){ - 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; - } - }else{ - rc = fts3EvalNext((Fts3Cursor *)pCursor); - } - assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 ); - return rc; -} - -/* -** The following are copied from sqliteInt.h. -** -** 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. -*/ -#ifndef SQLITE_AMALGAMATION -# define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32)) -# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64) -#endif - -/* -** 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); - - 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 ){ - rc = sqlite3_prepare_v3(p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0); - 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; - /* 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]); - case 5: iCol = sqlite3_value_int(apVal[4]); - case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]); - case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]); - 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 ); - assert( p->mxSavepoint >= iSavepoint ); - TESTONLY( p->mxSavepoint = iSavepoint ); - sqlite3Fts3PendingTermsClear(p); - return SQLITE_OK; -} - -static const sqlite3_module fts3Module = { - /* iVersion */ 2, - /* xCreate */ fts3CreateMethod, - /* xConnect */ fts3ConnectMethod, - /* xBestIndex */ fts3BestIndexMethod, - /* xDisconnect */ fts3DisconnectMethod, - /* xDestroy */ fts3DestroyMethod, - /* xOpen */ fts3OpenMethod, - /* xClose */ fts3CloseMethod, - /* xFilter */ fts3FilterMethod, - /* xNext */ fts3NextMethod, - /* xEof */ fts3EofMethod, - /* xColumn */ fts3ColumnMethod, - /* xRowid */ fts3RowidMethod, - /* xUpdate */ fts3UpdateMethod, - /* xBegin */ fts3BeginMethod, - /* xSync */ fts3SyncMethod, - /* xCommit */ fts3CommitMethod, - /* xRollback */ fts3RollbackMethod, - /* xFindFunction */ fts3FindFunctionMethod, - /* xRename */ fts3RenameMethod, - /* xSavepoint */ fts3SavepointMethod, - /* xRelease */ fts3ReleaseMethod, - /* xRollbackTo */ fts3RollbackToMethod, -}; - -/* -** This function is registered as the module destructor (called when an -** FTS3 enabled database connection is closed). It frees the memory -** allocated for the tokenizer hash table. -*/ -static void hashDestroy(void *p){ - Fts3Hash *pHash = (Fts3Hash *)p; - sqlite3Fts3HashClear(pHash); - sqlite3_free(pHash); -} - -/* -** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are -** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c -** respectively. The following three forward declarations are for functions -** declared in these files used to retrieve the respective implementations. -** -** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed -** to by the argument to point to the "simple" tokenizer implementation. -** And so on. -*/ -SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); -SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule); -#ifndef SQLITE_DISABLE_FTS3_UNICODE -SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule); -#endif -#ifdef SQLITE_ENABLE_ICU -SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule); -#endif - -/* -** Initialize the fts3 extension. If this extension is built as part -** of the sqlite library, then this function is called directly by -** SQLite. If fts3 is built as a dynamically loadable extension, this -** function is called by the sqlite3_extension_init() entry point. -*/ -SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){ - int rc = SQLITE_OK; - Fts3Hash *pHash = 0; - const sqlite3_tokenizer_module *pSimple = 0; - const sqlite3_tokenizer_module *pPorter = 0; -#ifndef SQLITE_DISABLE_FTS3_UNICODE - const sqlite3_tokenizer_module *pUnicode = 0; -#endif - -#ifdef SQLITE_ENABLE_ICU - const sqlite3_tokenizer_module *pIcu = 0; - sqlite3Fts3IcuTokenizerModule(&pIcu); -#endif - -#ifndef SQLITE_DISABLE_FTS3_UNICODE - sqlite3Fts3UnicodeTokenizer(&pUnicode); -#endif - -#ifdef SQLITE_TEST - rc = sqlite3Fts3InitTerm(db); - if( rc!=SQLITE_OK ) return rc; -#endif - - rc = sqlite3Fts3InitAux(db); - if( rc!=SQLITE_OK ) return rc; - - sqlite3Fts3SimpleTokenizerModule(&pSimple); - sqlite3Fts3PorterTokenizerModule(&pPorter); - - /* Allocate and initialize the hash-table used to store tokenizers. */ - pHash = sqlite3_malloc(sizeof(Fts3Hash)); - if( !pHash ){ - rc = SQLITE_NOMEM; - }else{ - sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1); - } - - /* Load the built-in tokenizers into the hash table */ - if( rc==SQLITE_OK ){ - if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple) - || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) - -#ifndef SQLITE_DISABLE_FTS3_UNICODE - || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode) -#endif -#ifdef SQLITE_ENABLE_ICU - || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu)) -#endif - ){ - rc = SQLITE_NOMEM; - } - } - -#ifdef SQLITE_TEST - if( rc==SQLITE_OK ){ - rc = sqlite3Fts3ExprInitTestInterface(db); - } -#endif - - /* Create the virtual table wrapper around the hash-table and overload - ** the four scalar functions. If this is successful, register the - ** module with sqlite. - */ - if( SQLITE_OK==rc - && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer")) - && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1)) - && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1)) - && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1)) - && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2)) - && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1)) - ){ - rc = sqlite3_create_module_v2( - db, "fts3", &fts3Module, (void *)pHash, hashDestroy - ); - if( rc==SQLITE_OK ){ - rc = sqlite3_create_module_v2( - db, "fts4", &fts3Module, (void *)pHash, 0 - ); - } - if( rc==SQLITE_OK ){ - rc = sqlite3Fts3InitTok(db, (void *)pHash); - } - return rc; - } - - - /* An error has occurred. Delete the hash table and return the error code. */ - assert( rc!=SQLITE_OK ); - if( pHash ){ - sqlite3Fts3HashClear(pHash); - sqlite3_free(pHash); - } - return rc; -} - -/* -** Allocate an Fts3MultiSegReader for each token in the expression headed -** by pExpr. -** -** An Fts3SegReader object is a cursor that can seek or scan a range of -** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple -** Fts3SegReader objects internally to provide an interface to seek or scan -** within the union of all segments of a b-tree. Hence the name. -** -** If the allocated Fts3MultiSegReader just seeks to a single entry in a -** segment b-tree (if the term is not a prefix or it is a prefix for which -** there exists prefix b-tree of the right length) then it may be traversed -** and merged incrementally. Otherwise, it has to be merged into an in-memory -** doclist and then traversed. -*/ -static void fts3EvalAllocateReaders( - Fts3Cursor *pCsr, /* FTS cursor handle */ - Fts3Expr *pExpr, /* Allocate readers for this expression */ - int *pnToken, /* OUT: Total number of tokens in phrase. */ - int *pnOr, /* OUT: Total number of OR nodes in expr. */ - int *pRc /* IN/OUT: Error code */ -){ - if( pExpr && SQLITE_OK==*pRc ){ - if( pExpr->eType==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; -} - -/* -** 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; -} - -/* -** 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 -#ifdef 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( 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 = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */ - - if( pDL->pNextDocid ){ - pIter = pDL->pNextDocid; - }else{ - pIter = pDL->aAll; - } - - if( pIter>=pEnd ){ - /* 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+1); - if( !aDoclist ) return SQLITE_NOMEM; - memcpy(aDoclist, a[p->nToken-1].pList, nByte+1); - - 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); - assert( a ); - - pEnd = &a[sqlite3_column_bytes(pStmt, 0)]; - a += sqlite3Fts3GetVarint(a, &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_malloc( - 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; - 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); - } - } - } - } - 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; - int 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_malloc(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); - } - 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){ - if( pExpr ){ - Fts3Phrase *pPhrase = pExpr->pPhrase; - if( pPhrase && pPhrase->doclist.pList ){ - int iCol = 0; - char *p = pPhrase->doclist.pList; - - assert( *p ); - while( 1 ){ - 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); - } - } - - fts3EvalUpdateCounts(pExpr->pLeft); - fts3EvalUpdateCounts(pExpr->pRight); - } -} - -/* -** 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_malloc(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); - } - } - - 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 ); - }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) */ - int 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_malloc(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_realloc(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); - pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]); - if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM; - } - } - - if( iLe>=0 ){ - pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe])); - pCsr->nStop = sqlite3_value_bytes(apVal[iLe]); - if( pCsr->zStop==0 ) return SQLITE_NOMEM; - } - - 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 */ - }; - 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(int nByte){ - void *pRet = sqlite3_malloc(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; - int 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, int nNew){ - void *pRet = sqlite3_realloc(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' ){ - nNear = 0; - for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){ - nNear = nNear * 10 + (zInput[nKey] - '0'); - } - } - } - - /* 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); - if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; } - *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_malloc(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 */ - -/* -** Function to query the hash-table of tokenizers (see README.tokenizers). -*/ -static int queryTestTokenizer( - sqlite3 *db, - const 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 ){ - memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp)); - } - } - - return sqlite3_finalize(pStmt); -} - -/* -** 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 fts3ExprTest( - sqlite3_context *context, - int argc, - sqlite3_value **argv -){ - sqlite3_tokenizer_module const *pModule = 0; - sqlite3_tokenizer *pTokenizer = 0; - int rc; - char **azCol = 0; - const char *zExpr; - int nExpr; - int nCol; - int ii; - Fts3Expr *pExpr; - char *zBuf = 0; - sqlite3 *db = sqlite3_context_db_handle(context); - - if( argc<3 ){ - sqlite3_result_error(context, - "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1 - ); - return; - } - - rc = queryTestTokenizer(db, - (const char *)sqlite3_value_text(argv[0]), &pModule); - if( rc==SQLITE_NOMEM ){ - sqlite3_result_error_nomem(context); - goto exprtest_out; - }else if( !pModule ){ - sqlite3_result_error(context, "No such tokenizer module", -1); - goto exprtest_out; - } - - rc = pModule->xCreate(0, 0, &pTokenizer); - assert( rc==SQLITE_NOMEM || rc==SQLITE_OK ); - if( rc==SQLITE_NOMEM ){ - sqlite3_result_error_nomem(context); - goto exprtest_out; - } - pTokenizer->pModule = pModule; - - zExpr = (const char *)sqlite3_value_text(argv[1]); - nExpr = sqlite3_value_bytes(argv[1]); - nCol = argc-2; - azCol = (char **)sqlite3_malloc(nCol*sizeof(char *)); - if( !azCol ){ - sqlite3_result_error_nomem(context); - goto exprtest_out; - } - for(ii=0; iixDestroy(pTokenizer); - } - sqlite3_free(azCol); -} - -/* -** Register the query expression parser test function fts3_exprtest() -** with database connection db. -*/ -SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){ - int rc = sqlite3_create_function( - db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0 - ); - if( rc==SQLITE_OK ){ - rc = sqlite3_create_function(db, "fts3_exprtest_rebalance", - -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 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(int n){ - void *p = sqlite3_malloc(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) ){ - 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; - } - } - 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 ){ - 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_ANY; - -#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; ixCreate((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_malloc(nByte+1); - if( pCsr->zInput==0 ){ - rc = SQLITE_NOMEM; - }else{ - 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 */ - }; - 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 */ - - -#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 two 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 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 %Q.'%q_segdir' WHERE level = ? AND idx < ?", - -/* 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 ){ - 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 ){ - 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, SQLITE_PREPARE_PERSISTENT, - &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( 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 ){ - sqlite3_int64 iDelta = iDocid - (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>=FTS3_MERGE_COUNT ){ - 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; - } - } - - 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. */ - assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock ); - 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( nPrefix<0 || nSuffix<=0 - || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] - ){ - return FTS_CORRUPT_VTAB; - } - - if( nPrefix+nSuffix>pReader->nTermAlloc ){ - int nNew = (nPrefix+nSuffix)*2; - char *zNew = sqlite3_realloc(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->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] - || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1]) - ){ - 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 ){ - sqlite3_int64 iDelta; - pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta); - if( pTab->bDescIdx ){ - pReader->iDocid -= iDelta; - }else{ - pReader->iDocid += iDelta; - } - } - } - } - - return SQLITE_OK; -} - - -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( iStartLeaf<=iEndLeaf ); - if( iStartLeaf==0 ){ - 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; - 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 ){ - int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *); - pReader = (Fts3SegReader *)sqlite3_malloc(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); - } - 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); - } - 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; - - 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; - - /* 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. */ - 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); - memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix); - nData += nSuffix; - nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist); - 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 ); - 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, - ((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( ppMsr->nBuffer ){ - char *pNew; - pMsr->nBuffer = nList*2; - pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer); - if( !pNew ) return SQLITE_NOMEM; - pMsr->aBuffer = pNew; - } - - 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; -} - - -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 ){ - iDelta = iPrev - iDocid; - }else{ - iDelta = iDocid - iPrev; - } - assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) ); - assert( nDoclist>0 || iDelta==iDocid ); - - nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0); - if( nDoclist+nByte>pCsr->nBuffer ){ - char *aNew; - pCsr->nBuffer = (nDoclist+nByte)*2; - aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer); - if( !aNew ){ - return SQLITE_NOMEM; - } - pCsr->aBuffer = aNew; - } - - 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 ){ - 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; - i64 iVal = 0; - for(i=0; zText[i]>='0' && zText[i]<='9'; i++){ - iVal = iVal*10 + (zText[i] - '0'); - } - *piEndBlock = 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 = (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( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) ); - assert( 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_malloc( 10*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_malloc( (sizeof(u32)+10)*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_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 = 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); - sqlite3Fts3PendingTermsClear(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 ){ - int nByte = sizeof(u32) * (p->nColumn+1)*3; - aSz = (u32 *)sqlite3_malloc(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 */ - int 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_malloc(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); - - 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); - p->aDoclist = &p->aNode[p->iOff]; - p->iOff += p->nDoclist; - } - } - } - - assert( 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( p->aNode[0] ){ - /* An internal node. */ - p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild); - }else{ - p->iOff = 1; - } - - return nodeReaderNext(p); -} - -/* -** 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; - 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( (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; - 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 = memcmp(zLhs, zRhs, nCmp); - 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); - }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; - - 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), &rc); - if( rc==SQLITE_OK ){ - memcpy(pNode->block.a, aRoot, nRoot); - pNode->block.n = nRoot; - } - - for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){ - NodeReader reader; - pNode = &pWriter->aNodeWriter[i]; - - 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), &rc); - if( rc==SQLITE_OK ){ - memcpy(pNode->block.a, aBlock, nBlock); - pNode->block.n = nBlock; - } - 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 = aNode[0]=='\0'; /* True for a leaf node */ - - /* 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_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); - } - - 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-2; - while( i>0 && (pHint->a[i-1] & 0x80) ) 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); - 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) ){ - iAbsLevel = iHintAbsLevel; - 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; - - /* 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)) - && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr)) - ){ - 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); - 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 = (FTS3_MERGE_COUNT / 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>FTS3_MERGE_COUNT ){ - 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; - i64 iPos = 0; - - pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid); - while( pCsriPrevLangid); - 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); - int nText = sqlite3_column_bytes(pStmt, iCol+1); - sqlite3_tokenizer_cursor *pT = 0; - - rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&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; /* 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]); -#ifdef SQLITE_TEST - }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){ - p->nNodeSize = atoi(&zVal[9]); - rc = SQLITE_OK; - }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){ - p->nMaxPendingData = atoi(&zVal[11]); - rc = SQLITE_OK; - }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){ - p->bNoIncrDoclist = atoi(&zVal[21]); - rc = SQLITE_OK; -#endif - }else{ - rc = SQLITE_ERROR; - } - - 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 */ - int isRemove = 0; /* True for an UPDATE or DELETE */ - 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_malloc( sizeof(aSzDel[0])*(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); - isRemove = 1; - } - - /* 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 && (!isRemove || *pRowid!=p->iPrevDocid ) ){ - 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(int nElem, const char *zMatchinfo){ - MatchinfoBuffer *pRet; - int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer); - int nStr = (int)strlen(zMatchinfo); - - pRet = sqlite3_malloc(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)*(nElem+1); - pRet->nElem = 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_malloc(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) ){ - int j; - u64 mPhrase = (u64)1 << i; - u64 mPos = (u64)1 << (iCsr - iStart); - assert( iCsr>=iStart ); - 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); - assert( iFirst>=0 ); - 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 */ - int 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_malloc(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 ){ - int nAlloc = pStr->nAlloc+nAppend+100; - char *zNew = sqlite3_realloc(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++); - 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 void 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); - } - - 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); - } -} - -/* -** Gather the results for matchinfo directives 'y' and 'b'. -*/ -static void fts3ExprLHitGather( - Fts3Expr *pExpr, - MatchInfo *p -){ - assert( (pExpr->pLeft==0)==(pExpr->pRight==0) ); - if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){ - if( pExpr->pLeft ){ - fts3ExprLHitGather(pExpr->pLeft, p); - fts3ExprLHitGather(pExpr->pRight, p); - }else{ - fts3ExprLHits(pExpr, p); - } - } -} - -/* -** 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 int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){ - int 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 -){ - sqlite3_stmt *pStmt; - const char *a; - sqlite3_int64 nDoc; - - if( !*ppStmt ){ - int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt); - if( rc!=SQLITE_OK ) return rc; - } - pStmt = *ppStmt; - assert( sqlite3_data_count(pStmt)==1 ); - - a = sqlite3_column_blob(pStmt, 0); - a += sqlite3Fts3GetVarint(a, &nDoc); - if( nDoc==0 ) return FTS_CORRUPT_VTAB; - *pnDoc = (u32)nDoc; - - if( paLen ) *paLen = a; - 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; - - /* Allocate and populate the array of LcsIterator objects. The array - ** contains one element for each matchable phrase in the query. - **/ - aIter = sqlite3_malloc(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++){ - int rc; - LcsIterator *pIt = &aIter[i]; - rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead); - if( rc!=SQLITE_OK ) return rc; - if( pIt->pRead ){ - pIt->iPos = pIt->iPosOffset; - fts3LcsIteratorAdvance(&aIter[i]); - 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; - } - - sqlite3_free(aIter); - return SQLITE_OK; -} - -/* -** 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); - 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 */ - - rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a); - if( rc==SQLITE_OK ){ - int iCol; - for(iCol=0; iColnCol; iCol++){ - u32 iVal; - sqlite3_int64 nToken; - a += sqlite3Fts3GetVarint(a, &nToken); - 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); - for(iCol=0; iColnCol; iCol++){ - sqlite3_int64 nToken; - a += sqlite3Fts3GetVarint(a, &nToken); - 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: { - int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32); - memset(pInfo->aMatchinfo, 0, nZero); - 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); - 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 ){ - int 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; - } - - 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( 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_malloc(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( 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 bRemoveDiacritic; - 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->bRemoveDiacritic = 1; - - for(i=0; rc==SQLITE_OK && ibRemoveDiacritic = 1; - } - else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){ - pNew->bRemoveDiacritic = 0; - } - 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_realloc(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->bRemoveDiacritic); - 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 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. -** -****************************************************************************** -*/ - -/* -** 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){ - 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, 3896, 3912, 3928, - 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234, - 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504, - 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529, - 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726, - 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122, - 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536, - 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730, - 62924, 63050, 63082, 63274, 63390, - }; - 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', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r', - 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0', - '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h', - 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't', - 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a', - 'e', 'i', 'o', 'u', '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] ); - return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]); -} - - -/* -** 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 & (1 << (c-768))) : - (mask1 & (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 bRemoveDiacritic){ - /* 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( bRemoveDiacritic ) ret = remove_diacritic(ret); - } - - 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 rtree.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 for implementations of the r-tree and r*-tree -** algorithms packaged as an SQLite virtual table module. -*/ - -/* -** Database Format of R-Tree Tables -** -------------------------------- -** -** The data structure for a single virtual r-tree table is stored in three -** native SQLite tables declared as follows. In each case, the '%' character -** in the table name is replaced with the user-supplied name of the r-tree -** table. -** -** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB) -** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER) -** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER) -** -** The data for each node of the r-tree structure is stored in the %_node -** table. For each node that is not the root node of the r-tree, there is -** an entry in the %_parent table associating the node with its parent. -** And for each row of data in the table, there is an entry in the %_rowid -** table that maps from the entries rowid to the id of the node that it -** is stored on. -** -** The root node of an r-tree always exists, even if the r-tree table is -** empty. The nodeno of the root node is always 1. All other nodes in the -** table must be the same size as the root node. The content of each node -** is formatted as follows: -** -** 1. If the node is the root node (node 1), then the first 2 bytes -** of the node contain the tree depth as a big-endian integer. -** For non-root nodes, the first 2 bytes are left unused. -** -** 2. The next 2 bytes contain the number of entries currently -** stored in the node. -** -** 3. The remainder of the node contains the node entries. Each entry -** consists of a single 8-byte integer followed by an even number -** of 4-byte coordinates. For leaf nodes the integer is the rowid -** of a record. For internal nodes it is the node number of a -** child page. -*/ - -#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE) - -#ifndef SQLITE_CORE -/* #include "sqlite3ext.h" */ - SQLITE_EXTENSION_INIT1 -#else -/* #include "sqlite3.h" */ -#endif - -/* #include */ -/* #include */ -/* #include */ - -#ifndef SQLITE_AMALGAMATION -#include "sqlite3rtree.h" -typedef sqlite3_int64 i64; -typedef sqlite3_uint64 u64; -typedef unsigned char u8; -typedef unsigned short u16; -typedef unsigned int u32; -#endif - -/* 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 - -/* 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 */ - 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 */ - - /* 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; - - 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 - -/* -** 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 -** 2^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 */ - 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 */ - 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() */ - - -/* -** 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 - -/* -** 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 ){ - 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 int nodeHash(i64 iNode){ - return 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_malloc(sizeof(RtreeNode) + pRtree->iNodeSize); - if( pNode ){ - memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize); - pNode->zData = (u8 *)&pNode[1]; - pNode->nRef = 1; - 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); - } -} - -/* -** 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)) ){ - assert( !pParent || !pNode->pParent || pNode->pParent==pParent ); - if( pParent && !pNode->pParent ){ - nodeReference(pParent); - pNode->pParent = pParent; - } - 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; - }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){ - pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize); - if( !pNode ){ - rc = SQLITE_NOMEM; - }else{ - pNode->pParent = pParent; - pNode->zData = (u8 *)&pNode[1]; - pNode->nRef = 1; - pNode->iNode = iNode; - pNode->isDirty = 0; - pNode->pNext = 0; - rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData, - pRtree->iNodeSize, 0); - nodeReference(pParent); - } - } - - /* 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; - } - } - - /* 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; - } - } - - if( rc==SQLITE_OK ){ - if( pNode!=0 ){ - nodeHashInsert(pRtree, pNode); - }else{ - rc = SQLITE_CORRUPT_VTAB; - } - *ppNode = pNode; - }else{ - 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); - 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 ); - pNode->nRef--; - if( pNode->nRef==0 ){ - 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; - pRtree->nCursor = 0; - nodeBlobReset(pRtree); - 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_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_malloc(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; -} - - -/* -** Free the RtreeCursor.aConstraint[] array and its contents. -*/ -static void freeCursorConstraints(RtreeCursor *pCsr){ - 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; - } -} - -/* -** Rtree virtual table module xClose method. -*/ -static int rtreeClose(sqlite3_vtab_cursor *cur){ - Rtree *pRtree = (Rtree *)(cur->pVtab); - int ii; - RtreeCursor *pCsr = (RtreeCursor *)cur; - assert( pRtree->nCursor>0 ); - freeCursorConstraints(pCsr); - sqlite3_free(pCsr->aPoint); - for(ii=0; iiaNode[ii]); - 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 ); - assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */ - switch( p->op ){ - 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 ); - 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_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_realloc(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 ){ - pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc); - if( rc ) return rc; - nCell = NCELL(pNode); - assert( nCell<200 ); - while( p->iCellzData + (4+pRtree->nBytesPerCell*p->iCell); - eWithin = FULLY_WITHIN; - for(ii=0; iiaConstraint + 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 ) break; - } - p->iCell++; - if( eWithin==NOT_WITHIN ) continue; - x.iLevel = p->iLevel - 1; - if( x.iLevel ){ - x.id = readInt64(pCellData); - 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:"); - 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{ - 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); - } - } - 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. */ - freeCursorConstraints(pCsr); - sqlite3_free(pCsr->aPoint); - memset(pCsr, 0, sizeof(RtreeCursor)); - pCsr->base.pVtab = (sqlite3_vtab*)pRtree; - - 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 && argc>0 ){ - pCsr->aConstraint = sqlite3_malloc(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]; - 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{ -#ifdef SQLITE_RTREE_INT_ONLY - p->u.rValue = sqlite3_value_int64(argv[ii]); -#else - p->u.rValue = sqlite3_value_double(argv[ii]); -#endif - } - } - } - } - 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; - return SQLITE_OK; - } - - if( p->usable && (p->iColumn>0 || 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; - default: - assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH ); - op = RTREE_MATCH; - break; - } - 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 = p->aCoord[9].i - p->aCoord[8].i; - case 4: area *= p->aCoord[7].i - p->aCoord[6].i; - case 3: area *= p->aCoord[5].i - p->aCoord[4].i; - case 2: area *= p->aCoord[3].i - p->aCoord[2].i; - default: area *= p->aCoord[1].i - 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( nodeParentIndex(pRtree, p, &iCell) ){ - 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_malloc(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_malloc((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); - nodeReference(pLeft); - } - - 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 ) 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 newRowid(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); - } - - /* Delete the cell in question from the leaf node. */ - if( rc==SQLITE_OK ){ - 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; - 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; - 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 **azData, - 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 */ - - 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; - - /* Populate the cell.aCoord[] array. The first coordinate is azData[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. - */ - assert( nData<=(pRtree->nDim2 + 3) ); - -#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(azData[2])!=SQLITE_NULL ){ - cell.iRowid = sqlite3_value_int64(azData[2]); - if( sqlite3_value_type(azData[0])==SQLITE_NULL - || sqlite3_value_int64(azData[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 azData[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(azData[0])!=SQLITE_NULL ){ - rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0])); - } - - /* If the azData[] array contains more than one element, elements - ** (azData[2]..azData[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 = newRowid(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; - } - } - } - -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; - int 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; -} - -static sqlite3_module rtreeModule = { - 2, /* iVersion */ - rtreeCreate, /* xCreate - create a table */ - rtreeConnect, /* xConnect - connect to an existing table */ - rtreeBestIndex, /* 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 */ - rtreeFilter, /* xFilter - configure scan constraints */ - rtreeNext, /* xNext - advance a cursor */ - rtreeEof, /* xEof */ - rtreeColumn, /* xColumn - read data */ - rtreeRowid, /* xRowid - read data */ - rtreeUpdate, /* xUpdate - write data */ - rtreeBeginTransaction, /* xBegin - begin transaction */ - rtreeEndTransaction, /* xSync - sync transaction */ - rtreeEndTransaction, /* xCommit - commit transaction */ - rtreeEndTransaction, /* xRollback - rollback transaction */ - 0, /* xFindFunction - function overloading */ - rtreeRename, /* xRename - rename the table */ - rtreeSavepoint, /* xSavepoint */ - 0, /* xRelease */ - 0, /* xRollbackTo */ -}; - -static int rtreeSqlInit( - Rtree *pRtree, - sqlite3 *db, - const char *zDb, - const char *zPrefix, - int isCreate -){ - int rc = SQLITE_OK; - - #define N_STATEMENT 8 - static const char *azSql[N_STATEMENT] = { - /* Write the xxx_node table */ - "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)", - "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1", - - /* Read and write the xxx_rowid table */ - "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1", - "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)", - "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1", - - /* Read and write the xxx_parent table */ - "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1", - "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)", - "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1" - }; - sqlite3_stmt **appStmt[N_STATEMENT]; - int i; - - pRtree->db = db; - - if( isCreate ){ - char *zCreate = sqlite3_mprintf( -"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);" -"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);" -"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY," - " parentnode INTEGER);" -"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))", - zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize - ); - 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; iiNodeSize 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; - *pzErr = sqlite3_mprintf("undersize RTree blobs in \"%q_node\"", - pRtree->zName); - } - } - - sqlite3_free(zSql); - return rc; -} - -/* -** 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); - - 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 */ - }; - - int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2; - if( aErrMsg[iErr] ){ - *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]); - 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_malloc(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->nDim = (u8)((argc-4)/2); - pRtree->nDim2 = pRtree->nDim*2; - pRtree->nBytesPerCell = 8 + pRtree->nDim2*4; - pRtree->eCoordType = (u8)eCoordType; - memcpy(pRtree->zDb, argv[1], nDb); - memcpy(pRtree->zName, argv[2], nName); - - /* Figure out the node size to use. */ - rc = getNodeSize(db, pRtree, isCreate, pzErr); - - /* Create/Connect to the underlying relational database schema. If - ** that is successful, call sqlite3_declare_vtab() to configure - ** the r-tree table schema. - */ - if( rc==SQLITE_OK ){ - if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){ - *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); - }else{ - char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]); - char *zTmp; - int ii; - for(ii=4; zSql && iinBusy==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){ - char *zText = 0; - RtreeNode node; - Rtree tree; - int ii; - - UNUSED_PARAMETER(nArg); - memset(&node, 0, sizeof(RtreeNode)); - memset(&tree, 0, sizeof(Rtree)); - tree.nDim = (u8)sqlite3_value_int(apArg[0]); - tree.nDim2 = tree.nDim*2; - tree.nBytesPerCell = 8 + 8 * tree.nDim; - node.zData = (u8 *)sqlite3_value_blob(apArg[1]); - - for(ii=0; iixDestructor ) 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; - int nBlob; - int memErr = 0; - - nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue) - + nArg*sizeof(sqlite3_value*); - pBlob = (RtreeMatchArg *)sqlite3_malloc(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) - -/* Include ICU headers */ -#include -#include -#include -#include - -/* #include */ - -#ifndef SQLITE_CORE -/* #include "sqlite3ext.h" */ - SQLITE_EXTENSION_INIT1 -#else -/* #include "sqlite3.h" */ -#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 - -/* -** 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( !prevEscape && uPattern==MATCH_ALL ){ - /* 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( !prevEscape && uPattern==MATCH_ONE ){ - /* Case 2. */ - if( *zString==0 ) return 0; - SQLITE_ICU_SKIP_UTF8(zString); - - }else if( !prevEscape && uPattern==(uint32_t)uEsc){ - /* 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)); - } -} - -/* -** 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); -} - -/* -** 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 */ -} - -/* -** 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){ - static const struct IcuScalar { - const char *zName; /* Function name */ - unsigned char nArg; /* Number of arguments */ - unsigned short 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, 1, icuLoadCollation}, - {"regexp", 2, SQLITE_ANY|SQLITE_DETERMINISTIC, 0, icuRegexpFunc}, - {"lower", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16}, - {"lower", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16}, - {"upper", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 1, icuCaseFunc16}, - {"upper", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 1, icuCaseFunc16}, - {"lower", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16}, - {"lower", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16}, - {"upper", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 1, icuCaseFunc16}, - {"upper", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 1, icuCaseFunc16}, - {"like", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc}, - {"like", 3, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc}, - }; - 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_malloc(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_malloc( - 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. -** -** 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. -*/ -#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_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 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 *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; -}; - -/* -** 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. -** -*/ -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 */ - - /* 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; /* Linked list of main db files */ -}; - -/* -** 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 */ -}; - -/* -** 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_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; - } - - pIter->pSelect = 0; - pIter->pInsert = 0; - pIter->pDelete = 0; - pIter->pRbuUpdate = 0; - pIter->pTmpInsert = 0; - pIter->nCol = 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) ){ - 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_master " - "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_master " - " 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, int 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){ - int 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; - - assert( *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_master ){ -** 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_master ){ -** *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_master where name=%Q AND IsVirtual(%Q) - ** 1) PRAGMA index_list = ? - ** 2) SELECT count(*) FROM sqlite_master 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_master" - " 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_master 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); - sqlite3_stmt *pXInfo = 0; - if( zIdx==0 ) break; - 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; - } - 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); - pIter->abTblPk[iOrder] = (iPk!=0); - 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; -} - -/* -** 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; - const char *zType; - - 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; - int nByte = nBind*2 + 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_master 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 %s", 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 %s%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); - } -} - -/* -** 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; - int nBind = 0; - - assert( pIter->eType!=RBU_PK_VTAB ); - 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) ){ - zSql = sqlite3_mprintf( - "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s", - zCollist, - pIter->zDataTbl, - zCollist, zLimit - ); - }else - - if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){ - zSql = sqlite3_mprintf( - "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s", - zCollist, p->zStateDb, pIter->zDataTbl, - zCollist, zLimit - ); - }else{ - zSql = sqlite3_mprintf( - "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' " - "UNION ALL " - "SELECT %s, rbu_control FROM '%q' " - "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 " - "ORDER BY %s%s", - zCollist, p->zStateDb, pIter->zDataTbl, - zCollist, pIter->zDataTbl, - zCollist, zLimit - ); - } - p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql); - } - - sqlite3_free(zImposterCols); - sqlite3_free(zImposterPK); - sqlite3_free(zWhere); - sqlite3_free(zBind); - }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 = ""; - if( bRbuRowid ){ - zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid"; - } - p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, - sqlite3_mprintf( - "SELECT %s,%s rbu_control%s FROM '%q'%s", - zCollist, - (rbuIsVacuum(p) ? "0 AS " : ""), - zRbuRowid, - pIter->zDataTbl, zLimit - ) - ); - } - - 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->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; - - 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_master" - ); - 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-vacuum?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_master"); - - /* 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_master", 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
  • -8OQq)QIAR_0Pdw-h$!wpBl9KA_0!MhIV1$}XevD# z7g1GAV%%7-okUNhT7{pB#T)32q#~}2&2tGq-Bz<7Iq<320n%7VHKC^zLP^;WBC81# zuCI$6~eGHVM+Rs525;*)T*4Uwv}5rJ(U>Q0f1g>U~z}?-#p`Wb6dcXprcF z*z@Km#E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